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/Basic/TypeTraits.h" 39#include "clang/Lex/LiteralSupport.h" 40#include "clang/Lex/Preprocessor.h" 41#include "clang/Sema/AnalysisBasedWarnings.h" 42#include "clang/Sema/DeclSpec.h" 43#include "clang/Sema/DelayedDiagnostic.h" 44#include "clang/Sema/Designator.h" 45#include "clang/Sema/EnterExpressionEvaluationContext.h" 46#include "clang/Sema/Initialization.h" 47#include "clang/Sema/Lookup.h" 48#include "clang/Sema/Overload.h" 49#include "clang/Sema/ParsedTemplate.h" 50#include "clang/Sema/Scope.h" 51#include "clang/Sema/ScopeInfo.h" 52#include "clang/Sema/SemaFixItUtils.h" 53#include "clang/Sema/SemaInternal.h" 54#include "clang/Sema/Template.h" 55#include "llvm/ADT/STLExtras.h" 56#include "llvm/ADT/StringExtras.h" 57#include "llvm/Support/Casting.h" 58#include "llvm/Support/ConvertUTF.h" 59#include "llvm/Support/SaveAndRestore.h" 60#include "llvm/Support/TypeSize.h" 61#include <optional> 62 63using namespace clang; 64using namespace sema; 65 66/// Determine whether the use of this declaration is valid, without 67/// emitting diagnostics. 68bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 69 // See if this is an auto-typed variable whose initializer we are parsing. 70 if (ParsingInitForAutoVars.count(D)) 71 return false; 72 73 // See if this is a deleted function. 74 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 75 if (FD->isDeleted()) 76 return false; 77 78 // If the function has a deduced return type, and we can't deduce it, 79 // then we can't use it either. 80 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 81 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 82 return false; 83 84 // See if this is an aligned allocation/deallocation function that is 85 // unavailable. 86 if (TreatUnavailableAsInvalid && 87 isUnavailableAlignedAllocationFunction(*FD)) 88 return false; 89 } 90 91 // See if this function is unavailable. 92 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 93 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 94 return false; 95 96 if (isa<UnresolvedUsingIfExistsDecl>(D)) 97 return false; 98 99 return true; 100} 101 102static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 103 // Warn if this is used but marked unused. 104 if (const auto *A = D->getAttr<UnusedAttr>()) { 105 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 106 // should diagnose them. 107 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 108 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) { 109 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 110 if (DC && !DC->hasAttr<UnusedAttr>()) 111 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 112 } 113 } 114} 115 116/// Emit a note explaining that this function is deleted. 117void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 118 assert(Decl && Decl->isDeleted()); 119 120 if (Decl->isDefaulted()) { 121 // If the method was explicitly defaulted, point at that declaration. 122 if (!Decl->isImplicit()) 123 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 124 125 // Try to diagnose why this special member function was implicitly 126 // deleted. This might fail, if that reason no longer applies. 127 DiagnoseDeletedDefaultedFunction(Decl); 128 return; 129 } 130 131 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 132 if (Ctor && Ctor->isInheritingConstructor()) 133 return NoteDeletedInheritingConstructor(Ctor); 134 135 Diag(Decl->getLocation(), diag::note_availability_specified_here) 136 << Decl << 1; 137} 138 139/// Determine whether a FunctionDecl was ever declared with an 140/// explicit storage class. 141static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 142 for (auto *I : D->redecls()) { 143 if (I->getStorageClass() != SC_None) 144 return true; 145 } 146 return false; 147} 148 149/// Check whether we're in an extern inline function and referring to a 150/// variable or function with internal linkage (C11 6.7.4p3). 151/// 152/// This is only a warning because we used to silently accept this code, but 153/// in many cases it will not behave correctly. This is not enabled in C++ mode 154/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 155/// and so while there may still be user mistakes, most of the time we can't 156/// prove that there are errors. 157static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 158 const NamedDecl *D, 159 SourceLocation Loc) { 160 // This is disabled under C++; there are too many ways for this to fire in 161 // contexts where the warning is a false positive, or where it is technically 162 // correct but benign. 163 if (S.getLangOpts().CPlusPlus) 164 return; 165 166 // Check if this is an inlined function or method. 167 FunctionDecl *Current = S.getCurFunctionDecl(); 168 if (!Current) 169 return; 170 if (!Current->isInlined()) 171 return; 172 if (!Current->isExternallyVisible()) 173 return; 174 175 // Check if the decl has internal linkage. 176 if (D->getFormalLinkage() != Linkage::Internal) 177 return; 178 179 // Downgrade from ExtWarn to Extension if 180 // (1) the supposedly external inline function is in the main file, 181 // and probably won't be included anywhere else. 182 // (2) the thing we're referencing is a pure function. 183 // (3) the thing we're referencing is another inline function. 184 // This last can give us false negatives, but it's better than warning on 185 // wrappers for simple C library functions. 186 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 187 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 188 if (!DowngradeWarning && UsedFn) 189 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 190 191 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 192 : diag::ext_internal_in_extern_inline) 193 << /*IsVar=*/!UsedFn << D; 194 195 S.MaybeSuggestAddingStaticToDecl(Current); 196 197 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 198 << D; 199} 200 201void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 202 const FunctionDecl *First = Cur->getFirstDecl(); 203 204 // Suggest "static" on the function, if possible. 205 if (!hasAnyExplicitStorageClass(First)) { 206 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 207 Diag(DeclBegin, diag::note_convert_inline_to_static) 208 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 209 } 210} 211 212/// Determine whether the use of this declaration is valid, and 213/// emit any corresponding diagnostics. 214/// 215/// This routine diagnoses various problems with referencing 216/// declarations that can occur when using a declaration. For example, 217/// it might warn if a deprecated or unavailable declaration is being 218/// used, or produce an error (and return true) if a C++0x deleted 219/// function is being used. 220/// 221/// \returns true if there was an error (this declaration cannot be 222/// referenced), false otherwise. 223/// 224bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 225 const ObjCInterfaceDecl *UnknownObjCClass, 226 bool ObjCPropertyAccess, 227 bool AvoidPartialAvailabilityChecks, 228 ObjCInterfaceDecl *ClassReceiver, 229 bool SkipTrailingRequiresClause) { 230 SourceLocation Loc = Locs.front(); 231 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 232 // If there were any diagnostics suppressed by template argument deduction, 233 // emit them now. 234 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 235 if (Pos != SuppressedDiagnostics.end()) { 236 for (const PartialDiagnosticAt &Suppressed : Pos->second) 237 Diag(Suppressed.first, Suppressed.second); 238 239 // Clear out the list of suppressed diagnostics, so that we don't emit 240 // them again for this specialization. However, we don't obsolete this 241 // entry from the table, because we want to avoid ever emitting these 242 // diagnostics again. 243 Pos->second.clear(); 244 } 245 246 // C++ [basic.start.main]p3: 247 // The function 'main' shall not be used within a program. 248 if (cast<FunctionDecl>(D)->isMain()) 249 Diag(Loc, diag::ext_main_used); 250 251 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 252 } 253 254 // See if this is an auto-typed variable whose initializer we are parsing. 255 if (ParsingInitForAutoVars.count(D)) { 256 if (isa<BindingDecl>(D)) { 257 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 258 << D->getDeclName(); 259 } else { 260 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 261 << D->getDeclName() << cast<VarDecl>(D)->getType(); 262 } 263 return true; 264 } 265 266 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 267 // See if this is a deleted function. 268 if (FD->isDeleted()) { 269 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 270 if (Ctor && Ctor->isInheritingConstructor()) 271 Diag(Loc, diag::err_deleted_inherited_ctor_use) 272 << Ctor->getParent() 273 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 274 else 275 Diag(Loc, diag::err_deleted_function_use); 276 NoteDeletedFunction(FD); 277 return true; 278 } 279 280 // [expr.prim.id]p4 281 // A program that refers explicitly or implicitly to a function with a 282 // trailing requires-clause whose constraint-expression is not satisfied, 283 // other than to declare it, is ill-formed. [...] 284 // 285 // See if this is a function with constraints that need to be satisfied. 286 // Check this before deducing the return type, as it might instantiate the 287 // definition. 288 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) { 289 ConstraintSatisfaction Satisfaction; 290 if (CheckFunctionConstraints(FD, Satisfaction, Loc, 291 /*ForOverloadResolution*/ true)) 292 // A diagnostic will have already been generated (non-constant 293 // constraint expression, for example) 294 return true; 295 if (!Satisfaction.IsSatisfied) { 296 Diag(Loc, 297 diag::err_reference_to_function_with_unsatisfied_constraints) 298 << D; 299 DiagnoseUnsatisfiedConstraint(Satisfaction); 300 return true; 301 } 302 } 303 304 // If the function has a deduced return type, and we can't deduce it, 305 // then we can't use it either. 306 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 307 DeduceReturnType(FD, Loc)) 308 return true; 309 310 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 311 return true; 312 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 (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) { 379 if (getLangOpts().getFPEvalMethod() != 380 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine && 381 PP.getLastFPEvalPragmaLocation().isValid() && 382 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod()) 383 Diag(D->getLocation(), 384 diag::err_type_available_only_in_default_eval_method) 385 << D->getName(); 386 } 387 388 if (auto *VD = dyn_cast<ValueDecl>(D)) 389 checkTypeSupport(VD->getType(), Loc, VD); 390 391 if (LangOpts.SYCLIsDevice || 392 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) { 393 if (!Context.getTargetInfo().isTLSSupported()) 394 if (const auto *VD = dyn_cast<VarDecl>(D)) 395 if (VD->getTLSKind() != VarDecl::TLS_None) 396 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 397 } 398 399 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 400 !isUnevaluatedContext()) { 401 // C++ [expr.prim.req.nested] p3 402 // A local parameter shall only appear as an unevaluated operand 403 // (Clause 8) within the constraint-expression. 404 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 405 << D; 406 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 407 return true; 408 } 409 410 return false; 411} 412 413/// DiagnoseSentinelCalls - This routine checks whether a call or 414/// message-send is to a declaration with the sentinel attribute, and 415/// if so, it checks that the requirements of the sentinel are 416/// satisfied. 417void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, 418 ArrayRef<Expr *> Args) { 419 const SentinelAttr *Attr = D->getAttr<SentinelAttr>(); 420 if (!Attr) 421 return; 422 423 // The number of formal parameters of the declaration. 424 unsigned NumFormalParams; 425 426 // The kind of declaration. This is also an index into a %select in 427 // the diagnostic. 428 enum { CK_Function, CK_Method, CK_Block } CalleeKind; 429 430 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 431 NumFormalParams = MD->param_size(); 432 CalleeKind = CK_Method; 433 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 434 NumFormalParams = FD->param_size(); 435 CalleeKind = CK_Function; 436 } else if (const auto *VD = dyn_cast<VarDecl>(D)) { 437 QualType Ty = VD->getType(); 438 const FunctionType *Fn = nullptr; 439 if (const auto *PtrTy = Ty->getAs<PointerType>()) { 440 Fn = PtrTy->getPointeeType()->getAs<FunctionType>(); 441 if (!Fn) 442 return; 443 CalleeKind = CK_Function; 444 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) { 445 Fn = PtrTy->getPointeeType()->castAs<FunctionType>(); 446 CalleeKind = CK_Block; 447 } else { 448 return; 449 } 450 451 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn)) 452 NumFormalParams = proto->getNumParams(); 453 else 454 NumFormalParams = 0; 455 } else { 456 return; 457 } 458 459 // "NullPos" is the number of formal parameters at the end which 460 // effectively count as part of the variadic arguments. This is 461 // useful if you would prefer to not have *any* formal parameters, 462 // but the language forces you to have at least one. 463 unsigned NullPos = Attr->getNullPos(); 464 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel"); 465 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos); 466 467 // The number of arguments which should follow the sentinel. 468 unsigned NumArgsAfterSentinel = Attr->getSentinel(); 469 470 // If there aren't enough arguments for all the formal parameters, 471 // the sentinel, and the args after the sentinel, complain. 472 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) { 473 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 474 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind); 475 return; 476 } 477 478 // Otherwise, find the sentinel expression. 479 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1]; 480 if (!SentinelExpr) 481 return; 482 if (SentinelExpr->isValueDependent()) 483 return; 484 if (Context.isSentinelNullExpr(SentinelExpr)) 485 return; 486 487 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 488 // or 'NULL' if those are actually defined in the context. Only use 489 // 'nil' for ObjC methods, where it's much more likely that the 490 // variadic arguments form a list of object pointers. 491 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc()); 492 std::string NullValue; 493 if (CalleeKind == CK_Method && PP.isMacroDefined("nil")) 494 NullValue = "nil"; 495 else if (getLangOpts().CPlusPlus11) 496 NullValue = "nullptr"; 497 else if (PP.isMacroDefined("NULL")) 498 NullValue = "NULL"; 499 else 500 NullValue = "(void*) 0"; 501 502 if (MissingNilLoc.isInvalid()) 503 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind); 504 else 505 Diag(MissingNilLoc, diag::warn_missing_sentinel) 506 << int(CalleeKind) 507 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 508 Diag(D->getLocation(), diag::note_sentinel_here) 509 << int(CalleeKind) << Attr->getRange(); 510} 511 512SourceRange Sema::getExprRange(Expr *E) const { 513 return E ? E->getSourceRange() : SourceRange(); 514} 515 516//===----------------------------------------------------------------------===// 517// Standard Promotions and Conversions 518//===----------------------------------------------------------------------===// 519 520/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 521ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 522 // Handle any placeholder expressions which made it here. 523 if (E->hasPlaceholderType()) { 524 ExprResult result = CheckPlaceholderExpr(E); 525 if (result.isInvalid()) return ExprError(); 526 E = result.get(); 527 } 528 529 QualType Ty = E->getType(); 530 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 531 532 if (Ty->isFunctionType()) { 533 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 534 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 535 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 536 return ExprError(); 537 538 E = ImpCastExprToType(E, Context.getPointerType(Ty), 539 CK_FunctionToPointerDecay).get(); 540 } else if (Ty->isArrayType()) { 541 // In C90 mode, arrays only promote to pointers if the array expression is 542 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 543 // type 'array of type' is converted to an expression that has type 'pointer 544 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 545 // that has type 'array of type' ...". The relevant change is "an lvalue" 546 // (C90) to "an expression" (C99). 547 // 548 // C++ 4.2p1: 549 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 550 // T" can be converted to an rvalue of type "pointer to T". 551 // 552 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 553 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 554 CK_ArrayToPointerDecay); 555 if (Res.isInvalid()) 556 return ExprError(); 557 E = Res.get(); 558 } 559 } 560 return E; 561} 562 563static void CheckForNullPointerDereference(Sema &S, Expr *E) { 564 // Check to see if we are dereferencing a null pointer. If so, 565 // and if not volatile-qualified, this is undefined behavior that the 566 // optimizer will delete, so warn about it. People sometimes try to use this 567 // to get a deterministic trap and are surprised by clang's behavior. This 568 // only handles the pattern "*null", which is a very syntactic check. 569 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 570 if (UO && UO->getOpcode() == UO_Deref && 571 UO->getSubExpr()->getType()->isPointerType()) { 572 const LangAS AS = 573 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 574 if ((!isTargetAddressSpace(AS) || 575 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 576 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 577 S.Context, Expr::NPC_ValueDependentIsNotNull) && 578 !UO->getType().isVolatileQualified()) { 579 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 580 S.PDiag(diag::warn_indirection_through_null) 581 << UO->getSubExpr()->getSourceRange()); 582 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 583 S.PDiag(diag::note_indirection_through_null)); 584 } 585 } 586} 587 588static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 589 SourceLocation AssignLoc, 590 const Expr* RHS) { 591 const ObjCIvarDecl *IV = OIRE->getDecl(); 592 if (!IV) 593 return; 594 595 DeclarationName MemberName = IV->getDeclName(); 596 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 597 if (!Member || !Member->isStr("isa")) 598 return; 599 600 const Expr *Base = OIRE->getBase(); 601 QualType BaseType = Base->getType(); 602 if (OIRE->isArrow()) 603 BaseType = BaseType->getPointeeType(); 604 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 605 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 606 ObjCInterfaceDecl *ClassDeclared = nullptr; 607 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 608 if (!ClassDeclared->getSuperClass() 609 && (*ClassDeclared->ivar_begin()) == IV) { 610 if (RHS) { 611 NamedDecl *ObjectSetClass = 612 S.LookupSingleName(S.TUScope, 613 &S.Context.Idents.get("object_setClass"), 614 SourceLocation(), S.LookupOrdinaryName); 615 if (ObjectSetClass) { 616 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 617 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 618 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 619 "object_setClass(") 620 << FixItHint::CreateReplacement( 621 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 622 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 623 } 624 else 625 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 626 } else { 627 NamedDecl *ObjectGetClass = 628 S.LookupSingleName(S.TUScope, 629 &S.Context.Idents.get("object_getClass"), 630 SourceLocation(), S.LookupOrdinaryName); 631 if (ObjectGetClass) 632 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 633 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 634 "object_getClass(") 635 << FixItHint::CreateReplacement( 636 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 637 else 638 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 639 } 640 S.Diag(IV->getLocation(), diag::note_ivar_decl); 641 } 642 } 643} 644 645ExprResult Sema::DefaultLvalueConversion(Expr *E) { 646 // Handle any placeholder expressions which made it here. 647 if (E->hasPlaceholderType()) { 648 ExprResult result = CheckPlaceholderExpr(E); 649 if (result.isInvalid()) return ExprError(); 650 E = result.get(); 651 } 652 653 // C++ [conv.lval]p1: 654 // A glvalue of a non-function, non-array type T can be 655 // converted to a prvalue. 656 if (!E->isGLValue()) return E; 657 658 QualType T = E->getType(); 659 assert(!T.isNull() && "r-value conversion on typeless expression?"); 660 661 // lvalue-to-rvalue conversion cannot be applied to function or array types. 662 if (T->isFunctionType() || T->isArrayType()) 663 return E; 664 665 // We don't want to throw lvalue-to-rvalue casts on top of 666 // expressions of certain types in C++. 667 if (getLangOpts().CPlusPlus && 668 (E->getType() == Context.OverloadTy || 669 T->isDependentType() || 670 T->isRecordType())) 671 return E; 672 673 // The C standard is actually really unclear on this point, and 674 // DR106 tells us what the result should be but not why. It's 675 // generally best to say that void types just doesn't undergo 676 // lvalue-to-rvalue at all. Note that expressions of unqualified 677 // 'void' type are never l-values, but qualified void can be. 678 if (T->isVoidType()) 679 return E; 680 681 // OpenCL usually rejects direct accesses to values of 'half' type. 682 if (getLangOpts().OpenCL && 683 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 684 T->isHalfType()) { 685 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 686 << 0 << T; 687 return ExprError(); 688 } 689 690 CheckForNullPointerDereference(*this, E); 691 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 692 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 693 &Context.Idents.get("object_getClass"), 694 SourceLocation(), LookupOrdinaryName); 695 if (ObjectGetClass) 696 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 697 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 698 << FixItHint::CreateReplacement( 699 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 700 else 701 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 702 } 703 else if (const ObjCIvarRefExpr *OIRE = 704 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 705 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 706 707 // C++ [conv.lval]p1: 708 // [...] If T is a non-class type, the type of the prvalue is the 709 // cv-unqualified version of T. Otherwise, the type of the 710 // rvalue is T. 711 // 712 // C99 6.3.2.1p2: 713 // If the lvalue has qualified type, the value has the unqualified 714 // version of the type of the lvalue; otherwise, the value has the 715 // type of the lvalue. 716 if (T.hasQualifiers()) 717 T = T.getUnqualifiedType(); 718 719 // Under the MS ABI, lock down the inheritance model now. 720 if (T->isMemberPointerType() && 721 Context.getTargetInfo().getCXXABI().isMicrosoft()) 722 (void)isCompleteType(E->getExprLoc(), T); 723 724 ExprResult Res = CheckLValueToRValueConversionOperand(E); 725 if (Res.isInvalid()) 726 return Res; 727 E = Res.get(); 728 729 // Loading a __weak object implicitly retains the value, so we need a cleanup to 730 // balance that. 731 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 732 Cleanup.setExprNeedsCleanups(true); 733 734 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 735 Cleanup.setExprNeedsCleanups(true); 736 737 // C++ [conv.lval]p3: 738 // If T is cv std::nullptr_t, the result is a null pointer constant. 739 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 740 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 741 CurFPFeatureOverrides()); 742 743 // C11 6.3.2.1p2: 744 // ... if the lvalue has atomic type, the value has the non-atomic version 745 // of the type of the lvalue ... 746 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 747 T = Atomic->getValueType().getUnqualifiedType(); 748 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 749 nullptr, VK_PRValue, FPOptionsOverride()); 750 } 751 752 return Res; 753} 754 755ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 756 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 757 if (Res.isInvalid()) 758 return ExprError(); 759 Res = DefaultLvalueConversion(Res.get()); 760 if (Res.isInvalid()) 761 return ExprError(); 762 return Res; 763} 764 765/// CallExprUnaryConversions - a special case of an unary conversion 766/// performed on a function designator of a call expression. 767ExprResult Sema::CallExprUnaryConversions(Expr *E) { 768 QualType Ty = E->getType(); 769 ExprResult Res = E; 770 // Only do implicit cast for a function type, but not for a pointer 771 // to function type. 772 if (Ty->isFunctionType()) { 773 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 774 CK_FunctionToPointerDecay); 775 if (Res.isInvalid()) 776 return ExprError(); 777 } 778 Res = DefaultLvalueConversion(Res.get()); 779 if (Res.isInvalid()) 780 return ExprError(); 781 return Res.get(); 782} 783 784/// UsualUnaryConversions - Performs various conversions that are common to most 785/// operators (C99 6.3). The conversions of array and function types are 786/// sometimes suppressed. For example, the array->pointer conversion doesn't 787/// apply if the array is an argument to the sizeof or address (&) operators. 788/// In these instances, this routine should *not* be called. 789ExprResult Sema::UsualUnaryConversions(Expr *E) { 790 // First, convert to an r-value. 791 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 792 if (Res.isInvalid()) 793 return ExprError(); 794 E = Res.get(); 795 796 QualType Ty = E->getType(); 797 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 798 799 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); 800 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() && 801 (getLangOpts().getFPEvalMethod() != 802 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine || 803 PP.getLastFPEvalPragmaLocation().isValid())) { 804 switch (EvalMethod) { 805 default: 806 llvm_unreachable("Unrecognized float evaluation method"); 807 break; 808 case LangOptions::FEM_UnsetOnCommandLine: 809 llvm_unreachable("Float evaluation method should be set by now"); 810 break; 811 case LangOptions::FEM_Double: 812 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0) 813 // Widen the expression to double. 814 return Ty->isComplexType() 815 ? ImpCastExprToType(E, 816 Context.getComplexType(Context.DoubleTy), 817 CK_FloatingComplexCast) 818 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast); 819 break; 820 case LangOptions::FEM_Extended: 821 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0) 822 // Widen the expression to long double. 823 return Ty->isComplexType() 824 ? ImpCastExprToType( 825 E, Context.getComplexType(Context.LongDoubleTy), 826 CK_FloatingComplexCast) 827 : ImpCastExprToType(E, Context.LongDoubleTy, 828 CK_FloatingCast); 829 break; 830 } 831 } 832 833 // Half FP have to be promoted to float unless it is natively supported 834 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 835 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 836 837 // Try to perform integral promotions if the object has a theoretically 838 // promotable type. 839 if (Ty->isIntegralOrUnscopedEnumerationType()) { 840 // C99 6.3.1.1p2: 841 // 842 // The following may be used in an expression wherever an int or 843 // unsigned int may be used: 844 // - an object or expression with an integer type whose integer 845 // conversion rank is less than or equal to the rank of int 846 // and unsigned int. 847 // - A bit-field of type _Bool, int, signed int, or unsigned int. 848 // 849 // If an int can represent all values of the original type, the 850 // value is converted to an int; otherwise, it is converted to an 851 // unsigned int. These are called the integer promotions. All 852 // other types are unchanged by the integer promotions. 853 854 QualType PTy = Context.isPromotableBitField(E); 855 if (!PTy.isNull()) { 856 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 857 return E; 858 } 859 if (Context.isPromotableIntegerType(Ty)) { 860 QualType PT = Context.getPromotedIntegerType(Ty); 861 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 862 return E; 863 } 864 } 865 return E; 866} 867 868/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 869/// do not have a prototype. Arguments that have type float or __fp16 870/// are promoted to double. All other argument types are converted by 871/// UsualUnaryConversions(). 872ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 873 QualType Ty = E->getType(); 874 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 875 876 ExprResult Res = UsualUnaryConversions(E); 877 if (Res.isInvalid()) 878 return ExprError(); 879 E = Res.get(); 880 881 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 882 // promote to double. 883 // Note that default argument promotion applies only to float (and 884 // half/fp16); it does not apply to _Float16. 885 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 886 if (BTy && (BTy->getKind() == BuiltinType::Half || 887 BTy->getKind() == BuiltinType::Float)) { 888 if (getLangOpts().OpenCL && 889 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 890 if (BTy->getKind() == BuiltinType::Half) { 891 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 892 } 893 } else { 894 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 895 } 896 } 897 if (BTy && 898 getLangOpts().getExtendIntArgs() == 899 LangOptions::ExtendArgsKind::ExtendTo64 && 900 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 901 Context.getTypeSizeInChars(BTy) < 902 Context.getTypeSizeInChars(Context.LongLongTy)) { 903 E = (Ty->isUnsignedIntegerType()) 904 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 905 .get() 906 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 907 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 908 "Unexpected typesize for LongLongTy"); 909 } 910 911 // C++ performs lvalue-to-rvalue conversion as a default argument 912 // promotion, even on class types, but note: 913 // C++11 [conv.lval]p2: 914 // When an lvalue-to-rvalue conversion occurs in an unevaluated 915 // operand or a subexpression thereof the value contained in the 916 // referenced object is not accessed. Otherwise, if the glvalue 917 // has a class type, the conversion copy-initializes a temporary 918 // of type T from the glvalue and the result of the conversion 919 // is a prvalue for the temporary. 920 // FIXME: add some way to gate this entire thing for correctness in 921 // potentially potentially evaluated contexts. 922 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 923 ExprResult Temp = PerformCopyInitialization( 924 InitializedEntity::InitializeTemporary(E->getType()), 925 E->getExprLoc(), E); 926 if (Temp.isInvalid()) 927 return ExprError(); 928 E = Temp.get(); 929 } 930 931 return E; 932} 933 934/// Determine the degree of POD-ness for an expression. 935/// Incomplete types are considered POD, since this check can be performed 936/// when we're in an unevaluated context. 937Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 938 if (Ty->isIncompleteType()) { 939 // C++11 [expr.call]p7: 940 // After these conversions, if the argument does not have arithmetic, 941 // enumeration, pointer, pointer to member, or class type, the program 942 // is ill-formed. 943 // 944 // Since we've already performed array-to-pointer and function-to-pointer 945 // decay, the only such type in C++ is cv void. This also handles 946 // initializer lists as variadic arguments. 947 if (Ty->isVoidType()) 948 return VAK_Invalid; 949 950 if (Ty->isObjCObjectType()) 951 return VAK_Invalid; 952 return VAK_Valid; 953 } 954 955 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 956 return VAK_Invalid; 957 958 if (Context.getTargetInfo().getTriple().isWasm() && 959 Ty.isWebAssemblyReferenceType()) { 960 return VAK_Invalid; 961 } 962 963 if (Ty.isCXX98PODType(Context)) 964 return VAK_Valid; 965 966 // C++11 [expr.call]p7: 967 // Passing a potentially-evaluated argument of class type (Clause 9) 968 // having a non-trivial copy constructor, a non-trivial move constructor, 969 // or a non-trivial destructor, with no corresponding parameter, 970 // is conditionally-supported with implementation-defined semantics. 971 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 972 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 973 if (!Record->hasNonTrivialCopyConstructor() && 974 !Record->hasNonTrivialMoveConstructor() && 975 !Record->hasNonTrivialDestructor()) 976 return VAK_ValidInCXX11; 977 978 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 979 return VAK_Valid; 980 981 if (Ty->isObjCObjectType()) 982 return VAK_Invalid; 983 984 if (getLangOpts().MSVCCompat) 985 return VAK_MSVCUndefined; 986 987 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 988 // permitted to reject them. We should consider doing so. 989 return VAK_Undefined; 990} 991 992void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 993 // Don't allow one to pass an Objective-C interface to a vararg. 994 const QualType &Ty = E->getType(); 995 VarArgKind VAK = isValidVarArgType(Ty); 996 997 // Complain about passing non-POD types through varargs. 998 switch (VAK) { 999 case VAK_ValidInCXX11: 1000 DiagRuntimeBehavior( 1001 E->getBeginLoc(), nullptr, 1002 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 1003 [[fallthrough]]; 1004 case VAK_Valid: 1005 if (Ty->isRecordType()) { 1006 // This is unlikely to be what the user intended. If the class has a 1007 // 'c_str' member function, the user probably meant to call that. 1008 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 1009 PDiag(diag::warn_pass_class_arg_to_vararg) 1010 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 1011 } 1012 break; 1013 1014 case VAK_Undefined: 1015 case VAK_MSVCUndefined: 1016 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 1017 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 1018 << getLangOpts().CPlusPlus11 << Ty << CT); 1019 break; 1020 1021 case VAK_Invalid: 1022 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 1023 Diag(E->getBeginLoc(), 1024 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 1025 << Ty << CT; 1026 else if (Ty->isObjCObjectType()) 1027 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 1028 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 1029 << Ty << CT); 1030 else 1031 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 1032 << isa<InitListExpr>(E) << Ty << CT; 1033 break; 1034 } 1035} 1036 1037/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 1038/// will create a trap if the resulting type is not a POD type. 1039ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 1040 FunctionDecl *FDecl) { 1041 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 1042 // Strip the unbridged-cast placeholder expression off, if applicable. 1043 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 1044 (CT == VariadicMethod || 1045 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 1046 E = stripARCUnbridgedCast(E); 1047 1048 // Otherwise, do normal placeholder checking. 1049 } else { 1050 ExprResult ExprRes = CheckPlaceholderExpr(E); 1051 if (ExprRes.isInvalid()) 1052 return ExprError(); 1053 E = ExprRes.get(); 1054 } 1055 } 1056 1057 ExprResult ExprRes = DefaultArgumentPromotion(E); 1058 if (ExprRes.isInvalid()) 1059 return ExprError(); 1060 1061 // Copy blocks to the heap. 1062 if (ExprRes.get()->getType()->isBlockPointerType()) 1063 maybeExtendBlockObject(ExprRes); 1064 1065 E = ExprRes.get(); 1066 1067 // Diagnostics regarding non-POD argument types are 1068 // emitted along with format string checking in Sema::CheckFunctionCall(). 1069 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1070 // Turn this into a trap. 1071 CXXScopeSpec SS; 1072 SourceLocation TemplateKWLoc; 1073 UnqualifiedId Name; 1074 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1075 E->getBeginLoc()); 1076 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1077 /*HasTrailingLParen=*/true, 1078 /*IsAddressOfOperand=*/false); 1079 if (TrapFn.isInvalid()) 1080 return ExprError(); 1081 1082 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1083 std::nullopt, E->getEndLoc()); 1084 if (Call.isInvalid()) 1085 return ExprError(); 1086 1087 ExprResult Comma = 1088 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1089 if (Comma.isInvalid()) 1090 return ExprError(); 1091 return Comma.get(); 1092 } 1093 1094 if (!getLangOpts().CPlusPlus && 1095 RequireCompleteType(E->getExprLoc(), E->getType(), 1096 diag::err_call_incomplete_argument)) 1097 return ExprError(); 1098 1099 return E; 1100} 1101 1102/// Converts an integer to complex float type. Helper function of 1103/// UsualArithmeticConversions() 1104/// 1105/// \return false if the integer expression is an integer type and is 1106/// successfully converted to the complex type. 1107static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1108 ExprResult &ComplexExpr, 1109 QualType IntTy, 1110 QualType ComplexTy, 1111 bool SkipCast) { 1112 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1113 if (SkipCast) return false; 1114 if (IntTy->isIntegerType()) { 1115 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType(); 1116 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1117 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1118 CK_FloatingRealToComplex); 1119 } else { 1120 assert(IntTy->isComplexIntegerType()); 1121 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1122 CK_IntegralComplexToFloatingComplex); 1123 } 1124 return false; 1125} 1126 1127// This handles complex/complex, complex/float, or float/complex. 1128// When both operands are complex, the shorter operand is converted to the 1129// type of the longer, and that is the type of the result. This corresponds 1130// to what is done when combining two real floating-point operands. 1131// The fun begins when size promotion occur across type domains. 1132// From H&S 6.3.4: When one operand is complex and the other is a real 1133// floating-point type, the less precise type is converted, within it's 1134// real or complex domain, to the precision of the other type. For example, 1135// when combining a "long double" with a "double _Complex", the 1136// "double _Complex" is promoted to "long double _Complex". 1137static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, 1138 QualType ShorterType, 1139 QualType LongerType, 1140 bool PromotePrecision) { 1141 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType()); 1142 QualType Result = 1143 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType); 1144 1145 if (PromotePrecision) { 1146 if (isa<ComplexType>(ShorterType.getCanonicalType())) { 1147 Shorter = 1148 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast); 1149 } else { 1150 if (LongerIsComplex) 1151 LongerType = LongerType->castAs<ComplexType>()->getElementType(); 1152 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast); 1153 } 1154 } 1155 return Result; 1156} 1157 1158/// Handle arithmetic conversion with complex types. Helper function of 1159/// UsualArithmeticConversions() 1160static QualType handleComplexConversion(Sema &S, ExprResult &LHS, 1161 ExprResult &RHS, QualType LHSType, 1162 QualType RHSType, bool IsCompAssign) { 1163 // if we have an integer operand, the result is the complex type. 1164 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1165 /*SkipCast=*/false)) 1166 return LHSType; 1167 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1168 /*SkipCast=*/IsCompAssign)) 1169 return RHSType; 1170 1171 // Compute the rank of the two types, regardless of whether they are complex. 1172 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1173 if (Order < 0) 1174 // Promote the precision of the LHS if not an assignment. 1175 return handleComplexFloatConversion(S, LHS, LHSType, RHSType, 1176 /*PromotePrecision=*/!IsCompAssign); 1177 // Promote the precision of the RHS unless it is already the same as the LHS. 1178 return handleComplexFloatConversion(S, RHS, RHSType, LHSType, 1179 /*PromotePrecision=*/Order > 0); 1180} 1181 1182/// Handle arithmetic conversion from integer to float. Helper function 1183/// of UsualArithmeticConversions() 1184static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1185 ExprResult &IntExpr, 1186 QualType FloatTy, QualType IntTy, 1187 bool ConvertFloat, bool ConvertInt) { 1188 if (IntTy->isIntegerType()) { 1189 if (ConvertInt) 1190 // Convert intExpr to the lhs floating point type. 1191 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1192 CK_IntegralToFloating); 1193 return FloatTy; 1194 } 1195 1196 // Convert both sides to the appropriate complex float. 1197 assert(IntTy->isComplexIntegerType()); 1198 QualType result = S.Context.getComplexType(FloatTy); 1199 1200 // _Complex int -> _Complex float 1201 if (ConvertInt) 1202 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1203 CK_IntegralComplexToFloatingComplex); 1204 1205 // float -> _Complex float 1206 if (ConvertFloat) 1207 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1208 CK_FloatingRealToComplex); 1209 1210 return result; 1211} 1212 1213/// Handle arithmethic conversion with floating point types. Helper 1214/// function of UsualArithmeticConversions() 1215static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1216 ExprResult &RHS, QualType LHSType, 1217 QualType RHSType, bool IsCompAssign) { 1218 bool LHSFloat = LHSType->isRealFloatingType(); 1219 bool RHSFloat = RHSType->isRealFloatingType(); 1220 1221 // N1169 4.1.4: If one of the operands has a floating type and the other 1222 // operand has a fixed-point type, the fixed-point operand 1223 // is converted to the floating type [...] 1224 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1225 if (LHSFloat) 1226 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1227 else if (!IsCompAssign) 1228 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1229 return LHSFloat ? LHSType : RHSType; 1230 } 1231 1232 // If we have two real floating types, convert the smaller operand 1233 // to the bigger result. 1234 if (LHSFloat && RHSFloat) { 1235 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1236 if (order > 0) { 1237 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1238 return LHSType; 1239 } 1240 1241 assert(order < 0 && "illegal float comparison"); 1242 if (!IsCompAssign) 1243 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1244 return RHSType; 1245 } 1246 1247 if (LHSFloat) { 1248 // Half FP has to be promoted to float unless it is natively supported 1249 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1250 LHSType = S.Context.FloatTy; 1251 1252 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1253 /*ConvertFloat=*/!IsCompAssign, 1254 /*ConvertInt=*/ true); 1255 } 1256 assert(RHSFloat); 1257 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1258 /*ConvertFloat=*/ true, 1259 /*ConvertInt=*/!IsCompAssign); 1260} 1261 1262/// Diagnose attempts to convert between __float128, __ibm128 and 1263/// long double if there is no support for such conversion. 1264/// Helper function of UsualArithmeticConversions(). 1265static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1266 QualType RHSType) { 1267 // No issue if either is not a floating point type. 1268 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1269 return false; 1270 1271 // No issue if both have the same 128-bit float semantics. 1272 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1273 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1274 1275 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1276 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1277 1278 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1279 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1280 1281 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1282 &RHSSem != &llvm::APFloat::IEEEquad()) && 1283 (&LHSSem != &llvm::APFloat::IEEEquad() || 1284 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1285 return false; 1286 1287 return true; 1288} 1289 1290typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1291 1292namespace { 1293/// These helper callbacks are placed in an anonymous namespace to 1294/// permit their use as function template parameters. 1295ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1296 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1297} 1298 1299ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1300 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1301 CK_IntegralComplexCast); 1302} 1303} 1304 1305/// Handle integer arithmetic conversions. Helper function of 1306/// UsualArithmeticConversions() 1307template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1308static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1309 ExprResult &RHS, QualType LHSType, 1310 QualType RHSType, bool IsCompAssign) { 1311 // The rules for this case are in C99 6.3.1.8 1312 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1313 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1314 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1315 if (LHSSigned == RHSSigned) { 1316 // Same signedness; use the higher-ranked type 1317 if (order >= 0) { 1318 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1319 return LHSType; 1320 } else if (!IsCompAssign) 1321 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1322 return RHSType; 1323 } else if (order != (LHSSigned ? 1 : -1)) { 1324 // The unsigned type has greater than or equal rank to the 1325 // signed type, so use the unsigned type 1326 if (RHSSigned) { 1327 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1328 return LHSType; 1329 } else if (!IsCompAssign) 1330 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1331 return RHSType; 1332 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1333 // The two types are different widths; if we are here, that 1334 // means the signed type is larger than the unsigned type, so 1335 // use the signed type. 1336 if (LHSSigned) { 1337 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1338 return LHSType; 1339 } else if (!IsCompAssign) 1340 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1341 return RHSType; 1342 } else { 1343 // The signed type is higher-ranked than the unsigned type, 1344 // but isn't actually any bigger (like unsigned int and long 1345 // on most 32-bit systems). Use the unsigned type corresponding 1346 // to the signed type. 1347 QualType result = 1348 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1349 RHS = (*doRHSCast)(S, RHS.get(), result); 1350 if (!IsCompAssign) 1351 LHS = (*doLHSCast)(S, LHS.get(), result); 1352 return result; 1353 } 1354} 1355 1356/// Handle conversions with GCC complex int extension. Helper function 1357/// of UsualArithmeticConversions() 1358static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1359 ExprResult &RHS, QualType LHSType, 1360 QualType RHSType, 1361 bool IsCompAssign) { 1362 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1363 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1364 1365 if (LHSComplexInt && RHSComplexInt) { 1366 QualType LHSEltType = LHSComplexInt->getElementType(); 1367 QualType RHSEltType = RHSComplexInt->getElementType(); 1368 QualType ScalarType = 1369 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1370 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1371 1372 return S.Context.getComplexType(ScalarType); 1373 } 1374 1375 if (LHSComplexInt) { 1376 QualType LHSEltType = LHSComplexInt->getElementType(); 1377 QualType ScalarType = 1378 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1379 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1380 QualType ComplexType = S.Context.getComplexType(ScalarType); 1381 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1382 CK_IntegralRealToComplex); 1383 1384 return ComplexType; 1385 } 1386 1387 assert(RHSComplexInt); 1388 1389 QualType RHSEltType = RHSComplexInt->getElementType(); 1390 QualType ScalarType = 1391 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1392 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1393 QualType ComplexType = S.Context.getComplexType(ScalarType); 1394 1395 if (!IsCompAssign) 1396 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1397 CK_IntegralRealToComplex); 1398 return ComplexType; 1399} 1400 1401/// Return the rank of a given fixed point or integer type. The value itself 1402/// doesn't matter, but the values must be increasing with proper increasing 1403/// rank as described in N1169 4.1.1. 1404static unsigned GetFixedPointRank(QualType Ty) { 1405 const auto *BTy = Ty->getAs<BuiltinType>(); 1406 assert(BTy && "Expected a builtin type."); 1407 1408 switch (BTy->getKind()) { 1409 case BuiltinType::ShortFract: 1410 case BuiltinType::UShortFract: 1411 case BuiltinType::SatShortFract: 1412 case BuiltinType::SatUShortFract: 1413 return 1; 1414 case BuiltinType::Fract: 1415 case BuiltinType::UFract: 1416 case BuiltinType::SatFract: 1417 case BuiltinType::SatUFract: 1418 return 2; 1419 case BuiltinType::LongFract: 1420 case BuiltinType::ULongFract: 1421 case BuiltinType::SatLongFract: 1422 case BuiltinType::SatULongFract: 1423 return 3; 1424 case BuiltinType::ShortAccum: 1425 case BuiltinType::UShortAccum: 1426 case BuiltinType::SatShortAccum: 1427 case BuiltinType::SatUShortAccum: 1428 return 4; 1429 case BuiltinType::Accum: 1430 case BuiltinType::UAccum: 1431 case BuiltinType::SatAccum: 1432 case BuiltinType::SatUAccum: 1433 return 5; 1434 case BuiltinType::LongAccum: 1435 case BuiltinType::ULongAccum: 1436 case BuiltinType::SatLongAccum: 1437 case BuiltinType::SatULongAccum: 1438 return 6; 1439 default: 1440 if (BTy->isInteger()) 1441 return 0; 1442 llvm_unreachable("Unexpected fixed point or integer type"); 1443 } 1444} 1445 1446/// handleFixedPointConversion - Fixed point operations between fixed 1447/// point types and integers or other fixed point types do not fall under 1448/// usual arithmetic conversion since these conversions could result in loss 1449/// of precsision (N1169 4.1.4). These operations should be calculated with 1450/// the full precision of their result type (N1169 4.1.6.2.1). 1451static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1452 QualType RHSTy) { 1453 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1454 "Expected at least one of the operands to be a fixed point type"); 1455 assert((LHSTy->isFixedPointOrIntegerType() || 1456 RHSTy->isFixedPointOrIntegerType()) && 1457 "Special fixed point arithmetic operation conversions are only " 1458 "applied to ints or other fixed point types"); 1459 1460 // If one operand has signed fixed-point type and the other operand has 1461 // unsigned fixed-point type, then the unsigned fixed-point operand is 1462 // converted to its corresponding signed fixed-point type and the resulting 1463 // type is the type of the converted operand. 1464 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1465 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1466 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1467 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1468 1469 // The result type is the type with the highest rank, whereby a fixed-point 1470 // conversion rank is always greater than an integer conversion rank; if the 1471 // type of either of the operands is a saturating fixedpoint type, the result 1472 // type shall be the saturating fixed-point type corresponding to the type 1473 // with the highest rank; the resulting value is converted (taking into 1474 // account rounding and overflow) to the precision of the resulting type. 1475 // Same ranks between signed and unsigned types are resolved earlier, so both 1476 // types are either signed or both unsigned at this point. 1477 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1478 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1479 1480 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1481 1482 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1483 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1484 1485 return ResultTy; 1486} 1487 1488/// Check that the usual arithmetic conversions can be performed on this pair of 1489/// expressions that might be of enumeration type. 1490static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1491 SourceLocation Loc, 1492 Sema::ArithConvKind ACK) { 1493 // C++2a [expr.arith.conv]p1: 1494 // If one operand is of enumeration type and the other operand is of a 1495 // different enumeration type or a floating-point type, this behavior is 1496 // deprecated ([depr.arith.conv.enum]). 1497 // 1498 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1499 // Eventually we will presumably reject these cases (in C++23 onwards?). 1500 QualType L = LHS->getType(), R = RHS->getType(); 1501 bool LEnum = L->isUnscopedEnumerationType(), 1502 REnum = R->isUnscopedEnumerationType(); 1503 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1504 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1505 (REnum && L->isFloatingType())) { 1506 S.Diag(Loc, S.getLangOpts().CPlusPlus26 1507 ? diag::err_arith_conv_enum_float_cxx26 1508 : S.getLangOpts().CPlusPlus20 1509 ? diag::warn_arith_conv_enum_float_cxx20 1510 : diag::warn_arith_conv_enum_float) 1511 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum 1512 << L << R; 1513 } else if (!IsCompAssign && LEnum && REnum && 1514 !S.Context.hasSameUnqualifiedType(L, R)) { 1515 unsigned DiagID; 1516 // In C++ 26, usual arithmetic conversions between 2 different enum types 1517 // are ill-formed. 1518 if (S.getLangOpts().CPlusPlus26) 1519 DiagID = diag::err_conv_mixed_enum_types_cxx26; 1520 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1521 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1522 // If either enumeration type is unnamed, it's less likely that the 1523 // user cares about this, but this situation is still deprecated in 1524 // C++2a. Use a different warning group. 1525 DiagID = S.getLangOpts().CPlusPlus20 1526 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1527 : diag::warn_arith_conv_mixed_anon_enum_types; 1528 } else if (ACK == Sema::ACK_Conditional) { 1529 // Conditional expressions are separated out because they have 1530 // historically had a different warning flag. 1531 DiagID = S.getLangOpts().CPlusPlus20 1532 ? diag::warn_conditional_mixed_enum_types_cxx20 1533 : diag::warn_conditional_mixed_enum_types; 1534 } else if (ACK == Sema::ACK_Comparison) { 1535 // Comparison expressions are separated out because they have 1536 // historically had a different warning flag. 1537 DiagID = S.getLangOpts().CPlusPlus20 1538 ? diag::warn_comparison_mixed_enum_types_cxx20 1539 : diag::warn_comparison_mixed_enum_types; 1540 } else { 1541 DiagID = S.getLangOpts().CPlusPlus20 1542 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1543 : diag::warn_arith_conv_mixed_enum_types; 1544 } 1545 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1546 << (int)ACK << L << R; 1547 } 1548} 1549 1550/// UsualArithmeticConversions - Performs various conversions that are common to 1551/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1552/// routine returns the first non-arithmetic type found. The client is 1553/// responsible for emitting appropriate error diagnostics. 1554QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1555 SourceLocation Loc, 1556 ArithConvKind ACK) { 1557 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1558 1559 if (ACK != ACK_CompAssign) { 1560 LHS = UsualUnaryConversions(LHS.get()); 1561 if (LHS.isInvalid()) 1562 return QualType(); 1563 } 1564 1565 RHS = UsualUnaryConversions(RHS.get()); 1566 if (RHS.isInvalid()) 1567 return QualType(); 1568 1569 // For conversion purposes, we ignore any qualifiers. 1570 // For example, "const float" and "float" are equivalent. 1571 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 1572 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 1573 1574 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1575 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1576 LHSType = AtomicLHS->getValueType(); 1577 1578 // If both types are identical, no conversion is needed. 1579 if (Context.hasSameType(LHSType, RHSType)) 1580 return Context.getCommonSugaredType(LHSType, RHSType); 1581 1582 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1583 // The caller can deal with this (e.g. pointer + int). 1584 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1585 return QualType(); 1586 1587 // Apply unary and bitfield promotions to the LHS's type. 1588 QualType LHSUnpromotedType = LHSType; 1589 if (Context.isPromotableIntegerType(LHSType)) 1590 LHSType = Context.getPromotedIntegerType(LHSType); 1591 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1592 if (!LHSBitfieldPromoteTy.isNull()) 1593 LHSType = LHSBitfieldPromoteTy; 1594 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1595 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1596 1597 // If both types are identical, no conversion is needed. 1598 if (Context.hasSameType(LHSType, RHSType)) 1599 return Context.getCommonSugaredType(LHSType, RHSType); 1600 1601 // At this point, we have two different arithmetic types. 1602 1603 // Diagnose attempts to convert between __ibm128, __float128 and long double 1604 // where such conversions currently can't be handled. 1605 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1606 return QualType(); 1607 1608 // Handle complex types first (C99 6.3.1.8p1). 1609 if (LHSType->isComplexType() || RHSType->isComplexType()) 1610 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType, 1611 ACK == ACK_CompAssign); 1612 1613 // Now handle "real" floating types (i.e. float, double, long double). 1614 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1615 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1616 ACK == ACK_CompAssign); 1617 1618 // Handle GCC complex int extension. 1619 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1620 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1621 ACK == ACK_CompAssign); 1622 1623 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1624 return handleFixedPointConversion(*this, LHSType, RHSType); 1625 1626 // Finally, we have two differing integer types. 1627 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1628 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1629} 1630 1631//===----------------------------------------------------------------------===// 1632// Semantic Analysis for various Expression Types 1633//===----------------------------------------------------------------------===// 1634 1635 1636ExprResult Sema::ActOnGenericSelectionExpr( 1637 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, 1638 bool PredicateIsExpr, void *ControllingExprOrType, 1639 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) { 1640 unsigned NumAssocs = ArgTypes.size(); 1641 assert(NumAssocs == ArgExprs.size()); 1642 1643 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1644 for (unsigned i = 0; i < NumAssocs; ++i) { 1645 if (ArgTypes[i]) 1646 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1647 else 1648 Types[i] = nullptr; 1649 } 1650 1651 // If we have a controlling type, we need to convert it from a parsed type 1652 // into a semantic type and then pass that along. 1653 if (!PredicateIsExpr) { 1654 TypeSourceInfo *ControllingType; 1655 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType), 1656 &ControllingType); 1657 assert(ControllingType && "couldn't get the type out of the parser"); 1658 ControllingExprOrType = ControllingType; 1659 } 1660 1661 ExprResult ER = CreateGenericSelectionExpr( 1662 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType, 1663 llvm::ArrayRef(Types, NumAssocs), ArgExprs); 1664 delete [] Types; 1665 return ER; 1666} 1667 1668ExprResult Sema::CreateGenericSelectionExpr( 1669 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, 1670 bool PredicateIsExpr, void *ControllingExprOrType, 1671 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) { 1672 unsigned NumAssocs = Types.size(); 1673 assert(NumAssocs == Exprs.size()); 1674 assert(ControllingExprOrType && 1675 "Must have either a controlling expression or a controlling type"); 1676 1677 Expr *ControllingExpr = nullptr; 1678 TypeSourceInfo *ControllingType = nullptr; 1679 if (PredicateIsExpr) { 1680 // Decay and strip qualifiers for the controlling expression type, and 1681 // handle placeholder type replacement. See committee discussion from WG14 1682 // DR423. 1683 EnterExpressionEvaluationContext Unevaluated( 1684 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1685 ExprResult R = DefaultFunctionArrayLvalueConversion( 1686 reinterpret_cast<Expr *>(ControllingExprOrType)); 1687 if (R.isInvalid()) 1688 return ExprError(); 1689 ControllingExpr = R.get(); 1690 } else { 1691 // The extension form uses the type directly rather than converting it. 1692 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType); 1693 if (!ControllingType) 1694 return ExprError(); 1695 } 1696 1697 bool TypeErrorFound = false, 1698 IsResultDependent = ControllingExpr 1699 ? ControllingExpr->isTypeDependent() 1700 : ControllingType->getType()->isDependentType(), 1701 ContainsUnexpandedParameterPack = 1702 ControllingExpr 1703 ? ControllingExpr->containsUnexpandedParameterPack() 1704 : ControllingType->getType()->containsUnexpandedParameterPack(); 1705 1706 // The controlling expression is an unevaluated operand, so side effects are 1707 // likely unintended. 1708 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr && 1709 ControllingExpr->HasSideEffects(Context, false)) 1710 Diag(ControllingExpr->getExprLoc(), 1711 diag::warn_side_effects_unevaluated_context); 1712 1713 for (unsigned i = 0; i < NumAssocs; ++i) { 1714 if (Exprs[i]->containsUnexpandedParameterPack()) 1715 ContainsUnexpandedParameterPack = true; 1716 1717 if (Types[i]) { 1718 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1719 ContainsUnexpandedParameterPack = true; 1720 1721 if (Types[i]->getType()->isDependentType()) { 1722 IsResultDependent = true; 1723 } else { 1724 // We relax the restriction on use of incomplete types and non-object 1725 // types with the type-based extension of _Generic. Allowing incomplete 1726 // objects means those can be used as "tags" for a type-safe way to map 1727 // to a value. Similarly, matching on function types rather than 1728 // function pointer types can be useful. However, the restriction on VM 1729 // types makes sense to retain as there are open questions about how 1730 // the selection can be made at compile time. 1731 // 1732 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1733 // complete object type other than a variably modified type." 1734 unsigned D = 0; 1735 if (ControllingExpr && Types[i]->getType()->isIncompleteType()) 1736 D = diag::err_assoc_type_incomplete; 1737 else if (ControllingExpr && !Types[i]->getType()->isObjectType()) 1738 D = diag::err_assoc_type_nonobject; 1739 else if (Types[i]->getType()->isVariablyModifiedType()) 1740 D = diag::err_assoc_type_variably_modified; 1741 else if (ControllingExpr) { 1742 // Because the controlling expression undergoes lvalue conversion, 1743 // array conversion, and function conversion, an association which is 1744 // of array type, function type, or is qualified can never be 1745 // reached. We will warn about this so users are less surprised by 1746 // the unreachable association. However, we don't have to handle 1747 // function types; that's not an object type, so it's handled above. 1748 // 1749 // The logic is somewhat different for C++ because C++ has different 1750 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says, 1751 // If T is a non-class type, the type of the prvalue is the cv- 1752 // unqualified version of T. Otherwise, the type of the prvalue is T. 1753 // The result of these rules is that all qualified types in an 1754 // association in C are unreachable, and in C++, only qualified non- 1755 // class types are unreachable. 1756 // 1757 // NB: this does not apply when the first operand is a type rather 1758 // than an expression, because the type form does not undergo 1759 // conversion. 1760 unsigned Reason = 0; 1761 QualType QT = Types[i]->getType(); 1762 if (QT->isArrayType()) 1763 Reason = 1; 1764 else if (QT.hasQualifiers() && 1765 (!LangOpts.CPlusPlus || !QT->isRecordType())) 1766 Reason = 2; 1767 1768 if (Reason) 1769 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1770 diag::warn_unreachable_association) 1771 << QT << (Reason - 1); 1772 } 1773 1774 if (D != 0) { 1775 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1776 << Types[i]->getTypeLoc().getSourceRange() 1777 << Types[i]->getType(); 1778 TypeErrorFound = true; 1779 } 1780 1781 // C11 6.5.1.1p2 "No two generic associations in the same generic 1782 // selection shall specify compatible types." 1783 for (unsigned j = i+1; j < NumAssocs; ++j) 1784 if (Types[j] && !Types[j]->getType()->isDependentType() && 1785 Context.typesAreCompatible(Types[i]->getType(), 1786 Types[j]->getType())) { 1787 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1788 diag::err_assoc_compatible_types) 1789 << Types[j]->getTypeLoc().getSourceRange() 1790 << Types[j]->getType() 1791 << Types[i]->getType(); 1792 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1793 diag::note_compat_assoc) 1794 << Types[i]->getTypeLoc().getSourceRange() 1795 << Types[i]->getType(); 1796 TypeErrorFound = true; 1797 } 1798 } 1799 } 1800 } 1801 if (TypeErrorFound) 1802 return ExprError(); 1803 1804 // If we determined that the generic selection is result-dependent, don't 1805 // try to compute the result expression. 1806 if (IsResultDependent) { 1807 if (ControllingExpr) 1808 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, 1809 Types, Exprs, DefaultLoc, RParenLoc, 1810 ContainsUnexpandedParameterPack); 1811 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types, 1812 Exprs, DefaultLoc, RParenLoc, 1813 ContainsUnexpandedParameterPack); 1814 } 1815 1816 SmallVector<unsigned, 1> CompatIndices; 1817 unsigned DefaultIndex = -1U; 1818 // Look at the canonical type of the controlling expression in case it was a 1819 // deduced type like __auto_type. However, when issuing diagnostics, use the 1820 // type the user wrote in source rather than the canonical one. 1821 for (unsigned i = 0; i < NumAssocs; ++i) { 1822 if (!Types[i]) 1823 DefaultIndex = i; 1824 else if (ControllingExpr && 1825 Context.typesAreCompatible( 1826 ControllingExpr->getType().getCanonicalType(), 1827 Types[i]->getType())) 1828 CompatIndices.push_back(i); 1829 else if (ControllingType && 1830 Context.typesAreCompatible( 1831 ControllingType->getType().getCanonicalType(), 1832 Types[i]->getType())) 1833 CompatIndices.push_back(i); 1834 } 1835 1836 auto GetControllingRangeAndType = [](Expr *ControllingExpr, 1837 TypeSourceInfo *ControllingType) { 1838 // We strip parens here because the controlling expression is typically 1839 // parenthesized in macro definitions. 1840 if (ControllingExpr) 1841 ControllingExpr = ControllingExpr->IgnoreParens(); 1842 1843 SourceRange SR = ControllingExpr 1844 ? ControllingExpr->getSourceRange() 1845 : ControllingType->getTypeLoc().getSourceRange(); 1846 QualType QT = ControllingExpr ? ControllingExpr->getType() 1847 : ControllingType->getType(); 1848 1849 return std::make_pair(SR, QT); 1850 }; 1851 1852 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1853 // type compatible with at most one of the types named in its generic 1854 // association list." 1855 if (CompatIndices.size() > 1) { 1856 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType); 1857 SourceRange SR = P.first; 1858 Diag(SR.getBegin(), diag::err_generic_sel_multi_match) 1859 << SR << P.second << (unsigned)CompatIndices.size(); 1860 for (unsigned I : CompatIndices) { 1861 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1862 diag::note_compat_assoc) 1863 << Types[I]->getTypeLoc().getSourceRange() 1864 << Types[I]->getType(); 1865 } 1866 return ExprError(); 1867 } 1868 1869 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1870 // its controlling expression shall have type compatible with exactly one of 1871 // the types named in its generic association list." 1872 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1873 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType); 1874 SourceRange SR = P.first; 1875 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second; 1876 return ExprError(); 1877 } 1878 1879 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1880 // type name that is compatible with the type of the controlling expression, 1881 // then the result expression of the generic selection is the expression 1882 // in that generic association. Otherwise, the result expression of the 1883 // generic selection is the expression in the default generic association." 1884 unsigned ResultIndex = 1885 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1886 1887 if (ControllingExpr) { 1888 return GenericSelectionExpr::Create( 1889 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1890 ContainsUnexpandedParameterPack, ResultIndex); 1891 } 1892 return GenericSelectionExpr::Create( 1893 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc, 1894 ContainsUnexpandedParameterPack, ResultIndex); 1895} 1896 1897static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) { 1898 switch (Kind) { 1899 default: 1900 llvm_unreachable("unexpected TokenKind"); 1901 case tok::kw___func__: 1902 return PredefinedIdentKind::Func; // [C99 6.4.2.2] 1903 case tok::kw___FUNCTION__: 1904 return PredefinedIdentKind::Function; 1905 case tok::kw___FUNCDNAME__: 1906 return PredefinedIdentKind::FuncDName; // [MS] 1907 case tok::kw___FUNCSIG__: 1908 return PredefinedIdentKind::FuncSig; // [MS] 1909 case tok::kw_L__FUNCTION__: 1910 return PredefinedIdentKind::LFunction; // [MS] 1911 case tok::kw_L__FUNCSIG__: 1912 return PredefinedIdentKind::LFuncSig; // [MS] 1913 case tok::kw___PRETTY_FUNCTION__: 1914 return PredefinedIdentKind::PrettyFunction; // [GNU] 1915 } 1916} 1917 1918/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used 1919/// to determine the value of a PredefinedExpr. This can be either a 1920/// block, lambda, captured statement, function, otherwise a nullptr. 1921static Decl *getPredefinedExprDecl(DeclContext *DC) { 1922 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC)) 1923 DC = DC->getParent(); 1924 return cast_or_null<Decl>(DC); 1925} 1926 1927/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1928/// location of the token and the offset of the ud-suffix within it. 1929static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1930 unsigned Offset) { 1931 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1932 S.getLangOpts()); 1933} 1934 1935/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1936/// the corresponding cooked (non-raw) literal operator, and build a call to it. 1937static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1938 IdentifierInfo *UDSuffix, 1939 SourceLocation UDSuffixLoc, 1940 ArrayRef<Expr*> Args, 1941 SourceLocation LitEndLoc) { 1942 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1943 1944 QualType ArgTy[2]; 1945 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1946 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1947 if (ArgTy[ArgIdx]->isArrayType()) 1948 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1949 } 1950 1951 DeclarationName OpName = 1952 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1953 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1954 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1955 1956 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1957 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()), 1958 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1959 /*AllowStringTemplatePack*/ false, 1960 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1961 return ExprError(); 1962 1963 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1964} 1965 1966ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) { 1967 // StringToks needs backing storage as it doesn't hold array elements itself 1968 std::vector<Token> ExpandedToks; 1969 if (getLangOpts().MicrosoftExt) 1970 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks); 1971 1972 StringLiteralParser Literal(StringToks, PP, 1973 StringLiteralEvalMethod::Unevaluated); 1974 if (Literal.hadError) 1975 return ExprError(); 1976 1977 SmallVector<SourceLocation, 4> StringTokLocs; 1978 for (const Token &Tok : StringToks) 1979 StringTokLocs.push_back(Tok.getLocation()); 1980 1981 StringLiteral *Lit = StringLiteral::Create( 1982 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {}, 1983 &StringTokLocs[0], StringTokLocs.size()); 1984 1985 if (!Literal.getUDSuffix().empty()) { 1986 SourceLocation UDSuffixLoc = 1987 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1988 Literal.getUDSuffixOffset()); 1989 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1990 } 1991 1992 return Lit; 1993} 1994 1995std::vector<Token> 1996Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) { 1997 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function 1998 // local macros that expand to string literals that may be concatenated. 1999 // These macros are expanded here (in Sema), because StringLiteralParser 2000 // (in Lex) doesn't know the enclosing function (because it hasn't been 2001 // parsed yet). 2002 assert(getLangOpts().MicrosoftExt); 2003 2004 // Note: Although function local macros are defined only inside functions, 2005 // we ensure a valid `CurrentDecl` even outside of a function. This allows 2006 // expansion of macros into empty string literals without additional checks. 2007 Decl *CurrentDecl = getPredefinedExprDecl(CurContext); 2008 if (!CurrentDecl) 2009 CurrentDecl = Context.getTranslationUnitDecl(); 2010 2011 std::vector<Token> ExpandedToks; 2012 ExpandedToks.reserve(Toks.size()); 2013 for (const Token &Tok : Toks) { 2014 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) { 2015 assert(tok::isStringLiteral(Tok.getKind())); 2016 ExpandedToks.emplace_back(Tok); 2017 continue; 2018 } 2019 if (isa<TranslationUnitDecl>(CurrentDecl)) 2020 Diag(Tok.getLocation(), diag::ext_predef_outside_function); 2021 // Stringify predefined expression 2022 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined) 2023 << Tok.getKind(); 2024 SmallString<64> Str; 2025 llvm::raw_svector_ostream OS(Str); 2026 Token &Exp = ExpandedToks.emplace_back(); 2027 Exp.startToken(); 2028 if (Tok.getKind() == tok::kw_L__FUNCTION__ || 2029 Tok.getKind() == tok::kw_L__FUNCSIG__) { 2030 OS << 'L'; 2031 Exp.setKind(tok::wide_string_literal); 2032 } else { 2033 Exp.setKind(tok::string_literal); 2034 } 2035 OS << '"' 2036 << Lexer::Stringify(PredefinedExpr::ComputeName( 2037 getPredefinedExprKind(Tok.getKind()), CurrentDecl)) 2038 << '"'; 2039 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc()); 2040 } 2041 return ExpandedToks; 2042} 2043 2044/// ActOnStringLiteral - The specified tokens were lexed as pasted string 2045/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 2046/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 2047/// multiple tokens. However, the common case is that StringToks points to one 2048/// string. 2049/// 2050ExprResult 2051Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 2052 assert(!StringToks.empty() && "Must have at least one string!"); 2053 2054 // StringToks needs backing storage as it doesn't hold array elements itself 2055 std::vector<Token> ExpandedToks; 2056 if (getLangOpts().MicrosoftExt) 2057 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks); 2058 2059 StringLiteralParser Literal(StringToks, PP); 2060 if (Literal.hadError) 2061 return ExprError(); 2062 2063 SmallVector<SourceLocation, 4> StringTokLocs; 2064 for (const Token &Tok : StringToks) 2065 StringTokLocs.push_back(Tok.getLocation()); 2066 2067 QualType CharTy = Context.CharTy; 2068 StringLiteralKind Kind = StringLiteralKind::Ordinary; 2069 if (Literal.isWide()) { 2070 CharTy = Context.getWideCharType(); 2071 Kind = StringLiteralKind::Wide; 2072 } else if (Literal.isUTF8()) { 2073 if (getLangOpts().Char8) 2074 CharTy = Context.Char8Ty; 2075 Kind = StringLiteralKind::UTF8; 2076 } else if (Literal.isUTF16()) { 2077 CharTy = Context.Char16Ty; 2078 Kind = StringLiteralKind::UTF16; 2079 } else if (Literal.isUTF32()) { 2080 CharTy = Context.Char32Ty; 2081 Kind = StringLiteralKind::UTF32; 2082 } else if (Literal.isPascal()) { 2083 CharTy = Context.UnsignedCharTy; 2084 } 2085 2086 // Warn on initializing an array of char from a u8 string literal; this 2087 // becomes ill-formed in C++2a. 2088 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 2089 !getLangOpts().Char8 && Kind == StringLiteralKind::UTF8) { 2090 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 2091 2092 // Create removals for all 'u8' prefixes in the string literal(s). This 2093 // ensures C++2a compatibility (but may change the program behavior when 2094 // built by non-Clang compilers for which the execution character set is 2095 // not always UTF-8). 2096 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 2097 SourceLocation RemovalDiagLoc; 2098 for (const Token &Tok : StringToks) { 2099 if (Tok.getKind() == tok::utf8_string_literal) { 2100 if (RemovalDiagLoc.isInvalid()) 2101 RemovalDiagLoc = Tok.getLocation(); 2102 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 2103 Tok.getLocation(), 2104 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 2105 getSourceManager(), getLangOpts()))); 2106 } 2107 } 2108 Diag(RemovalDiagLoc, RemovalDiag); 2109 } 2110 2111 QualType StrTy = 2112 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 2113 2114 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 2115 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 2116 Kind, Literal.Pascal, StrTy, 2117 &StringTokLocs[0], 2118 StringTokLocs.size()); 2119 if (Literal.getUDSuffix().empty()) 2120 return Lit; 2121 2122 // We're building a user-defined literal. 2123 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2124 SourceLocation UDSuffixLoc = 2125 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 2126 Literal.getUDSuffixOffset()); 2127 2128 // Make sure we're allowed user-defined literals here. 2129 if (!UDLScope) 2130 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 2131 2132 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 2133 // operator "" X (str, len) 2134 QualType SizeType = Context.getSizeType(); 2135 2136 DeclarationName OpName = 2137 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2138 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2139 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2140 2141 QualType ArgTy[] = { 2142 Context.getArrayDecayedType(StrTy), SizeType 2143 }; 2144 2145 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2146 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 2147 /*AllowRaw*/ false, /*AllowTemplate*/ true, 2148 /*AllowStringTemplatePack*/ true, 2149 /*DiagnoseMissing*/ true, Lit)) { 2150 2151 case LOLR_Cooked: { 2152 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 2153 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 2154 StringTokLocs[0]); 2155 Expr *Args[] = { Lit, LenArg }; 2156 2157 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 2158 } 2159 2160 case LOLR_Template: { 2161 TemplateArgumentListInfo ExplicitArgs; 2162 TemplateArgument Arg(Lit); 2163 TemplateArgumentLocInfo ArgInfo(Lit); 2164 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 2165 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, 2166 StringTokLocs.back(), &ExplicitArgs); 2167 } 2168 2169 case LOLR_StringTemplatePack: { 2170 TemplateArgumentListInfo ExplicitArgs; 2171 2172 unsigned CharBits = Context.getIntWidth(CharTy); 2173 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 2174 llvm::APSInt Value(CharBits, CharIsUnsigned); 2175 2176 TemplateArgument TypeArg(CharTy); 2177 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 2178 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 2179 2180 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 2181 Value = Lit->getCodeUnit(I); 2182 TemplateArgument Arg(Context, Value, CharTy); 2183 TemplateArgumentLocInfo ArgInfo; 2184 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 2185 } 2186 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, 2187 StringTokLocs.back(), &ExplicitArgs); 2188 } 2189 case LOLR_Raw: 2190 case LOLR_ErrorNoDiagnostic: 2191 llvm_unreachable("unexpected literal operator lookup result"); 2192 case LOLR_Error: 2193 return ExprError(); 2194 } 2195 llvm_unreachable("unexpected literal operator lookup result"); 2196} 2197 2198DeclRefExpr * 2199Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2200 SourceLocation Loc, 2201 const CXXScopeSpec *SS) { 2202 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 2203 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 2204} 2205 2206DeclRefExpr * 2207Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2208 const DeclarationNameInfo &NameInfo, 2209 const CXXScopeSpec *SS, NamedDecl *FoundD, 2210 SourceLocation TemplateKWLoc, 2211 const TemplateArgumentListInfo *TemplateArgs) { 2212 NestedNameSpecifierLoc NNS = 2213 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 2214 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 2215 TemplateArgs); 2216} 2217 2218// CUDA/HIP: Check whether a captured reference variable is referencing a 2219// host variable in a device or host device lambda. 2220static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 2221 VarDecl *VD) { 2222 if (!S.getLangOpts().CUDA || !VD->hasInit()) 2223 return false; 2224 assert(VD->getType()->isReferenceType()); 2225 2226 // Check whether the reference variable is referencing a host variable. 2227 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 2228 if (!DRE) 2229 return false; 2230 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 2231 if (!Referee || !Referee->hasGlobalStorage() || 2232 Referee->hasAttr<CUDADeviceAttr>()) 2233 return false; 2234 2235 // Check whether the current function is a device or host device lambda. 2236 // Check whether the reference variable is a capture by getDeclContext() 2237 // since refersToEnclosingVariableOrCapture() is not ready at this point. 2238 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 2239 if (MD && MD->getParent()->isLambda() && 2240 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 2241 VD->getDeclContext() != MD) 2242 return true; 2243 2244 return false; 2245} 2246 2247NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 2248 // A declaration named in an unevaluated operand never constitutes an odr-use. 2249 if (isUnevaluatedContext()) 2250 return NOUR_Unevaluated; 2251 2252 // C++2a [basic.def.odr]p4: 2253 // A variable x whose name appears as a potentially-evaluated expression e 2254 // is odr-used by e unless [...] x is a reference that is usable in 2255 // constant expressions. 2256 // CUDA/HIP: 2257 // If a reference variable referencing a host variable is captured in a 2258 // device or host device lambda, the value of the referee must be copied 2259 // to the capture and the reference variable must be treated as odr-use 2260 // since the value of the referee is not known at compile time and must 2261 // be loaded from the captured. 2262 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2263 if (VD->getType()->isReferenceType() && 2264 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2265 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2266 VD->isUsableInConstantExpressions(Context)) 2267 return NOUR_Constant; 2268 } 2269 2270 // All remaining non-variable cases constitute an odr-use. For variables, we 2271 // need to wait and see how the expression is used. 2272 return NOUR_None; 2273} 2274 2275/// BuildDeclRefExpr - Build an expression that references a 2276/// declaration that does not require a closure capture. 2277DeclRefExpr * 2278Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2279 const DeclarationNameInfo &NameInfo, 2280 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2281 SourceLocation TemplateKWLoc, 2282 const TemplateArgumentListInfo *TemplateArgs) { 2283 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) && 2284 NeedToCaptureVariable(D, NameInfo.getLoc()); 2285 2286 DeclRefExpr *E = DeclRefExpr::Create( 2287 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2288 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2289 MarkDeclRefReferenced(E); 2290 2291 // C++ [except.spec]p17: 2292 // An exception-specification is considered to be needed when: 2293 // - in an expression, the function is the unique lookup result or 2294 // the selected member of a set of overloaded functions. 2295 // 2296 // We delay doing this until after we've built the function reference and 2297 // marked it as used so that: 2298 // a) if the function is defaulted, we get errors from defining it before / 2299 // instead of errors from computing its exception specification, and 2300 // b) if the function is a defaulted comparison, we can use the body we 2301 // build when defining it as input to the exception specification 2302 // computation rather than computing a new body. 2303 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) { 2304 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2305 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2306 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2307 } 2308 } 2309 2310 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2311 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2312 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2313 getCurFunction()->recordUseOfWeak(E); 2314 2315 const auto *FD = dyn_cast<FieldDecl>(D); 2316 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) 2317 FD = IFD->getAnonField(); 2318 if (FD) { 2319 UnusedPrivateFields.remove(FD); 2320 // Just in case we're building an illegal pointer-to-member. 2321 if (FD->isBitField()) 2322 E->setObjectKind(OK_BitField); 2323 } 2324 2325 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2326 // designates a bit-field. 2327 if (const auto *BD = dyn_cast<BindingDecl>(D)) 2328 if (const auto *BE = BD->getBinding()) 2329 E->setObjectKind(BE->getObjectKind()); 2330 2331 return E; 2332} 2333 2334/// Decomposes the given name into a DeclarationNameInfo, its location, and 2335/// possibly a list of template arguments. 2336/// 2337/// If this produces template arguments, it is permitted to call 2338/// DecomposeTemplateName. 2339/// 2340/// This actually loses a lot of source location information for 2341/// non-standard name kinds; we should consider preserving that in 2342/// some way. 2343void 2344Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2345 TemplateArgumentListInfo &Buffer, 2346 DeclarationNameInfo &NameInfo, 2347 const TemplateArgumentListInfo *&TemplateArgs) { 2348 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2349 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2350 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2351 2352 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2353 Id.TemplateId->NumArgs); 2354 translateTemplateArguments(TemplateArgsPtr, Buffer); 2355 2356 TemplateName TName = Id.TemplateId->Template.get(); 2357 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2358 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2359 TemplateArgs = &Buffer; 2360 } else { 2361 NameInfo = GetNameFromUnqualifiedId(Id); 2362 TemplateArgs = nullptr; 2363 } 2364} 2365 2366static void emitEmptyLookupTypoDiagnostic( 2367 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2368 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2369 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2370 DeclContext *Ctx = 2371 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2372 if (!TC) { 2373 // Emit a special diagnostic for failed member lookups. 2374 // FIXME: computing the declaration context might fail here (?) 2375 if (Ctx) 2376 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2377 << SS.getRange(); 2378 else 2379 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2380 return; 2381 } 2382 2383 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2384 bool DroppedSpecifier = 2385 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2386 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2387 ? diag::note_implicit_param_decl 2388 : diag::note_previous_decl; 2389 if (!Ctx) 2390 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2391 SemaRef.PDiag(NoteID)); 2392 else 2393 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2394 << Typo << Ctx << DroppedSpecifier 2395 << SS.getRange(), 2396 SemaRef.PDiag(NoteID)); 2397} 2398 2399/// Diagnose a lookup that found results in an enclosing class during error 2400/// recovery. This usually indicates that the results were found in a dependent 2401/// base class that could not be searched as part of a template definition. 2402/// Always issues a diagnostic (though this may be only a warning in MS 2403/// compatibility mode). 2404/// 2405/// Return \c true if the error is unrecoverable, or \c false if the caller 2406/// should attempt to recover using these lookup results. 2407bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) { 2408 // During a default argument instantiation the CurContext points 2409 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2410 // function parameter list, hence add an explicit check. 2411 bool isDefaultArgument = 2412 !CodeSynthesisContexts.empty() && 2413 CodeSynthesisContexts.back().Kind == 2414 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2415 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2416 bool isInstance = CurMethod && CurMethod->isInstance() && 2417 R.getNamingClass() == CurMethod->getParent() && 2418 !isDefaultArgument; 2419 2420 // There are two ways we can find a class-scope declaration during template 2421 // instantiation that we did not find in the template definition: if it is a 2422 // member of a dependent base class, or if it is declared after the point of 2423 // use in the same class. Distinguish these by comparing the class in which 2424 // the member was found to the naming class of the lookup. 2425 unsigned DiagID = diag::err_found_in_dependent_base; 2426 unsigned NoteID = diag::note_member_declared_at; 2427 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2428 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2429 : diag::err_found_later_in_class; 2430 } else if (getLangOpts().MSVCCompat) { 2431 DiagID = diag::ext_found_in_dependent_base; 2432 NoteID = diag::note_dependent_member_use; 2433 } 2434 2435 if (isInstance) { 2436 // Give a code modification hint to insert 'this->'. 2437 Diag(R.getNameLoc(), DiagID) 2438 << R.getLookupName() 2439 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2440 CheckCXXThisCapture(R.getNameLoc()); 2441 } else { 2442 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2443 // they're not shadowed). 2444 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2445 } 2446 2447 for (const NamedDecl *D : R) 2448 Diag(D->getLocation(), NoteID); 2449 2450 // Return true if we are inside a default argument instantiation 2451 // and the found name refers to an instance member function, otherwise 2452 // the caller will try to create an implicit member call and this is wrong 2453 // for default arguments. 2454 // 2455 // FIXME: Is this special case necessary? We could allow the caller to 2456 // diagnose this. 2457 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2458 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0; 2459 return true; 2460 } 2461 2462 // Tell the callee to try to recover. 2463 return false; 2464} 2465 2466/// Diagnose an empty lookup. 2467/// 2468/// \return false if new lookup candidates were found 2469bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2470 CorrectionCandidateCallback &CCC, 2471 TemplateArgumentListInfo *ExplicitTemplateArgs, 2472 ArrayRef<Expr *> Args, DeclContext *LookupCtx, 2473 TypoExpr **Out) { 2474 DeclarationName Name = R.getLookupName(); 2475 2476 unsigned diagnostic = diag::err_undeclared_var_use; 2477 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2478 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2479 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2480 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2481 diagnostic = diag::err_undeclared_use; 2482 diagnostic_suggest = diag::err_undeclared_use_suggest; 2483 } 2484 2485 // If the original lookup was an unqualified lookup, fake an 2486 // unqualified lookup. This is useful when (for example) the 2487 // original lookup would not have found something because it was a 2488 // dependent name. 2489 DeclContext *DC = 2490 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr); 2491 while (DC) { 2492 if (isa<CXXRecordDecl>(DC)) { 2493 LookupQualifiedName(R, DC); 2494 2495 if (!R.empty()) { 2496 // Don't give errors about ambiguities in this lookup. 2497 R.suppressDiagnostics(); 2498 2499 // If there's a best viable function among the results, only mention 2500 // that one in the notes. 2501 OverloadCandidateSet Candidates(R.getNameLoc(), 2502 OverloadCandidateSet::CSK_Normal); 2503 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2504 OverloadCandidateSet::iterator Best; 2505 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2506 OR_Success) { 2507 R.clear(); 2508 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2509 R.resolveKind(); 2510 } 2511 2512 return DiagnoseDependentMemberLookup(R); 2513 } 2514 2515 R.clear(); 2516 } 2517 2518 DC = DC->getLookupParent(); 2519 } 2520 2521 // We didn't find anything, so try to correct for a typo. 2522 TypoCorrection Corrected; 2523 if (S && Out) { 2524 SourceLocation TypoLoc = R.getNameLoc(); 2525 assert(!ExplicitTemplateArgs && 2526 "Diagnosing an empty lookup with explicit template args!"); 2527 *Out = CorrectTypoDelayed( 2528 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2529 [=](const TypoCorrection &TC) { 2530 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2531 diagnostic, diagnostic_suggest); 2532 }, 2533 nullptr, CTK_ErrorRecovery, LookupCtx); 2534 if (*Out) 2535 return true; 2536 } else if (S && (Corrected = 2537 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 2538 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) { 2539 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2540 bool DroppedSpecifier = 2541 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2542 R.setLookupName(Corrected.getCorrection()); 2543 2544 bool AcceptableWithRecovery = false; 2545 bool AcceptableWithoutRecovery = false; 2546 NamedDecl *ND = Corrected.getFoundDecl(); 2547 if (ND) { 2548 if (Corrected.isOverloaded()) { 2549 OverloadCandidateSet OCS(R.getNameLoc(), 2550 OverloadCandidateSet::CSK_Normal); 2551 OverloadCandidateSet::iterator Best; 2552 for (NamedDecl *CD : Corrected) { 2553 if (FunctionTemplateDecl *FTD = 2554 dyn_cast<FunctionTemplateDecl>(CD)) 2555 AddTemplateOverloadCandidate( 2556 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2557 Args, OCS); 2558 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2559 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2560 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2561 Args, OCS); 2562 } 2563 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2564 case OR_Success: 2565 ND = Best->FoundDecl; 2566 Corrected.setCorrectionDecl(ND); 2567 break; 2568 default: 2569 // FIXME: Arbitrarily pick the first declaration for the note. 2570 Corrected.setCorrectionDecl(ND); 2571 break; 2572 } 2573 } 2574 R.addDecl(ND); 2575 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2576 CXXRecordDecl *Record = nullptr; 2577 if (Corrected.getCorrectionSpecifier()) { 2578 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2579 Record = Ty->getAsCXXRecordDecl(); 2580 } 2581 if (!Record) 2582 Record = cast<CXXRecordDecl>( 2583 ND->getDeclContext()->getRedeclContext()); 2584 R.setNamingClass(Record); 2585 } 2586 2587 auto *UnderlyingND = ND->getUnderlyingDecl(); 2588 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2589 isa<FunctionTemplateDecl>(UnderlyingND); 2590 // FIXME: If we ended up with a typo for a type name or 2591 // Objective-C class name, we're in trouble because the parser 2592 // is in the wrong place to recover. Suggest the typo 2593 // correction, but don't make it a fix-it since we're not going 2594 // to recover well anyway. 2595 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2596 getAsTypeTemplateDecl(UnderlyingND) || 2597 isa<ObjCInterfaceDecl>(UnderlyingND); 2598 } else { 2599 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2600 // because we aren't able to recover. 2601 AcceptableWithoutRecovery = true; 2602 } 2603 2604 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2605 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2606 ? diag::note_implicit_param_decl 2607 : diag::note_previous_decl; 2608 if (SS.isEmpty()) 2609 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2610 PDiag(NoteID), AcceptableWithRecovery); 2611 else 2612 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2613 << Name << computeDeclContext(SS, false) 2614 << DroppedSpecifier << SS.getRange(), 2615 PDiag(NoteID), AcceptableWithRecovery); 2616 2617 // Tell the callee whether to try to recover. 2618 return !AcceptableWithRecovery; 2619 } 2620 } 2621 R.clear(); 2622 2623 // Emit a special diagnostic for failed member lookups. 2624 // FIXME: computing the declaration context might fail here (?) 2625 if (!SS.isEmpty()) { 2626 Diag(R.getNameLoc(), diag::err_no_member) 2627 << Name << computeDeclContext(SS, false) 2628 << SS.getRange(); 2629 return true; 2630 } 2631 2632 // Give up, we can't recover. 2633 Diag(R.getNameLoc(), diagnostic) << Name; 2634 return true; 2635} 2636 2637/// In Microsoft mode, if we are inside a template class whose parent class has 2638/// dependent base classes, and we can't resolve an unqualified identifier, then 2639/// assume the identifier is a member of a dependent base class. We can only 2640/// recover successfully in static methods, instance methods, and other contexts 2641/// where 'this' is available. This doesn't precisely match MSVC's 2642/// instantiation model, but it's close enough. 2643static Expr * 2644recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2645 DeclarationNameInfo &NameInfo, 2646 SourceLocation TemplateKWLoc, 2647 const TemplateArgumentListInfo *TemplateArgs) { 2648 // Only try to recover from lookup into dependent bases in static methods or 2649 // contexts where 'this' is available. 2650 QualType ThisType = S.getCurrentThisType(); 2651 const CXXRecordDecl *RD = nullptr; 2652 if (!ThisType.isNull()) 2653 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2654 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2655 RD = MD->getParent(); 2656 if (!RD || !RD->hasAnyDependentBases()) 2657 return nullptr; 2658 2659 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2660 // is available, suggest inserting 'this->' as a fixit. 2661 SourceLocation Loc = NameInfo.getLoc(); 2662 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2663 DB << NameInfo.getName() << RD; 2664 2665 if (!ThisType.isNull()) { 2666 DB << FixItHint::CreateInsertion(Loc, "this->"); 2667 return CXXDependentScopeMemberExpr::Create( 2668 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2669 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2670 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2671 } 2672 2673 // Synthesize a fake NNS that points to the derived class. This will 2674 // perform name lookup during template instantiation. 2675 CXXScopeSpec SS; 2676 auto *NNS = 2677 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2678 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2679 return DependentScopeDeclRefExpr::Create( 2680 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2681 TemplateArgs); 2682} 2683 2684ExprResult 2685Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2686 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2687 bool HasTrailingLParen, bool IsAddressOfOperand, 2688 CorrectionCandidateCallback *CCC, 2689 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2690 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2691 "cannot be direct & operand and have a trailing lparen"); 2692 if (SS.isInvalid()) 2693 return ExprError(); 2694 2695 TemplateArgumentListInfo TemplateArgsBuffer; 2696 2697 // Decompose the UnqualifiedId into the following data. 2698 DeclarationNameInfo NameInfo; 2699 const TemplateArgumentListInfo *TemplateArgs; 2700 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2701 2702 DeclarationName Name = NameInfo.getName(); 2703 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2704 SourceLocation NameLoc = NameInfo.getLoc(); 2705 2706 if (II && II->isEditorPlaceholder()) { 2707 // FIXME: When typed placeholders are supported we can create a typed 2708 // placeholder expression node. 2709 return ExprError(); 2710 } 2711 2712 // C++ [temp.dep.expr]p3: 2713 // An id-expression is type-dependent if it contains: 2714 // -- an identifier that was declared with a dependent type, 2715 // (note: handled after lookup) 2716 // -- a template-id that is dependent, 2717 // (note: handled in BuildTemplateIdExpr) 2718 // -- a conversion-function-id that specifies a dependent type, 2719 // -- a nested-name-specifier that contains a class-name that 2720 // names a dependent type. 2721 // Determine whether this is a member of an unknown specialization; 2722 // we need to handle these differently. 2723 bool DependentID = false; 2724 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2725 Name.getCXXNameType()->isDependentType()) { 2726 DependentID = true; 2727 } else if (SS.isSet()) { 2728 if (DeclContext *DC = computeDeclContext(SS, false)) { 2729 if (RequireCompleteDeclContext(SS, DC)) 2730 return ExprError(); 2731 } else { 2732 DependentID = true; 2733 } 2734 } 2735 2736 if (DependentID) 2737 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2738 IsAddressOfOperand, TemplateArgs); 2739 2740 // Perform the required lookup. 2741 LookupResult R(*this, NameInfo, 2742 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2743 ? LookupObjCImplicitSelfParam 2744 : LookupOrdinaryName); 2745 if (TemplateKWLoc.isValid() || TemplateArgs) { 2746 // Lookup the template name again to correctly establish the context in 2747 // which it was found. This is really unfortunate as we already did the 2748 // lookup to determine that it was a template name in the first place. If 2749 // this becomes a performance hit, we can work harder to preserve those 2750 // results until we get here but it's likely not worth it. 2751 bool MemberOfUnknownSpecialization; 2752 AssumedTemplateKind AssumedTemplate; 2753 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2754 MemberOfUnknownSpecialization, TemplateKWLoc, 2755 &AssumedTemplate)) 2756 return ExprError(); 2757 2758 if (MemberOfUnknownSpecialization || 2759 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2760 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2761 IsAddressOfOperand, TemplateArgs); 2762 } else { 2763 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2764 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2765 2766 // If the result might be in a dependent base class, this is a dependent 2767 // id-expression. 2768 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2769 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2770 IsAddressOfOperand, TemplateArgs); 2771 2772 // If this reference is in an Objective-C method, then we need to do 2773 // some special Objective-C lookup, too. 2774 if (IvarLookupFollowUp) { 2775 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2776 if (E.isInvalid()) 2777 return ExprError(); 2778 2779 if (Expr *Ex = E.getAs<Expr>()) 2780 return Ex; 2781 } 2782 } 2783 2784 if (R.isAmbiguous()) 2785 return ExprError(); 2786 2787 // This could be an implicitly declared function reference if the language 2788 // mode allows it as a feature. 2789 if (R.empty() && HasTrailingLParen && II && 2790 getLangOpts().implicitFunctionsAllowed()) { 2791 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2792 if (D) R.addDecl(D); 2793 } 2794 2795 // Determine whether this name might be a candidate for 2796 // argument-dependent lookup. 2797 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2798 2799 if (R.empty() && !ADL) { 2800 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2801 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2802 TemplateKWLoc, TemplateArgs)) 2803 return E; 2804 } 2805 2806 // Don't diagnose an empty lookup for inline assembly. 2807 if (IsInlineAsmIdentifier) 2808 return ExprError(); 2809 2810 // If this name wasn't predeclared and if this is not a function 2811 // call, diagnose the problem. 2812 TypoExpr *TE = nullptr; 2813 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2814 : nullptr); 2815 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2816 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2817 "Typo correction callback misconfigured"); 2818 if (CCC) { 2819 // Make sure the callback knows what the typo being diagnosed is. 2820 CCC->setTypoName(II); 2821 if (SS.isValid()) 2822 CCC->setTypoNNS(SS.getScopeRep()); 2823 } 2824 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2825 // a template name, but we happen to have always already looked up the name 2826 // before we get here if it must be a template name. 2827 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2828 std::nullopt, nullptr, &TE)) { 2829 if (TE && KeywordReplacement) { 2830 auto &State = getTypoExprState(TE); 2831 auto BestTC = State.Consumer->getNextCorrection(); 2832 if (BestTC.isKeyword()) { 2833 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2834 if (State.DiagHandler) 2835 State.DiagHandler(BestTC); 2836 KeywordReplacement->startToken(); 2837 KeywordReplacement->setKind(II->getTokenID()); 2838 KeywordReplacement->setIdentifierInfo(II); 2839 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2840 // Clean up the state associated with the TypoExpr, since it has 2841 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2842 clearDelayedTypo(TE); 2843 // Signal that a correction to a keyword was performed by returning a 2844 // valid-but-null ExprResult. 2845 return (Expr*)nullptr; 2846 } 2847 State.Consumer->resetCorrectionStream(); 2848 } 2849 return TE ? TE : ExprError(); 2850 } 2851 2852 assert(!R.empty() && 2853 "DiagnoseEmptyLookup returned false but added no results"); 2854 2855 // If we found an Objective-C instance variable, let 2856 // LookupInObjCMethod build the appropriate expression to 2857 // reference the ivar. 2858 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2859 R.clear(); 2860 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2861 // In a hopelessly buggy code, Objective-C instance variable 2862 // lookup fails and no expression will be built to reference it. 2863 if (!E.isInvalid() && !E.get()) 2864 return ExprError(); 2865 return E; 2866 } 2867 } 2868 2869 // This is guaranteed from this point on. 2870 assert(!R.empty() || ADL); 2871 2872 // Check whether this might be a C++ implicit instance member access. 2873 // C++ [class.mfct.non-static]p3: 2874 // When an id-expression that is not part of a class member access 2875 // syntax and not used to form a pointer to member is used in the 2876 // body of a non-static member function of class X, if name lookup 2877 // resolves the name in the id-expression to a non-static non-type 2878 // member of some class C, the id-expression is transformed into a 2879 // class member access expression using (*this) as the 2880 // postfix-expression to the left of the . operator. 2881 // 2882 // But we don't actually need to do this for '&' operands if R 2883 // resolved to a function or overloaded function set, because the 2884 // expression is ill-formed if it actually works out to be a 2885 // non-static member function: 2886 // 2887 // C++ [expr.ref]p4: 2888 // Otherwise, if E1.E2 refers to a non-static member function. . . 2889 // [t]he expression can be used only as the left-hand operand of a 2890 // member function call. 2891 // 2892 // There are other safeguards against such uses, but it's important 2893 // to get this right here so that we don't end up making a 2894 // spuriously dependent expression if we're inside a dependent 2895 // instance method. 2896 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2897 bool MightBeImplicitMember; 2898 if (!IsAddressOfOperand) 2899 MightBeImplicitMember = true; 2900 else if (!SS.isEmpty()) 2901 MightBeImplicitMember = false; 2902 else if (R.isOverloadedResult()) 2903 MightBeImplicitMember = false; 2904 else if (R.isUnresolvableResult()) 2905 MightBeImplicitMember = true; 2906 else 2907 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2908 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2909 isa<MSPropertyDecl>(R.getFoundDecl()); 2910 2911 if (MightBeImplicitMember) 2912 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2913 R, TemplateArgs, S); 2914 } 2915 2916 if (TemplateArgs || TemplateKWLoc.isValid()) { 2917 2918 // In C++1y, if this is a variable template id, then check it 2919 // in BuildTemplateIdExpr(). 2920 // The single lookup result must be a variable template declaration. 2921 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2922 Id.TemplateId->Kind == TNK_Var_template) { 2923 assert(R.getAsSingle<VarTemplateDecl>() && 2924 "There should only be one declaration found."); 2925 } 2926 2927 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2928 } 2929 2930 return BuildDeclarationNameExpr(SS, R, ADL); 2931} 2932 2933/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2934/// declaration name, generally during template instantiation. 2935/// There's a large number of things which don't need to be done along 2936/// this path. 2937ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2938 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2939 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2940 if (NameInfo.getName().isDependentName()) 2941 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2942 NameInfo, /*TemplateArgs=*/nullptr); 2943 2944 DeclContext *DC = computeDeclContext(SS, false); 2945 if (!DC) 2946 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2947 NameInfo, /*TemplateArgs=*/nullptr); 2948 2949 if (RequireCompleteDeclContext(SS, DC)) 2950 return ExprError(); 2951 2952 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2953 LookupQualifiedName(R, DC); 2954 2955 if (R.isAmbiguous()) 2956 return ExprError(); 2957 2958 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2959 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2960 NameInfo, /*TemplateArgs=*/nullptr); 2961 2962 if (R.empty()) { 2963 // Don't diagnose problems with invalid record decl, the secondary no_member 2964 // diagnostic during template instantiation is likely bogus, e.g. if a class 2965 // is invalid because it's derived from an invalid base class, then missing 2966 // members were likely supposed to be inherited. 2967 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2968 if (CD->isInvalidDecl()) 2969 return ExprError(); 2970 Diag(NameInfo.getLoc(), diag::err_no_member) 2971 << NameInfo.getName() << DC << SS.getRange(); 2972 return ExprError(); 2973 } 2974 2975 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2976 // Diagnose a missing typename if this resolved unambiguously to a type in 2977 // a dependent context. If we can recover with a type, downgrade this to 2978 // a warning in Microsoft compatibility mode. 2979 unsigned DiagID = diag::err_typename_missing; 2980 if (RecoveryTSI && getLangOpts().MSVCCompat) 2981 DiagID = diag::ext_typename_missing; 2982 SourceLocation Loc = SS.getBeginLoc(); 2983 auto D = Diag(Loc, DiagID); 2984 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2985 << SourceRange(Loc, NameInfo.getEndLoc()); 2986 2987 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2988 // context. 2989 if (!RecoveryTSI) 2990 return ExprError(); 2991 2992 // Only issue the fixit if we're prepared to recover. 2993 D << FixItHint::CreateInsertion(Loc, "typename "); 2994 2995 // Recover by pretending this was an elaborated type. 2996 QualType Ty = Context.getTypeDeclType(TD); 2997 TypeLocBuilder TLB; 2998 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2999 3000 QualType ET = getElaboratedType(ElaboratedTypeKeyword::None, SS, Ty); 3001 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 3002 QTL.setElaboratedKeywordLoc(SourceLocation()); 3003 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 3004 3005 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 3006 3007 return ExprEmpty(); 3008 } 3009 3010 // Defend against this resolving to an implicit member access. We usually 3011 // won't get here if this might be a legitimate a class member (we end up in 3012 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 3013 // a pointer-to-member or in an unevaluated context in C++11. 3014 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 3015 return BuildPossibleImplicitMemberExpr(SS, 3016 /*TemplateKWLoc=*/SourceLocation(), 3017 R, /*TemplateArgs=*/nullptr, S); 3018 3019 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 3020} 3021 3022/// The parser has read a name in, and Sema has detected that we're currently 3023/// inside an ObjC method. Perform some additional checks and determine if we 3024/// should form a reference to an ivar. 3025/// 3026/// Ideally, most of this would be done by lookup, but there's 3027/// actually quite a lot of extra work involved. 3028DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 3029 IdentifierInfo *II) { 3030 SourceLocation Loc = Lookup.getNameLoc(); 3031 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 3032 3033 // Check for error condition which is already reported. 3034 if (!CurMethod) 3035 return DeclResult(true); 3036 3037 // There are two cases to handle here. 1) scoped lookup could have failed, 3038 // in which case we should look for an ivar. 2) scoped lookup could have 3039 // found a decl, but that decl is outside the current instance method (i.e. 3040 // a global variable). In these two cases, we do a lookup for an ivar with 3041 // this name, if the lookup sucedes, we replace it our current decl. 3042 3043 // If we're in a class method, we don't normally want to look for 3044 // ivars. But if we don't find anything else, and there's an 3045 // ivar, that's an error. 3046 bool IsClassMethod = CurMethod->isClassMethod(); 3047 3048 bool LookForIvars; 3049 if (Lookup.empty()) 3050 LookForIvars = true; 3051 else if (IsClassMethod) 3052 LookForIvars = false; 3053 else 3054 LookForIvars = (Lookup.isSingleResult() && 3055 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 3056 ObjCInterfaceDecl *IFace = nullptr; 3057 if (LookForIvars) { 3058 IFace = CurMethod->getClassInterface(); 3059 ObjCInterfaceDecl *ClassDeclared; 3060 ObjCIvarDecl *IV = nullptr; 3061 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 3062 // Diagnose using an ivar in a class method. 3063 if (IsClassMethod) { 3064 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 3065 return DeclResult(true); 3066 } 3067 3068 // Diagnose the use of an ivar outside of the declaring class. 3069 if (IV->getAccessControl() == ObjCIvarDecl::Private && 3070 !declaresSameEntity(ClassDeclared, IFace) && 3071 !getLangOpts().DebuggerSupport) 3072 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 3073 3074 // Success. 3075 return IV; 3076 } 3077 } else if (CurMethod->isInstanceMethod()) { 3078 // We should warn if a local variable hides an ivar. 3079 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 3080 ObjCInterfaceDecl *ClassDeclared; 3081 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 3082 if (IV->getAccessControl() != ObjCIvarDecl::Private || 3083 declaresSameEntity(IFace, ClassDeclared)) 3084 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 3085 } 3086 } 3087 } else if (Lookup.isSingleResult() && 3088 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 3089 // If accessing a stand-alone ivar in a class method, this is an error. 3090 if (const ObjCIvarDecl *IV = 3091 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 3092 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 3093 return DeclResult(true); 3094 } 3095 } 3096 3097 // Didn't encounter an error, didn't find an ivar. 3098 return DeclResult(false); 3099} 3100 3101ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 3102 ObjCIvarDecl *IV) { 3103 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 3104 assert(CurMethod && CurMethod->isInstanceMethod() && 3105 "should not reference ivar from this context"); 3106 3107 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 3108 assert(IFace && "should not reference ivar from this context"); 3109 3110 // If we're referencing an invalid decl, just return this as a silent 3111 // error node. The error diagnostic was already emitted on the decl. 3112 if (IV->isInvalidDecl()) 3113 return ExprError(); 3114 3115 // Check if referencing a field with __attribute__((deprecated)). 3116 if (DiagnoseUseOfDecl(IV, Loc)) 3117 return ExprError(); 3118 3119 // FIXME: This should use a new expr for a direct reference, don't 3120 // turn this into Self->ivar, just return a BareIVarExpr or something. 3121 IdentifierInfo &II = Context.Idents.get("self"); 3122 UnqualifiedId SelfName; 3123 SelfName.setImplicitSelfParam(&II); 3124 CXXScopeSpec SelfScopeSpec; 3125 SourceLocation TemplateKWLoc; 3126 ExprResult SelfExpr = 3127 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 3128 /*HasTrailingLParen=*/false, 3129 /*IsAddressOfOperand=*/false); 3130 if (SelfExpr.isInvalid()) 3131 return ExprError(); 3132 3133 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 3134 if (SelfExpr.isInvalid()) 3135 return ExprError(); 3136 3137 MarkAnyDeclReferenced(Loc, IV, true); 3138 3139 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 3140 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 3141 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 3142 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 3143 3144 ObjCIvarRefExpr *Result = new (Context) 3145 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 3146 IV->getLocation(), SelfExpr.get(), true, true); 3147 3148 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 3149 if (!isUnevaluatedContext() && 3150 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 3151 getCurFunction()->recordUseOfWeak(Result); 3152 } 3153 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext()) 3154 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 3155 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 3156 3157 return Result; 3158} 3159 3160/// The parser has read a name in, and Sema has detected that we're currently 3161/// inside an ObjC method. Perform some additional checks and determine if we 3162/// should form a reference to an ivar. If so, build an expression referencing 3163/// that ivar. 3164ExprResult 3165Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 3166 IdentifierInfo *II, bool AllowBuiltinCreation) { 3167 // FIXME: Integrate this lookup step into LookupParsedName. 3168 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 3169 if (Ivar.isInvalid()) 3170 return ExprError(); 3171 if (Ivar.isUsable()) 3172 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 3173 cast<ObjCIvarDecl>(Ivar.get())); 3174 3175 if (Lookup.empty() && II && AllowBuiltinCreation) 3176 LookupBuiltin(Lookup); 3177 3178 // Sentinel value saying that we didn't do anything special. 3179 return ExprResult(false); 3180} 3181 3182/// Cast a base object to a member's actual type. 3183/// 3184/// There are two relevant checks: 3185/// 3186/// C++ [class.access.base]p7: 3187/// 3188/// If a class member access operator [...] is used to access a non-static 3189/// data member or non-static member function, the reference is ill-formed if 3190/// the left operand [...] cannot be implicitly converted to a pointer to the 3191/// naming class of the right operand. 3192/// 3193/// C++ [expr.ref]p7: 3194/// 3195/// If E2 is a non-static data member or a non-static member function, the 3196/// program is ill-formed if the class of which E2 is directly a member is an 3197/// ambiguous base (11.8) of the naming class (11.9.3) of E2. 3198/// 3199/// Note that the latter check does not consider access; the access of the 3200/// "real" base class is checked as appropriate when checking the access of the 3201/// member name. 3202ExprResult 3203Sema::PerformObjectMemberConversion(Expr *From, 3204 NestedNameSpecifier *Qualifier, 3205 NamedDecl *FoundDecl, 3206 NamedDecl *Member) { 3207 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 3208 if (!RD) 3209 return From; 3210 3211 QualType DestRecordType; 3212 QualType DestType; 3213 QualType FromRecordType; 3214 QualType FromType = From->getType(); 3215 bool PointerConversions = false; 3216 if (isa<FieldDecl>(Member)) { 3217 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 3218 auto FromPtrType = FromType->getAs<PointerType>(); 3219 DestRecordType = Context.getAddrSpaceQualType( 3220 DestRecordType, FromPtrType 3221 ? FromType->getPointeeType().getAddressSpace() 3222 : FromType.getAddressSpace()); 3223 3224 if (FromPtrType) { 3225 DestType = Context.getPointerType(DestRecordType); 3226 FromRecordType = FromPtrType->getPointeeType(); 3227 PointerConversions = true; 3228 } else { 3229 DestType = DestRecordType; 3230 FromRecordType = FromType; 3231 } 3232 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) { 3233 if (!Method->isImplicitObjectMemberFunction()) 3234 return From; 3235 3236 DestType = Method->getThisType().getNonReferenceType(); 3237 DestRecordType = Method->getFunctionObjectParameterType(); 3238 3239 if (FromType->getAs<PointerType>()) { 3240 FromRecordType = FromType->getPointeeType(); 3241 PointerConversions = true; 3242 } else { 3243 FromRecordType = FromType; 3244 DestType = DestRecordType; 3245 } 3246 3247 LangAS FromAS = FromRecordType.getAddressSpace(); 3248 LangAS DestAS = DestRecordType.getAddressSpace(); 3249 if (FromAS != DestAS) { 3250 QualType FromRecordTypeWithoutAS = 3251 Context.removeAddrSpaceQualType(FromRecordType); 3252 QualType FromTypeWithDestAS = 3253 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 3254 if (PointerConversions) 3255 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 3256 From = ImpCastExprToType(From, FromTypeWithDestAS, 3257 CK_AddressSpaceConversion, From->getValueKind()) 3258 .get(); 3259 } 3260 } else { 3261 // No conversion necessary. 3262 return From; 3263 } 3264 3265 if (DestType->isDependentType() || FromType->isDependentType()) 3266 return From; 3267 3268 // If the unqualified types are the same, no conversion is necessary. 3269 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3270 return From; 3271 3272 SourceRange FromRange = From->getSourceRange(); 3273 SourceLocation FromLoc = FromRange.getBegin(); 3274 3275 ExprValueKind VK = From->getValueKind(); 3276 3277 // C++ [class.member.lookup]p8: 3278 // [...] Ambiguities can often be resolved by qualifying a name with its 3279 // class name. 3280 // 3281 // If the member was a qualified name and the qualified referred to a 3282 // specific base subobject type, we'll cast to that intermediate type 3283 // first and then to the object in which the member is declared. That allows 3284 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3285 // 3286 // class Base { public: int x; }; 3287 // class Derived1 : public Base { }; 3288 // class Derived2 : public Base { }; 3289 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3290 // 3291 // void VeryDerived::f() { 3292 // x = 17; // error: ambiguous base subobjects 3293 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3294 // } 3295 if (Qualifier && Qualifier->getAsType()) { 3296 QualType QType = QualType(Qualifier->getAsType(), 0); 3297 assert(QType->isRecordType() && "lookup done with non-record type"); 3298 3299 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); 3300 3301 // In C++98, the qualifier type doesn't actually have to be a base 3302 // type of the object type, in which case we just ignore it. 3303 // Otherwise build the appropriate casts. 3304 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3305 CXXCastPath BasePath; 3306 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3307 FromLoc, FromRange, &BasePath)) 3308 return ExprError(); 3309 3310 if (PointerConversions) 3311 QType = Context.getPointerType(QType); 3312 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3313 VK, &BasePath).get(); 3314 3315 FromType = QType; 3316 FromRecordType = QRecordType; 3317 3318 // If the qualifier type was the same as the destination type, 3319 // we're done. 3320 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3321 return From; 3322 } 3323 } 3324 3325 CXXCastPath BasePath; 3326 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3327 FromLoc, FromRange, &BasePath, 3328 /*IgnoreAccess=*/true)) 3329 return ExprError(); 3330 3331 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3332 VK, &BasePath); 3333} 3334 3335bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3336 const LookupResult &R, 3337 bool HasTrailingLParen) { 3338 // Only when used directly as the postfix-expression of a call. 3339 if (!HasTrailingLParen) 3340 return false; 3341 3342 // Never if a scope specifier was provided. 3343 if (SS.isSet()) 3344 return false; 3345 3346 // Only in C++ or ObjC++. 3347 if (!getLangOpts().CPlusPlus) 3348 return false; 3349 3350 // Turn off ADL when we find certain kinds of declarations during 3351 // normal lookup: 3352 for (const NamedDecl *D : R) { 3353 // C++0x [basic.lookup.argdep]p3: 3354 // -- a declaration of a class member 3355 // Since using decls preserve this property, we check this on the 3356 // original decl. 3357 if (D->isCXXClassMember()) 3358 return false; 3359 3360 // C++0x [basic.lookup.argdep]p3: 3361 // -- a block-scope function declaration that is not a 3362 // using-declaration 3363 // NOTE: we also trigger this for function templates (in fact, we 3364 // don't check the decl type at all, since all other decl types 3365 // turn off ADL anyway). 3366 if (isa<UsingShadowDecl>(D)) 3367 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3368 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3369 return false; 3370 3371 // C++0x [basic.lookup.argdep]p3: 3372 // -- a declaration that is neither a function or a function 3373 // template 3374 // And also for builtin functions. 3375 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) { 3376 // But also builtin functions. 3377 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3378 return false; 3379 } else if (!isa<FunctionTemplateDecl>(D)) 3380 return false; 3381 } 3382 3383 return true; 3384} 3385 3386 3387/// Diagnoses obvious problems with the use of the given declaration 3388/// as an expression. This is only actually called for lookups that 3389/// were not overloaded, and it doesn't promise that the declaration 3390/// will in fact be used. 3391static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, 3392 bool AcceptInvalid) { 3393 if (D->isInvalidDecl() && !AcceptInvalid) 3394 return true; 3395 3396 if (isa<TypedefNameDecl>(D)) { 3397 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3398 return true; 3399 } 3400 3401 if (isa<ObjCInterfaceDecl>(D)) { 3402 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3403 return true; 3404 } 3405 3406 if (isa<NamespaceDecl>(D)) { 3407 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3408 return true; 3409 } 3410 3411 return false; 3412} 3413 3414// Certain multiversion types should be treated as overloaded even when there is 3415// only one result. 3416static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3417 assert(R.isSingleResult() && "Expected only a single result"); 3418 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3419 return FD && 3420 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3421} 3422 3423ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3424 LookupResult &R, bool NeedsADL, 3425 bool AcceptInvalidDecl) { 3426 // If this is a single, fully-resolved result and we don't need ADL, 3427 // just build an ordinary singleton decl ref. 3428 if (!NeedsADL && R.isSingleResult() && 3429 !R.getAsSingle<FunctionTemplateDecl>() && 3430 !ShouldLookupResultBeMultiVersionOverload(R)) 3431 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3432 R.getRepresentativeDecl(), nullptr, 3433 AcceptInvalidDecl); 3434 3435 // We only need to check the declaration if there's exactly one 3436 // result, because in the overloaded case the results can only be 3437 // functions and function templates. 3438 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3439 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(), 3440 AcceptInvalidDecl)) 3441 return ExprError(); 3442 3443 // Otherwise, just build an unresolved lookup expression. Suppress 3444 // any lookup-related diagnostics; we'll hash these out later, when 3445 // we've picked a target. 3446 R.suppressDiagnostics(); 3447 3448 UnresolvedLookupExpr *ULE 3449 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3450 SS.getWithLocInContext(Context), 3451 R.getLookupNameInfo(), 3452 NeedsADL, R.isOverloadedResult(), 3453 R.begin(), R.end()); 3454 3455 return ULE; 3456} 3457 3458static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, 3459 SourceLocation loc, 3460 ValueDecl *var); 3461 3462/// Complete semantic analysis for a reference to the given declaration. 3463ExprResult Sema::BuildDeclarationNameExpr( 3464 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3465 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3466 bool AcceptInvalidDecl) { 3467 assert(D && "Cannot refer to a NULL declaration"); 3468 assert(!isa<FunctionTemplateDecl>(D) && 3469 "Cannot refer unambiguously to a function template"); 3470 3471 SourceLocation Loc = NameInfo.getLoc(); 3472 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) { 3473 // Recovery from invalid cases (e.g. D is an invalid Decl). 3474 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up 3475 // diagnostics, as invalid decls use int as a fallback type. 3476 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {}); 3477 } 3478 3479 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3480 // Specifically diagnose references to class templates that are missing 3481 // a template argument list. 3482 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3483 return ExprError(); 3484 } 3485 3486 // Make sure that we're referring to a value. 3487 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3488 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3489 Diag(D->getLocation(), diag::note_declared_at); 3490 return ExprError(); 3491 } 3492 3493 // Check whether this declaration can be used. Note that we suppress 3494 // this check when we're going to perform argument-dependent lookup 3495 // on this function name, because this might not be the function 3496 // that overload resolution actually selects. 3497 if (DiagnoseUseOfDecl(D, Loc)) 3498 return ExprError(); 3499 3500 auto *VD = cast<ValueDecl>(D); 3501 3502 // Only create DeclRefExpr's for valid Decl's. 3503 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3504 return ExprError(); 3505 3506 // Handle members of anonymous structs and unions. If we got here, 3507 // and the reference is to a class member indirect field, then this 3508 // must be the subject of a pointer-to-member expression. 3509 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD); 3510 IndirectField && !IndirectField->isCXXClassMember()) 3511 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3512 IndirectField); 3513 3514 QualType type = VD->getType(); 3515 if (type.isNull()) 3516 return ExprError(); 3517 ExprValueKind valueKind = VK_PRValue; 3518 3519 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3520 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3521 // is expanded by some outer '...' in the context of the use. 3522 type = type.getNonPackExpansionType(); 3523 3524 switch (D->getKind()) { 3525 // Ignore all the non-ValueDecl kinds. 3526#define ABSTRACT_DECL(kind) 3527#define VALUE(type, base) 3528#define DECL(type, base) case Decl::type: 3529#include "clang/AST/DeclNodes.inc" 3530 llvm_unreachable("invalid value decl kind"); 3531 3532 // These shouldn't make it here. 3533 case Decl::ObjCAtDefsField: 3534 llvm_unreachable("forming non-member reference to ivar?"); 3535 3536 // Enum constants are always r-values and never references. 3537 // Unresolved using declarations are dependent. 3538 case Decl::EnumConstant: 3539 case Decl::UnresolvedUsingValue: 3540 case Decl::OMPDeclareReduction: 3541 case Decl::OMPDeclareMapper: 3542 valueKind = VK_PRValue; 3543 break; 3544 3545 // Fields and indirect fields that got here must be for 3546 // pointer-to-member expressions; we just call them l-values for 3547 // internal consistency, because this subexpression doesn't really 3548 // exist in the high-level semantics. 3549 case Decl::Field: 3550 case Decl::IndirectField: 3551 case Decl::ObjCIvar: 3552 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3553 3554 // These can't have reference type in well-formed programs, but 3555 // for internal consistency we do this anyway. 3556 type = type.getNonReferenceType(); 3557 valueKind = VK_LValue; 3558 break; 3559 3560 // Non-type template parameters are either l-values or r-values 3561 // depending on the type. 3562 case Decl::NonTypeTemplateParm: { 3563 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3564 type = reftype->getPointeeType(); 3565 valueKind = VK_LValue; // even if the parameter is an r-value reference 3566 break; 3567 } 3568 3569 // [expr.prim.id.unqual]p2: 3570 // If the entity is a template parameter object for a template 3571 // parameter of type T, the type of the expression is const T. 3572 // [...] The expression is an lvalue if the entity is a [...] template 3573 // parameter object. 3574 if (type->isRecordType()) { 3575 type = type.getUnqualifiedType().withConst(); 3576 valueKind = VK_LValue; 3577 break; 3578 } 3579 3580 // For non-references, we need to strip qualifiers just in case 3581 // the template parameter was declared as 'const int' or whatever. 3582 valueKind = VK_PRValue; 3583 type = type.getUnqualifiedType(); 3584 break; 3585 } 3586 3587 case Decl::Var: 3588 case Decl::VarTemplateSpecialization: 3589 case Decl::VarTemplatePartialSpecialization: 3590 case Decl::Decomposition: 3591 case Decl::OMPCapturedExpr: 3592 // In C, "extern void blah;" is valid and is an r-value. 3593 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3594 type->isVoidType()) { 3595 valueKind = VK_PRValue; 3596 break; 3597 } 3598 [[fallthrough]]; 3599 3600 case Decl::ImplicitParam: 3601 case Decl::ParmVar: { 3602 // These are always l-values. 3603 valueKind = VK_LValue; 3604 type = type.getNonReferenceType(); 3605 3606 // FIXME: Does the addition of const really only apply in 3607 // potentially-evaluated contexts? Since the variable isn't actually 3608 // captured in an unevaluated context, it seems that the answer is no. 3609 if (!isUnevaluatedContext()) { 3610 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3611 if (!CapturedType.isNull()) 3612 type = CapturedType; 3613 } 3614 3615 break; 3616 } 3617 3618 case Decl::Binding: 3619 // These are always lvalues. 3620 valueKind = VK_LValue; 3621 type = type.getNonReferenceType(); 3622 break; 3623 3624 case Decl::Function: { 3625 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3626 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 3627 type = Context.BuiltinFnTy; 3628 valueKind = VK_PRValue; 3629 break; 3630 } 3631 } 3632 3633 const FunctionType *fty = type->castAs<FunctionType>(); 3634 3635 // If we're referring to a function with an __unknown_anytype 3636 // result type, make the entire expression __unknown_anytype. 3637 if (fty->getReturnType() == Context.UnknownAnyTy) { 3638 type = Context.UnknownAnyTy; 3639 valueKind = VK_PRValue; 3640 break; 3641 } 3642 3643 // Functions are l-values in C++. 3644 if (getLangOpts().CPlusPlus) { 3645 valueKind = VK_LValue; 3646 break; 3647 } 3648 3649 // C99 DR 316 says that, if a function type comes from a 3650 // function definition (without a prototype), that type is only 3651 // used for checking compatibility. Therefore, when referencing 3652 // the function, we pretend that we don't have the full function 3653 // type. 3654 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3655 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3656 fty->getExtInfo()); 3657 3658 // Functions are r-values in C. 3659 valueKind = VK_PRValue; 3660 break; 3661 } 3662 3663 case Decl::CXXDeductionGuide: 3664 llvm_unreachable("building reference to deduction guide"); 3665 3666 case Decl::MSProperty: 3667 case Decl::MSGuid: 3668 case Decl::TemplateParamObject: 3669 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3670 // capture in OpenMP, or duplicated between host and device? 3671 valueKind = VK_LValue; 3672 break; 3673 3674 case Decl::UnnamedGlobalConstant: 3675 valueKind = VK_LValue; 3676 break; 3677 3678 case Decl::CXXMethod: 3679 // If we're referring to a method with an __unknown_anytype 3680 // result type, make the entire expression __unknown_anytype. 3681 // This should only be possible with a type written directly. 3682 if (const FunctionProtoType *proto = 3683 dyn_cast<FunctionProtoType>(VD->getType())) 3684 if (proto->getReturnType() == Context.UnknownAnyTy) { 3685 type = Context.UnknownAnyTy; 3686 valueKind = VK_PRValue; 3687 break; 3688 } 3689 3690 // C++ methods are l-values if static, r-values if non-static. 3691 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3692 valueKind = VK_LValue; 3693 break; 3694 } 3695 [[fallthrough]]; 3696 3697 case Decl::CXXConversion: 3698 case Decl::CXXDestructor: 3699 case Decl::CXXConstructor: 3700 valueKind = VK_PRValue; 3701 break; 3702 } 3703 3704 auto *E = 3705 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3706 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs); 3707 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We 3708 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type 3709 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus 3710 // diagnostics). 3711 if (VD->isInvalidDecl() && E) 3712 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E}); 3713 return E; 3714} 3715 3716static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3717 SmallString<32> &Target) { 3718 Target.resize(CharByteWidth * (Source.size() + 1)); 3719 char *ResultPtr = &Target[0]; 3720 const llvm::UTF8 *ErrorPtr; 3721 bool success = 3722 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3723 (void)success; 3724 assert(success); 3725 Target.resize(ResultPtr - &Target[0]); 3726} 3727 3728ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3729 PredefinedIdentKind IK) { 3730 Decl *currentDecl = getPredefinedExprDecl(CurContext); 3731 if (!currentDecl) { 3732 Diag(Loc, diag::ext_predef_outside_function); 3733 currentDecl = Context.getTranslationUnitDecl(); 3734 } 3735 3736 QualType ResTy; 3737 StringLiteral *SL = nullptr; 3738 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3739 ResTy = Context.DependentTy; 3740 else { 3741 // Pre-defined identifiers are of type char[x], where x is the length of 3742 // the string. 3743 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3744 unsigned Length = Str.length(); 3745 3746 llvm::APInt LengthI(32, Length + 1); 3747 if (IK == PredefinedIdentKind::LFunction || 3748 IK == PredefinedIdentKind::LFuncSig) { 3749 ResTy = 3750 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3751 SmallString<32> RawChars; 3752 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3753 Str, RawChars); 3754 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3755 ArraySizeModifier::Normal, 3756 /*IndexTypeQuals*/ 0); 3757 SL = StringLiteral::Create(Context, RawChars, StringLiteralKind::Wide, 3758 /*Pascal*/ false, ResTy, Loc); 3759 } else { 3760 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3761 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3762 ArraySizeModifier::Normal, 3763 /*IndexTypeQuals*/ 0); 3764 SL = StringLiteral::Create(Context, Str, StringLiteralKind::Ordinary, 3765 /*Pascal*/ false, ResTy, Loc); 3766 } 3767 } 3768 3769 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt, 3770 SL); 3771} 3772 3773ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3774 SourceLocation LParen, 3775 SourceLocation RParen, 3776 TypeSourceInfo *TSI) { 3777 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3778} 3779 3780ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3781 SourceLocation LParen, 3782 SourceLocation RParen, 3783 ParsedType ParsedTy) { 3784 TypeSourceInfo *TSI = nullptr; 3785 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3786 3787 if (Ty.isNull()) 3788 return ExprError(); 3789 if (!TSI) 3790 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3791 3792 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3793} 3794 3795ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3796 return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind)); 3797} 3798 3799ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3800 SmallString<16> CharBuffer; 3801 bool Invalid = false; 3802 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3803 if (Invalid) 3804 return ExprError(); 3805 3806 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3807 PP, Tok.getKind()); 3808 if (Literal.hadError()) 3809 return ExprError(); 3810 3811 QualType Ty; 3812 if (Literal.isWide()) 3813 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3814 else if (Literal.isUTF8() && getLangOpts().C23) 3815 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23 3816 else if (Literal.isUTF8() && getLangOpts().Char8) 3817 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3818 else if (Literal.isUTF16()) 3819 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3820 else if (Literal.isUTF32()) 3821 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3822 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3823 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3824 else 3825 Ty = Context.CharTy; // 'x' -> char in C++; 3826 // u8'x' -> char in C11-C17 and in C++ without char8_t. 3827 3828 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii; 3829 if (Literal.isWide()) 3830 Kind = CharacterLiteralKind::Wide; 3831 else if (Literal.isUTF16()) 3832 Kind = CharacterLiteralKind::UTF16; 3833 else if (Literal.isUTF32()) 3834 Kind = CharacterLiteralKind::UTF32; 3835 else if (Literal.isUTF8()) 3836 Kind = CharacterLiteralKind::UTF8; 3837 3838 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3839 Tok.getLocation()); 3840 3841 if (Literal.getUDSuffix().empty()) 3842 return Lit; 3843 3844 // We're building a user-defined literal. 3845 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3846 SourceLocation UDSuffixLoc = 3847 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3848 3849 // Make sure we're allowed user-defined literals here. 3850 if (!UDLScope) 3851 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3852 3853 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3854 // operator "" X (ch) 3855 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3856 Lit, Tok.getLocation()); 3857} 3858 3859ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3860 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3861 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3862 Context.IntTy, Loc); 3863} 3864 3865static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3866 QualType Ty, SourceLocation Loc) { 3867 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3868 3869 using llvm::APFloat; 3870 APFloat Val(Format); 3871 3872 APFloat::opStatus result = Literal.GetFloatValue(Val); 3873 3874 // Overflow is always an error, but underflow is only an error if 3875 // we underflowed to zero (APFloat reports denormals as underflow). 3876 if ((result & APFloat::opOverflow) || 3877 ((result & APFloat::opUnderflow) && Val.isZero())) { 3878 unsigned diagnostic; 3879 SmallString<20> buffer; 3880 if (result & APFloat::opOverflow) { 3881 diagnostic = diag::warn_float_overflow; 3882 APFloat::getLargest(Format).toString(buffer); 3883 } else { 3884 diagnostic = diag::warn_float_underflow; 3885 APFloat::getSmallest(Format).toString(buffer); 3886 } 3887 3888 S.Diag(Loc, diagnostic) 3889 << Ty 3890 << StringRef(buffer.data(), buffer.size()); 3891 } 3892 3893 bool isExact = (result == APFloat::opOK); 3894 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3895} 3896 3897bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3898 assert(E && "Invalid expression"); 3899 3900 if (E->isValueDependent()) 3901 return false; 3902 3903 QualType QT = E->getType(); 3904 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3905 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3906 return true; 3907 } 3908 3909 llvm::APSInt ValueAPS; 3910 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3911 3912 if (R.isInvalid()) 3913 return true; 3914 3915 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3916 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3917 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3918 << toString(ValueAPS, 10) << ValueIsPositive; 3919 return true; 3920 } 3921 3922 return false; 3923} 3924 3925ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3926 // Fast path for a single digit (which is quite common). A single digit 3927 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3928 if (Tok.getLength() == 1) { 3929 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3930 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3931 } 3932 3933 SmallString<128> SpellingBuffer; 3934 // NumericLiteralParser wants to overread by one character. Add padding to 3935 // the buffer in case the token is copied to the buffer. If getSpelling() 3936 // returns a StringRef to the memory buffer, it should have a null char at 3937 // the EOF, so it is also safe. 3938 SpellingBuffer.resize(Tok.getLength() + 1); 3939 3940 // Get the spelling of the token, which eliminates trigraphs, etc. 3941 bool Invalid = false; 3942 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3943 if (Invalid) 3944 return ExprError(); 3945 3946 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3947 PP.getSourceManager(), PP.getLangOpts(), 3948 PP.getTargetInfo(), PP.getDiagnostics()); 3949 if (Literal.hadError) 3950 return ExprError(); 3951 3952 if (Literal.hasUDSuffix()) { 3953 // We're building a user-defined literal. 3954 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3955 SourceLocation UDSuffixLoc = 3956 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3957 3958 // Make sure we're allowed user-defined literals here. 3959 if (!UDLScope) 3960 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3961 3962 QualType CookedTy; 3963 if (Literal.isFloatingLiteral()) { 3964 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3965 // long double, the literal is treated as a call of the form 3966 // operator "" X (f L) 3967 CookedTy = Context.LongDoubleTy; 3968 } else { 3969 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3970 // unsigned long long, the literal is treated as a call of the form 3971 // operator "" X (n ULL) 3972 CookedTy = Context.UnsignedLongLongTy; 3973 } 3974 3975 DeclarationName OpName = 3976 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3977 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3978 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3979 3980 SourceLocation TokLoc = Tok.getLocation(); 3981 3982 // Perform literal operator lookup to determine if we're building a raw 3983 // literal or a cooked one. 3984 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3985 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3986 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3987 /*AllowStringTemplatePack*/ false, 3988 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3989 case LOLR_ErrorNoDiagnostic: 3990 // Lookup failure for imaginary constants isn't fatal, there's still the 3991 // GNU extension producing _Complex types. 3992 break; 3993 case LOLR_Error: 3994 return ExprError(); 3995 case LOLR_Cooked: { 3996 Expr *Lit; 3997 if (Literal.isFloatingLiteral()) { 3998 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3999 } else { 4000 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 4001 if (Literal.GetIntegerValue(ResultVal)) 4002 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 4003 << /* Unsigned */ 1; 4004 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 4005 Tok.getLocation()); 4006 } 4007 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 4008 } 4009 4010 case LOLR_Raw: { 4011 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 4012 // literal is treated as a call of the form 4013 // operator "" X ("n") 4014 unsigned Length = Literal.getUDSuffixOffset(); 4015 QualType StrTy = Context.getConstantArrayType( 4016 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 4017 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0); 4018 Expr *Lit = 4019 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length), 4020 StringLiteralKind::Ordinary, 4021 /*Pascal*/ false, StrTy, &TokLoc, 1); 4022 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 4023 } 4024 4025 case LOLR_Template: { 4026 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 4027 // template), L is treated as a call fo the form 4028 // operator "" X <'c1', 'c2', ... 'ck'>() 4029 // where n is the source character sequence c1 c2 ... ck. 4030 TemplateArgumentListInfo ExplicitArgs; 4031 unsigned CharBits = Context.getIntWidth(Context.CharTy); 4032 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 4033 llvm::APSInt Value(CharBits, CharIsUnsigned); 4034 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 4035 Value = TokSpelling[I]; 4036 TemplateArgument Arg(Context, Value, Context.CharTy); 4037 TemplateArgumentLocInfo ArgInfo; 4038 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 4039 } 4040 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc, 4041 &ExplicitArgs); 4042 } 4043 case LOLR_StringTemplatePack: 4044 llvm_unreachable("unexpected literal operator lookup result"); 4045 } 4046 } 4047 4048 Expr *Res; 4049 4050 if (Literal.isFixedPointLiteral()) { 4051 QualType Ty; 4052 4053 if (Literal.isAccum) { 4054 if (Literal.isHalf) { 4055 Ty = Context.ShortAccumTy; 4056 } else if (Literal.isLong) { 4057 Ty = Context.LongAccumTy; 4058 } else { 4059 Ty = Context.AccumTy; 4060 } 4061 } else if (Literal.isFract) { 4062 if (Literal.isHalf) { 4063 Ty = Context.ShortFractTy; 4064 } else if (Literal.isLong) { 4065 Ty = Context.LongFractTy; 4066 } else { 4067 Ty = Context.FractTy; 4068 } 4069 } 4070 4071 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 4072 4073 bool isSigned = !Literal.isUnsigned; 4074 unsigned scale = Context.getFixedPointScale(Ty); 4075 unsigned bit_width = Context.getTypeInfo(Ty).Width; 4076 4077 llvm::APInt Val(bit_width, 0, isSigned); 4078 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 4079 bool ValIsZero = Val.isZero() && !Overflowed; 4080 4081 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 4082 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 4083 // Clause 6.4.4 - The value of a constant shall be in the range of 4084 // representable values for its type, with exception for constants of a 4085 // fract type with a value of exactly 1; such a constant shall denote 4086 // the maximal value for the type. 4087 --Val; 4088 else if (Val.ugt(MaxVal) || Overflowed) 4089 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 4090 4091 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 4092 Tok.getLocation(), scale); 4093 } else if (Literal.isFloatingLiteral()) { 4094 QualType Ty; 4095 if (Literal.isHalf){ 4096 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 4097 Ty = Context.HalfTy; 4098 else { 4099 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 4100 return ExprError(); 4101 } 4102 } else if (Literal.isFloat) 4103 Ty = Context.FloatTy; 4104 else if (Literal.isLong) 4105 Ty = Context.LongDoubleTy; 4106 else if (Literal.isFloat16) 4107 Ty = Context.Float16Ty; 4108 else if (Literal.isFloat128) 4109 Ty = Context.Float128Ty; 4110 else 4111 Ty = Context.DoubleTy; 4112 4113 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 4114 4115 if (Ty == Context.DoubleTy) { 4116 if (getLangOpts().SinglePrecisionConstants) { 4117 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 4118 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 4119 } 4120 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 4121 "cl_khr_fp64", getLangOpts())) { 4122 // Impose single-precision float type when cl_khr_fp64 is not enabled. 4123 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 4124 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 4125 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 4126 } 4127 } 4128 } else if (!Literal.isIntegerLiteral()) { 4129 return ExprError(); 4130 } else { 4131 QualType Ty; 4132 4133 // 'z/uz' literals are a C++23 feature. 4134 if (Literal.isSizeT) 4135 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 4136 ? getLangOpts().CPlusPlus23 4137 ? diag::warn_cxx20_compat_size_t_suffix 4138 : diag::ext_cxx23_size_t_suffix 4139 : diag::err_cxx23_size_t_suffix); 4140 4141 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++, 4142 // but we do not currently support the suffix in C++ mode because it's not 4143 // entirely clear whether WG21 will prefer this suffix to return a library 4144 // type such as std::bit_int instead of returning a _BitInt. 4145 if (Literal.isBitInt && !getLangOpts().CPlusPlus) 4146 PP.Diag(Tok.getLocation(), getLangOpts().C23 4147 ? diag::warn_c23_compat_bitint_suffix 4148 : diag::ext_c23_bitint_suffix); 4149 4150 // Get the value in the widest-possible width. What is "widest" depends on 4151 // whether the literal is a bit-precise integer or not. For a bit-precise 4152 // integer type, try to scan the source to determine how many bits are 4153 // needed to represent the value. This may seem a bit expensive, but trying 4154 // to get the integer value from an overly-wide APInt is *extremely* 4155 // expensive, so the naive approach of assuming 4156 // llvm::IntegerType::MAX_INT_BITS is a big performance hit. 4157 unsigned BitsNeeded = 4158 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded( 4159 Literal.getLiteralDigits(), Literal.getRadix()) 4160 : Context.getTargetInfo().getIntMaxTWidth(); 4161 llvm::APInt ResultVal(BitsNeeded, 0); 4162 4163 if (Literal.GetIntegerValue(ResultVal)) { 4164 // If this value didn't fit into uintmax_t, error and force to ull. 4165 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 4166 << /* Unsigned */ 1; 4167 Ty = Context.UnsignedLongLongTy; 4168 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 4169 "long long is not intmax_t?"); 4170 } else { 4171 // If this value fits into a ULL, try to figure out what else it fits into 4172 // according to the rules of C99 6.4.4.1p5. 4173 4174 // Octal, Hexadecimal, and integers with a U suffix are allowed to 4175 // be an unsigned int. 4176 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 4177 4178 // Check from smallest to largest, picking the smallest type we can. 4179 unsigned Width = 0; 4180 4181 // Microsoft specific integer suffixes are explicitly sized. 4182 if (Literal.MicrosoftInteger) { 4183 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 4184 Width = 8; 4185 Ty = Context.CharTy; 4186 } else { 4187 Width = Literal.MicrosoftInteger; 4188 Ty = Context.getIntTypeForBitwidth(Width, 4189 /*Signed=*/!Literal.isUnsigned); 4190 } 4191 } 4192 4193 // Bit-precise integer literals are automagically-sized based on the 4194 // width required by the literal. 4195 if (Literal.isBitInt) { 4196 // The signed version has one more bit for the sign value. There are no 4197 // zero-width bit-precise integers, even if the literal value is 0. 4198 Width = std::max(ResultVal.getActiveBits(), 1u) + 4199 (Literal.isUnsigned ? 0u : 1u); 4200 4201 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, 4202 // and reset the type to the largest supported width. 4203 unsigned int MaxBitIntWidth = 4204 Context.getTargetInfo().getMaxBitIntWidth(); 4205 if (Width > MaxBitIntWidth) { 4206 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 4207 << Literal.isUnsigned; 4208 Width = MaxBitIntWidth; 4209 } 4210 4211 // Reset the result value to the smaller APInt and select the correct 4212 // type to be used. Note, we zext even for signed values because the 4213 // literal itself is always an unsigned value (a preceeding - is a 4214 // unary operator, not part of the literal). 4215 ResultVal = ResultVal.zextOrTrunc(Width); 4216 Ty = Context.getBitIntType(Literal.isUnsigned, Width); 4217 } 4218 4219 // Check C++23 size_t literals. 4220 if (Literal.isSizeT) { 4221 assert(!Literal.MicrosoftInteger && 4222 "size_t literals can't be Microsoft literals"); 4223 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 4224 Context.getTargetInfo().getSizeType()); 4225 4226 // Does it fit in size_t? 4227 if (ResultVal.isIntN(SizeTSize)) { 4228 // Does it fit in ssize_t? 4229 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 4230 Ty = Context.getSignedSizeType(); 4231 else if (AllowUnsigned) 4232 Ty = Context.getSizeType(); 4233 Width = SizeTSize; 4234 } 4235 } 4236 4237 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 4238 !Literal.isSizeT) { 4239 // Are int/unsigned possibilities? 4240 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 4241 4242 // Does it fit in a unsigned int? 4243 if (ResultVal.isIntN(IntSize)) { 4244 // Does it fit in a signed int? 4245 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 4246 Ty = Context.IntTy; 4247 else if (AllowUnsigned) 4248 Ty = Context.UnsignedIntTy; 4249 Width = IntSize; 4250 } 4251 } 4252 4253 // Are long/unsigned long possibilities? 4254 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 4255 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 4256 4257 // Does it fit in a unsigned long? 4258 if (ResultVal.isIntN(LongSize)) { 4259 // Does it fit in a signed long? 4260 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 4261 Ty = Context.LongTy; 4262 else if (AllowUnsigned) 4263 Ty = Context.UnsignedLongTy; 4264 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 4265 // is compatible. 4266 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 4267 const unsigned LongLongSize = 4268 Context.getTargetInfo().getLongLongWidth(); 4269 Diag(Tok.getLocation(), 4270 getLangOpts().CPlusPlus 4271 ? Literal.isLong 4272 ? diag::warn_old_implicitly_unsigned_long_cxx 4273 : /*C++98 UB*/ diag:: 4274 ext_old_implicitly_unsigned_long_cxx 4275 : diag::warn_old_implicitly_unsigned_long) 4276 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4277 : /*will be ill-formed*/ 1); 4278 Ty = Context.UnsignedLongTy; 4279 } 4280 Width = LongSize; 4281 } 4282 } 4283 4284 // Check long long if needed. 4285 if (Ty.isNull() && !Literal.isSizeT) { 4286 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4287 4288 // Does it fit in a unsigned long long? 4289 if (ResultVal.isIntN(LongLongSize)) { 4290 // Does it fit in a signed long long? 4291 // To be compatible with MSVC, hex integer literals ending with the 4292 // LL or i64 suffix are always signed in Microsoft mode. 4293 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4294 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4295 Ty = Context.LongLongTy; 4296 else if (AllowUnsigned) 4297 Ty = Context.UnsignedLongLongTy; 4298 Width = LongLongSize; 4299 4300 // 'long long' is a C99 or C++11 feature, whether the literal 4301 // explicitly specified 'long long' or we needed the extra width. 4302 if (getLangOpts().CPlusPlus) 4303 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 4304 ? diag::warn_cxx98_compat_longlong 4305 : diag::ext_cxx11_longlong); 4306 else if (!getLangOpts().C99) 4307 Diag(Tok.getLocation(), diag::ext_c99_longlong); 4308 } 4309 } 4310 4311 // If we still couldn't decide a type, we either have 'size_t' literal 4312 // that is out of range, or a decimal literal that does not fit in a 4313 // signed long long and has no U suffix. 4314 if (Ty.isNull()) { 4315 if (Literal.isSizeT) 4316 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4317 << Literal.isUnsigned; 4318 else 4319 Diag(Tok.getLocation(), 4320 diag::ext_integer_literal_too_large_for_signed); 4321 Ty = Context.UnsignedLongLongTy; 4322 Width = Context.getTargetInfo().getLongLongWidth(); 4323 } 4324 4325 if (ResultVal.getBitWidth() != Width) 4326 ResultVal = ResultVal.trunc(Width); 4327 } 4328 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4329 } 4330 4331 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4332 if (Literal.isImaginary) { 4333 Res = new (Context) ImaginaryLiteral(Res, 4334 Context.getComplexType(Res->getType())); 4335 4336 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4337 } 4338 return Res; 4339} 4340 4341ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4342 assert(E && "ActOnParenExpr() missing expr"); 4343 QualType ExprTy = E->getType(); 4344 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4345 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4346 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4347 return new (Context) ParenExpr(L, R, E); 4348} 4349 4350static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4351 SourceLocation Loc, 4352 SourceRange ArgRange) { 4353 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4354 // scalar or vector data type argument..." 4355 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4356 // type (C99 6.2.5p18) or void. 4357 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4358 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4359 << T << ArgRange; 4360 return true; 4361 } 4362 4363 assert((T->isVoidType() || !T->isIncompleteType()) && 4364 "Scalar types should always be complete"); 4365 return false; 4366} 4367 4368static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, 4369 SourceLocation Loc, 4370 SourceRange ArgRange) { 4371 // builtin_vectorelements supports both fixed-sized and scalable vectors. 4372 if (!T->isVectorType() && !T->isSizelessVectorType()) 4373 return S.Diag(Loc, diag::err_builtin_non_vector_type) 4374 << "" 4375 << "__builtin_vectorelements" << T << ArgRange; 4376 4377 return false; 4378} 4379 4380static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4381 SourceLocation Loc, 4382 SourceRange ArgRange, 4383 UnaryExprOrTypeTrait TraitKind) { 4384 // Invalid types must be hard errors for SFINAE in C++. 4385 if (S.LangOpts.CPlusPlus) 4386 return true; 4387 4388 // C99 6.5.3.4p1: 4389 if (T->isFunctionType() && 4390 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4391 TraitKind == UETT_PreferredAlignOf)) { 4392 // sizeof(function)/alignof(function) is allowed as an extension. 4393 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4394 << getTraitSpelling(TraitKind) << ArgRange; 4395 return false; 4396 } 4397 4398 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4399 // this is an error (OpenCL v1.1 s6.3.k) 4400 if (T->isVoidType()) { 4401 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4402 : diag::ext_sizeof_alignof_void_type; 4403 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4404 return false; 4405 } 4406 4407 return true; 4408} 4409 4410static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4411 SourceLocation Loc, 4412 SourceRange ArgRange, 4413 UnaryExprOrTypeTrait TraitKind) { 4414 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4415 // runtime doesn't allow it. 4416 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4417 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4418 << T << (TraitKind == UETT_SizeOf) 4419 << ArgRange; 4420 return true; 4421 } 4422 4423 return false; 4424} 4425 4426/// Check whether E is a pointer from a decayed array type (the decayed 4427/// pointer type is equal to T) and emit a warning if it is. 4428static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4429 const Expr *E) { 4430 // Don't warn if the operation changed the type. 4431 if (T != E->getType()) 4432 return; 4433 4434 // Now look for array decays. 4435 const auto *ICE = dyn_cast<ImplicitCastExpr>(E); 4436 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4437 return; 4438 4439 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4440 << ICE->getType() 4441 << ICE->getSubExpr()->getType(); 4442} 4443 4444/// Check the constraints on expression operands to unary type expression 4445/// and type traits. 4446/// 4447/// Completes any types necessary and validates the constraints on the operand 4448/// expression. The logic mostly mirrors the type-based overload, but may modify 4449/// the expression as it completes the type for that expression through template 4450/// instantiation, etc. 4451bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4452 UnaryExprOrTypeTrait ExprKind) { 4453 QualType ExprTy = E->getType(); 4454 assert(!ExprTy->isReferenceType()); 4455 4456 bool IsUnevaluatedOperand = 4457 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf || 4458 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4459 ExprKind == UETT_VecStep); 4460 if (IsUnevaluatedOperand) { 4461 ExprResult Result = CheckUnevaluatedOperand(E); 4462 if (Result.isInvalid()) 4463 return true; 4464 E = Result.get(); 4465 } 4466 4467 // The operand for sizeof and alignof is in an unevaluated expression context, 4468 // so side effects could result in unintended consequences. 4469 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4470 // used to build SFINAE gadgets. 4471 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4472 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4473 !E->isInstantiationDependent() && 4474 !E->getType()->isVariableArrayType() && 4475 E->HasSideEffects(Context, false)) 4476 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4477 4478 if (ExprKind == UETT_VecStep) 4479 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4480 E->getSourceRange()); 4481 4482 if (ExprKind == UETT_VectorElements) 4483 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(), 4484 E->getSourceRange()); 4485 4486 // Explicitly list some types as extensions. 4487 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4488 E->getSourceRange(), ExprKind)) 4489 return false; 4490 4491 // WebAssembly tables are always illegal operands to unary expressions and 4492 // type traits. 4493 if (Context.getTargetInfo().getTriple().isWasm() && 4494 E->getType()->isWebAssemblyTableType()) { 4495 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand) 4496 << getTraitSpelling(ExprKind); 4497 return true; 4498 } 4499 4500 // 'alignof' applied to an expression only requires the base element type of 4501 // the expression to be complete. 'sizeof' requires the expression's type to 4502 // be complete (and will attempt to complete it if it's an array of unknown 4503 // bound). 4504 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4505 if (RequireCompleteSizedType( 4506 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4507 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4508 getTraitSpelling(ExprKind), E->getSourceRange())) 4509 return true; 4510 } else { 4511 if (RequireCompleteSizedExprType( 4512 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4513 getTraitSpelling(ExprKind), E->getSourceRange())) 4514 return true; 4515 } 4516 4517 // Completing the expression's type may have changed it. 4518 ExprTy = E->getType(); 4519 assert(!ExprTy->isReferenceType()); 4520 4521 if (ExprTy->isFunctionType()) { 4522 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4523 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4524 return true; 4525 } 4526 4527 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4528 E->getSourceRange(), ExprKind)) 4529 return true; 4530 4531 if (ExprKind == UETT_SizeOf) { 4532 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4533 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4534 QualType OType = PVD->getOriginalType(); 4535 QualType Type = PVD->getType(); 4536 if (Type->isPointerType() && OType->isArrayType()) { 4537 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4538 << Type << OType; 4539 Diag(PVD->getLocation(), diag::note_declared_at); 4540 } 4541 } 4542 } 4543 4544 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4545 // decays into a pointer and returns an unintended result. This is most 4546 // likely a typo for "sizeof(array) op x". 4547 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4548 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4549 BO->getLHS()); 4550 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4551 BO->getRHS()); 4552 } 4553 } 4554 4555 return false; 4556} 4557 4558static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4559 // Cannot know anything else if the expression is dependent. 4560 if (E->isTypeDependent()) 4561 return false; 4562 4563 if (E->getObjectKind() == OK_BitField) { 4564 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4565 << 1 << E->getSourceRange(); 4566 return true; 4567 } 4568 4569 ValueDecl *D = nullptr; 4570 Expr *Inner = E->IgnoreParens(); 4571 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4572 D = DRE->getDecl(); 4573 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4574 D = ME->getMemberDecl(); 4575 } 4576 4577 // If it's a field, require the containing struct to have a 4578 // complete definition so that we can compute the layout. 4579 // 4580 // This can happen in C++11 onwards, either by naming the member 4581 // in a way that is not transformed into a member access expression 4582 // (in an unevaluated operand, for instance), or by naming the member 4583 // in a trailing-return-type. 4584 // 4585 // For the record, since __alignof__ on expressions is a GCC 4586 // extension, GCC seems to permit this but always gives the 4587 // nonsensical answer 0. 4588 // 4589 // We don't really need the layout here --- we could instead just 4590 // directly check for all the appropriate alignment-lowing 4591 // attributes --- but that would require duplicating a lot of 4592 // logic that just isn't worth duplicating for such a marginal 4593 // use-case. 4594 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4595 // Fast path this check, since we at least know the record has a 4596 // definition if we can find a member of it. 4597 if (!FD->getParent()->isCompleteDefinition()) { 4598 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4599 << E->getSourceRange(); 4600 return true; 4601 } 4602 4603 // Otherwise, if it's a field, and the field doesn't have 4604 // reference type, then it must have a complete type (or be a 4605 // flexible array member, which we explicitly want to 4606 // white-list anyway), which makes the following checks trivial. 4607 if (!FD->getType()->isReferenceType()) 4608 return false; 4609 } 4610 4611 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4612} 4613 4614bool Sema::CheckVecStepExpr(Expr *E) { 4615 E = E->IgnoreParens(); 4616 4617 // Cannot know anything else if the expression is dependent. 4618 if (E->isTypeDependent()) 4619 return false; 4620 4621 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4622} 4623 4624static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4625 CapturingScopeInfo *CSI) { 4626 assert(T->isVariablyModifiedType()); 4627 assert(CSI != nullptr); 4628 4629 // We're going to walk down into the type and look for VLA expressions. 4630 do { 4631 const Type *Ty = T.getTypePtr(); 4632 switch (Ty->getTypeClass()) { 4633#define TYPE(Class, Base) 4634#define ABSTRACT_TYPE(Class, Base) 4635#define NON_CANONICAL_TYPE(Class, Base) 4636#define DEPENDENT_TYPE(Class, Base) case Type::Class: 4637#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4638#include "clang/AST/TypeNodes.inc" 4639 T = QualType(); 4640 break; 4641 // These types are never variably-modified. 4642 case Type::Builtin: 4643 case Type::Complex: 4644 case Type::Vector: 4645 case Type::ExtVector: 4646 case Type::ConstantMatrix: 4647 case Type::Record: 4648 case Type::Enum: 4649 case Type::TemplateSpecialization: 4650 case Type::ObjCObject: 4651 case Type::ObjCInterface: 4652 case Type::ObjCObjectPointer: 4653 case Type::ObjCTypeParam: 4654 case Type::Pipe: 4655 case Type::BitInt: 4656 llvm_unreachable("type class is never variably-modified!"); 4657 case Type::Elaborated: 4658 T = cast<ElaboratedType>(Ty)->getNamedType(); 4659 break; 4660 case Type::Adjusted: 4661 T = cast<AdjustedType>(Ty)->getOriginalType(); 4662 break; 4663 case Type::Decayed: 4664 T = cast<DecayedType>(Ty)->getPointeeType(); 4665 break; 4666 case Type::Pointer: 4667 T = cast<PointerType>(Ty)->getPointeeType(); 4668 break; 4669 case Type::BlockPointer: 4670 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4671 break; 4672 case Type::LValueReference: 4673 case Type::RValueReference: 4674 T = cast<ReferenceType>(Ty)->getPointeeType(); 4675 break; 4676 case Type::MemberPointer: 4677 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4678 break; 4679 case Type::ConstantArray: 4680 case Type::IncompleteArray: 4681 // Losing element qualification here is fine. 4682 T = cast<ArrayType>(Ty)->getElementType(); 4683 break; 4684 case Type::VariableArray: { 4685 // Losing element qualification here is fine. 4686 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4687 4688 // Unknown size indication requires no size computation. 4689 // Otherwise, evaluate and record it. 4690 auto Size = VAT->getSizeExpr(); 4691 if (Size && !CSI->isVLATypeCaptured(VAT) && 4692 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4693 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4694 4695 T = VAT->getElementType(); 4696 break; 4697 } 4698 case Type::FunctionProto: 4699 case Type::FunctionNoProto: 4700 T = cast<FunctionType>(Ty)->getReturnType(); 4701 break; 4702 case Type::Paren: 4703 case Type::TypeOf: 4704 case Type::UnaryTransform: 4705 case Type::Attributed: 4706 case Type::BTFTagAttributed: 4707 case Type::SubstTemplateTypeParm: 4708 case Type::MacroQualified: 4709 // Keep walking after single level desugaring. 4710 T = T.getSingleStepDesugaredType(Context); 4711 break; 4712 case Type::Typedef: 4713 T = cast<TypedefType>(Ty)->desugar(); 4714 break; 4715 case Type::Decltype: 4716 T = cast<DecltypeType>(Ty)->desugar(); 4717 break; 4718 case Type::Using: 4719 T = cast<UsingType>(Ty)->desugar(); 4720 break; 4721 case Type::Auto: 4722 case Type::DeducedTemplateSpecialization: 4723 T = cast<DeducedType>(Ty)->getDeducedType(); 4724 break; 4725 case Type::TypeOfExpr: 4726 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4727 break; 4728 case Type::Atomic: 4729 T = cast<AtomicType>(Ty)->getValueType(); 4730 break; 4731 } 4732 } while (!T.isNull() && T->isVariablyModifiedType()); 4733} 4734 4735/// Check the constraints on operands to unary expression and type 4736/// traits. 4737/// 4738/// This will complete any types necessary, and validate the various constraints 4739/// on those operands. 4740/// 4741/// The UsualUnaryConversions() function is *not* called by this routine. 4742/// C99 6.3.2.1p[2-4] all state: 4743/// Except when it is the operand of the sizeof operator ... 4744/// 4745/// C++ [expr.sizeof]p4 4746/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4747/// standard conversions are not applied to the operand of sizeof. 4748/// 4749/// This policy is followed for all of the unary trait expressions. 4750bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4751 SourceLocation OpLoc, 4752 SourceRange ExprRange, 4753 UnaryExprOrTypeTrait ExprKind, 4754 StringRef KWName) { 4755 if (ExprType->isDependentType()) 4756 return false; 4757 4758 // C++ [expr.sizeof]p2: 4759 // When applied to a reference or a reference type, the result 4760 // is the size of the referenced type. 4761 // C++11 [expr.alignof]p3: 4762 // When alignof is applied to a reference type, the result 4763 // shall be the alignment of the referenced type. 4764 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4765 ExprType = Ref->getPointeeType(); 4766 4767 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4768 // When alignof or _Alignof is applied to an array type, the result 4769 // is the alignment of the element type. 4770 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4771 ExprKind == UETT_OpenMPRequiredSimdAlign) 4772 ExprType = Context.getBaseElementType(ExprType); 4773 4774 if (ExprKind == UETT_VecStep) 4775 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4776 4777 if (ExprKind == UETT_VectorElements) 4778 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc, 4779 ExprRange); 4780 4781 // Explicitly list some types as extensions. 4782 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4783 ExprKind)) 4784 return false; 4785 4786 if (RequireCompleteSizedType( 4787 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4788 KWName, ExprRange)) 4789 return true; 4790 4791 if (ExprType->isFunctionType()) { 4792 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange; 4793 return true; 4794 } 4795 4796 // WebAssembly tables are always illegal operands to unary expressions and 4797 // type traits. 4798 if (Context.getTargetInfo().getTriple().isWasm() && 4799 ExprType->isWebAssemblyTableType()) { 4800 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand) 4801 << getTraitSpelling(ExprKind); 4802 return true; 4803 } 4804 4805 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4806 ExprKind)) 4807 return true; 4808 4809 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4810 if (auto *TT = ExprType->getAs<TypedefType>()) { 4811 for (auto I = FunctionScopes.rbegin(), 4812 E = std::prev(FunctionScopes.rend()); 4813 I != E; ++I) { 4814 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4815 if (CSI == nullptr) 4816 break; 4817 DeclContext *DC = nullptr; 4818 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4819 DC = LSI->CallOperator; 4820 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4821 DC = CRSI->TheCapturedDecl; 4822 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4823 DC = BSI->TheDecl; 4824 if (DC) { 4825 if (DC->containsDecl(TT->getDecl())) 4826 break; 4827 captureVariablyModifiedType(Context, ExprType, CSI); 4828 } 4829 } 4830 } 4831 } 4832 4833 return false; 4834} 4835 4836/// Build a sizeof or alignof expression given a type operand. 4837ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4838 SourceLocation OpLoc, 4839 UnaryExprOrTypeTrait ExprKind, 4840 SourceRange R) { 4841 if (!TInfo) 4842 return ExprError(); 4843 4844 QualType T = TInfo->getType(); 4845 4846 if (!T->isDependentType() && 4847 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind, 4848 getTraitSpelling(ExprKind))) 4849 return ExprError(); 4850 4851 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to 4852 // properly deal with VLAs in nested calls of sizeof and typeof. 4853 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && 4854 TInfo->getType()->isVariablyModifiedType()) 4855 TInfo = TransformToPotentiallyEvaluated(TInfo); 4856 4857 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4858 return new (Context) UnaryExprOrTypeTraitExpr( 4859 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4860} 4861 4862/// Build a sizeof or alignof expression given an expression 4863/// operand. 4864ExprResult 4865Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4866 UnaryExprOrTypeTrait ExprKind) { 4867 ExprResult PE = CheckPlaceholderExpr(E); 4868 if (PE.isInvalid()) 4869 return ExprError(); 4870 4871 E = PE.get(); 4872 4873 // Verify that the operand is valid. 4874 bool isInvalid = false; 4875 if (E->isTypeDependent()) { 4876 // Delay type-checking for type-dependent expressions. 4877 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4878 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4879 } else if (ExprKind == UETT_VecStep) { 4880 isInvalid = CheckVecStepExpr(E); 4881 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4882 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4883 isInvalid = true; 4884 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4885 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4886 isInvalid = true; 4887 } else if (ExprKind == UETT_VectorElements) { 4888 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements); 4889 } else { 4890 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4891 } 4892 4893 if (isInvalid) 4894 return ExprError(); 4895 4896 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4897 PE = TransformToPotentiallyEvaluated(E); 4898 if (PE.isInvalid()) return ExprError(); 4899 E = PE.get(); 4900 } 4901 4902 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4903 return new (Context) UnaryExprOrTypeTraitExpr( 4904 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4905} 4906 4907/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4908/// expr and the same for @c alignof and @c __alignof 4909/// Note that the ArgRange is invalid if isType is false. 4910ExprResult 4911Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4912 UnaryExprOrTypeTrait ExprKind, bool IsType, 4913 void *TyOrEx, SourceRange ArgRange) { 4914 // If error parsing type, ignore. 4915 if (!TyOrEx) return ExprError(); 4916 4917 if (IsType) { 4918 TypeSourceInfo *TInfo; 4919 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4920 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4921 } 4922 4923 Expr *ArgEx = (Expr *)TyOrEx; 4924 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4925 return Result; 4926} 4927 4928bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, 4929 SourceLocation OpLoc, SourceRange R) { 4930 if (!TInfo) 4931 return true; 4932 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R, 4933 UETT_AlignOf, KWName); 4934} 4935 4936/// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c 4937/// _Alignas(type-name) . 4938/// [dcl.align] An alignment-specifier of the form 4939/// alignas(type-id) has the same effect as alignas(alignof(type-id)). 4940/// 4941/// [N1570 6.7.5] _Alignas(type-name) is equivalent to 4942/// _Alignas(_Alignof(type-name)). 4943bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, 4944 SourceLocation OpLoc, SourceRange R) { 4945 TypeSourceInfo *TInfo; 4946 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty.getAsOpaquePtr()), 4947 &TInfo); 4948 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R); 4949} 4950 4951static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4952 bool IsReal) { 4953 if (V.get()->isTypeDependent()) 4954 return S.Context.DependentTy; 4955 4956 // _Real and _Imag are only l-values for normal l-values. 4957 if (V.get()->getObjectKind() != OK_Ordinary) { 4958 V = S.DefaultLvalueConversion(V.get()); 4959 if (V.isInvalid()) 4960 return QualType(); 4961 } 4962 4963 // These operators return the element type of a complex type. 4964 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4965 return CT->getElementType(); 4966 4967 // Otherwise they pass through real integer and floating point types here. 4968 if (V.get()->getType()->isArithmeticType()) 4969 return V.get()->getType(); 4970 4971 // Test for placeholders. 4972 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4973 if (PR.isInvalid()) return QualType(); 4974 if (PR.get() != V.get()) { 4975 V = PR; 4976 return CheckRealImagOperand(S, V, Loc, IsReal); 4977 } 4978 4979 // Reject anything else. 4980 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4981 << (IsReal ? "__real" : "__imag"); 4982 return QualType(); 4983} 4984 4985 4986 4987ExprResult 4988Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4989 tok::TokenKind Kind, Expr *Input) { 4990 UnaryOperatorKind Opc; 4991 switch (Kind) { 4992 default: llvm_unreachable("Unknown unary op!"); 4993 case tok::plusplus: Opc = UO_PostInc; break; 4994 case tok::minusminus: Opc = UO_PostDec; break; 4995 } 4996 4997 // Since this might is a postfix expression, get rid of ParenListExprs. 4998 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4999 if (Result.isInvalid()) return ExprError(); 5000 Input = Result.get(); 5001 5002 return BuildUnaryOp(S, OpLoc, Opc, Input); 5003} 5004 5005/// Diagnose if arithmetic on the given ObjC pointer is illegal. 5006/// 5007/// \return true on error 5008static bool checkArithmeticOnObjCPointer(Sema &S, 5009 SourceLocation opLoc, 5010 Expr *op) { 5011 assert(op->getType()->isObjCObjectPointerType()); 5012 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 5013 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 5014 return false; 5015 5016 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 5017 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 5018 << op->getSourceRange(); 5019 return true; 5020} 5021 5022static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 5023 auto *BaseNoParens = Base->IgnoreParens(); 5024 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 5025 return MSProp->getPropertyDecl()->getType()->isArrayType(); 5026 return isa<MSPropertySubscriptExpr>(BaseNoParens); 5027} 5028 5029// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. 5030// Typically this is DependentTy, but can sometimes be more precise. 5031// 5032// There are cases when we could determine a non-dependent type: 5033// - LHS and RHS may have non-dependent types despite being type-dependent 5034// (e.g. unbounded array static members of the current instantiation) 5035// - one may be a dependent-sized array with known element type 5036// - one may be a dependent-typed valid index (enum in current instantiation) 5037// 5038// We *always* return a dependent type, in such cases it is DependentTy. 5039// This avoids creating type-dependent expressions with non-dependent types. 5040// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 5041static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, 5042 const ASTContext &Ctx) { 5043 assert(LHS->isTypeDependent() || RHS->isTypeDependent()); 5044 QualType LTy = LHS->getType(), RTy = RHS->getType(); 5045 QualType Result = Ctx.DependentTy; 5046 if (RTy->isIntegralOrUnscopedEnumerationType()) { 5047 if (const PointerType *PT = LTy->getAs<PointerType>()) 5048 Result = PT->getPointeeType(); 5049 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) 5050 Result = AT->getElementType(); 5051 } else if (LTy->isIntegralOrUnscopedEnumerationType()) { 5052 if (const PointerType *PT = RTy->getAs<PointerType>()) 5053 Result = PT->getPointeeType(); 5054 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) 5055 Result = AT->getElementType(); 5056 } 5057 // Ensure we return a dependent type. 5058 return Result->isDependentType() ? Result : Ctx.DependentTy; 5059} 5060 5061ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, 5062 SourceLocation lbLoc, 5063 MultiExprArg ArgExprs, 5064 SourceLocation rbLoc) { 5065 5066 if (base && !base->getType().isNull() && 5067 base->hasPlaceholderType(BuiltinType::OMPArraySection)) 5068 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(), 5069 SourceLocation(), /*Length*/ nullptr, 5070 /*Stride=*/nullptr, rbLoc); 5071 5072 // Since this might be a postfix expression, get rid of ParenListExprs. 5073 if (isa<ParenListExpr>(base)) { 5074 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 5075 if (result.isInvalid()) 5076 return ExprError(); 5077 base = result.get(); 5078 } 5079 5080 // Check if base and idx form a MatrixSubscriptExpr. 5081 // 5082 // Helper to check for comma expressions, which are not allowed as indices for 5083 // matrix subscript expressions. 5084 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 5085 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 5086 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 5087 << SourceRange(base->getBeginLoc(), rbLoc); 5088 return true; 5089 } 5090 return false; 5091 }; 5092 // The matrix subscript operator ([][])is considered a single operator. 5093 // Separating the index expressions by parenthesis is not allowed. 5094 if (base && !base->getType().isNull() && 5095 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) && 5096 !isa<MatrixSubscriptExpr>(base)) { 5097 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 5098 << SourceRange(base->getBeginLoc(), rbLoc); 5099 return ExprError(); 5100 } 5101 // If the base is a MatrixSubscriptExpr, try to create a new 5102 // MatrixSubscriptExpr. 5103 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 5104 if (matSubscriptE) { 5105 assert(ArgExprs.size() == 1); 5106 if (CheckAndReportCommaError(ArgExprs.front())) 5107 return ExprError(); 5108 5109 assert(matSubscriptE->isIncomplete() && 5110 "base has to be an incomplete matrix subscript"); 5111 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(), 5112 matSubscriptE->getRowIdx(), 5113 ArgExprs.front(), rbLoc); 5114 } 5115 if (base->getType()->isWebAssemblyTableType()) { 5116 Diag(base->getExprLoc(), diag::err_wasm_table_art) 5117 << SourceRange(base->getBeginLoc(), rbLoc) << 3; 5118 return ExprError(); 5119 } 5120 5121 // Handle any non-overload placeholder types in the base and index 5122 // expressions. We can't handle overloads here because the other 5123 // operand might be an overloadable type, in which case the overload 5124 // resolution for the operator overload should get the first crack 5125 // at the overload. 5126 bool IsMSPropertySubscript = false; 5127 if (base->getType()->isNonOverloadPlaceholderType()) { 5128 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 5129 if (!IsMSPropertySubscript) { 5130 ExprResult result = CheckPlaceholderExpr(base); 5131 if (result.isInvalid()) 5132 return ExprError(); 5133 base = result.get(); 5134 } 5135 } 5136 5137 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 5138 if (base->getType()->isMatrixType()) { 5139 assert(ArgExprs.size() == 1); 5140 if (CheckAndReportCommaError(ArgExprs.front())) 5141 return ExprError(); 5142 5143 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr, 5144 rbLoc); 5145 } 5146 5147 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { 5148 Expr *idx = ArgExprs[0]; 5149 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 5150 (isa<CXXOperatorCallExpr>(idx) && 5151 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) { 5152 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 5153 << SourceRange(base->getBeginLoc(), rbLoc); 5154 } 5155 } 5156 5157 if (ArgExprs.size() == 1 && 5158 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { 5159 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]); 5160 if (result.isInvalid()) 5161 return ExprError(); 5162 ArgExprs[0] = result.get(); 5163 } else { 5164 if (CheckArgsForPlaceholders(ArgExprs)) 5165 return ExprError(); 5166 } 5167 5168 // Build an unanalyzed expression if either operand is type-dependent. 5169 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && 5170 (base->isTypeDependent() || 5171 Expr::hasAnyTypeDependentArguments(ArgExprs)) && 5172 !isa<PackExpansionExpr>(ArgExprs[0])) { 5173 return new (Context) ArraySubscriptExpr( 5174 base, ArgExprs.front(), 5175 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()), 5176 VK_LValue, OK_Ordinary, rbLoc); 5177 } 5178 5179 // MSDN, property (C++) 5180 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 5181 // This attribute can also be used in the declaration of an empty array in a 5182 // class or structure definition. For example: 5183 // __declspec(property(get=GetX, put=PutX)) int x[]; 5184 // The above statement indicates that x[] can be used with one or more array 5185 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 5186 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 5187 if (IsMSPropertySubscript) { 5188 assert(ArgExprs.size() == 1); 5189 // Build MS property subscript expression if base is MS property reference 5190 // or MS property subscript. 5191 return new (Context) 5192 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, 5193 VK_LValue, OK_Ordinary, rbLoc); 5194 } 5195 5196 // Use C++ overloaded-operator rules if either operand has record 5197 // type. The spec says to do this if either type is *overloadable*, 5198 // but enum types can't declare subscript operators or conversion 5199 // operators, so there's nothing interesting for overload resolution 5200 // to do if there aren't any record types involved. 5201 // 5202 // ObjC pointers have their own subscripting logic that is not tied 5203 // to overload resolution and so should not take this path. 5204 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && 5205 ((base->getType()->isRecordType() || 5206 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) || 5207 ArgExprs[0]->getType()->isRecordType())))) { 5208 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs); 5209 } 5210 5211 ExprResult Res = 5212 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc); 5213 5214 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 5215 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 5216 5217 return Res; 5218} 5219 5220ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 5221 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 5222 InitializationKind Kind = 5223 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 5224 InitializationSequence InitSeq(*this, Entity, Kind, E); 5225 return InitSeq.Perform(*this, Entity, Kind, E); 5226} 5227 5228ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 5229 Expr *ColumnIdx, 5230 SourceLocation RBLoc) { 5231 ExprResult BaseR = CheckPlaceholderExpr(Base); 5232 if (BaseR.isInvalid()) 5233 return BaseR; 5234 Base = BaseR.get(); 5235 5236 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 5237 if (RowR.isInvalid()) 5238 return RowR; 5239 RowIdx = RowR.get(); 5240 5241 if (!ColumnIdx) 5242 return new (Context) MatrixSubscriptExpr( 5243 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 5244 5245 // Build an unanalyzed expression if any of the operands is type-dependent. 5246 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 5247 ColumnIdx->isTypeDependent()) 5248 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 5249 Context.DependentTy, RBLoc); 5250 5251 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 5252 if (ColumnR.isInvalid()) 5253 return ColumnR; 5254 ColumnIdx = ColumnR.get(); 5255 5256 // Check that IndexExpr is an integer expression. If it is a constant 5257 // expression, check that it is less than Dim (= the number of elements in the 5258 // corresponding dimension). 5259 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 5260 bool IsColumnIdx) -> Expr * { 5261 if (!IndexExpr->getType()->isIntegerType() && 5262 !IndexExpr->isTypeDependent()) { 5263 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 5264 << IsColumnIdx; 5265 return nullptr; 5266 } 5267 5268 if (std::optional<llvm::APSInt> Idx = 5269 IndexExpr->getIntegerConstantExpr(Context)) { 5270 if ((*Idx < 0 || *Idx >= Dim)) { 5271 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 5272 << IsColumnIdx << Dim; 5273 return nullptr; 5274 } 5275 } 5276 5277 ExprResult ConvExpr = 5278 tryConvertExprToType(IndexExpr, Context.getSizeType()); 5279 assert(!ConvExpr.isInvalid() && 5280 "should be able to convert any integer type to size type"); 5281 return ConvExpr.get(); 5282 }; 5283 5284 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 5285 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 5286 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 5287 if (!RowIdx || !ColumnIdx) 5288 return ExprError(); 5289 5290 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 5291 MTy->getElementType(), RBLoc); 5292} 5293 5294void Sema::CheckAddressOfNoDeref(const Expr *E) { 5295 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5296 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 5297 5298 // For expressions like `&(*s).b`, the base is recorded and what should be 5299 // checked. 5300 const MemberExpr *Member = nullptr; 5301 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 5302 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 5303 5304 LastRecord.PossibleDerefs.erase(StrippedExpr); 5305} 5306 5307void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 5308 if (isUnevaluatedContext()) 5309 return; 5310 5311 QualType ResultTy = E->getType(); 5312 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5313 5314 // Bail if the element is an array since it is not memory access. 5315 if (isa<ArrayType>(ResultTy)) 5316 return; 5317 5318 if (ResultTy->hasAttr(attr::NoDeref)) { 5319 LastRecord.PossibleDerefs.insert(E); 5320 return; 5321 } 5322 5323 // Check if the base type is a pointer to a member access of a struct 5324 // marked with noderef. 5325 const Expr *Base = E->getBase(); 5326 QualType BaseTy = Base->getType(); 5327 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 5328 // Not a pointer access 5329 return; 5330 5331 const MemberExpr *Member = nullptr; 5332 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 5333 Member->isArrow()) 5334 Base = Member->getBase(); 5335 5336 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 5337 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 5338 LastRecord.PossibleDerefs.insert(E); 5339 } 5340} 5341 5342ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 5343 Expr *LowerBound, 5344 SourceLocation ColonLocFirst, 5345 SourceLocation ColonLocSecond, 5346 Expr *Length, Expr *Stride, 5347 SourceLocation RBLoc) { 5348 if (Base->hasPlaceholderType() && 5349 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5350 ExprResult Result = CheckPlaceholderExpr(Base); 5351 if (Result.isInvalid()) 5352 return ExprError(); 5353 Base = Result.get(); 5354 } 5355 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 5356 ExprResult Result = CheckPlaceholderExpr(LowerBound); 5357 if (Result.isInvalid()) 5358 return ExprError(); 5359 Result = DefaultLvalueConversion(Result.get()); 5360 if (Result.isInvalid()) 5361 return ExprError(); 5362 LowerBound = Result.get(); 5363 } 5364 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 5365 ExprResult Result = CheckPlaceholderExpr(Length); 5366 if (Result.isInvalid()) 5367 return ExprError(); 5368 Result = DefaultLvalueConversion(Result.get()); 5369 if (Result.isInvalid()) 5370 return ExprError(); 5371 Length = Result.get(); 5372 } 5373 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 5374 ExprResult Result = CheckPlaceholderExpr(Stride); 5375 if (Result.isInvalid()) 5376 return ExprError(); 5377 Result = DefaultLvalueConversion(Result.get()); 5378 if (Result.isInvalid()) 5379 return ExprError(); 5380 Stride = Result.get(); 5381 } 5382 5383 // Build an unanalyzed expression if either operand is type-dependent. 5384 if (Base->isTypeDependent() || 5385 (LowerBound && 5386 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 5387 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 5388 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 5389 return new (Context) OMPArraySectionExpr( 5390 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 5391 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5392 } 5393 5394 // Perform default conversions. 5395 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 5396 QualType ResultTy; 5397 if (OriginalTy->isAnyPointerType()) { 5398 ResultTy = OriginalTy->getPointeeType(); 5399 } else if (OriginalTy->isArrayType()) { 5400 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 5401 } else { 5402 return ExprError( 5403 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 5404 << Base->getSourceRange()); 5405 } 5406 // C99 6.5.2.1p1 5407 if (LowerBound) { 5408 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 5409 LowerBound); 5410 if (Res.isInvalid()) 5411 return ExprError(Diag(LowerBound->getExprLoc(), 5412 diag::err_omp_typecheck_section_not_integer) 5413 << 0 << LowerBound->getSourceRange()); 5414 LowerBound = Res.get(); 5415 5416 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5417 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5418 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5419 << 0 << LowerBound->getSourceRange(); 5420 } 5421 if (Length) { 5422 auto Res = 5423 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5424 if (Res.isInvalid()) 5425 return ExprError(Diag(Length->getExprLoc(), 5426 diag::err_omp_typecheck_section_not_integer) 5427 << 1 << Length->getSourceRange()); 5428 Length = Res.get(); 5429 5430 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5431 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5432 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5433 << 1 << Length->getSourceRange(); 5434 } 5435 if (Stride) { 5436 ExprResult Res = 5437 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5438 if (Res.isInvalid()) 5439 return ExprError(Diag(Stride->getExprLoc(), 5440 diag::err_omp_typecheck_section_not_integer) 5441 << 1 << Stride->getSourceRange()); 5442 Stride = Res.get(); 5443 5444 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5445 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5446 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5447 << 1 << Stride->getSourceRange(); 5448 } 5449 5450 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5451 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5452 // type. Note that functions are not objects, and that (in C99 parlance) 5453 // incomplete types are not object types. 5454 if (ResultTy->isFunctionType()) { 5455 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5456 << ResultTy << Base->getSourceRange(); 5457 return ExprError(); 5458 } 5459 5460 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5461 diag::err_omp_section_incomplete_type, Base)) 5462 return ExprError(); 5463 5464 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5465 Expr::EvalResult Result; 5466 if (LowerBound->EvaluateAsInt(Result, Context)) { 5467 // OpenMP 5.0, [2.1.5 Array Sections] 5468 // The array section must be a subset of the original array. 5469 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5470 if (LowerBoundValue.isNegative()) { 5471 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5472 << LowerBound->getSourceRange(); 5473 return ExprError(); 5474 } 5475 } 5476 } 5477 5478 if (Length) { 5479 Expr::EvalResult Result; 5480 if (Length->EvaluateAsInt(Result, Context)) { 5481 // OpenMP 5.0, [2.1.5 Array Sections] 5482 // The length must evaluate to non-negative integers. 5483 llvm::APSInt LengthValue = Result.Val.getInt(); 5484 if (LengthValue.isNegative()) { 5485 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5486 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5487 << Length->getSourceRange(); 5488 return ExprError(); 5489 } 5490 } 5491 } else if (ColonLocFirst.isValid() && 5492 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5493 !OriginalTy->isVariableArrayType()))) { 5494 // OpenMP 5.0, [2.1.5 Array Sections] 5495 // When the size of the array dimension is not known, the length must be 5496 // specified explicitly. 5497 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5498 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5499 return ExprError(); 5500 } 5501 5502 if (Stride) { 5503 Expr::EvalResult Result; 5504 if (Stride->EvaluateAsInt(Result, Context)) { 5505 // OpenMP 5.0, [2.1.5 Array Sections] 5506 // The stride must evaluate to a positive integer. 5507 llvm::APSInt StrideValue = Result.Val.getInt(); 5508 if (!StrideValue.isStrictlyPositive()) { 5509 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5510 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5511 << Stride->getSourceRange(); 5512 return ExprError(); 5513 } 5514 } 5515 } 5516 5517 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5518 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5519 if (Result.isInvalid()) 5520 return ExprError(); 5521 Base = Result.get(); 5522 } 5523 return new (Context) OMPArraySectionExpr( 5524 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5525 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5526} 5527 5528ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5529 SourceLocation RParenLoc, 5530 ArrayRef<Expr *> Dims, 5531 ArrayRef<SourceRange> Brackets) { 5532 if (Base->hasPlaceholderType()) { 5533 ExprResult Result = CheckPlaceholderExpr(Base); 5534 if (Result.isInvalid()) 5535 return ExprError(); 5536 Result = DefaultLvalueConversion(Result.get()); 5537 if (Result.isInvalid()) 5538 return ExprError(); 5539 Base = Result.get(); 5540 } 5541 QualType BaseTy = Base->getType(); 5542 // Delay analysis of the types/expressions if instantiation/specialization is 5543 // required. 5544 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5545 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5546 LParenLoc, RParenLoc, Dims, Brackets); 5547 if (!BaseTy->isPointerType() || 5548 (!Base->isTypeDependent() && 5549 BaseTy->getPointeeType()->isIncompleteType())) 5550 return ExprError(Diag(Base->getExprLoc(), 5551 diag::err_omp_non_pointer_type_array_shaping_base) 5552 << Base->getSourceRange()); 5553 5554 SmallVector<Expr *, 4> NewDims; 5555 bool ErrorFound = false; 5556 for (Expr *Dim : Dims) { 5557 if (Dim->hasPlaceholderType()) { 5558 ExprResult Result = CheckPlaceholderExpr(Dim); 5559 if (Result.isInvalid()) { 5560 ErrorFound = true; 5561 continue; 5562 } 5563 Result = DefaultLvalueConversion(Result.get()); 5564 if (Result.isInvalid()) { 5565 ErrorFound = true; 5566 continue; 5567 } 5568 Dim = Result.get(); 5569 } 5570 if (!Dim->isTypeDependent()) { 5571 ExprResult Result = 5572 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5573 if (Result.isInvalid()) { 5574 ErrorFound = true; 5575 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5576 << Dim->getSourceRange(); 5577 continue; 5578 } 5579 Dim = Result.get(); 5580 Expr::EvalResult EvResult; 5581 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5582 // OpenMP 5.0, [2.1.4 Array Shaping] 5583 // Each si is an integral type expression that must evaluate to a 5584 // positive integer. 5585 llvm::APSInt Value = EvResult.Val.getInt(); 5586 if (!Value.isStrictlyPositive()) { 5587 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5588 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5589 << Dim->getSourceRange(); 5590 ErrorFound = true; 5591 continue; 5592 } 5593 } 5594 } 5595 NewDims.push_back(Dim); 5596 } 5597 if (ErrorFound) 5598 return ExprError(); 5599 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5600 LParenLoc, RParenLoc, NewDims, Brackets); 5601} 5602 5603ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5604 SourceLocation LLoc, SourceLocation RLoc, 5605 ArrayRef<OMPIteratorData> Data) { 5606 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5607 bool IsCorrect = true; 5608 for (const OMPIteratorData &D : Data) { 5609 TypeSourceInfo *TInfo = nullptr; 5610 SourceLocation StartLoc; 5611 QualType DeclTy; 5612 if (!D.Type.getAsOpaquePtr()) { 5613 // OpenMP 5.0, 2.1.6 Iterators 5614 // In an iterator-specifier, if the iterator-type is not specified then 5615 // the type of that iterator is of int type. 5616 DeclTy = Context.IntTy; 5617 StartLoc = D.DeclIdentLoc; 5618 } else { 5619 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5620 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5621 } 5622 5623 bool IsDeclTyDependent = DeclTy->isDependentType() || 5624 DeclTy->containsUnexpandedParameterPack() || 5625 DeclTy->isInstantiationDependentType(); 5626 if (!IsDeclTyDependent) { 5627 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5628 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5629 // The iterator-type must be an integral or pointer type. 5630 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5631 << DeclTy; 5632 IsCorrect = false; 5633 continue; 5634 } 5635 if (DeclTy.isConstant(Context)) { 5636 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5637 // The iterator-type must not be const qualified. 5638 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5639 << DeclTy; 5640 IsCorrect = false; 5641 continue; 5642 } 5643 } 5644 5645 // Iterator declaration. 5646 assert(D.DeclIdent && "Identifier expected."); 5647 // Always try to create iterator declarator to avoid extra error messages 5648 // about unknown declarations use. 5649 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5650 D.DeclIdent, DeclTy, TInfo, SC_None); 5651 VD->setImplicit(); 5652 if (S) { 5653 // Check for conflicting previous declaration. 5654 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5655 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5656 ForVisibleRedeclaration); 5657 Previous.suppressDiagnostics(); 5658 LookupName(Previous, S); 5659 5660 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5661 /*AllowInlineNamespace=*/false); 5662 if (!Previous.empty()) { 5663 NamedDecl *Old = Previous.getRepresentativeDecl(); 5664 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5665 Diag(Old->getLocation(), diag::note_previous_definition); 5666 } else { 5667 PushOnScopeChains(VD, S); 5668 } 5669 } else { 5670 CurContext->addDecl(VD); 5671 } 5672 5673 /// Act on the iterator variable declaration. 5674 ActOnOpenMPIteratorVarDecl(VD); 5675 5676 Expr *Begin = D.Range.Begin; 5677 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5678 ExprResult BeginRes = 5679 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5680 Begin = BeginRes.get(); 5681 } 5682 Expr *End = D.Range.End; 5683 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5684 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5685 End = EndRes.get(); 5686 } 5687 Expr *Step = D.Range.Step; 5688 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5689 if (!Step->getType()->isIntegralType(Context)) { 5690 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5691 << Step << Step->getSourceRange(); 5692 IsCorrect = false; 5693 continue; 5694 } 5695 std::optional<llvm::APSInt> Result = 5696 Step->getIntegerConstantExpr(Context); 5697 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5698 // If the step expression of a range-specification equals zero, the 5699 // behavior is unspecified. 5700 if (Result && Result->isZero()) { 5701 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5702 << Step << Step->getSourceRange(); 5703 IsCorrect = false; 5704 continue; 5705 } 5706 } 5707 if (!Begin || !End || !IsCorrect) { 5708 IsCorrect = false; 5709 continue; 5710 } 5711 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5712 IDElem.IteratorDecl = VD; 5713 IDElem.AssignmentLoc = D.AssignLoc; 5714 IDElem.Range.Begin = Begin; 5715 IDElem.Range.End = End; 5716 IDElem.Range.Step = Step; 5717 IDElem.ColonLoc = D.ColonLoc; 5718 IDElem.SecondColonLoc = D.SecColonLoc; 5719 } 5720 if (!IsCorrect) { 5721 // Invalidate all created iterator declarations if error is found. 5722 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5723 if (Decl *ID = D.IteratorDecl) 5724 ID->setInvalidDecl(); 5725 } 5726 return ExprError(); 5727 } 5728 SmallVector<OMPIteratorHelperData, 4> Helpers; 5729 if (!CurContext->isDependentContext()) { 5730 // Build number of ityeration for each iteration range. 5731 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5732 // ((Begini-Stepi-1-Endi) / -Stepi); 5733 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5734 // (Endi - Begini) 5735 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5736 D.Range.Begin); 5737 if(!Res.isUsable()) { 5738 IsCorrect = false; 5739 continue; 5740 } 5741 ExprResult St, St1; 5742 if (D.Range.Step) { 5743 St = D.Range.Step; 5744 // (Endi - Begini) + Stepi 5745 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5746 if (!Res.isUsable()) { 5747 IsCorrect = false; 5748 continue; 5749 } 5750 // (Endi - Begini) + Stepi - 1 5751 Res = 5752 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5753 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5754 if (!Res.isUsable()) { 5755 IsCorrect = false; 5756 continue; 5757 } 5758 // ((Endi - Begini) + Stepi - 1) / Stepi 5759 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5760 if (!Res.isUsable()) { 5761 IsCorrect = false; 5762 continue; 5763 } 5764 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5765 // (Begini - Endi) 5766 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5767 D.Range.Begin, D.Range.End); 5768 if (!Res1.isUsable()) { 5769 IsCorrect = false; 5770 continue; 5771 } 5772 // (Begini - Endi) - Stepi 5773 Res1 = 5774 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5775 if (!Res1.isUsable()) { 5776 IsCorrect = false; 5777 continue; 5778 } 5779 // (Begini - Endi) - Stepi - 1 5780 Res1 = 5781 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5782 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5783 if (!Res1.isUsable()) { 5784 IsCorrect = false; 5785 continue; 5786 } 5787 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5788 Res1 = 5789 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5790 if (!Res1.isUsable()) { 5791 IsCorrect = false; 5792 continue; 5793 } 5794 // Stepi > 0. 5795 ExprResult CmpRes = 5796 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5797 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5798 if (!CmpRes.isUsable()) { 5799 IsCorrect = false; 5800 continue; 5801 } 5802 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5803 Res.get(), Res1.get()); 5804 if (!Res.isUsable()) { 5805 IsCorrect = false; 5806 continue; 5807 } 5808 } 5809 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5810 if (!Res.isUsable()) { 5811 IsCorrect = false; 5812 continue; 5813 } 5814 5815 // Build counter update. 5816 // Build counter. 5817 auto *CounterVD = 5818 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5819 D.IteratorDecl->getBeginLoc(), nullptr, 5820 Res.get()->getType(), nullptr, SC_None); 5821 CounterVD->setImplicit(); 5822 ExprResult RefRes = 5823 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5824 D.IteratorDecl->getBeginLoc()); 5825 // Build counter update. 5826 // I = Begini + counter * Stepi; 5827 ExprResult UpdateRes; 5828 if (D.Range.Step) { 5829 UpdateRes = CreateBuiltinBinOp( 5830 D.AssignmentLoc, BO_Mul, 5831 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5832 } else { 5833 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5834 } 5835 if (!UpdateRes.isUsable()) { 5836 IsCorrect = false; 5837 continue; 5838 } 5839 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5840 UpdateRes.get()); 5841 if (!UpdateRes.isUsable()) { 5842 IsCorrect = false; 5843 continue; 5844 } 5845 ExprResult VDRes = 5846 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5847 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5848 D.IteratorDecl->getBeginLoc()); 5849 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5850 UpdateRes.get()); 5851 if (!UpdateRes.isUsable()) { 5852 IsCorrect = false; 5853 continue; 5854 } 5855 UpdateRes = 5856 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5857 if (!UpdateRes.isUsable()) { 5858 IsCorrect = false; 5859 continue; 5860 } 5861 ExprResult CounterUpdateRes = 5862 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5863 if (!CounterUpdateRes.isUsable()) { 5864 IsCorrect = false; 5865 continue; 5866 } 5867 CounterUpdateRes = 5868 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5869 if (!CounterUpdateRes.isUsable()) { 5870 IsCorrect = false; 5871 continue; 5872 } 5873 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5874 HD.CounterVD = CounterVD; 5875 HD.Upper = Res.get(); 5876 HD.Update = UpdateRes.get(); 5877 HD.CounterUpdate = CounterUpdateRes.get(); 5878 } 5879 } else { 5880 Helpers.assign(ID.size(), {}); 5881 } 5882 if (!IsCorrect) { 5883 // Invalidate all created iterator declarations if error is found. 5884 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5885 if (Decl *ID = D.IteratorDecl) 5886 ID->setInvalidDecl(); 5887 } 5888 return ExprError(); 5889 } 5890 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5891 LLoc, RLoc, ID, Helpers); 5892} 5893 5894ExprResult 5895Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5896 Expr *Idx, SourceLocation RLoc) { 5897 Expr *LHSExp = Base; 5898 Expr *RHSExp = Idx; 5899 5900 ExprValueKind VK = VK_LValue; 5901 ExprObjectKind OK = OK_Ordinary; 5902 5903 // Per C++ core issue 1213, the result is an xvalue if either operand is 5904 // a non-lvalue array, and an lvalue otherwise. 5905 if (getLangOpts().CPlusPlus11) { 5906 for (auto *Op : {LHSExp, RHSExp}) { 5907 Op = Op->IgnoreImplicit(); 5908 if (Op->getType()->isArrayType() && !Op->isLValue()) 5909 VK = VK_XValue; 5910 } 5911 } 5912 5913 // Perform default conversions. 5914 if (!LHSExp->getType()->getAs<VectorType>()) { 5915 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5916 if (Result.isInvalid()) 5917 return ExprError(); 5918 LHSExp = Result.get(); 5919 } 5920 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5921 if (Result.isInvalid()) 5922 return ExprError(); 5923 RHSExp = Result.get(); 5924 5925 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5926 5927 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5928 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5929 // in the subscript position. As a result, we need to derive the array base 5930 // and index from the expression types. 5931 Expr *BaseExpr, *IndexExpr; 5932 QualType ResultType; 5933 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5934 BaseExpr = LHSExp; 5935 IndexExpr = RHSExp; 5936 ResultType = 5937 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); 5938 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5939 BaseExpr = LHSExp; 5940 IndexExpr = RHSExp; 5941 ResultType = PTy->getPointeeType(); 5942 } else if (const ObjCObjectPointerType *PTy = 5943 LHSTy->getAs<ObjCObjectPointerType>()) { 5944 BaseExpr = LHSExp; 5945 IndexExpr = RHSExp; 5946 5947 // Use custom logic if this should be the pseudo-object subscript 5948 // expression. 5949 if (!LangOpts.isSubscriptPointerArithmetic()) 5950 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5951 nullptr); 5952 5953 ResultType = PTy->getPointeeType(); 5954 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5955 // Handle the uncommon case of "123[Ptr]". 5956 BaseExpr = RHSExp; 5957 IndexExpr = LHSExp; 5958 ResultType = PTy->getPointeeType(); 5959 } else if (const ObjCObjectPointerType *PTy = 5960 RHSTy->getAs<ObjCObjectPointerType>()) { 5961 // Handle the uncommon case of "123[Ptr]". 5962 BaseExpr = RHSExp; 5963 IndexExpr = LHSExp; 5964 ResultType = PTy->getPointeeType(); 5965 if (!LangOpts.isSubscriptPointerArithmetic()) { 5966 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5967 << ResultType << BaseExpr->getSourceRange(); 5968 return ExprError(); 5969 } 5970 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5971 BaseExpr = LHSExp; // vectors: V[123] 5972 IndexExpr = RHSExp; 5973 // We apply C++ DR1213 to vector subscripting too. 5974 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5975 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5976 if (Materialized.isInvalid()) 5977 return ExprError(); 5978 LHSExp = Materialized.get(); 5979 } 5980 VK = LHSExp->getValueKind(); 5981 if (VK != VK_PRValue) 5982 OK = OK_VectorComponent; 5983 5984 ResultType = VTy->getElementType(); 5985 QualType BaseType = BaseExpr->getType(); 5986 Qualifiers BaseQuals = BaseType.getQualifiers(); 5987 Qualifiers MemberQuals = ResultType.getQualifiers(); 5988 Qualifiers Combined = BaseQuals + MemberQuals; 5989 if (Combined != MemberQuals) 5990 ResultType = Context.getQualifiedType(ResultType, Combined); 5991 } else if (LHSTy->isBuiltinType() && 5992 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) { 5993 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>(); 5994 if (BTy->isSVEBool()) 5995 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t) 5996 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5997 5998 BaseExpr = LHSExp; 5999 IndexExpr = RHSExp; 6000 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 6001 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 6002 if (Materialized.isInvalid()) 6003 return ExprError(); 6004 LHSExp = Materialized.get(); 6005 } 6006 VK = LHSExp->getValueKind(); 6007 if (VK != VK_PRValue) 6008 OK = OK_VectorComponent; 6009 6010 ResultType = BTy->getSveEltType(Context); 6011 6012 QualType BaseType = BaseExpr->getType(); 6013 Qualifiers BaseQuals = BaseType.getQualifiers(); 6014 Qualifiers MemberQuals = ResultType.getQualifiers(); 6015 Qualifiers Combined = BaseQuals + MemberQuals; 6016 if (Combined != MemberQuals) 6017 ResultType = Context.getQualifiedType(ResultType, Combined); 6018 } else if (LHSTy->isArrayType()) { 6019 // If we see an array that wasn't promoted by 6020 // DefaultFunctionArrayLvalueConversion, it must be an array that 6021 // wasn't promoted because of the C90 rule that doesn't 6022 // allow promoting non-lvalue arrays. Warn, then 6023 // force the promotion here. 6024 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 6025 << LHSExp->getSourceRange(); 6026 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 6027 CK_ArrayToPointerDecay).get(); 6028 LHSTy = LHSExp->getType(); 6029 6030 BaseExpr = LHSExp; 6031 IndexExpr = RHSExp; 6032 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 6033 } else if (RHSTy->isArrayType()) { 6034 // Same as previous, except for 123[f().a] case 6035 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 6036 << RHSExp->getSourceRange(); 6037 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 6038 CK_ArrayToPointerDecay).get(); 6039 RHSTy = RHSExp->getType(); 6040 6041 BaseExpr = RHSExp; 6042 IndexExpr = LHSExp; 6043 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 6044 } else { 6045 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 6046 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 6047 } 6048 // C99 6.5.2.1p1 6049 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 6050 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 6051 << IndexExpr->getSourceRange()); 6052 6053 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 6054 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) && 6055 !IndexExpr->isTypeDependent()) { 6056 std::optional<llvm::APSInt> IntegerContantExpr = 6057 IndexExpr->getIntegerConstantExpr(getASTContext()); 6058 if (!IntegerContantExpr.has_value() || 6059 IntegerContantExpr.value().isNegative()) 6060 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 6061 } 6062 6063 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 6064 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 6065 // type. Note that Functions are not objects, and that (in C99 parlance) 6066 // incomplete types are not object types. 6067 if (ResultType->isFunctionType()) { 6068 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 6069 << ResultType << BaseExpr->getSourceRange(); 6070 return ExprError(); 6071 } 6072 6073 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 6074 // GNU extension: subscripting on pointer to void 6075 Diag(LLoc, diag::ext_gnu_subscript_void_type) 6076 << BaseExpr->getSourceRange(); 6077 6078 // C forbids expressions of unqualified void type from being l-values. 6079 // See IsCForbiddenLValueType. 6080 if (!ResultType.hasQualifiers()) 6081 VK = VK_PRValue; 6082 } else if (!ResultType->isDependentType() && 6083 !ResultType.isWebAssemblyReferenceType() && 6084 RequireCompleteSizedType( 6085 LLoc, ResultType, 6086 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 6087 return ExprError(); 6088 6089 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 6090 !ResultType.isCForbiddenLValueType()); 6091 6092 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 6093 FunctionScopes.size() > 1) { 6094 if (auto *TT = 6095 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 6096 for (auto I = FunctionScopes.rbegin(), 6097 E = std::prev(FunctionScopes.rend()); 6098 I != E; ++I) { 6099 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 6100 if (CSI == nullptr) 6101 break; 6102 DeclContext *DC = nullptr; 6103 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 6104 DC = LSI->CallOperator; 6105 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 6106 DC = CRSI->TheCapturedDecl; 6107 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 6108 DC = BSI->TheDecl; 6109 if (DC) { 6110 if (DC->containsDecl(TT->getDecl())) 6111 break; 6112 captureVariablyModifiedType( 6113 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 6114 } 6115 } 6116 } 6117 } 6118 6119 return new (Context) 6120 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 6121} 6122 6123bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 6124 ParmVarDecl *Param, Expr *RewrittenInit, 6125 bool SkipImmediateInvocations) { 6126 if (Param->hasUnparsedDefaultArg()) { 6127 assert(!RewrittenInit && "Should not have a rewritten init expression yet"); 6128 // If we've already cleared out the location for the default argument, 6129 // that means we're parsing it right now. 6130 if (!UnparsedDefaultArgLocs.count(Param)) { 6131 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 6132 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 6133 Param->setInvalidDecl(); 6134 return true; 6135 } 6136 6137 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 6138 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 6139 Diag(UnparsedDefaultArgLocs[Param], 6140 diag::note_default_argument_declared_here); 6141 return true; 6142 } 6143 6144 if (Param->hasUninstantiatedDefaultArg()) { 6145 assert(!RewrittenInit && "Should not have a rewitten init expression yet"); 6146 if (InstantiateDefaultArgument(CallLoc, FD, Param)) 6147 return true; 6148 } 6149 6150 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit(); 6151 assert(Init && "default argument but no initializer?"); 6152 6153 // If the default expression creates temporaries, we need to 6154 // push them to the current stack of expression temporaries so they'll 6155 // be properly destroyed. 6156 // FIXME: We should really be rebuilding the default argument with new 6157 // bound temporaries; see the comment in PR5810. 6158 // We don't need to do that with block decls, though, because 6159 // blocks in default argument expression can never capture anything. 6160 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) { 6161 // Set the "needs cleanups" bit regardless of whether there are 6162 // any explicit objects. 6163 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects()); 6164 // Append all the objects to the cleanup list. Right now, this 6165 // should always be a no-op, because blocks in default argument 6166 // expressions should never be able to capture anything. 6167 assert(!InitWithCleanup->getNumObjects() && 6168 "default argument expression has capturing blocks?"); 6169 } 6170 // C++ [expr.const]p15.1: 6171 // An expression or conversion is in an immediate function context if it is 6172 // potentially evaluated and [...] its innermost enclosing non-block scope 6173 // is a function parameter scope of an immediate function. 6174 EnterExpressionEvaluationContext EvalContext( 6175 *this, 6176 FD->isImmediateFunction() 6177 ? ExpressionEvaluationContext::ImmediateFunctionContext 6178 : ExpressionEvaluationContext::PotentiallyEvaluated, 6179 Param); 6180 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = 6181 SkipImmediateInvocations; 6182 runWithSufficientStackSpace(CallLoc, [&] { 6183 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true); 6184 }); 6185 return false; 6186} 6187 6188struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> { 6189 const ASTContext &Context; 6190 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {} 6191 6192 bool HasImmediateCalls = false; 6193 bool shouldVisitImplicitCode() const { return true; } 6194 6195 bool VisitCallExpr(CallExpr *E) { 6196 if (const FunctionDecl *FD = E->getDirectCallee()) 6197 HasImmediateCalls |= FD->isImmediateFunction(); 6198 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E); 6199 } 6200 6201 // SourceLocExpr are not immediate invocations 6202 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr 6203 // need to be rebuilt so that they refer to the correct SourceLocation and 6204 // DeclContext. 6205 bool VisitSourceLocExpr(SourceLocExpr *E) { 6206 HasImmediateCalls = true; 6207 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E); 6208 } 6209 6210 // A nested lambda might have parameters with immediate invocations 6211 // in their default arguments. 6212 // The compound statement is not visited (as it does not constitute a 6213 // subexpression). 6214 // FIXME: We should consider visiting and transforming captures 6215 // with init expressions. 6216 bool VisitLambdaExpr(LambdaExpr *E) { 6217 return VisitCXXMethodDecl(E->getCallOperator()); 6218 } 6219 6220 // Blocks don't support default parameters, and, as for lambdas, 6221 // we don't consider their body a subexpression. 6222 bool VisitBlockDecl(BlockDecl *B) { return false; } 6223 6224 bool VisitCompoundStmt(CompoundStmt *B) { return false; } 6225 6226 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 6227 return TraverseStmt(E->getExpr()); 6228 } 6229 6230 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) { 6231 return TraverseStmt(E->getExpr()); 6232 } 6233}; 6234 6235struct EnsureImmediateInvocationInDefaultArgs 6236 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> { 6237 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef) 6238 : TreeTransform(SemaRef) {} 6239 6240 // Lambda can only have immediate invocations in the default 6241 // args of their parameters, which is transformed upon calling the closure. 6242 // The body is not a subexpression, so we have nothing to do. 6243 // FIXME: Immediate calls in capture initializers should be transformed. 6244 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; } 6245 ExprResult TransformBlockExpr(BlockExpr *E) { return E; } 6246 6247 // Make sure we don't rebuild the this pointer as it would 6248 // cause it to incorrectly point it to the outermost class 6249 // in the case of nested struct initialization. 6250 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; } 6251}; 6252 6253ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 6254 FunctionDecl *FD, ParmVarDecl *Param, 6255 Expr *Init) { 6256 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 6257 6258 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); 6259 6260 std::optional<ExpressionEvaluationContextRecord::InitializationContext> 6261 InitializationContext = 6262 OutermostDeclarationWithDelayedImmediateInvocations(); 6263 if (!InitializationContext.has_value()) 6264 InitializationContext.emplace(CallLoc, Param, CurContext); 6265 6266 if (!Init && !Param->hasUnparsedDefaultArg()) { 6267 // Mark that we are replacing a default argument first. 6268 // If we are instantiating a template we won't have to 6269 // retransform immediate calls. 6270 // C++ [expr.const]p15.1: 6271 // An expression or conversion is in an immediate function context if it 6272 // is potentially evaluated and [...] its innermost enclosing non-block 6273 // scope is a function parameter scope of an immediate function. 6274 EnterExpressionEvaluationContext EvalContext( 6275 *this, 6276 FD->isImmediateFunction() 6277 ? ExpressionEvaluationContext::ImmediateFunctionContext 6278 : ExpressionEvaluationContext::PotentiallyEvaluated, 6279 Param); 6280 6281 if (Param->hasUninstantiatedDefaultArg()) { 6282 if (InstantiateDefaultArgument(CallLoc, FD, Param)) 6283 return ExprError(); 6284 } 6285 // CWG2631 6286 // An immediate invocation that is not evaluated where it appears is 6287 // evaluated and checked for whether it is a constant expression at the 6288 // point where the enclosing initializer is used in a function call. 6289 ImmediateCallVisitor V(getASTContext()); 6290 if (!NestedDefaultChecking) 6291 V.TraverseDecl(Param); 6292 if (V.HasImmediateCalls) { 6293 ExprEvalContexts.back().DelayedDefaultInitializationContext = { 6294 CallLoc, Param, CurContext}; 6295 EnsureImmediateInvocationInDefaultArgs Immediate(*this); 6296 ExprResult Res; 6297 runWithSufficientStackSpace(CallLoc, [&] { 6298 Res = Immediate.TransformInitializer(Param->getInit(), 6299 /*NotCopy=*/false); 6300 }); 6301 if (Res.isInvalid()) 6302 return ExprError(); 6303 Res = ConvertParamDefaultArgument(Param, Res.get(), 6304 Res.get()->getBeginLoc()); 6305 if (Res.isInvalid()) 6306 return ExprError(); 6307 Init = Res.get(); 6308 } 6309 } 6310 6311 if (CheckCXXDefaultArgExpr( 6312 CallLoc, FD, Param, Init, 6313 /*SkipImmediateInvocations=*/NestedDefaultChecking)) 6314 return ExprError(); 6315 6316 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param, 6317 Init, InitializationContext->Context); 6318} 6319 6320ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 6321 assert(Field->hasInClassInitializer()); 6322 6323 // If we might have already tried and failed to instantiate, don't try again. 6324 if (Field->isInvalidDecl()) 6325 return ExprError(); 6326 6327 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers()); 6328 6329 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 6330 6331 std::optional<ExpressionEvaluationContextRecord::InitializationContext> 6332 InitializationContext = 6333 OutermostDeclarationWithDelayedImmediateInvocations(); 6334 if (!InitializationContext.has_value()) 6335 InitializationContext.emplace(Loc, Field, CurContext); 6336 6337 Expr *Init = nullptr; 6338 6339 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); 6340 6341 EnterExpressionEvaluationContext EvalContext( 6342 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field); 6343 6344 if (!Field->getInClassInitializer()) { 6345 // Maybe we haven't instantiated the in-class initializer. Go check the 6346 // pattern FieldDecl to see if it has one. 6347 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 6348 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 6349 DeclContext::lookup_result Lookup = 6350 ClassPattern->lookup(Field->getDeclName()); 6351 6352 FieldDecl *Pattern = nullptr; 6353 for (auto *L : Lookup) { 6354 if ((Pattern = dyn_cast<FieldDecl>(L))) 6355 break; 6356 } 6357 assert(Pattern && "We must have set the Pattern!"); 6358 if (!Pattern->hasInClassInitializer() || 6359 InstantiateInClassInitializer(Loc, Field, Pattern, 6360 getTemplateInstantiationArgs(Field))) { 6361 Field->setInvalidDecl(); 6362 return ExprError(); 6363 } 6364 } 6365 } 6366 6367 // CWG2631 6368 // An immediate invocation that is not evaluated where it appears is 6369 // evaluated and checked for whether it is a constant expression at the 6370 // point where the enclosing initializer is used in a [...] a constructor 6371 // definition, or an aggregate initialization. 6372 ImmediateCallVisitor V(getASTContext()); 6373 if (!NestedDefaultChecking) 6374 V.TraverseDecl(Field); 6375 if (V.HasImmediateCalls) { 6376 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field, 6377 CurContext}; 6378 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = 6379 NestedDefaultChecking; 6380 6381 EnsureImmediateInvocationInDefaultArgs Immediate(*this); 6382 ExprResult Res; 6383 runWithSufficientStackSpace(Loc, [&] { 6384 Res = Immediate.TransformInitializer(Field->getInClassInitializer(), 6385 /*CXXDirectInit=*/false); 6386 }); 6387 if (!Res.isInvalid()) 6388 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc); 6389 if (Res.isInvalid()) { 6390 Field->setInvalidDecl(); 6391 return ExprError(); 6392 } 6393 Init = Res.get(); 6394 } 6395 6396 if (Field->getInClassInitializer()) { 6397 Expr *E = Init ? Init : Field->getInClassInitializer(); 6398 if (!NestedDefaultChecking) 6399 runWithSufficientStackSpace(Loc, [&] { 6400 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false); 6401 }); 6402 // C++11 [class.base.init]p7: 6403 // The initialization of each base and member constitutes a 6404 // full-expression. 6405 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false); 6406 if (Res.isInvalid()) { 6407 Field->setInvalidDecl(); 6408 return ExprError(); 6409 } 6410 Init = Res.get(); 6411 6412 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc, 6413 Field, InitializationContext->Context, 6414 Init); 6415 } 6416 6417 // DR1351: 6418 // If the brace-or-equal-initializer of a non-static data member 6419 // invokes a defaulted default constructor of its class or of an 6420 // enclosing class in a potentially evaluated subexpression, the 6421 // program is ill-formed. 6422 // 6423 // This resolution is unworkable: the exception specification of the 6424 // default constructor can be needed in an unevaluated context, in 6425 // particular, in the operand of a noexcept-expression, and we can be 6426 // unable to compute an exception specification for an enclosed class. 6427 // 6428 // Any attempt to resolve the exception specification of a defaulted default 6429 // constructor before the initializer is lexically complete will ultimately 6430 // come here at which point we can diagnose it. 6431 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 6432 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 6433 << OutermostClass << Field; 6434 Diag(Field->getEndLoc(), 6435 diag::note_default_member_initializer_not_yet_parsed); 6436 // Recover by marking the field invalid, unless we're in a SFINAE context. 6437 if (!isSFINAEContext()) 6438 Field->setInvalidDecl(); 6439 return ExprError(); 6440} 6441 6442Sema::VariadicCallType 6443Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 6444 Expr *Fn) { 6445 if (Proto && Proto->isVariadic()) { 6446 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 6447 return VariadicConstructor; 6448 else if (Fn && Fn->getType()->isBlockPointerType()) 6449 return VariadicBlock; 6450 else if (FDecl) { 6451 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6452 if (Method->isInstance()) 6453 return VariadicMethod; 6454 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 6455 return VariadicMethod; 6456 return VariadicFunction; 6457 } 6458 return VariadicDoesNotApply; 6459} 6460 6461namespace { 6462class FunctionCallCCC final : public FunctionCallFilterCCC { 6463public: 6464 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 6465 unsigned NumArgs, MemberExpr *ME) 6466 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 6467 FunctionName(FuncName) {} 6468 6469 bool ValidateCandidate(const TypoCorrection &candidate) override { 6470 if (!candidate.getCorrectionSpecifier() || 6471 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 6472 return false; 6473 } 6474 6475 return FunctionCallFilterCCC::ValidateCandidate(candidate); 6476 } 6477 6478 std::unique_ptr<CorrectionCandidateCallback> clone() override { 6479 return std::make_unique<FunctionCallCCC>(*this); 6480 } 6481 6482private: 6483 const IdentifierInfo *const FunctionName; 6484}; 6485} 6486 6487static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 6488 FunctionDecl *FDecl, 6489 ArrayRef<Expr *> Args) { 6490 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 6491 DeclarationName FuncName = FDecl->getDeclName(); 6492 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 6493 6494 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 6495 if (TypoCorrection Corrected = S.CorrectTypo( 6496 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 6497 S.getScopeForContext(S.CurContext), nullptr, CCC, 6498 Sema::CTK_ErrorRecovery)) { 6499 if (NamedDecl *ND = Corrected.getFoundDecl()) { 6500 if (Corrected.isOverloaded()) { 6501 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 6502 OverloadCandidateSet::iterator Best; 6503 for (NamedDecl *CD : Corrected) { 6504 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 6505 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 6506 OCS); 6507 } 6508 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 6509 case OR_Success: 6510 ND = Best->FoundDecl; 6511 Corrected.setCorrectionDecl(ND); 6512 break; 6513 default: 6514 break; 6515 } 6516 } 6517 ND = ND->getUnderlyingDecl(); 6518 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 6519 return Corrected; 6520 } 6521 } 6522 return TypoCorrection(); 6523} 6524 6525/// ConvertArgumentsForCall - Converts the arguments specified in 6526/// Args/NumArgs to the parameter types of the function FDecl with 6527/// function prototype Proto. Call is the call expression itself, and 6528/// Fn is the function expression. For a C++ member function, this 6529/// routine does not attempt to convert the object argument. Returns 6530/// true if the call is ill-formed. 6531bool 6532Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 6533 FunctionDecl *FDecl, 6534 const FunctionProtoType *Proto, 6535 ArrayRef<Expr *> Args, 6536 SourceLocation RParenLoc, 6537 bool IsExecConfig) { 6538 // Bail out early if calling a builtin with custom typechecking. 6539 if (FDecl) 6540 if (unsigned ID = FDecl->getBuiltinID()) 6541 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 6542 return false; 6543 6544 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 6545 // assignment, to the types of the corresponding parameter, ... 6546 bool HasExplicitObjectParameter = 6547 FDecl && FDecl->hasCXXExplicitFunctionObjectParameter(); 6548 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0; 6549 unsigned NumParams = Proto->getNumParams(); 6550 bool Invalid = false; 6551 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 6552 unsigned FnKind = Fn->getType()->isBlockPointerType() 6553 ? 1 /* block */ 6554 : (IsExecConfig ? 3 /* kernel function (exec config) */ 6555 : 0 /* function */); 6556 6557 // If too few arguments are available (and we don't have default 6558 // arguments for the remaining parameters), don't make the call. 6559 if (Args.size() < NumParams) { 6560 if (Args.size() < MinArgs) { 6561 TypoCorrection TC; 6562 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6563 unsigned diag_id = 6564 MinArgs == NumParams && !Proto->isVariadic() 6565 ? diag::err_typecheck_call_too_few_args_suggest 6566 : diag::err_typecheck_call_too_few_args_at_least_suggest; 6567 diagnoseTypo( 6568 TC, PDiag(diag_id) 6569 << FnKind << MinArgs - ExplicitObjectParameterOffset 6570 << static_cast<unsigned>(Args.size()) - 6571 ExplicitObjectParameterOffset 6572 << HasExplicitObjectParameter << TC.getCorrectionRange()); 6573 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl && 6574 FDecl->getParamDecl(ExplicitObjectParameterOffset) 6575 ->getDeclName()) 6576 Diag(RParenLoc, 6577 MinArgs == NumParams && !Proto->isVariadic() 6578 ? diag::err_typecheck_call_too_few_args_one 6579 : diag::err_typecheck_call_too_few_args_at_least_one) 6580 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset) 6581 << HasExplicitObjectParameter << Fn->getSourceRange(); 6582 else 6583 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 6584 ? diag::err_typecheck_call_too_few_args 6585 : diag::err_typecheck_call_too_few_args_at_least) 6586 << FnKind << MinArgs - ExplicitObjectParameterOffset 6587 << static_cast<unsigned>(Args.size()) - 6588 ExplicitObjectParameterOffset 6589 << HasExplicitObjectParameter << Fn->getSourceRange(); 6590 6591 // Emit the location of the prototype. 6592 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6593 Diag(FDecl->getLocation(), diag::note_callee_decl) 6594 << FDecl << FDecl->getParametersSourceRange(); 6595 6596 return true; 6597 } 6598 // We reserve space for the default arguments when we create 6599 // the call expression, before calling ConvertArgumentsForCall. 6600 assert((Call->getNumArgs() == NumParams) && 6601 "We should have reserved space for the default arguments before!"); 6602 } 6603 6604 // If too many are passed and not variadic, error on the extras and drop 6605 // them. 6606 if (Args.size() > NumParams) { 6607 if (!Proto->isVariadic()) { 6608 TypoCorrection TC; 6609 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6610 unsigned diag_id = 6611 MinArgs == NumParams && !Proto->isVariadic() 6612 ? diag::err_typecheck_call_too_many_args_suggest 6613 : diag::err_typecheck_call_too_many_args_at_most_suggest; 6614 diagnoseTypo( 6615 TC, PDiag(diag_id) 6616 << FnKind << NumParams - ExplicitObjectParameterOffset 6617 << static_cast<unsigned>(Args.size()) - 6618 ExplicitObjectParameterOffset 6619 << HasExplicitObjectParameter << TC.getCorrectionRange()); 6620 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl && 6621 FDecl->getParamDecl(ExplicitObjectParameterOffset) 6622 ->getDeclName()) 6623 Diag(Args[NumParams]->getBeginLoc(), 6624 MinArgs == NumParams 6625 ? diag::err_typecheck_call_too_many_args_one 6626 : diag::err_typecheck_call_too_many_args_at_most_one) 6627 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset) 6628 << static_cast<unsigned>(Args.size()) - 6629 ExplicitObjectParameterOffset 6630 << HasExplicitObjectParameter << Fn->getSourceRange() 6631 << SourceRange(Args[NumParams]->getBeginLoc(), 6632 Args.back()->getEndLoc()); 6633 else 6634 Diag(Args[NumParams]->getBeginLoc(), 6635 MinArgs == NumParams 6636 ? diag::err_typecheck_call_too_many_args 6637 : diag::err_typecheck_call_too_many_args_at_most) 6638 << FnKind << NumParams - ExplicitObjectParameterOffset 6639 << static_cast<unsigned>(Args.size()) - 6640 ExplicitObjectParameterOffset 6641 << HasExplicitObjectParameter << Fn->getSourceRange() 6642 << SourceRange(Args[NumParams]->getBeginLoc(), 6643 Args.back()->getEndLoc()); 6644 6645 // Emit the location of the prototype. 6646 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6647 Diag(FDecl->getLocation(), diag::note_callee_decl) 6648 << FDecl << FDecl->getParametersSourceRange(); 6649 6650 // This deletes the extra arguments. 6651 Call->shrinkNumArgs(NumParams); 6652 return true; 6653 } 6654 } 6655 SmallVector<Expr *, 8> AllArgs; 6656 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 6657 6658 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 6659 AllArgs, CallType); 6660 if (Invalid) 6661 return true; 6662 unsigned TotalNumArgs = AllArgs.size(); 6663 for (unsigned i = 0; i < TotalNumArgs; ++i) 6664 Call->setArg(i, AllArgs[i]); 6665 6666 Call->computeDependence(); 6667 return false; 6668} 6669 6670bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 6671 const FunctionProtoType *Proto, 6672 unsigned FirstParam, ArrayRef<Expr *> Args, 6673 SmallVectorImpl<Expr *> &AllArgs, 6674 VariadicCallType CallType, bool AllowExplicit, 6675 bool IsListInitialization) { 6676 unsigned NumParams = Proto->getNumParams(); 6677 bool Invalid = false; 6678 size_t ArgIx = 0; 6679 // Continue to check argument types (even if we have too few/many args). 6680 for (unsigned i = FirstParam; i < NumParams; i++) { 6681 QualType ProtoArgType = Proto->getParamType(i); 6682 6683 Expr *Arg; 6684 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 6685 if (ArgIx < Args.size()) { 6686 Arg = Args[ArgIx++]; 6687 6688 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 6689 diag::err_call_incomplete_argument, Arg)) 6690 return true; 6691 6692 // Strip the unbridged-cast placeholder expression off, if applicable. 6693 bool CFAudited = false; 6694 if (Arg->getType() == Context.ARCUnbridgedCastTy && 6695 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6696 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6697 Arg = stripARCUnbridgedCast(Arg); 6698 else if (getLangOpts().ObjCAutoRefCount && 6699 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6700 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6701 CFAudited = true; 6702 6703 if (Proto->getExtParameterInfo(i).isNoEscape() && 6704 ProtoArgType->isBlockPointerType()) 6705 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 6706 BE->getBlockDecl()->setDoesNotEscape(); 6707 6708 InitializedEntity Entity = 6709 Param ? InitializedEntity::InitializeParameter(Context, Param, 6710 ProtoArgType) 6711 : InitializedEntity::InitializeParameter( 6712 Context, ProtoArgType, Proto->isParamConsumed(i)); 6713 6714 // Remember that parameter belongs to a CF audited API. 6715 if (CFAudited) 6716 Entity.setParameterCFAudited(); 6717 6718 ExprResult ArgE = PerformCopyInitialization( 6719 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 6720 if (ArgE.isInvalid()) 6721 return true; 6722 6723 Arg = ArgE.getAs<Expr>(); 6724 } else { 6725 assert(Param && "can't use default arguments without a known callee"); 6726 6727 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 6728 if (ArgExpr.isInvalid()) 6729 return true; 6730 6731 Arg = ArgExpr.getAs<Expr>(); 6732 } 6733 6734 // Check for array bounds violations for each argument to the call. This 6735 // check only triggers warnings when the argument isn't a more complex Expr 6736 // with its own checking, such as a BinaryOperator. 6737 CheckArrayAccess(Arg); 6738 6739 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6740 CheckStaticArrayArgument(CallLoc, Param, Arg); 6741 6742 AllArgs.push_back(Arg); 6743 } 6744 6745 // If this is a variadic call, handle args passed through "...". 6746 if (CallType != VariadicDoesNotApply) { 6747 // Assume that extern "C" functions with variadic arguments that 6748 // return __unknown_anytype aren't *really* variadic. 6749 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6750 FDecl->isExternC()) { 6751 for (Expr *A : Args.slice(ArgIx)) { 6752 QualType paramType; // ignored 6753 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6754 Invalid |= arg.isInvalid(); 6755 AllArgs.push_back(arg.get()); 6756 } 6757 6758 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6759 } else { 6760 for (Expr *A : Args.slice(ArgIx)) { 6761 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6762 Invalid |= Arg.isInvalid(); 6763 AllArgs.push_back(Arg.get()); 6764 } 6765 } 6766 6767 // Check for array bounds violations. 6768 for (Expr *A : Args.slice(ArgIx)) 6769 CheckArrayAccess(A); 6770 } 6771 return Invalid; 6772} 6773 6774static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6775 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6776 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6777 TL = DTL.getOriginalLoc(); 6778 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6779 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6780 << ATL.getLocalSourceRange(); 6781} 6782 6783/// CheckStaticArrayArgument - If the given argument corresponds to a static 6784/// array parameter, check that it is non-null, and that if it is formed by 6785/// array-to-pointer decay, the underlying array is sufficiently large. 6786/// 6787/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6788/// array type derivation, then for each call to the function, the value of the 6789/// corresponding actual argument shall provide access to the first element of 6790/// an array with at least as many elements as specified by the size expression. 6791void 6792Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6793 ParmVarDecl *Param, 6794 const Expr *ArgExpr) { 6795 // Static array parameters are not supported in C++. 6796 if (!Param || getLangOpts().CPlusPlus) 6797 return; 6798 6799 QualType OrigTy = Param->getOriginalType(); 6800 6801 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6802 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static) 6803 return; 6804 6805 if (ArgExpr->isNullPointerConstant(Context, 6806 Expr::NPC_NeverValueDependent)) { 6807 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6808 DiagnoseCalleeStaticArrayParam(*this, Param); 6809 return; 6810 } 6811 6812 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6813 if (!CAT) 6814 return; 6815 6816 const ConstantArrayType *ArgCAT = 6817 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6818 if (!ArgCAT) 6819 return; 6820 6821 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6822 ArgCAT->getElementType())) { 6823 if (ArgCAT->getSize().ult(CAT->getSize())) { 6824 Diag(CallLoc, diag::warn_static_array_too_small) 6825 << ArgExpr->getSourceRange() 6826 << (unsigned)ArgCAT->getSize().getZExtValue() 6827 << (unsigned)CAT->getSize().getZExtValue() << 0; 6828 DiagnoseCalleeStaticArrayParam(*this, Param); 6829 } 6830 return; 6831 } 6832 6833 std::optional<CharUnits> ArgSize = 6834 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6835 std::optional<CharUnits> ParmSize = 6836 getASTContext().getTypeSizeInCharsIfKnown(CAT); 6837 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6838 Diag(CallLoc, diag::warn_static_array_too_small) 6839 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6840 << (unsigned)ParmSize->getQuantity() << 1; 6841 DiagnoseCalleeStaticArrayParam(*this, Param); 6842 } 6843} 6844 6845/// Given a function expression of unknown-any type, try to rebuild it 6846/// to have a function type. 6847static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6848 6849/// Is the given type a placeholder that we need to lower out 6850/// immediately during argument processing? 6851static bool isPlaceholderToRemoveAsArg(QualType type) { 6852 // Placeholders are never sugared. 6853 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6854 if (!placeholder) return false; 6855 6856 switch (placeholder->getKind()) { 6857 // Ignore all the non-placeholder types. 6858#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6859 case BuiltinType::Id: 6860#include "clang/Basic/OpenCLImageTypes.def" 6861#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6862 case BuiltinType::Id: 6863#include "clang/Basic/OpenCLExtensionTypes.def" 6864 // In practice we'll never use this, since all SVE types are sugared 6865 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6866#define SVE_TYPE(Name, Id, SingletonId) \ 6867 case BuiltinType::Id: 6868#include "clang/Basic/AArch64SVEACLETypes.def" 6869#define PPC_VECTOR_TYPE(Name, Id, Size) \ 6870 case BuiltinType::Id: 6871#include "clang/Basic/PPCTypes.def" 6872#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6873#include "clang/Basic/RISCVVTypes.def" 6874#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6875#include "clang/Basic/WebAssemblyReferenceTypes.def" 6876#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6877#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6878#include "clang/AST/BuiltinTypes.def" 6879 return false; 6880 6881 // We cannot lower out overload sets; they might validly be resolved 6882 // by the call machinery. 6883 case BuiltinType::Overload: 6884 return false; 6885 6886 // Unbridged casts in ARC can be handled in some call positions and 6887 // should be left in place. 6888 case BuiltinType::ARCUnbridgedCast: 6889 return false; 6890 6891 // Pseudo-objects should be converted as soon as possible. 6892 case BuiltinType::PseudoObject: 6893 return true; 6894 6895 // The debugger mode could theoretically but currently does not try 6896 // to resolve unknown-typed arguments based on known parameter types. 6897 case BuiltinType::UnknownAny: 6898 return true; 6899 6900 // These are always invalid as call arguments and should be reported. 6901 case BuiltinType::BoundMember: 6902 case BuiltinType::BuiltinFn: 6903 case BuiltinType::IncompleteMatrixIdx: 6904 case BuiltinType::OMPArraySection: 6905 case BuiltinType::OMPArrayShaping: 6906 case BuiltinType::OMPIterator: 6907 return true; 6908 6909 } 6910 llvm_unreachable("bad builtin type kind"); 6911} 6912 6913bool Sema::CheckArgsForPlaceholders(MultiExprArg args) { 6914 // Apply this processing to all the arguments at once instead of 6915 // dying at the first failure. 6916 bool hasInvalid = false; 6917 for (size_t i = 0, e = args.size(); i != e; i++) { 6918 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6919 ExprResult result = CheckPlaceholderExpr(args[i]); 6920 if (result.isInvalid()) hasInvalid = true; 6921 else args[i] = result.get(); 6922 } 6923 } 6924 return hasInvalid; 6925} 6926 6927/// If a builtin function has a pointer argument with no explicit address 6928/// space, then it should be able to accept a pointer to any address 6929/// space as input. In order to do this, we need to replace the 6930/// standard builtin declaration with one that uses the same address space 6931/// as the call. 6932/// 6933/// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6934/// it does not contain any pointer arguments without 6935/// an address space qualifer. Otherwise the rewritten 6936/// FunctionDecl is returned. 6937/// TODO: Handle pointer return types. 6938static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6939 FunctionDecl *FDecl, 6940 MultiExprArg ArgExprs) { 6941 6942 QualType DeclType = FDecl->getType(); 6943 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6944 6945 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6946 ArgExprs.size() < FT->getNumParams()) 6947 return nullptr; 6948 6949 bool NeedsNewDecl = false; 6950 unsigned i = 0; 6951 SmallVector<QualType, 8> OverloadParams; 6952 6953 for (QualType ParamType : FT->param_types()) { 6954 6955 // Convert array arguments to pointer to simplify type lookup. 6956 ExprResult ArgRes = 6957 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6958 if (ArgRes.isInvalid()) 6959 return nullptr; 6960 Expr *Arg = ArgRes.get(); 6961 QualType ArgType = Arg->getType(); 6962 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() || 6963 !ArgType->isPointerType() || 6964 !ArgType->getPointeeType().hasAddressSpace() || 6965 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) { 6966 OverloadParams.push_back(ParamType); 6967 continue; 6968 } 6969 6970 QualType PointeeType = ParamType->getPointeeType(); 6971 if (PointeeType.hasAddressSpace()) 6972 continue; 6973 6974 NeedsNewDecl = true; 6975 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6976 6977 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6978 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6979 } 6980 6981 if (!NeedsNewDecl) 6982 return nullptr; 6983 6984 FunctionProtoType::ExtProtoInfo EPI; 6985 EPI.Variadic = FT->isVariadic(); 6986 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6987 OverloadParams, EPI); 6988 DeclContext *Parent = FDecl->getParent(); 6989 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6990 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6991 FDecl->getIdentifier(), OverloadTy, 6992 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6993 false, 6994 /*hasPrototype=*/true); 6995 SmallVector<ParmVarDecl*, 16> Params; 6996 FT = cast<FunctionProtoType>(OverloadTy); 6997 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6998 QualType ParamType = FT->getParamType(i); 6999 ParmVarDecl *Parm = 7000 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 7001 SourceLocation(), nullptr, ParamType, 7002 /*TInfo=*/nullptr, SC_None, nullptr); 7003 Parm->setScopeInfo(0, i); 7004 Params.push_back(Parm); 7005 } 7006 OverloadDecl->setParams(Params); 7007 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 7008 return OverloadDecl; 7009} 7010 7011static void checkDirectCallValidity(Sema &S, const Expr *Fn, 7012 FunctionDecl *Callee, 7013 MultiExprArg ArgExprs) { 7014 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 7015 // similar attributes) really don't like it when functions are called with an 7016 // invalid number of args. 7017 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 7018 /*PartialOverloading=*/false) && 7019 !Callee->isVariadic()) 7020 return; 7021 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 7022 return; 7023 7024 if (const EnableIfAttr *Attr = 7025 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 7026 S.Diag(Fn->getBeginLoc(), 7027 isa<CXXMethodDecl>(Callee) 7028 ? diag::err_ovl_no_viable_member_function_in_call 7029 : diag::err_ovl_no_viable_function_in_call) 7030 << Callee << Callee->getSourceRange(); 7031 S.Diag(Callee->getLocation(), 7032 diag::note_ovl_candidate_disabled_by_function_cond_attr) 7033 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 7034 return; 7035 } 7036} 7037 7038static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 7039 const UnresolvedMemberExpr *const UME, Sema &S) { 7040 7041 const auto GetFunctionLevelDCIfCXXClass = 7042 [](Sema &S) -> const CXXRecordDecl * { 7043 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 7044 if (!DC || !DC->getParent()) 7045 return nullptr; 7046 7047 // If the call to some member function was made from within a member 7048 // function body 'M' return return 'M's parent. 7049 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 7050 return MD->getParent()->getCanonicalDecl(); 7051 // else the call was made from within a default member initializer of a 7052 // class, so return the class. 7053 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 7054 return RD->getCanonicalDecl(); 7055 return nullptr; 7056 }; 7057 // If our DeclContext is neither a member function nor a class (in the 7058 // case of a lambda in a default member initializer), we can't have an 7059 // enclosing 'this'. 7060 7061 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 7062 if (!CurParentClass) 7063 return false; 7064 7065 // The naming class for implicit member functions call is the class in which 7066 // name lookup starts. 7067 const CXXRecordDecl *const NamingClass = 7068 UME->getNamingClass()->getCanonicalDecl(); 7069 assert(NamingClass && "Must have naming class even for implicit access"); 7070 7071 // If the unresolved member functions were found in a 'naming class' that is 7072 // related (either the same or derived from) to the class that contains the 7073 // member function that itself contained the implicit member access. 7074 7075 return CurParentClass == NamingClass || 7076 CurParentClass->isDerivedFrom(NamingClass); 7077} 7078 7079static void 7080tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 7081 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 7082 7083 if (!UME) 7084 return; 7085 7086 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 7087 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 7088 // already been captured, or if this is an implicit member function call (if 7089 // it isn't, an attempt to capture 'this' should already have been made). 7090 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 7091 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 7092 return; 7093 7094 // Check if the naming class in which the unresolved members were found is 7095 // related (same as or is a base of) to the enclosing class. 7096 7097 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 7098 return; 7099 7100 7101 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 7102 // If the enclosing function is not dependent, then this lambda is 7103 // capture ready, so if we can capture this, do so. 7104 if (!EnclosingFunctionCtx->isDependentContext()) { 7105 // If the current lambda and all enclosing lambdas can capture 'this' - 7106 // then go ahead and capture 'this' (since our unresolved overload set 7107 // contains at least one non-static member function). 7108 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 7109 S.CheckCXXThisCapture(CallLoc); 7110 } else if (S.CurContext->isDependentContext()) { 7111 // ... since this is an implicit member reference, that might potentially 7112 // involve a 'this' capture, mark 'this' for potential capture in 7113 // enclosing lambdas. 7114 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 7115 CurLSI->addPotentialThisCapture(CallLoc); 7116 } 7117} 7118 7119// Once a call is fully resolved, warn for unqualified calls to specific 7120// C++ standard functions, like move and forward. 7121static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, 7122 const CallExpr *Call) { 7123 // We are only checking unary move and forward so exit early here. 7124 if (Call->getNumArgs() != 1) 7125 return; 7126 7127 const Expr *E = Call->getCallee()->IgnoreParenImpCasts(); 7128 if (!E || isa<UnresolvedLookupExpr>(E)) 7129 return; 7130 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E); 7131 if (!DRE || !DRE->getLocation().isValid()) 7132 return; 7133 7134 if (DRE->getQualifier()) 7135 return; 7136 7137 const FunctionDecl *FD = Call->getDirectCallee(); 7138 if (!FD) 7139 return; 7140 7141 // Only warn for some functions deemed more frequent or problematic. 7142 unsigned BuiltinID = FD->getBuiltinID(); 7143 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward) 7144 return; 7145 7146 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function) 7147 << FD->getQualifiedNameAsString() 7148 << FixItHint::CreateInsertion(DRE->getLocation(), "std::"); 7149} 7150 7151ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 7152 MultiExprArg ArgExprs, SourceLocation RParenLoc, 7153 Expr *ExecConfig) { 7154 ExprResult Call = 7155 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 7156 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 7157 if (Call.isInvalid()) 7158 return Call; 7159 7160 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 7161 // language modes. 7162 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn); 7163 ULE && ULE->hasExplicitTemplateArgs() && 7164 ULE->decls_begin() == ULE->decls_end()) { 7165 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 7166 ? diag::warn_cxx17_compat_adl_only_template_id 7167 : diag::ext_adl_only_template_id) 7168 << ULE->getName(); 7169 } 7170 7171 if (LangOpts.OpenMP) 7172 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 7173 ExecConfig); 7174 if (LangOpts.CPlusPlus) { 7175 if (const auto *CE = dyn_cast<CallExpr>(Call.get())) 7176 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE); 7177 } 7178 return Call; 7179} 7180 7181/// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 7182/// This provides the location of the left/right parens and a list of comma 7183/// locations. 7184ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 7185 MultiExprArg ArgExprs, SourceLocation RParenLoc, 7186 Expr *ExecConfig, bool IsExecConfig, 7187 bool AllowRecovery) { 7188 // Since this might be a postfix expression, get rid of ParenListExprs. 7189 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 7190 if (Result.isInvalid()) return ExprError(); 7191 Fn = Result.get(); 7192 7193 if (CheckArgsForPlaceholders(ArgExprs)) 7194 return ExprError(); 7195 7196 if (getLangOpts().CPlusPlus) { 7197 // If this is a pseudo-destructor expression, build the call immediately. 7198 if (isa<CXXPseudoDestructorExpr>(Fn)) { 7199 if (!ArgExprs.empty()) { 7200 // Pseudo-destructor calls should not have any arguments. 7201 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 7202 << FixItHint::CreateRemoval( 7203 SourceRange(ArgExprs.front()->getBeginLoc(), 7204 ArgExprs.back()->getEndLoc())); 7205 } 7206 7207 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 7208 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 7209 } 7210 if (Fn->getType() == Context.PseudoObjectTy) { 7211 ExprResult result = CheckPlaceholderExpr(Fn); 7212 if (result.isInvalid()) return ExprError(); 7213 Fn = result.get(); 7214 } 7215 7216 // Determine whether this is a dependent call inside a C++ template, 7217 // in which case we won't do any semantic analysis now. 7218 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 7219 if (ExecConfig) { 7220 return CUDAKernelCallExpr::Create(Context, Fn, 7221 cast<CallExpr>(ExecConfig), ArgExprs, 7222 Context.DependentTy, VK_PRValue, 7223 RParenLoc, CurFPFeatureOverrides()); 7224 } else { 7225 7226 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 7227 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 7228 Fn->getBeginLoc()); 7229 7230 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 7231 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 7232 } 7233 } 7234 7235 // Determine whether this is a call to an object (C++ [over.call.object]). 7236 if (Fn->getType()->isRecordType()) 7237 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 7238 RParenLoc); 7239 7240 if (Fn->getType() == Context.UnknownAnyTy) { 7241 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 7242 if (result.isInvalid()) return ExprError(); 7243 Fn = result.get(); 7244 } 7245 7246 if (Fn->getType() == Context.BoundMemberTy) { 7247 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 7248 RParenLoc, ExecConfig, IsExecConfig, 7249 AllowRecovery); 7250 } 7251 } 7252 7253 // Check for overloaded calls. This can happen even in C due to extensions. 7254 if (Fn->getType() == Context.OverloadTy) { 7255 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 7256 7257 // We aren't supposed to apply this logic if there's an '&' involved. 7258 if (!find.HasFormOfMemberPointer) { 7259 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 7260 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 7261 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 7262 OverloadExpr *ovl = find.Expression; 7263 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 7264 return BuildOverloadedCallExpr( 7265 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 7266 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 7267 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 7268 RParenLoc, ExecConfig, IsExecConfig, 7269 AllowRecovery); 7270 } 7271 } 7272 7273 // If we're directly calling a function, get the appropriate declaration. 7274 if (Fn->getType() == Context.UnknownAnyTy) { 7275 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 7276 if (result.isInvalid()) return ExprError(); 7277 Fn = result.get(); 7278 } 7279 7280 Expr *NakedFn = Fn->IgnoreParens(); 7281 7282 bool CallingNDeclIndirectly = false; 7283 NamedDecl *NDecl = nullptr; 7284 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 7285 if (UnOp->getOpcode() == UO_AddrOf) { 7286 CallingNDeclIndirectly = true; 7287 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 7288 } 7289 } 7290 7291 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 7292 NDecl = DRE->getDecl(); 7293 7294 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 7295 if (FDecl && FDecl->getBuiltinID()) { 7296 // Rewrite the function decl for this builtin by replacing parameters 7297 // with no explicit address space with the address space of the arguments 7298 // in ArgExprs. 7299 if ((FDecl = 7300 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 7301 NDecl = FDecl; 7302 Fn = DeclRefExpr::Create( 7303 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 7304 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 7305 nullptr, DRE->isNonOdrUse()); 7306 } 7307 } 7308 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn)) 7309 NDecl = ME->getMemberDecl(); 7310 7311 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 7312 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 7313 FD, /*Complain=*/true, Fn->getBeginLoc())) 7314 return ExprError(); 7315 7316 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 7317 7318 // If this expression is a call to a builtin function in HIP device 7319 // compilation, allow a pointer-type argument to default address space to be 7320 // passed as a pointer-type parameter to a non-default address space. 7321 // If Arg is declared in the default address space and Param is declared 7322 // in a non-default address space, perform an implicit address space cast to 7323 // the parameter type. 7324 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 7325 FD->getBuiltinID()) { 7326 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 7327 ParmVarDecl *Param = FD->getParamDecl(Idx); 7328 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 7329 !ArgExprs[Idx]->getType()->isPointerType()) 7330 continue; 7331 7332 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 7333 auto ArgTy = ArgExprs[Idx]->getType(); 7334 auto ArgPtTy = ArgTy->getPointeeType(); 7335 auto ArgAS = ArgPtTy.getAddressSpace(); 7336 7337 // Add address space cast if target address spaces are different 7338 bool NeedImplicitASC = 7339 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 7340 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 7341 // or from specific AS which has target AS matching that of Param. 7342 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 7343 if (!NeedImplicitASC) 7344 continue; 7345 7346 // First, ensure that the Arg is an RValue. 7347 if (ArgExprs[Idx]->isGLValue()) { 7348 ArgExprs[Idx] = ImplicitCastExpr::Create( 7349 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 7350 nullptr, VK_PRValue, FPOptionsOverride()); 7351 } 7352 7353 // Construct a new arg type with address space of Param 7354 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 7355 ArgPtQuals.setAddressSpace(ParamAS); 7356 auto NewArgPtTy = 7357 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 7358 auto NewArgTy = 7359 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 7360 ArgTy.getQualifiers()); 7361 7362 // Finally perform an implicit address space cast 7363 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 7364 CK_AddressSpaceConversion) 7365 .get(); 7366 } 7367 } 7368 } 7369 7370 if (Context.isDependenceAllowed() && 7371 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 7372 assert(!getLangOpts().CPlusPlus); 7373 assert((Fn->containsErrors() || 7374 llvm::any_of(ArgExprs, 7375 [](clang::Expr *E) { return E->containsErrors(); })) && 7376 "should only occur in error-recovery path."); 7377 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 7378 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 7379 } 7380 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 7381 ExecConfig, IsExecConfig); 7382} 7383 7384/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 7385// with the specified CallArgs 7386Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 7387 MultiExprArg CallArgs) { 7388 StringRef Name = Context.BuiltinInfo.getName(Id); 7389 LookupResult R(*this, &Context.Idents.get(Name), Loc, 7390 Sema::LookupOrdinaryName); 7391 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 7392 7393 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 7394 assert(BuiltInDecl && "failed to find builtin declaration"); 7395 7396 ExprResult DeclRef = 7397 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 7398 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 7399 7400 ExprResult Call = 7401 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 7402 7403 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 7404 return Call.get(); 7405} 7406 7407/// Parse a __builtin_astype expression. 7408/// 7409/// __builtin_astype( value, dst type ) 7410/// 7411ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 7412 SourceLocation BuiltinLoc, 7413 SourceLocation RParenLoc) { 7414 QualType DstTy = GetTypeFromParser(ParsedDestTy); 7415 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 7416} 7417 7418/// Create a new AsTypeExpr node (bitcast) from the arguments. 7419ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 7420 SourceLocation BuiltinLoc, 7421 SourceLocation RParenLoc) { 7422 ExprValueKind VK = VK_PRValue; 7423 ExprObjectKind OK = OK_Ordinary; 7424 QualType SrcTy = E->getType(); 7425 if (!SrcTy->isDependentType() && 7426 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 7427 return ExprError( 7428 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 7429 << DestTy << SrcTy << E->getSourceRange()); 7430 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 7431} 7432 7433/// ActOnConvertVectorExpr - create a new convert-vector expression from the 7434/// provided arguments. 7435/// 7436/// __builtin_convertvector( value, dst type ) 7437/// 7438ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 7439 SourceLocation BuiltinLoc, 7440 SourceLocation RParenLoc) { 7441 TypeSourceInfo *TInfo; 7442 GetTypeFromParser(ParsedDestTy, &TInfo); 7443 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 7444} 7445 7446/// BuildResolvedCallExpr - Build a call to a resolved expression, 7447/// i.e. an expression not of \p OverloadTy. The expression should 7448/// unary-convert to an expression of function-pointer or 7449/// block-pointer type. 7450/// 7451/// \param NDecl the declaration being called, if available 7452ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 7453 SourceLocation LParenLoc, 7454 ArrayRef<Expr *> Args, 7455 SourceLocation RParenLoc, Expr *Config, 7456 bool IsExecConfig, ADLCallKind UsesADL) { 7457 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 7458 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 7459 7460 // Functions with 'interrupt' attribute cannot be called directly. 7461 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 7462 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 7463 return ExprError(); 7464 } 7465 7466 // Interrupt handlers don't save off the VFP regs automatically on ARM, 7467 // so there's some risk when calling out to non-interrupt handler functions 7468 // that the callee might not preserve them. This is easy to diagnose here, 7469 // but can be very challenging to debug. 7470 // Likewise, X86 interrupt handlers may only call routines with attribute 7471 // no_caller_saved_registers since there is no efficient way to 7472 // save and restore the non-GPR state. 7473 if (auto *Caller = getCurFunctionDecl()) { 7474 if (Caller->hasAttr<ARMInterruptAttr>()) { 7475 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 7476 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 7477 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 7478 if (FDecl) 7479 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 7480 } 7481 } 7482 if (Caller->hasAttr<AnyX86InterruptAttr>() || 7483 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) { 7484 const TargetInfo &TI = Context.getTargetInfo(); 7485 bool HasNonGPRRegisters = 7486 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx"); 7487 if (HasNonGPRRegisters && 7488 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) { 7489 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave) 7490 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1); 7491 if (FDecl) 7492 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 7493 } 7494 } 7495 } 7496 7497 // Promote the function operand. 7498 // We special-case function promotion here because we only allow promoting 7499 // builtin functions to function pointers in the callee of a call. 7500 ExprResult Result; 7501 QualType ResultTy; 7502 if (BuiltinID && 7503 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 7504 // Extract the return type from the (builtin) function pointer type. 7505 // FIXME Several builtins still have setType in 7506 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 7507 // Builtins.def to ensure they are correct before removing setType calls. 7508 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 7509 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 7510 ResultTy = FDecl->getCallResultType(); 7511 } else { 7512 Result = CallExprUnaryConversions(Fn); 7513 ResultTy = Context.BoolTy; 7514 } 7515 if (Result.isInvalid()) 7516 return ExprError(); 7517 Fn = Result.get(); 7518 7519 // Check for a valid function type, but only if it is not a builtin which 7520 // requires custom type checking. These will be handled by 7521 // CheckBuiltinFunctionCall below just after creation of the call expression. 7522 const FunctionType *FuncT = nullptr; 7523 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 7524 retry: 7525 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 7526 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 7527 // have type pointer to function". 7528 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 7529 if (!FuncT) 7530 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 7531 << Fn->getType() << Fn->getSourceRange()); 7532 } else if (const BlockPointerType *BPT = 7533 Fn->getType()->getAs<BlockPointerType>()) { 7534 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 7535 } else { 7536 // Handle calls to expressions of unknown-any type. 7537 if (Fn->getType() == Context.UnknownAnyTy) { 7538 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 7539 if (rewrite.isInvalid()) 7540 return ExprError(); 7541 Fn = rewrite.get(); 7542 goto retry; 7543 } 7544 7545 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 7546 << Fn->getType() << Fn->getSourceRange()); 7547 } 7548 } 7549 7550 // Get the number of parameters in the function prototype, if any. 7551 // We will allocate space for max(Args.size(), NumParams) arguments 7552 // in the call expression. 7553 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 7554 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 7555 7556 CallExpr *TheCall; 7557 if (Config) { 7558 assert(UsesADL == ADLCallKind::NotADL && 7559 "CUDAKernelCallExpr should not use ADL"); 7560 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 7561 Args, ResultTy, VK_PRValue, RParenLoc, 7562 CurFPFeatureOverrides(), NumParams); 7563 } else { 7564 TheCall = 7565 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 7566 CurFPFeatureOverrides(), NumParams, UsesADL); 7567 } 7568 7569 if (!Context.isDependenceAllowed()) { 7570 // Forget about the nulled arguments since typo correction 7571 // do not handle them well. 7572 TheCall->shrinkNumArgs(Args.size()); 7573 // C cannot always handle TypoExpr nodes in builtin calls and direct 7574 // function calls as their argument checking don't necessarily handle 7575 // dependent types properly, so make sure any TypoExprs have been 7576 // dealt with. 7577 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 7578 if (!Result.isUsable()) return ExprError(); 7579 CallExpr *TheOldCall = TheCall; 7580 TheCall = dyn_cast<CallExpr>(Result.get()); 7581 bool CorrectedTypos = TheCall != TheOldCall; 7582 if (!TheCall) return Result; 7583 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 7584 7585 // A new call expression node was created if some typos were corrected. 7586 // However it may not have been constructed with enough storage. In this 7587 // case, rebuild the node with enough storage. The waste of space is 7588 // immaterial since this only happens when some typos were corrected. 7589 if (CorrectedTypos && Args.size() < NumParams) { 7590 if (Config) 7591 TheCall = CUDAKernelCallExpr::Create( 7592 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 7593 RParenLoc, CurFPFeatureOverrides(), NumParams); 7594 else 7595 TheCall = 7596 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 7597 CurFPFeatureOverrides(), NumParams, UsesADL); 7598 } 7599 // We can now handle the nulled arguments for the default arguments. 7600 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 7601 } 7602 7603 // Bail out early if calling a builtin with custom type checking. 7604 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 7605 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7606 7607 if (getLangOpts().CUDA) { 7608 if (Config) { 7609 // CUDA: Kernel calls must be to global functions 7610 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 7611 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 7612 << FDecl << Fn->getSourceRange()); 7613 7614 // CUDA: Kernel function must have 'void' return type 7615 if (!FuncT->getReturnType()->isVoidType() && 7616 !FuncT->getReturnType()->getAs<AutoType>() && 7617 !FuncT->getReturnType()->isInstantiationDependentType()) 7618 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 7619 << Fn->getType() << Fn->getSourceRange()); 7620 } else { 7621 // CUDA: Calls to global functions must be configured 7622 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 7623 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 7624 << FDecl << Fn->getSourceRange()); 7625 } 7626 } 7627 7628 // Check for a valid return type 7629 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 7630 FDecl)) 7631 return ExprError(); 7632 7633 // We know the result type of the call, set it. 7634 TheCall->setType(FuncT->getCallResultType(Context)); 7635 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 7636 7637 // WebAssembly tables can't be used as arguments. 7638 if (Context.getTargetInfo().getTriple().isWasm()) { 7639 for (const Expr *Arg : Args) { 7640 if (Arg && Arg->getType()->isWebAssemblyTableType()) { 7641 return ExprError(Diag(Arg->getExprLoc(), 7642 diag::err_wasm_table_as_function_parameter)); 7643 } 7644 } 7645 } 7646 7647 if (Proto) { 7648 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 7649 IsExecConfig)) 7650 return ExprError(); 7651 } else { 7652 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 7653 7654 if (FDecl) { 7655 // Check if we have too few/too many template arguments, based 7656 // on our knowledge of the function definition. 7657 const FunctionDecl *Def = nullptr; 7658 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 7659 Proto = Def->getType()->getAs<FunctionProtoType>(); 7660 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 7661 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 7662 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 7663 } 7664 7665 // If the function we're calling isn't a function prototype, but we have 7666 // a function prototype from a prior declaratiom, use that prototype. 7667 if (!FDecl->hasPrototype()) 7668 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 7669 } 7670 7671 // If we still haven't found a prototype to use but there are arguments to 7672 // the call, diagnose this as calling a function without a prototype. 7673 // However, if we found a function declaration, check to see if 7674 // -Wdeprecated-non-prototype was disabled where the function was declared. 7675 // If so, we will silence the diagnostic here on the assumption that this 7676 // interface is intentional and the user knows what they're doing. We will 7677 // also silence the diagnostic if there is a function declaration but it 7678 // was implicitly defined (the user already gets diagnostics about the 7679 // creation of the implicit function declaration, so the additional warning 7680 // is not helpful). 7681 if (!Proto && !Args.empty() && 7682 (!FDecl || (!FDecl->isImplicit() && 7683 !Diags.isIgnored(diag::warn_strict_uses_without_prototype, 7684 FDecl->getLocation())))) 7685 Diag(LParenLoc, diag::warn_strict_uses_without_prototype) 7686 << (FDecl != nullptr) << FDecl; 7687 7688 // Promote the arguments (C99 6.5.2.2p6). 7689 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7690 Expr *Arg = Args[i]; 7691 7692 if (Proto && i < Proto->getNumParams()) { 7693 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7694 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 7695 ExprResult ArgE = 7696 PerformCopyInitialization(Entity, SourceLocation(), Arg); 7697 if (ArgE.isInvalid()) 7698 return true; 7699 7700 Arg = ArgE.getAs<Expr>(); 7701 7702 } else { 7703 ExprResult ArgE = DefaultArgumentPromotion(Arg); 7704 7705 if (ArgE.isInvalid()) 7706 return true; 7707 7708 Arg = ArgE.getAs<Expr>(); 7709 } 7710 7711 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 7712 diag::err_call_incomplete_argument, Arg)) 7713 return ExprError(); 7714 7715 TheCall->setArg(i, Arg); 7716 } 7717 TheCall->computeDependence(); 7718 } 7719 7720 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 7721 if (Method->isImplicitObjectMemberFunction()) 7722 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 7723 << Fn->getSourceRange() << 0); 7724 7725 // Check for sentinels 7726 if (NDecl) 7727 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 7728 7729 // Warn for unions passing across security boundary (CMSE). 7730 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 7731 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7732 if (const auto *RT = 7733 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 7734 if (RT->getDecl()->isOrContainsUnion()) 7735 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 7736 << 0 << i; 7737 } 7738 } 7739 } 7740 7741 // Do special checking on direct calls to functions. 7742 if (FDecl) { 7743 if (CheckFunctionCall(FDecl, TheCall, Proto)) 7744 return ExprError(); 7745 7746 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 7747 7748 if (BuiltinID) 7749 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7750 } else if (NDecl) { 7751 if (CheckPointerCall(NDecl, TheCall, Proto)) 7752 return ExprError(); 7753 } else { 7754 if (CheckOtherCall(TheCall, Proto)) 7755 return ExprError(); 7756 } 7757 7758 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 7759} 7760 7761ExprResult 7762Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 7763 SourceLocation RParenLoc, Expr *InitExpr) { 7764 assert(Ty && "ActOnCompoundLiteral(): missing type"); 7765 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 7766 7767 TypeSourceInfo *TInfo; 7768 QualType literalType = GetTypeFromParser(Ty, &TInfo); 7769 if (!TInfo) 7770 TInfo = Context.getTrivialTypeSourceInfo(literalType); 7771 7772 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 7773} 7774 7775ExprResult 7776Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 7777 SourceLocation RParenLoc, Expr *LiteralExpr) { 7778 QualType literalType = TInfo->getType(); 7779 7780 if (literalType->isArrayType()) { 7781 if (RequireCompleteSizedType( 7782 LParenLoc, Context.getBaseElementType(literalType), 7783 diag::err_array_incomplete_or_sizeless_type, 7784 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7785 return ExprError(); 7786 if (literalType->isVariableArrayType()) { 7787 // C23 6.7.10p4: An entity of variable length array type shall not be 7788 // initialized except by an empty initializer. 7789 // 7790 // The C extension warnings are issued from ParseBraceInitializer() and 7791 // do not need to be issued here. However, we continue to issue an error 7792 // in the case there are initializers or we are compiling C++. We allow 7793 // use of VLAs in C++, but it's not clear we want to allow {} to zero 7794 // init a VLA in C++ in all cases (such as with non-trivial constructors). 7795 // FIXME: should we allow this construct in C++ when it makes sense to do 7796 // so? 7797 std::optional<unsigned> NumInits; 7798 if (const auto *ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7799 NumInits = ILE->getNumInits(); 7800 if ((LangOpts.CPlusPlus || NumInits.value_or(0)) && 7801 !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 7802 diag::err_variable_object_no_init)) 7803 return ExprError(); 7804 } 7805 } else if (!literalType->isDependentType() && 7806 RequireCompleteType(LParenLoc, literalType, 7807 diag::err_typecheck_decl_incomplete_type, 7808 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7809 return ExprError(); 7810 7811 InitializedEntity Entity 7812 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 7813 InitializationKind Kind 7814 = InitializationKind::CreateCStyleCast(LParenLoc, 7815 SourceRange(LParenLoc, RParenLoc), 7816 /*InitList=*/true); 7817 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 7818 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 7819 &literalType); 7820 if (Result.isInvalid()) 7821 return ExprError(); 7822 LiteralExpr = Result.get(); 7823 7824 bool isFileScope = !CurContext->isFunctionOrMethod(); 7825 7826 // In C, compound literals are l-values for some reason. 7827 // For GCC compatibility, in C++, file-scope array compound literals with 7828 // constant initializers are also l-values, and compound literals are 7829 // otherwise prvalues. 7830 // 7831 // (GCC also treats C++ list-initialized file-scope array prvalues with 7832 // constant initializers as l-values, but that's non-conforming, so we don't 7833 // follow it there.) 7834 // 7835 // FIXME: It would be better to handle the lvalue cases as materializing and 7836 // lifetime-extending a temporary object, but our materialized temporaries 7837 // representation only supports lifetime extension from a variable, not "out 7838 // of thin air". 7839 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7840 // is bound to the result of applying array-to-pointer decay to the compound 7841 // literal. 7842 // FIXME: GCC supports compound literals of reference type, which should 7843 // obviously have a value kind derived from the kind of reference involved. 7844 ExprValueKind VK = 7845 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7846 ? VK_PRValue 7847 : VK_LValue; 7848 7849 if (isFileScope) 7850 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7851 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7852 Expr *Init = ILE->getInit(i); 7853 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7854 } 7855 7856 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7857 VK, LiteralExpr, isFileScope); 7858 if (isFileScope) { 7859 if (!LiteralExpr->isTypeDependent() && 7860 !LiteralExpr->isValueDependent() && 7861 !literalType->isDependentType()) // C99 6.5.2.5p3 7862 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7863 return ExprError(); 7864 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7865 literalType.getAddressSpace() != LangAS::Default) { 7866 // Embedded-C extensions to C99 6.5.2.5: 7867 // "If the compound literal occurs inside the body of a function, the 7868 // type name shall not be qualified by an address-space qualifier." 7869 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7870 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7871 return ExprError(); 7872 } 7873 7874 if (!isFileScope && !getLangOpts().CPlusPlus) { 7875 // Compound literals that have automatic storage duration are destroyed at 7876 // the end of the scope in C; in C++, they're just temporaries. 7877 7878 // Emit diagnostics if it is or contains a C union type that is non-trivial 7879 // to destruct. 7880 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7881 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7882 NTCUC_CompoundLiteral, NTCUK_Destruct); 7883 7884 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7885 if (literalType.isDestructedType()) { 7886 Cleanup.setExprNeedsCleanups(true); 7887 ExprCleanupObjects.push_back(E); 7888 getCurFunction()->setHasBranchProtectedScope(); 7889 } 7890 } 7891 7892 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7893 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7894 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7895 E->getInitializer()->getExprLoc()); 7896 7897 return MaybeBindToTemporary(E); 7898} 7899 7900ExprResult 7901Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7902 SourceLocation RBraceLoc) { 7903 // Only produce each kind of designated initialization diagnostic once. 7904 SourceLocation FirstDesignator; 7905 bool DiagnosedArrayDesignator = false; 7906 bool DiagnosedNestedDesignator = false; 7907 bool DiagnosedMixedDesignator = false; 7908 7909 // Check that any designated initializers are syntactically valid in the 7910 // current language mode. 7911 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7912 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7913 if (FirstDesignator.isInvalid()) 7914 FirstDesignator = DIE->getBeginLoc(); 7915 7916 if (!getLangOpts().CPlusPlus) 7917 break; 7918 7919 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7920 DiagnosedNestedDesignator = true; 7921 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7922 << DIE->getDesignatorsSourceRange(); 7923 } 7924 7925 for (auto &Desig : DIE->designators()) { 7926 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7927 DiagnosedArrayDesignator = true; 7928 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7929 << Desig.getSourceRange(); 7930 } 7931 } 7932 7933 if (!DiagnosedMixedDesignator && 7934 !isa<DesignatedInitExpr>(InitArgList[0])) { 7935 DiagnosedMixedDesignator = true; 7936 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7937 << DIE->getSourceRange(); 7938 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7939 << InitArgList[0]->getSourceRange(); 7940 } 7941 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7942 isa<DesignatedInitExpr>(InitArgList[0])) { 7943 DiagnosedMixedDesignator = true; 7944 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7945 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7946 << DIE->getSourceRange(); 7947 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7948 << InitArgList[I]->getSourceRange(); 7949 } 7950 } 7951 7952 if (FirstDesignator.isValid()) { 7953 // Only diagnose designated initiaization as a C++20 extension if we didn't 7954 // already diagnose use of (non-C++20) C99 designator syntax. 7955 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7956 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7957 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7958 ? diag::warn_cxx17_compat_designated_init 7959 : diag::ext_cxx_designated_init); 7960 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7961 Diag(FirstDesignator, diag::ext_designated_init); 7962 } 7963 } 7964 7965 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7966} 7967 7968ExprResult 7969Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7970 SourceLocation RBraceLoc) { 7971 // Semantic analysis for initializers is done by ActOnDeclarator() and 7972 // CheckInitializer() - it requires knowledge of the object being initialized. 7973 7974 // Immediately handle non-overload placeholders. Overloads can be 7975 // resolved contextually, but everything else here can't. 7976 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7977 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7978 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7979 7980 // Ignore failures; dropping the entire initializer list because 7981 // of one failure would be terrible for indexing/etc. 7982 if (result.isInvalid()) continue; 7983 7984 InitArgList[I] = result.get(); 7985 } 7986 } 7987 7988 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7989 RBraceLoc); 7990 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7991 return E; 7992} 7993 7994/// Do an explicit extend of the given block pointer if we're in ARC. 7995void Sema::maybeExtendBlockObject(ExprResult &E) { 7996 assert(E.get()->getType()->isBlockPointerType()); 7997 assert(E.get()->isPRValue()); 7998 7999 // Only do this in an r-value context. 8000 if (!getLangOpts().ObjCAutoRefCount) return; 8001 8002 E = ImplicitCastExpr::Create( 8003 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 8004 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 8005 Cleanup.setExprNeedsCleanups(true); 8006} 8007 8008/// Prepare a conversion of the given expression to an ObjC object 8009/// pointer type. 8010CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 8011 QualType type = E.get()->getType(); 8012 if (type->isObjCObjectPointerType()) { 8013 return CK_BitCast; 8014 } else if (type->isBlockPointerType()) { 8015 maybeExtendBlockObject(E); 8016 return CK_BlockPointerToObjCPointerCast; 8017 } else { 8018 assert(type->isPointerType()); 8019 return CK_CPointerToObjCPointerCast; 8020 } 8021} 8022 8023/// Prepares for a scalar cast, performing all the necessary stages 8024/// except the final cast and returning the kind required. 8025CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 8026 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 8027 // Also, callers should have filtered out the invalid cases with 8028 // pointers. Everything else should be possible. 8029 8030 QualType SrcTy = Src.get()->getType(); 8031 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 8032 return CK_NoOp; 8033 8034 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 8035 case Type::STK_MemberPointer: 8036 llvm_unreachable("member pointer type in C"); 8037 8038 case Type::STK_CPointer: 8039 case Type::STK_BlockPointer: 8040 case Type::STK_ObjCObjectPointer: 8041 switch (DestTy->getScalarTypeKind()) { 8042 case Type::STK_CPointer: { 8043 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 8044 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 8045 if (SrcAS != DestAS) 8046 return CK_AddressSpaceConversion; 8047 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 8048 return CK_NoOp; 8049 return CK_BitCast; 8050 } 8051 case Type::STK_BlockPointer: 8052 return (SrcKind == Type::STK_BlockPointer 8053 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 8054 case Type::STK_ObjCObjectPointer: 8055 if (SrcKind == Type::STK_ObjCObjectPointer) 8056 return CK_BitCast; 8057 if (SrcKind == Type::STK_CPointer) 8058 return CK_CPointerToObjCPointerCast; 8059 maybeExtendBlockObject(Src); 8060 return CK_BlockPointerToObjCPointerCast; 8061 case Type::STK_Bool: 8062 return CK_PointerToBoolean; 8063 case Type::STK_Integral: 8064 return CK_PointerToIntegral; 8065 case Type::STK_Floating: 8066 case Type::STK_FloatingComplex: 8067 case Type::STK_IntegralComplex: 8068 case Type::STK_MemberPointer: 8069 case Type::STK_FixedPoint: 8070 llvm_unreachable("illegal cast from pointer"); 8071 } 8072 llvm_unreachable("Should have returned before this"); 8073 8074 case Type::STK_FixedPoint: 8075 switch (DestTy->getScalarTypeKind()) { 8076 case Type::STK_FixedPoint: 8077 return CK_FixedPointCast; 8078 case Type::STK_Bool: 8079 return CK_FixedPointToBoolean; 8080 case Type::STK_Integral: 8081 return CK_FixedPointToIntegral; 8082 case Type::STK_Floating: 8083 return CK_FixedPointToFloating; 8084 case Type::STK_IntegralComplex: 8085 case Type::STK_FloatingComplex: 8086 Diag(Src.get()->getExprLoc(), 8087 diag::err_unimplemented_conversion_with_fixed_point_type) 8088 << DestTy; 8089 return CK_IntegralCast; 8090 case Type::STK_CPointer: 8091 case Type::STK_ObjCObjectPointer: 8092 case Type::STK_BlockPointer: 8093 case Type::STK_MemberPointer: 8094 llvm_unreachable("illegal cast to pointer type"); 8095 } 8096 llvm_unreachable("Should have returned before this"); 8097 8098 case Type::STK_Bool: // casting from bool is like casting from an integer 8099 case Type::STK_Integral: 8100 switch (DestTy->getScalarTypeKind()) { 8101 case Type::STK_CPointer: 8102 case Type::STK_ObjCObjectPointer: 8103 case Type::STK_BlockPointer: 8104 if (Src.get()->isNullPointerConstant(Context, 8105 Expr::NPC_ValueDependentIsNull)) 8106 return CK_NullToPointer; 8107 return CK_IntegralToPointer; 8108 case Type::STK_Bool: 8109 return CK_IntegralToBoolean; 8110 case Type::STK_Integral: 8111 return CK_IntegralCast; 8112 case Type::STK_Floating: 8113 return CK_IntegralToFloating; 8114 case Type::STK_IntegralComplex: 8115 Src = ImpCastExprToType(Src.get(), 8116 DestTy->castAs<ComplexType>()->getElementType(), 8117 CK_IntegralCast); 8118 return CK_IntegralRealToComplex; 8119 case Type::STK_FloatingComplex: 8120 Src = ImpCastExprToType(Src.get(), 8121 DestTy->castAs<ComplexType>()->getElementType(), 8122 CK_IntegralToFloating); 8123 return CK_FloatingRealToComplex; 8124 case Type::STK_MemberPointer: 8125 llvm_unreachable("member pointer type in C"); 8126 case Type::STK_FixedPoint: 8127 return CK_IntegralToFixedPoint; 8128 } 8129 llvm_unreachable("Should have returned before this"); 8130 8131 case Type::STK_Floating: 8132 switch (DestTy->getScalarTypeKind()) { 8133 case Type::STK_Floating: 8134 return CK_FloatingCast; 8135 case Type::STK_Bool: 8136 return CK_FloatingToBoolean; 8137 case Type::STK_Integral: 8138 return CK_FloatingToIntegral; 8139 case Type::STK_FloatingComplex: 8140 Src = ImpCastExprToType(Src.get(), 8141 DestTy->castAs<ComplexType>()->getElementType(), 8142 CK_FloatingCast); 8143 return CK_FloatingRealToComplex; 8144 case Type::STK_IntegralComplex: 8145 Src = ImpCastExprToType(Src.get(), 8146 DestTy->castAs<ComplexType>()->getElementType(), 8147 CK_FloatingToIntegral); 8148 return CK_IntegralRealToComplex; 8149 case Type::STK_CPointer: 8150 case Type::STK_ObjCObjectPointer: 8151 case Type::STK_BlockPointer: 8152 llvm_unreachable("valid float->pointer cast?"); 8153 case Type::STK_MemberPointer: 8154 llvm_unreachable("member pointer type in C"); 8155 case Type::STK_FixedPoint: 8156 return CK_FloatingToFixedPoint; 8157 } 8158 llvm_unreachable("Should have returned before this"); 8159 8160 case Type::STK_FloatingComplex: 8161 switch (DestTy->getScalarTypeKind()) { 8162 case Type::STK_FloatingComplex: 8163 return CK_FloatingComplexCast; 8164 case Type::STK_IntegralComplex: 8165 return CK_FloatingComplexToIntegralComplex; 8166 case Type::STK_Floating: { 8167 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 8168 if (Context.hasSameType(ET, DestTy)) 8169 return CK_FloatingComplexToReal; 8170 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 8171 return CK_FloatingCast; 8172 } 8173 case Type::STK_Bool: 8174 return CK_FloatingComplexToBoolean; 8175 case Type::STK_Integral: 8176 Src = ImpCastExprToType(Src.get(), 8177 SrcTy->castAs<ComplexType>()->getElementType(), 8178 CK_FloatingComplexToReal); 8179 return CK_FloatingToIntegral; 8180 case Type::STK_CPointer: 8181 case Type::STK_ObjCObjectPointer: 8182 case Type::STK_BlockPointer: 8183 llvm_unreachable("valid complex float->pointer cast?"); 8184 case Type::STK_MemberPointer: 8185 llvm_unreachable("member pointer type in C"); 8186 case Type::STK_FixedPoint: 8187 Diag(Src.get()->getExprLoc(), 8188 diag::err_unimplemented_conversion_with_fixed_point_type) 8189 << SrcTy; 8190 return CK_IntegralCast; 8191 } 8192 llvm_unreachable("Should have returned before this"); 8193 8194 case Type::STK_IntegralComplex: 8195 switch (DestTy->getScalarTypeKind()) { 8196 case Type::STK_FloatingComplex: 8197 return CK_IntegralComplexToFloatingComplex; 8198 case Type::STK_IntegralComplex: 8199 return CK_IntegralComplexCast; 8200 case Type::STK_Integral: { 8201 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 8202 if (Context.hasSameType(ET, DestTy)) 8203 return CK_IntegralComplexToReal; 8204 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 8205 return CK_IntegralCast; 8206 } 8207 case Type::STK_Bool: 8208 return CK_IntegralComplexToBoolean; 8209 case Type::STK_Floating: 8210 Src = ImpCastExprToType(Src.get(), 8211 SrcTy->castAs<ComplexType>()->getElementType(), 8212 CK_IntegralComplexToReal); 8213 return CK_IntegralToFloating; 8214 case Type::STK_CPointer: 8215 case Type::STK_ObjCObjectPointer: 8216 case Type::STK_BlockPointer: 8217 llvm_unreachable("valid complex int->pointer cast?"); 8218 case Type::STK_MemberPointer: 8219 llvm_unreachable("member pointer type in C"); 8220 case Type::STK_FixedPoint: 8221 Diag(Src.get()->getExprLoc(), 8222 diag::err_unimplemented_conversion_with_fixed_point_type) 8223 << SrcTy; 8224 return CK_IntegralCast; 8225 } 8226 llvm_unreachable("Should have returned before this"); 8227 } 8228 8229 llvm_unreachable("Unhandled scalar cast"); 8230} 8231 8232static bool breakDownVectorType(QualType type, uint64_t &len, 8233 QualType &eltType) { 8234 // Vectors are simple. 8235 if (const VectorType *vecType = type->getAs<VectorType>()) { 8236 len = vecType->getNumElements(); 8237 eltType = vecType->getElementType(); 8238 assert(eltType->isScalarType()); 8239 return true; 8240 } 8241 8242 // We allow lax conversion to and from non-vector types, but only if 8243 // they're real types (i.e. non-complex, non-pointer scalar types). 8244 if (!type->isRealType()) return false; 8245 8246 len = 1; 8247 eltType = type; 8248 return true; 8249} 8250 8251/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 8252/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 8253/// allowed? 8254/// 8255/// This will also return false if the two given types do not make sense from 8256/// the perspective of SVE bitcasts. 8257bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 8258 assert(srcTy->isVectorType() || destTy->isVectorType()); 8259 8260 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 8261 if (!FirstType->isSVESizelessBuiltinType()) 8262 return false; 8263 8264 const auto *VecTy = SecondType->getAs<VectorType>(); 8265 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData; 8266 }; 8267 8268 return ValidScalableConversion(srcTy, destTy) || 8269 ValidScalableConversion(destTy, srcTy); 8270} 8271 8272/// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the 8273/// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV 8274/// VLS type) allowed? 8275/// 8276/// This will also return false if the two given types do not make sense from 8277/// the perspective of RVV bitcasts. 8278bool Sema::isValidRVVBitcast(QualType srcTy, QualType destTy) { 8279 assert(srcTy->isVectorType() || destTy->isVectorType()); 8280 8281 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 8282 if (!FirstType->isRVVSizelessBuiltinType()) 8283 return false; 8284 8285 const auto *VecTy = SecondType->getAs<VectorType>(); 8286 return VecTy && VecTy->getVectorKind() == VectorKind::RVVFixedLengthData; 8287 }; 8288 8289 return ValidScalableConversion(srcTy, destTy) || 8290 ValidScalableConversion(destTy, srcTy); 8291} 8292 8293/// Are the two types matrix types and do they have the same dimensions i.e. 8294/// do they have the same number of rows and the same number of columns? 8295bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 8296 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 8297 return false; 8298 8299 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 8300 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 8301 8302 return matSrcType->getNumRows() == matDestType->getNumRows() && 8303 matSrcType->getNumColumns() == matDestType->getNumColumns(); 8304} 8305 8306bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 8307 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 8308 8309 uint64_t SrcLen, DestLen; 8310 QualType SrcEltTy, DestEltTy; 8311 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 8312 return false; 8313 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 8314 return false; 8315 8316 // ASTContext::getTypeSize will return the size rounded up to a 8317 // power of 2, so instead of using that, we need to use the raw 8318 // element size multiplied by the element count. 8319 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 8320 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 8321 8322 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 8323} 8324 8325// This returns true if at least one of the types is an altivec vector. 8326bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) { 8327 assert((DestTy->isVectorType() || SrcTy->isVectorType()) && 8328 "expected at least one type to be a vector here"); 8329 8330 bool IsSrcTyAltivec = 8331 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() == 8332 VectorKind::AltiVecVector) || 8333 (SrcTy->castAs<VectorType>()->getVectorKind() == 8334 VectorKind::AltiVecBool) || 8335 (SrcTy->castAs<VectorType>()->getVectorKind() == 8336 VectorKind::AltiVecPixel)); 8337 8338 bool IsDestTyAltivec = DestTy->isVectorType() && 8339 ((DestTy->castAs<VectorType>()->getVectorKind() == 8340 VectorKind::AltiVecVector) || 8341 (DestTy->castAs<VectorType>()->getVectorKind() == 8342 VectorKind::AltiVecBool) || 8343 (DestTy->castAs<VectorType>()->getVectorKind() == 8344 VectorKind::AltiVecPixel)); 8345 8346 return (IsSrcTyAltivec || IsDestTyAltivec); 8347} 8348 8349/// Are the two types lax-compatible vector types? That is, given 8350/// that one of them is a vector, do they have equal storage sizes, 8351/// where the storage size is the number of elements times the element 8352/// size? 8353/// 8354/// This will also return false if either of the types is neither a 8355/// vector nor a real type. 8356bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 8357 assert(destTy->isVectorType() || srcTy->isVectorType()); 8358 8359 // Disallow lax conversions between scalars and ExtVectors (these 8360 // conversions are allowed for other vector types because common headers 8361 // depend on them). Most scalar OP ExtVector cases are handled by the 8362 // splat path anyway, which does what we want (convert, not bitcast). 8363 // What this rules out for ExtVectors is crazy things like char4*float. 8364 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 8365 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 8366 8367 return areVectorTypesSameSize(srcTy, destTy); 8368} 8369 8370/// Is this a legal conversion between two types, one of which is 8371/// known to be a vector type? 8372bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 8373 assert(destTy->isVectorType() || srcTy->isVectorType()); 8374 8375 switch (Context.getLangOpts().getLaxVectorConversions()) { 8376 case LangOptions::LaxVectorConversionKind::None: 8377 return false; 8378 8379 case LangOptions::LaxVectorConversionKind::Integer: 8380 if (!srcTy->isIntegralOrEnumerationType()) { 8381 auto *Vec = srcTy->getAs<VectorType>(); 8382 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 8383 return false; 8384 } 8385 if (!destTy->isIntegralOrEnumerationType()) { 8386 auto *Vec = destTy->getAs<VectorType>(); 8387 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 8388 return false; 8389 } 8390 // OK, integer (vector) -> integer (vector) bitcast. 8391 break; 8392 8393 case LangOptions::LaxVectorConversionKind::All: 8394 break; 8395 } 8396 8397 return areLaxCompatibleVectorTypes(srcTy, destTy); 8398} 8399 8400bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 8401 CastKind &Kind) { 8402 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 8403 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 8404 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 8405 << DestTy << SrcTy << R; 8406 } 8407 } else if (SrcTy->isMatrixType()) { 8408 return Diag(R.getBegin(), 8409 diag::err_invalid_conversion_between_matrix_and_type) 8410 << SrcTy << DestTy << R; 8411 } else if (DestTy->isMatrixType()) { 8412 return Diag(R.getBegin(), 8413 diag::err_invalid_conversion_between_matrix_and_type) 8414 << DestTy << SrcTy << R; 8415 } 8416 8417 Kind = CK_MatrixCast; 8418 return false; 8419} 8420 8421bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 8422 CastKind &Kind) { 8423 assert(VectorTy->isVectorType() && "Not a vector type!"); 8424 8425 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 8426 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 8427 return Diag(R.getBegin(), 8428 Ty->isVectorType() ? 8429 diag::err_invalid_conversion_between_vectors : 8430 diag::err_invalid_conversion_between_vector_and_integer) 8431 << VectorTy << Ty << R; 8432 } else 8433 return Diag(R.getBegin(), 8434 diag::err_invalid_conversion_between_vector_and_scalar) 8435 << VectorTy << Ty << R; 8436 8437 Kind = CK_BitCast; 8438 return false; 8439} 8440 8441ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 8442 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 8443 8444 if (DestElemTy == SplattedExpr->getType()) 8445 return SplattedExpr; 8446 8447 assert(DestElemTy->isFloatingType() || 8448 DestElemTy->isIntegralOrEnumerationType()); 8449 8450 CastKind CK; 8451 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 8452 // OpenCL requires that we convert `true` boolean expressions to -1, but 8453 // only when splatting vectors. 8454 if (DestElemTy->isFloatingType()) { 8455 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 8456 // in two steps: boolean to signed integral, then to floating. 8457 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 8458 CK_BooleanToSignedIntegral); 8459 SplattedExpr = CastExprRes.get(); 8460 CK = CK_IntegralToFloating; 8461 } else { 8462 CK = CK_BooleanToSignedIntegral; 8463 } 8464 } else { 8465 ExprResult CastExprRes = SplattedExpr; 8466 CK = PrepareScalarCast(CastExprRes, DestElemTy); 8467 if (CastExprRes.isInvalid()) 8468 return ExprError(); 8469 SplattedExpr = CastExprRes.get(); 8470 } 8471 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 8472} 8473 8474ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 8475 Expr *CastExpr, CastKind &Kind) { 8476 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 8477 8478 QualType SrcTy = CastExpr->getType(); 8479 8480 // If SrcTy is a VectorType, the total size must match to explicitly cast to 8481 // an ExtVectorType. 8482 // In OpenCL, casts between vectors of different types are not allowed. 8483 // (See OpenCL 6.2). 8484 if (SrcTy->isVectorType()) { 8485 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 8486 (getLangOpts().OpenCL && 8487 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 8488 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 8489 << DestTy << SrcTy << R; 8490 return ExprError(); 8491 } 8492 Kind = CK_BitCast; 8493 return CastExpr; 8494 } 8495 8496 // All non-pointer scalars can be cast to ExtVector type. The appropriate 8497 // conversion will take place first from scalar to elt type, and then 8498 // splat from elt type to vector. 8499 if (SrcTy->isPointerType()) 8500 return Diag(R.getBegin(), 8501 diag::err_invalid_conversion_between_vector_and_scalar) 8502 << DestTy << SrcTy << R; 8503 8504 Kind = CK_VectorSplat; 8505 return prepareVectorSplat(DestTy, CastExpr); 8506} 8507 8508ExprResult 8509Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 8510 Declarator &D, ParsedType &Ty, 8511 SourceLocation RParenLoc, Expr *CastExpr) { 8512 assert(!D.isInvalidType() && (CastExpr != nullptr) && 8513 "ActOnCastExpr(): missing type or expr"); 8514 8515 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 8516 if (D.isInvalidType()) 8517 return ExprError(); 8518 8519 if (getLangOpts().CPlusPlus) { 8520 // Check that there are no default arguments (C++ only). 8521 CheckExtraCXXDefaultArguments(D); 8522 } else { 8523 // Make sure any TypoExprs have been dealt with. 8524 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 8525 if (!Res.isUsable()) 8526 return ExprError(); 8527 CastExpr = Res.get(); 8528 } 8529 8530 checkUnusedDeclAttributes(D); 8531 8532 QualType castType = castTInfo->getType(); 8533 Ty = CreateParsedType(castType, castTInfo); 8534 8535 bool isVectorLiteral = false; 8536 8537 // Check for an altivec or OpenCL literal, 8538 // i.e. all the elements are integer constants. 8539 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 8540 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 8541 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 8542 && castType->isVectorType() && (PE || PLE)) { 8543 if (PLE && PLE->getNumExprs() == 0) { 8544 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 8545 return ExprError(); 8546 } 8547 if (PE || PLE->getNumExprs() == 1) { 8548 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 8549 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 8550 isVectorLiteral = true; 8551 } 8552 else 8553 isVectorLiteral = true; 8554 } 8555 8556 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 8557 // then handle it as such. 8558 if (isVectorLiteral) 8559 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 8560 8561 // If the Expr being casted is a ParenListExpr, handle it specially. 8562 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 8563 // sequence of BinOp comma operators. 8564 if (isa<ParenListExpr>(CastExpr)) { 8565 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 8566 if (Result.isInvalid()) return ExprError(); 8567 CastExpr = Result.get(); 8568 } 8569 8570 if (getLangOpts().CPlusPlus && !castType->isVoidType()) 8571 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 8572 8573 CheckTollFreeBridgeCast(castType, CastExpr); 8574 8575 CheckObjCBridgeRelatedCast(castType, CastExpr); 8576 8577 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 8578 8579 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 8580} 8581 8582ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 8583 SourceLocation RParenLoc, Expr *E, 8584 TypeSourceInfo *TInfo) { 8585 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 8586 "Expected paren or paren list expression"); 8587 8588 Expr **exprs; 8589 unsigned numExprs; 8590 Expr *subExpr; 8591 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 8592 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 8593 LiteralLParenLoc = PE->getLParenLoc(); 8594 LiteralRParenLoc = PE->getRParenLoc(); 8595 exprs = PE->getExprs(); 8596 numExprs = PE->getNumExprs(); 8597 } else { // isa<ParenExpr> by assertion at function entrance 8598 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 8599 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 8600 subExpr = cast<ParenExpr>(E)->getSubExpr(); 8601 exprs = &subExpr; 8602 numExprs = 1; 8603 } 8604 8605 QualType Ty = TInfo->getType(); 8606 assert(Ty->isVectorType() && "Expected vector type"); 8607 8608 SmallVector<Expr *, 8> initExprs; 8609 const VectorType *VTy = Ty->castAs<VectorType>(); 8610 unsigned numElems = VTy->getNumElements(); 8611 8612 // '(...)' form of vector initialization in AltiVec: the number of 8613 // initializers must be one or must match the size of the vector. 8614 // If a single value is specified in the initializer then it will be 8615 // replicated to all the components of the vector 8616 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 8617 VTy->getElementType())) 8618 return ExprError(); 8619 if (ShouldSplatAltivecScalarInCast(VTy)) { 8620 // The number of initializers must be one or must match the size of the 8621 // vector. If a single value is specified in the initializer then it will 8622 // be replicated to all the components of the vector 8623 if (numExprs == 1) { 8624 QualType ElemTy = VTy->getElementType(); 8625 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 8626 if (Literal.isInvalid()) 8627 return ExprError(); 8628 Literal = ImpCastExprToType(Literal.get(), ElemTy, 8629 PrepareScalarCast(Literal, ElemTy)); 8630 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 8631 } 8632 else if (numExprs < numElems) { 8633 Diag(E->getExprLoc(), 8634 diag::err_incorrect_number_of_vector_initializers); 8635 return ExprError(); 8636 } 8637 else 8638 initExprs.append(exprs, exprs + numExprs); 8639 } 8640 else { 8641 // For OpenCL, when the number of initializers is a single value, 8642 // it will be replicated to all components of the vector. 8643 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic && 8644 numExprs == 1) { 8645 QualType ElemTy = VTy->getElementType(); 8646 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 8647 if (Literal.isInvalid()) 8648 return ExprError(); 8649 Literal = ImpCastExprToType(Literal.get(), ElemTy, 8650 PrepareScalarCast(Literal, ElemTy)); 8651 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 8652 } 8653 8654 initExprs.append(exprs, exprs + numExprs); 8655 } 8656 // FIXME: This means that pretty-printing the final AST will produce curly 8657 // braces instead of the original commas. 8658 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 8659 initExprs, LiteralRParenLoc); 8660 initE->setType(Ty); 8661 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 8662} 8663 8664/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 8665/// the ParenListExpr into a sequence of comma binary operators. 8666ExprResult 8667Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 8668 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 8669 if (!E) 8670 return OrigExpr; 8671 8672 ExprResult Result(E->getExpr(0)); 8673 8674 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 8675 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 8676 E->getExpr(i)); 8677 8678 if (Result.isInvalid()) return ExprError(); 8679 8680 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 8681} 8682 8683ExprResult Sema::ActOnParenListExpr(SourceLocation L, 8684 SourceLocation R, 8685 MultiExprArg Val) { 8686 return ParenListExpr::Create(Context, L, Val, R); 8687} 8688 8689/// Emit a specialized diagnostic when one expression is a null pointer 8690/// constant and the other is not a pointer. Returns true if a diagnostic is 8691/// emitted. 8692bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, 8693 SourceLocation QuestionLoc) { 8694 const Expr *NullExpr = LHSExpr; 8695 const Expr *NonPointerExpr = RHSExpr; 8696 Expr::NullPointerConstantKind NullKind = 8697 NullExpr->isNullPointerConstant(Context, 8698 Expr::NPC_ValueDependentIsNotNull); 8699 8700 if (NullKind == Expr::NPCK_NotNull) { 8701 NullExpr = RHSExpr; 8702 NonPointerExpr = LHSExpr; 8703 NullKind = 8704 NullExpr->isNullPointerConstant(Context, 8705 Expr::NPC_ValueDependentIsNotNull); 8706 } 8707 8708 if (NullKind == Expr::NPCK_NotNull) 8709 return false; 8710 8711 if (NullKind == Expr::NPCK_ZeroExpression) 8712 return false; 8713 8714 if (NullKind == Expr::NPCK_ZeroLiteral) { 8715 // In this case, check to make sure that we got here from a "NULL" 8716 // string in the source code. 8717 NullExpr = NullExpr->IgnoreParenImpCasts(); 8718 SourceLocation loc = NullExpr->getExprLoc(); 8719 if (!findMacroSpelling(loc, "NULL")) 8720 return false; 8721 } 8722 8723 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 8724 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 8725 << NonPointerExpr->getType() << DiagType 8726 << NonPointerExpr->getSourceRange(); 8727 return true; 8728} 8729 8730/// Return false if the condition expression is valid, true otherwise. 8731static bool checkCondition(Sema &S, const Expr *Cond, 8732 SourceLocation QuestionLoc) { 8733 QualType CondTy = Cond->getType(); 8734 8735 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 8736 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 8737 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8738 << CondTy << Cond->getSourceRange(); 8739 return true; 8740 } 8741 8742 // C99 6.5.15p2 8743 if (CondTy->isScalarType()) return false; 8744 8745 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 8746 << CondTy << Cond->getSourceRange(); 8747 return true; 8748} 8749 8750/// Return false if the NullExpr can be promoted to PointerTy, 8751/// true otherwise. 8752static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 8753 QualType PointerTy) { 8754 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 8755 !NullExpr.get()->isNullPointerConstant(S.Context, 8756 Expr::NPC_ValueDependentIsNull)) 8757 return true; 8758 8759 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 8760 return false; 8761} 8762 8763/// Checks compatibility between two pointers and return the resulting 8764/// type. 8765static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 8766 ExprResult &RHS, 8767 SourceLocation Loc) { 8768 QualType LHSTy = LHS.get()->getType(); 8769 QualType RHSTy = RHS.get()->getType(); 8770 8771 if (S.Context.hasSameType(LHSTy, RHSTy)) { 8772 // Two identical pointers types are always compatible. 8773 return S.Context.getCommonSugaredType(LHSTy, RHSTy); 8774 } 8775 8776 QualType lhptee, rhptee; 8777 8778 // Get the pointee types. 8779 bool IsBlockPointer = false; 8780 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 8781 lhptee = LHSBTy->getPointeeType(); 8782 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 8783 IsBlockPointer = true; 8784 } else { 8785 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8786 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8787 } 8788 8789 // C99 6.5.15p6: If both operands are pointers to compatible types or to 8790 // differently qualified versions of compatible types, the result type is 8791 // a pointer to an appropriately qualified version of the composite 8792 // type. 8793 8794 // Only CVR-qualifiers exist in the standard, and the differently-qualified 8795 // clause doesn't make sense for our extensions. E.g. address space 2 should 8796 // be incompatible with address space 3: they may live on different devices or 8797 // anything. 8798 Qualifiers lhQual = lhptee.getQualifiers(); 8799 Qualifiers rhQual = rhptee.getQualifiers(); 8800 8801 LangAS ResultAddrSpace = LangAS::Default; 8802 LangAS LAddrSpace = lhQual.getAddressSpace(); 8803 LangAS RAddrSpace = rhQual.getAddressSpace(); 8804 8805 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 8806 // spaces is disallowed. 8807 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 8808 ResultAddrSpace = LAddrSpace; 8809 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 8810 ResultAddrSpace = RAddrSpace; 8811 else { 8812 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8813 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 8814 << RHS.get()->getSourceRange(); 8815 return QualType(); 8816 } 8817 8818 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 8819 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 8820 lhQual.removeCVRQualifiers(); 8821 rhQual.removeCVRQualifiers(); 8822 8823 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 8824 // (C99 6.7.3) for address spaces. We assume that the check should behave in 8825 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 8826 // qual types are compatible iff 8827 // * corresponded types are compatible 8828 // * CVR qualifiers are equal 8829 // * address spaces are equal 8830 // Thus for conditional operator we merge CVR and address space unqualified 8831 // pointees and if there is a composite type we return a pointer to it with 8832 // merged qualifiers. 8833 LHSCastKind = 8834 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8835 RHSCastKind = 8836 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8837 lhQual.removeAddressSpace(); 8838 rhQual.removeAddressSpace(); 8839 8840 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 8841 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 8842 8843 QualType CompositeTy = S.Context.mergeTypes( 8844 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false, 8845 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true); 8846 8847 if (CompositeTy.isNull()) { 8848 // In this situation, we assume void* type. No especially good 8849 // reason, but this is what gcc does, and we do have to pick 8850 // to get a consistent AST. 8851 QualType incompatTy; 8852 incompatTy = S.Context.getPointerType( 8853 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 8854 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 8855 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 8856 8857 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 8858 // for casts between types with incompatible address space qualifiers. 8859 // For the following code the compiler produces casts between global and 8860 // local address spaces of the corresponded innermost pointees: 8861 // local int *global *a; 8862 // global int *global *b; 8863 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8864 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8865 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8866 << RHS.get()->getSourceRange(); 8867 8868 return incompatTy; 8869 } 8870 8871 // The pointer types are compatible. 8872 // In case of OpenCL ResultTy should have the address space qualifier 8873 // which is a superset of address spaces of both the 2nd and the 3rd 8874 // operands of the conditional operator. 8875 QualType ResultTy = [&, ResultAddrSpace]() { 8876 if (S.getLangOpts().OpenCL) { 8877 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8878 CompositeQuals.setAddressSpace(ResultAddrSpace); 8879 return S.Context 8880 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8881 .withCVRQualifiers(MergedCVRQual); 8882 } 8883 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8884 }(); 8885 if (IsBlockPointer) 8886 ResultTy = S.Context.getBlockPointerType(ResultTy); 8887 else 8888 ResultTy = S.Context.getPointerType(ResultTy); 8889 8890 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8891 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8892 return ResultTy; 8893} 8894 8895/// Return the resulting type when the operands are both block pointers. 8896static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8897 ExprResult &LHS, 8898 ExprResult &RHS, 8899 SourceLocation Loc) { 8900 QualType LHSTy = LHS.get()->getType(); 8901 QualType RHSTy = RHS.get()->getType(); 8902 8903 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8904 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8905 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8906 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8907 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8908 return destType; 8909 } 8910 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8911 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8912 << RHS.get()->getSourceRange(); 8913 return QualType(); 8914 } 8915 8916 // We have 2 block pointer types. 8917 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8918} 8919 8920/// Return the resulting type when the operands are both pointers. 8921static QualType 8922checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8923 ExprResult &RHS, 8924 SourceLocation Loc) { 8925 // get the pointer types 8926 QualType LHSTy = LHS.get()->getType(); 8927 QualType RHSTy = RHS.get()->getType(); 8928 8929 // get the "pointed to" types 8930 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8931 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8932 8933 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8934 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8935 // Figure out necessary qualifiers (C99 6.5.15p6) 8936 QualType destPointee 8937 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8938 QualType destType = S.Context.getPointerType(destPointee); 8939 // Add qualifiers if necessary. 8940 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8941 // Promote to void*. 8942 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8943 return destType; 8944 } 8945 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8946 QualType destPointee 8947 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8948 QualType destType = S.Context.getPointerType(destPointee); 8949 // Add qualifiers if necessary. 8950 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8951 // Promote to void*. 8952 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8953 return destType; 8954 } 8955 8956 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8957} 8958 8959/// Return false if the first expression is not an integer and the second 8960/// expression is not a pointer, true otherwise. 8961static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8962 Expr* PointerExpr, SourceLocation Loc, 8963 bool IsIntFirstExpr) { 8964 if (!PointerExpr->getType()->isPointerType() || 8965 !Int.get()->getType()->isIntegerType()) 8966 return false; 8967 8968 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8969 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8970 8971 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8972 << Expr1->getType() << Expr2->getType() 8973 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8974 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8975 CK_IntegralToPointer); 8976 return true; 8977} 8978 8979/// Simple conversion between integer and floating point types. 8980/// 8981/// Used when handling the OpenCL conditional operator where the 8982/// condition is a vector while the other operands are scalar. 8983/// 8984/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8985/// types are either integer or floating type. Between the two 8986/// operands, the type with the higher rank is defined as the "result 8987/// type". The other operand needs to be promoted to the same type. No 8988/// other type promotion is allowed. We cannot use 8989/// UsualArithmeticConversions() for this purpose, since it always 8990/// promotes promotable types. 8991static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8992 ExprResult &RHS, 8993 SourceLocation QuestionLoc) { 8994 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8995 if (LHS.isInvalid()) 8996 return QualType(); 8997 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8998 if (RHS.isInvalid()) 8999 return QualType(); 9000 9001 // For conversion purposes, we ignore any qualifiers. 9002 // For example, "const float" and "float" are equivalent. 9003 QualType LHSType = 9004 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 9005 QualType RHSType = 9006 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 9007 9008 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 9009 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 9010 << LHSType << LHS.get()->getSourceRange(); 9011 return QualType(); 9012 } 9013 9014 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 9015 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 9016 << RHSType << RHS.get()->getSourceRange(); 9017 return QualType(); 9018 } 9019 9020 // If both types are identical, no conversion is needed. 9021 if (LHSType == RHSType) 9022 return LHSType; 9023 9024 // Now handle "real" floating types (i.e. float, double, long double). 9025 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 9026 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 9027 /*IsCompAssign = */ false); 9028 9029 // Finally, we have two differing integer types. 9030 return handleIntegerConversion<doIntegralCast, doIntegralCast> 9031 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 9032} 9033 9034/// Convert scalar operands to a vector that matches the 9035/// condition in length. 9036/// 9037/// Used when handling the OpenCL conditional operator where the 9038/// condition is a vector while the other operands are scalar. 9039/// 9040/// We first compute the "result type" for the scalar operands 9041/// according to OpenCL v1.1 s6.3.i. Both operands are then converted 9042/// into a vector of that type where the length matches the condition 9043/// vector type. s6.11.6 requires that the element types of the result 9044/// and the condition must have the same number of bits. 9045static QualType 9046OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 9047 QualType CondTy, SourceLocation QuestionLoc) { 9048 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 9049 if (ResTy.isNull()) return QualType(); 9050 9051 const VectorType *CV = CondTy->getAs<VectorType>(); 9052 assert(CV); 9053 9054 // Determine the vector result type 9055 unsigned NumElements = CV->getNumElements(); 9056 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 9057 9058 // Ensure that all types have the same number of bits 9059 if (S.Context.getTypeSize(CV->getElementType()) 9060 != S.Context.getTypeSize(ResTy)) { 9061 // Since VectorTy is created internally, it does not pretty print 9062 // with an OpenCL name. Instead, we just print a description. 9063 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 9064 SmallString<64> Str; 9065 llvm::raw_svector_ostream OS(Str); 9066 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 9067 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 9068 << CondTy << OS.str(); 9069 return QualType(); 9070 } 9071 9072 // Convert operands to the vector result type 9073 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 9074 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 9075 9076 return VectorTy; 9077} 9078 9079/// Return false if this is a valid OpenCL condition vector 9080static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 9081 SourceLocation QuestionLoc) { 9082 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 9083 // integral type. 9084 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 9085 assert(CondTy); 9086 QualType EleTy = CondTy->getElementType(); 9087 if (EleTy->isIntegerType()) return false; 9088 9089 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 9090 << Cond->getType() << Cond->getSourceRange(); 9091 return true; 9092} 9093 9094/// Return false if the vector condition type and the vector 9095/// result type are compatible. 9096/// 9097/// OpenCL v1.1 s6.11.6 requires that both vector types have the same 9098/// number of elements, and their element types have the same number 9099/// of bits. 9100static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 9101 SourceLocation QuestionLoc) { 9102 const VectorType *CV = CondTy->getAs<VectorType>(); 9103 const VectorType *RV = VecResTy->getAs<VectorType>(); 9104 assert(CV && RV); 9105 9106 if (CV->getNumElements() != RV->getNumElements()) { 9107 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 9108 << CondTy << VecResTy; 9109 return true; 9110 } 9111 9112 QualType CVE = CV->getElementType(); 9113 QualType RVE = RV->getElementType(); 9114 9115 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 9116 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 9117 << CondTy << VecResTy; 9118 return true; 9119 } 9120 9121 return false; 9122} 9123 9124/// Return the resulting type for the conditional operator in 9125/// OpenCL (aka "ternary selection operator", OpenCL v1.1 9126/// s6.3.i) when the condition is a vector type. 9127static QualType 9128OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 9129 ExprResult &LHS, ExprResult &RHS, 9130 SourceLocation QuestionLoc) { 9131 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 9132 if (Cond.isInvalid()) 9133 return QualType(); 9134 QualType CondTy = Cond.get()->getType(); 9135 9136 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 9137 return QualType(); 9138 9139 // If either operand is a vector then find the vector type of the 9140 // result as specified in OpenCL v1.1 s6.3.i. 9141 if (LHS.get()->getType()->isVectorType() || 9142 RHS.get()->getType()->isVectorType()) { 9143 bool IsBoolVecLang = 9144 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; 9145 QualType VecResTy = 9146 S.CheckVectorOperands(LHS, RHS, QuestionLoc, 9147 /*isCompAssign*/ false, 9148 /*AllowBothBool*/ true, 9149 /*AllowBoolConversions*/ false, 9150 /*AllowBooleanOperation*/ IsBoolVecLang, 9151 /*ReportInvalid*/ true); 9152 if (VecResTy.isNull()) 9153 return QualType(); 9154 // The result type must match the condition type as specified in 9155 // OpenCL v1.1 s6.11.6. 9156 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 9157 return QualType(); 9158 return VecResTy; 9159 } 9160 9161 // Both operands are scalar. 9162 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 9163} 9164 9165/// Return true if the Expr is block type 9166static bool checkBlockType(Sema &S, const Expr *E) { 9167 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9168 QualType Ty = CE->getCallee()->getType(); 9169 if (Ty->isBlockPointerType()) { 9170 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 9171 return true; 9172 } 9173 } 9174 return false; 9175} 9176 9177/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 9178/// In that case, LHS = cond. 9179/// C99 6.5.15 9180QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 9181 ExprResult &RHS, ExprValueKind &VK, 9182 ExprObjectKind &OK, 9183 SourceLocation QuestionLoc) { 9184 9185 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 9186 if (!LHSResult.isUsable()) return QualType(); 9187 LHS = LHSResult; 9188 9189 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 9190 if (!RHSResult.isUsable()) return QualType(); 9191 RHS = RHSResult; 9192 9193 // C++ is sufficiently different to merit its own checker. 9194 if (getLangOpts().CPlusPlus) 9195 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 9196 9197 VK = VK_PRValue; 9198 OK = OK_Ordinary; 9199 9200 if (Context.isDependenceAllowed() && 9201 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 9202 RHS.get()->isTypeDependent())) { 9203 assert(!getLangOpts().CPlusPlus); 9204 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 9205 RHS.get()->containsErrors()) && 9206 "should only occur in error-recovery path."); 9207 return Context.DependentTy; 9208 } 9209 9210 // The OpenCL operator with a vector condition is sufficiently 9211 // different to merit its own checker. 9212 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 9213 Cond.get()->getType()->isExtVectorType()) 9214 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 9215 9216 // First, check the condition. 9217 Cond = UsualUnaryConversions(Cond.get()); 9218 if (Cond.isInvalid()) 9219 return QualType(); 9220 if (checkCondition(*this, Cond.get(), QuestionLoc)) 9221 return QualType(); 9222 9223 // Handle vectors. 9224 if (LHS.get()->getType()->isVectorType() || 9225 RHS.get()->getType()->isVectorType()) 9226 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, 9227 /*AllowBothBool*/ true, 9228 /*AllowBoolConversions*/ false, 9229 /*AllowBooleanOperation*/ false, 9230 /*ReportInvalid*/ true); 9231 9232 QualType ResTy = 9233 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 9234 if (LHS.isInvalid() || RHS.isInvalid()) 9235 return QualType(); 9236 9237 // WebAssembly tables are not allowed as conditional LHS or RHS. 9238 QualType LHSTy = LHS.get()->getType(); 9239 QualType RHSTy = RHS.get()->getType(); 9240 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) { 9241 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression) 9242 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9243 return QualType(); 9244 } 9245 9246 // Diagnose attempts to convert between __ibm128, __float128 and long double 9247 // where such conversions currently can't be handled. 9248 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 9249 Diag(QuestionLoc, 9250 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 9251 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9252 return QualType(); 9253 } 9254 9255 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 9256 // selection operator (?:). 9257 if (getLangOpts().OpenCL && 9258 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 9259 return QualType(); 9260 } 9261 9262 // If both operands have arithmetic type, do the usual arithmetic conversions 9263 // to find a common type: C99 6.5.15p3,5. 9264 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 9265 // Disallow invalid arithmetic conversions, such as those between bit- 9266 // precise integers types of different sizes, or between a bit-precise 9267 // integer and another type. 9268 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { 9269 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 9270 << LHSTy << RHSTy << LHS.get()->getSourceRange() 9271 << RHS.get()->getSourceRange(); 9272 return QualType(); 9273 } 9274 9275 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 9276 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 9277 9278 return ResTy; 9279 } 9280 9281 // If both operands are the same structure or union type, the result is that 9282 // type. 9283 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 9284 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 9285 if (LHSRT->getDecl() == RHSRT->getDecl()) 9286 // "If both the operands have structure or union type, the result has 9287 // that type." This implies that CV qualifiers are dropped. 9288 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(), 9289 RHSTy.getUnqualifiedType()); 9290 // FIXME: Type of conditional expression must be complete in C mode. 9291 } 9292 9293 // C99 6.5.15p5: "If both operands have void type, the result has void type." 9294 // The following || allows only one side to be void (a GCC-ism). 9295 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 9296 QualType ResTy; 9297 if (LHSTy->isVoidType() && RHSTy->isVoidType()) { 9298 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy); 9299 } else if (RHSTy->isVoidType()) { 9300 ResTy = RHSTy; 9301 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void) 9302 << RHS.get()->getSourceRange(); 9303 } else { 9304 ResTy = LHSTy; 9305 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void) 9306 << LHS.get()->getSourceRange(); 9307 } 9308 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid); 9309 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid); 9310 return ResTy; 9311 } 9312 9313 // C23 6.5.15p7: 9314 // ... if both the second and third operands have nullptr_t type, the 9315 // result also has that type. 9316 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy)) 9317 return ResTy; 9318 9319 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 9320 // the type of the other operand." 9321 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 9322 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 9323 9324 // All objective-c pointer type analysis is done here. 9325 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 9326 QuestionLoc); 9327 if (LHS.isInvalid() || RHS.isInvalid()) 9328 return QualType(); 9329 if (!compositeType.isNull()) 9330 return compositeType; 9331 9332 9333 // Handle block pointer types. 9334 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 9335 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 9336 QuestionLoc); 9337 9338 // Check constraints for C object pointers types (C99 6.5.15p3,6). 9339 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 9340 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 9341 QuestionLoc); 9342 9343 // GCC compatibility: soften pointer/integer mismatch. Note that 9344 // null pointers have been filtered out by this point. 9345 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 9346 /*IsIntFirstExpr=*/true)) 9347 return RHSTy; 9348 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 9349 /*IsIntFirstExpr=*/false)) 9350 return LHSTy; 9351 9352 // Emit a better diagnostic if one of the expressions is a null pointer 9353 // constant and the other is not a pointer type. In this case, the user most 9354 // likely forgot to take the address of the other expression. 9355 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 9356 return QualType(); 9357 9358 // Finally, if the LHS and RHS types are canonically the same type, we can 9359 // use the common sugared type. 9360 if (Context.hasSameType(LHSTy, RHSTy)) 9361 return Context.getCommonSugaredType(LHSTy, RHSTy); 9362 9363 // Otherwise, the operands are not compatible. 9364 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 9365 << LHSTy << RHSTy << LHS.get()->getSourceRange() 9366 << RHS.get()->getSourceRange(); 9367 return QualType(); 9368} 9369 9370/// FindCompositeObjCPointerType - Helper method to find composite type of 9371/// two objective-c pointer types of the two input expressions. 9372QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 9373 SourceLocation QuestionLoc) { 9374 QualType LHSTy = LHS.get()->getType(); 9375 QualType RHSTy = RHS.get()->getType(); 9376 9377 // Handle things like Class and struct objc_class*. Here we case the result 9378 // to the pseudo-builtin, because that will be implicitly cast back to the 9379 // redefinition type if an attempt is made to access its fields. 9380 if (LHSTy->isObjCClassType() && 9381 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 9382 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 9383 return LHSTy; 9384 } 9385 if (RHSTy->isObjCClassType() && 9386 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 9387 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 9388 return RHSTy; 9389 } 9390 // And the same for struct objc_object* / id 9391 if (LHSTy->isObjCIdType() && 9392 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 9393 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 9394 return LHSTy; 9395 } 9396 if (RHSTy->isObjCIdType() && 9397 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 9398 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 9399 return RHSTy; 9400 } 9401 // And the same for struct objc_selector* / SEL 9402 if (Context.isObjCSelType(LHSTy) && 9403 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 9404 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 9405 return LHSTy; 9406 } 9407 if (Context.isObjCSelType(RHSTy) && 9408 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 9409 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 9410 return RHSTy; 9411 } 9412 // Check constraints for Objective-C object pointers types. 9413 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 9414 9415 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 9416 // Two identical object pointer types are always compatible. 9417 return LHSTy; 9418 } 9419 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 9420 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 9421 QualType compositeType = LHSTy; 9422 9423 // If both operands are interfaces and either operand can be 9424 // assigned to the other, use that type as the composite 9425 // type. This allows 9426 // xxx ? (A*) a : (B*) b 9427 // where B is a subclass of A. 9428 // 9429 // Additionally, as for assignment, if either type is 'id' 9430 // allow silent coercion. Finally, if the types are 9431 // incompatible then make sure to use 'id' as the composite 9432 // type so the result is acceptable for sending messages to. 9433 9434 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 9435 // It could return the composite type. 9436 if (!(compositeType = 9437 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 9438 // Nothing more to do. 9439 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 9440 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 9441 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 9442 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 9443 } else if ((LHSOPT->isObjCQualifiedIdType() || 9444 RHSOPT->isObjCQualifiedIdType()) && 9445 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 9446 true)) { 9447 // Need to handle "id<xx>" explicitly. 9448 // GCC allows qualified id and any Objective-C type to devolve to 9449 // id. Currently localizing to here until clear this should be 9450 // part of ObjCQualifiedIdTypesAreCompatible. 9451 compositeType = Context.getObjCIdType(); 9452 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 9453 compositeType = Context.getObjCIdType(); 9454 } else { 9455 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 9456 << LHSTy << RHSTy 9457 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9458 QualType incompatTy = Context.getObjCIdType(); 9459 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 9460 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 9461 return incompatTy; 9462 } 9463 // The object pointer types are compatible. 9464 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 9465 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 9466 return compositeType; 9467 } 9468 // Check Objective-C object pointer types and 'void *' 9469 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 9470 if (getLangOpts().ObjCAutoRefCount) { 9471 // ARC forbids the implicit conversion of object pointers to 'void *', 9472 // so these types are not compatible. 9473 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 9474 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9475 LHS = RHS = true; 9476 return QualType(); 9477 } 9478 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 9479 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 9480 QualType destPointee 9481 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 9482 QualType destType = Context.getPointerType(destPointee); 9483 // Add qualifiers if necessary. 9484 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 9485 // Promote to void*. 9486 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 9487 return destType; 9488 } 9489 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 9490 if (getLangOpts().ObjCAutoRefCount) { 9491 // ARC forbids the implicit conversion of object pointers to 'void *', 9492 // so these types are not compatible. 9493 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 9494 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9495 LHS = RHS = true; 9496 return QualType(); 9497 } 9498 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 9499 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 9500 QualType destPointee 9501 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 9502 QualType destType = Context.getPointerType(destPointee); 9503 // Add qualifiers if necessary. 9504 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 9505 // Promote to void*. 9506 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 9507 return destType; 9508 } 9509 return QualType(); 9510} 9511 9512/// SuggestParentheses - Emit a note with a fixit hint that wraps 9513/// ParenRange in parentheses. 9514static void SuggestParentheses(Sema &Self, SourceLocation Loc, 9515 const PartialDiagnostic &Note, 9516 SourceRange ParenRange) { 9517 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 9518 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 9519 EndLoc.isValid()) { 9520 Self.Diag(Loc, Note) 9521 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 9522 << FixItHint::CreateInsertion(EndLoc, ")"); 9523 } else { 9524 // We can't display the parentheses, so just show the bare note. 9525 Self.Diag(Loc, Note) << ParenRange; 9526 } 9527} 9528 9529static bool IsArithmeticOp(BinaryOperatorKind Opc) { 9530 return BinaryOperator::isAdditiveOp(Opc) || 9531 BinaryOperator::isMultiplicativeOp(Opc) || 9532 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 9533 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 9534 // not any of the logical operators. Bitwise-xor is commonly used as a 9535 // logical-xor because there is no logical-xor operator. The logical 9536 // operators, including uses of xor, have a high false positive rate for 9537 // precedence warnings. 9538} 9539 9540/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 9541/// expression, either using a built-in or overloaded operator, 9542/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 9543/// expression. 9544static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, 9545 const Expr **RHSExprs) { 9546 // Don't strip parenthesis: we should not warn if E is in parenthesis. 9547 E = E->IgnoreImpCasts(); 9548 E = E->IgnoreConversionOperatorSingleStep(); 9549 E = E->IgnoreImpCasts(); 9550 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 9551 E = MTE->getSubExpr(); 9552 E = E->IgnoreImpCasts(); 9553 } 9554 9555 // Built-in binary operator. 9556 if (const auto *OP = dyn_cast<BinaryOperator>(E); 9557 OP && IsArithmeticOp(OP->getOpcode())) { 9558 *Opcode = OP->getOpcode(); 9559 *RHSExprs = OP->getRHS(); 9560 return true; 9561 } 9562 9563 // Overloaded operator. 9564 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 9565 if (Call->getNumArgs() != 2) 9566 return false; 9567 9568 // Make sure this is really a binary operator that is safe to pass into 9569 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 9570 OverloadedOperatorKind OO = Call->getOperator(); 9571 if (OO < OO_Plus || OO > OO_Arrow || 9572 OO == OO_PlusPlus || OO == OO_MinusMinus) 9573 return false; 9574 9575 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 9576 if (IsArithmeticOp(OpKind)) { 9577 *Opcode = OpKind; 9578 *RHSExprs = Call->getArg(1); 9579 return true; 9580 } 9581 } 9582 9583 return false; 9584} 9585 9586/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 9587/// or is a logical expression such as (x==y) which has int type, but is 9588/// commonly interpreted as boolean. 9589static bool ExprLooksBoolean(const Expr *E) { 9590 E = E->IgnoreParenImpCasts(); 9591 9592 if (E->getType()->isBooleanType()) 9593 return true; 9594 if (const auto *OP = dyn_cast<BinaryOperator>(E)) 9595 return OP->isComparisonOp() || OP->isLogicalOp(); 9596 if (const auto *OP = dyn_cast<UnaryOperator>(E)) 9597 return OP->getOpcode() == UO_LNot; 9598 if (E->getType()->isPointerType()) 9599 return true; 9600 // FIXME: What about overloaded operator calls returning "unspecified boolean 9601 // type"s (commonly pointer-to-members)? 9602 9603 return false; 9604} 9605 9606/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 9607/// and binary operator are mixed in a way that suggests the programmer assumed 9608/// the conditional operator has higher precedence, for example: 9609/// "int x = a + someBinaryCondition ? 1 : 2". 9610static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, 9611 Expr *Condition, const Expr *LHSExpr, 9612 const Expr *RHSExpr) { 9613 BinaryOperatorKind CondOpcode; 9614 const Expr *CondRHS; 9615 9616 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 9617 return; 9618 if (!ExprLooksBoolean(CondRHS)) 9619 return; 9620 9621 // The condition is an arithmetic binary expression, with a right- 9622 // hand side that looks boolean, so warn. 9623 9624 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 9625 ? diag::warn_precedence_bitwise_conditional 9626 : diag::warn_precedence_conditional; 9627 9628 Self.Diag(OpLoc, DiagID) 9629 << Condition->getSourceRange() 9630 << BinaryOperator::getOpcodeStr(CondOpcode); 9631 9632 SuggestParentheses( 9633 Self, OpLoc, 9634 Self.PDiag(diag::note_precedence_silence) 9635 << BinaryOperator::getOpcodeStr(CondOpcode), 9636 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 9637 9638 SuggestParentheses(Self, OpLoc, 9639 Self.PDiag(diag::note_precedence_conditional_first), 9640 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 9641} 9642 9643/// Compute the nullability of a conditional expression. 9644static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 9645 QualType LHSTy, QualType RHSTy, 9646 ASTContext &Ctx) { 9647 if (!ResTy->isAnyPointerType()) 9648 return ResTy; 9649 9650 auto GetNullability = [](QualType Ty) { 9651 std::optional<NullabilityKind> Kind = Ty->getNullability(); 9652 if (Kind) { 9653 // For our purposes, treat _Nullable_result as _Nullable. 9654 if (*Kind == NullabilityKind::NullableResult) 9655 return NullabilityKind::Nullable; 9656 return *Kind; 9657 } 9658 return NullabilityKind::Unspecified; 9659 }; 9660 9661 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 9662 NullabilityKind MergedKind; 9663 9664 // Compute nullability of a binary conditional expression. 9665 if (IsBin) { 9666 if (LHSKind == NullabilityKind::NonNull) 9667 MergedKind = NullabilityKind::NonNull; 9668 else 9669 MergedKind = RHSKind; 9670 // Compute nullability of a normal conditional expression. 9671 } else { 9672 if (LHSKind == NullabilityKind::Nullable || 9673 RHSKind == NullabilityKind::Nullable) 9674 MergedKind = NullabilityKind::Nullable; 9675 else if (LHSKind == NullabilityKind::NonNull) 9676 MergedKind = RHSKind; 9677 else if (RHSKind == NullabilityKind::NonNull) 9678 MergedKind = LHSKind; 9679 else 9680 MergedKind = NullabilityKind::Unspecified; 9681 } 9682 9683 // Return if ResTy already has the correct nullability. 9684 if (GetNullability(ResTy) == MergedKind) 9685 return ResTy; 9686 9687 // Strip all nullability from ResTy. 9688 while (ResTy->getNullability()) 9689 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 9690 9691 // Create a new AttributedType with the new nullability kind. 9692 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 9693 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 9694} 9695 9696/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 9697/// in the case of a the GNU conditional expr extension. 9698ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 9699 SourceLocation ColonLoc, 9700 Expr *CondExpr, Expr *LHSExpr, 9701 Expr *RHSExpr) { 9702 if (!Context.isDependenceAllowed()) { 9703 // C cannot handle TypoExpr nodes in the condition because it 9704 // doesn't handle dependent types properly, so make sure any TypoExprs have 9705 // been dealt with before checking the operands. 9706 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 9707 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 9708 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 9709 9710 if (!CondResult.isUsable()) 9711 return ExprError(); 9712 9713 if (LHSExpr) { 9714 if (!LHSResult.isUsable()) 9715 return ExprError(); 9716 } 9717 9718 if (!RHSResult.isUsable()) 9719 return ExprError(); 9720 9721 CondExpr = CondResult.get(); 9722 LHSExpr = LHSResult.get(); 9723 RHSExpr = RHSResult.get(); 9724 } 9725 9726 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 9727 // was the condition. 9728 OpaqueValueExpr *opaqueValue = nullptr; 9729 Expr *commonExpr = nullptr; 9730 if (!LHSExpr) { 9731 commonExpr = CondExpr; 9732 // Lower out placeholder types first. This is important so that we don't 9733 // try to capture a placeholder. This happens in few cases in C++; such 9734 // as Objective-C++'s dictionary subscripting syntax. 9735 if (commonExpr->hasPlaceholderType()) { 9736 ExprResult result = CheckPlaceholderExpr(commonExpr); 9737 if (!result.isUsable()) return ExprError(); 9738 commonExpr = result.get(); 9739 } 9740 // We usually want to apply unary conversions *before* saving, except 9741 // in the special case of a C++ l-value conditional. 9742 if (!(getLangOpts().CPlusPlus 9743 && !commonExpr->isTypeDependent() 9744 && commonExpr->getValueKind() == RHSExpr->getValueKind() 9745 && commonExpr->isGLValue() 9746 && commonExpr->isOrdinaryOrBitFieldObject() 9747 && RHSExpr->isOrdinaryOrBitFieldObject() 9748 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 9749 ExprResult commonRes = UsualUnaryConversions(commonExpr); 9750 if (commonRes.isInvalid()) 9751 return ExprError(); 9752 commonExpr = commonRes.get(); 9753 } 9754 9755 // If the common expression is a class or array prvalue, materialize it 9756 // so that we can safely refer to it multiple times. 9757 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 9758 commonExpr->getType()->isArrayType())) { 9759 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 9760 if (MatExpr.isInvalid()) 9761 return ExprError(); 9762 commonExpr = MatExpr.get(); 9763 } 9764 9765 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 9766 commonExpr->getType(), 9767 commonExpr->getValueKind(), 9768 commonExpr->getObjectKind(), 9769 commonExpr); 9770 LHSExpr = CondExpr = opaqueValue; 9771 } 9772 9773 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 9774 ExprValueKind VK = VK_PRValue; 9775 ExprObjectKind OK = OK_Ordinary; 9776 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 9777 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 9778 VK, OK, QuestionLoc); 9779 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 9780 RHS.isInvalid()) 9781 return ExprError(); 9782 9783 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 9784 RHS.get()); 9785 9786 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 9787 9788 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 9789 Context); 9790 9791 if (!commonExpr) 9792 return new (Context) 9793 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 9794 RHS.get(), result, VK, OK); 9795 9796 return new (Context) BinaryConditionalOperator( 9797 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 9798 ColonLoc, result, VK, OK); 9799} 9800 9801// Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible. 9802bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) { 9803 unsigned FromAttributes = 0, ToAttributes = 0; 9804 if (const auto *FromFn = 9805 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType))) 9806 FromAttributes = 9807 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask; 9808 if (const auto *ToFn = 9809 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType))) 9810 ToAttributes = 9811 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask; 9812 9813 return FromAttributes != ToAttributes; 9814} 9815 9816// Check if we have a conversion between incompatible cmse function pointer 9817// types, that is, a conversion between a function pointer with the 9818// cmse_nonsecure_call attribute and one without. 9819static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 9820 QualType ToType) { 9821 if (const auto *ToFn = 9822 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 9823 if (const auto *FromFn = 9824 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 9825 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 9826 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 9827 9828 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 9829 } 9830 } 9831 return false; 9832} 9833 9834// checkPointerTypesForAssignment - This is a very tricky routine (despite 9835// being closely modeled after the C99 spec:-). The odd characteristic of this 9836// routine is it effectively iqnores the qualifiers on the top level pointee. 9837// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 9838// FIXME: add a couple examples in this comment. 9839static Sema::AssignConvertType 9840checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, 9841 SourceLocation Loc) { 9842 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9843 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9844 9845 // get the "pointed to" type (ignoring qualifiers at the top level) 9846 const Type *lhptee, *rhptee; 9847 Qualifiers lhq, rhq; 9848 std::tie(lhptee, lhq) = 9849 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 9850 std::tie(rhptee, rhq) = 9851 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 9852 9853 Sema::AssignConvertType ConvTy = Sema::Compatible; 9854 9855 // C99 6.5.16.1p1: This following citation is common to constraints 9856 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 9857 // qualifiers of the type *pointed to* by the right; 9858 9859 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 9860 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 9861 lhq.compatiblyIncludesObjCLifetime(rhq)) { 9862 // Ignore lifetime for further calculation. 9863 lhq.removeObjCLifetime(); 9864 rhq.removeObjCLifetime(); 9865 } 9866 9867 if (!lhq.compatiblyIncludes(rhq)) { 9868 // Treat address-space mismatches as fatal. 9869 if (!lhq.isAddressSpaceSupersetOf(rhq)) 9870 return Sema::IncompatiblePointerDiscardsQualifiers; 9871 9872 // It's okay to add or remove GC or lifetime qualifiers when converting to 9873 // and from void*. 9874 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 9875 .compatiblyIncludes( 9876 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 9877 && (lhptee->isVoidType() || rhptee->isVoidType())) 9878 ; // keep old 9879 9880 // Treat lifetime mismatches as fatal. 9881 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 9882 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 9883 9884 // For GCC/MS compatibility, other qualifier mismatches are treated 9885 // as still compatible in C. 9886 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9887 } 9888 9889 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 9890 // incomplete type and the other is a pointer to a qualified or unqualified 9891 // version of void... 9892 if (lhptee->isVoidType()) { 9893 if (rhptee->isIncompleteOrObjectType()) 9894 return ConvTy; 9895 9896 // As an extension, we allow cast to/from void* to function pointer. 9897 assert(rhptee->isFunctionType()); 9898 return Sema::FunctionVoidPointer; 9899 } 9900 9901 if (rhptee->isVoidType()) { 9902 if (lhptee->isIncompleteOrObjectType()) 9903 return ConvTy; 9904 9905 // As an extension, we allow cast to/from void* to function pointer. 9906 assert(lhptee->isFunctionType()); 9907 return Sema::FunctionVoidPointer; 9908 } 9909 9910 if (!S.Diags.isIgnored( 9911 diag::warn_typecheck_convert_incompatible_function_pointer_strict, 9912 Loc) && 9913 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() && 9914 !S.IsFunctionConversion(RHSType, LHSType, RHSType)) 9915 return Sema::IncompatibleFunctionPointerStrict; 9916 9917 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9918 // unqualified versions of compatible types, ... 9919 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9920 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9921 // Check if the pointee types are compatible ignoring the sign. 9922 // We explicitly check for char so that we catch "char" vs 9923 // "unsigned char" on systems where "char" is unsigned. 9924 if (lhptee->isCharType()) 9925 ltrans = S.Context.UnsignedCharTy; 9926 else if (lhptee->hasSignedIntegerRepresentation()) 9927 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9928 9929 if (rhptee->isCharType()) 9930 rtrans = S.Context.UnsignedCharTy; 9931 else if (rhptee->hasSignedIntegerRepresentation()) 9932 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9933 9934 if (ltrans == rtrans) { 9935 // Types are compatible ignoring the sign. Qualifier incompatibility 9936 // takes priority over sign incompatibility because the sign 9937 // warning can be disabled. 9938 if (ConvTy != Sema::Compatible) 9939 return ConvTy; 9940 9941 return Sema::IncompatiblePointerSign; 9942 } 9943 9944 // If we are a multi-level pointer, it's possible that our issue is simply 9945 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9946 // the eventual target type is the same and the pointers have the same 9947 // level of indirection, this must be the issue. 9948 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9949 do { 9950 std::tie(lhptee, lhq) = 9951 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9952 std::tie(rhptee, rhq) = 9953 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9954 9955 // Inconsistent address spaces at this point is invalid, even if the 9956 // address spaces would be compatible. 9957 // FIXME: This doesn't catch address space mismatches for pointers of 9958 // different nesting levels, like: 9959 // __local int *** a; 9960 // int ** b = a; 9961 // It's not clear how to actually determine when such pointers are 9962 // invalidly incompatible. 9963 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9964 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9965 9966 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9967 9968 if (lhptee == rhptee) 9969 return Sema::IncompatibleNestedPointerQualifiers; 9970 } 9971 9972 // General pointer incompatibility takes priority over qualifiers. 9973 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9974 return Sema::IncompatibleFunctionPointer; 9975 return Sema::IncompatiblePointer; 9976 } 9977 if (!S.getLangOpts().CPlusPlus && 9978 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9979 return Sema::IncompatibleFunctionPointer; 9980 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9981 return Sema::IncompatibleFunctionPointer; 9982 if (S.IsInvalidSMECallConversion(rtrans, ltrans)) 9983 return Sema::IncompatibleFunctionPointer; 9984 return ConvTy; 9985} 9986 9987/// checkBlockPointerTypesForAssignment - This routine determines whether two 9988/// block pointer types are compatible or whether a block and normal pointer 9989/// are compatible. It is more restrict than comparing two function pointer 9990// types. 9991static Sema::AssignConvertType 9992checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9993 QualType RHSType) { 9994 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9995 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9996 9997 QualType lhptee, rhptee; 9998 9999 // get the "pointed to" type (ignoring qualifiers at the top level) 10000 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 10001 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 10002 10003 // In C++, the types have to match exactly. 10004 if (S.getLangOpts().CPlusPlus) 10005 return Sema::IncompatibleBlockPointer; 10006 10007 Sema::AssignConvertType ConvTy = Sema::Compatible; 10008 10009 // For blocks we enforce that qualifiers are identical. 10010 Qualifiers LQuals = lhptee.getLocalQualifiers(); 10011 Qualifiers RQuals = rhptee.getLocalQualifiers(); 10012 if (S.getLangOpts().OpenCL) { 10013 LQuals.removeAddressSpace(); 10014 RQuals.removeAddressSpace(); 10015 } 10016 if (LQuals != RQuals) 10017 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 10018 10019 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 10020 // assignment. 10021 // The current behavior is similar to C++ lambdas. A block might be 10022 // assigned to a variable iff its return type and parameters are compatible 10023 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 10024 // an assignment. Presumably it should behave in way that a function pointer 10025 // assignment does in C, so for each parameter and return type: 10026 // * CVR and address space of LHS should be a superset of CVR and address 10027 // space of RHS. 10028 // * unqualified types should be compatible. 10029 if (S.getLangOpts().OpenCL) { 10030 if (!S.Context.typesAreBlockPointerCompatible( 10031 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 10032 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 10033 return Sema::IncompatibleBlockPointer; 10034 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 10035 return Sema::IncompatibleBlockPointer; 10036 10037 return ConvTy; 10038} 10039 10040/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 10041/// for assignment compatibility. 10042static Sema::AssignConvertType 10043checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 10044 QualType RHSType) { 10045 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 10046 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 10047 10048 if (LHSType->isObjCBuiltinType()) { 10049 // Class is not compatible with ObjC object pointers. 10050 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 10051 !RHSType->isObjCQualifiedClassType()) 10052 return Sema::IncompatiblePointer; 10053 return Sema::Compatible; 10054 } 10055 if (RHSType->isObjCBuiltinType()) { 10056 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 10057 !LHSType->isObjCQualifiedClassType()) 10058 return Sema::IncompatiblePointer; 10059 return Sema::Compatible; 10060 } 10061 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 10062 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 10063 10064 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 10065 // make an exception for id<P> 10066 !LHSType->isObjCQualifiedIdType()) 10067 return Sema::CompatiblePointerDiscardsQualifiers; 10068 10069 if (S.Context.typesAreCompatible(LHSType, RHSType)) 10070 return Sema::Compatible; 10071 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 10072 return Sema::IncompatibleObjCQualifiedId; 10073 return Sema::IncompatiblePointer; 10074} 10075 10076Sema::AssignConvertType 10077Sema::CheckAssignmentConstraints(SourceLocation Loc, 10078 QualType LHSType, QualType RHSType) { 10079 // Fake up an opaque expression. We don't actually care about what 10080 // cast operations are required, so if CheckAssignmentConstraints 10081 // adds casts to this they'll be wasted, but fortunately that doesn't 10082 // usually happen on valid code. 10083 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 10084 ExprResult RHSPtr = &RHSExpr; 10085 CastKind K; 10086 10087 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 10088} 10089 10090/// This helper function returns true if QT is a vector type that has element 10091/// type ElementType. 10092static bool isVector(QualType QT, QualType ElementType) { 10093 if (const VectorType *VT = QT->getAs<VectorType>()) 10094 return VT->getElementType().getCanonicalType() == ElementType; 10095 return false; 10096} 10097 10098/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 10099/// has code to accommodate several GCC extensions when type checking 10100/// pointers. Here are some objectionable examples that GCC considers warnings: 10101/// 10102/// int a, *pint; 10103/// short *pshort; 10104/// struct foo *pfoo; 10105/// 10106/// pint = pshort; // warning: assignment from incompatible pointer type 10107/// a = pint; // warning: assignment makes integer from pointer without a cast 10108/// pint = a; // warning: assignment makes pointer from integer without a cast 10109/// pint = pfoo; // warning: assignment from incompatible pointer type 10110/// 10111/// As a result, the code for dealing with pointers is more complex than the 10112/// C99 spec dictates. 10113/// 10114/// Sets 'Kind' for any result kind except Incompatible. 10115Sema::AssignConvertType 10116Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 10117 CastKind &Kind, bool ConvertRHS) { 10118 QualType RHSType = RHS.get()->getType(); 10119 QualType OrigLHSType = LHSType; 10120 10121 // Get canonical types. We're not formatting these types, just comparing 10122 // them. 10123 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 10124 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 10125 10126 // Common case: no conversion required. 10127 if (LHSType == RHSType) { 10128 Kind = CK_NoOp; 10129 return Compatible; 10130 } 10131 10132 // If the LHS has an __auto_type, there are no additional type constraints 10133 // to be worried about. 10134 if (const auto *AT = dyn_cast<AutoType>(LHSType)) { 10135 if (AT->isGNUAutoType()) { 10136 Kind = CK_NoOp; 10137 return Compatible; 10138 } 10139 } 10140 10141 // If we have an atomic type, try a non-atomic assignment, then just add an 10142 // atomic qualification step. 10143 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 10144 Sema::AssignConvertType result = 10145 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 10146 if (result != Compatible) 10147 return result; 10148 if (Kind != CK_NoOp && ConvertRHS) 10149 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 10150 Kind = CK_NonAtomicToAtomic; 10151 return Compatible; 10152 } 10153 10154 // If the left-hand side is a reference type, then we are in a 10155 // (rare!) case where we've allowed the use of references in C, 10156 // e.g., as a parameter type in a built-in function. In this case, 10157 // just make sure that the type referenced is compatible with the 10158 // right-hand side type. The caller is responsible for adjusting 10159 // LHSType so that the resulting expression does not have reference 10160 // type. 10161 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 10162 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 10163 Kind = CK_LValueBitCast; 10164 return Compatible; 10165 } 10166 return Incompatible; 10167 } 10168 10169 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 10170 // to the same ExtVector type. 10171 if (LHSType->isExtVectorType()) { 10172 if (RHSType->isExtVectorType()) 10173 return Incompatible; 10174 if (RHSType->isArithmeticType()) { 10175 // CK_VectorSplat does T -> vector T, so first cast to the element type. 10176 if (ConvertRHS) 10177 RHS = prepareVectorSplat(LHSType, RHS.get()); 10178 Kind = CK_VectorSplat; 10179 return Compatible; 10180 } 10181 } 10182 10183 // Conversions to or from vector type. 10184 if (LHSType->isVectorType() || RHSType->isVectorType()) { 10185 if (LHSType->isVectorType() && RHSType->isVectorType()) { 10186 // Allow assignments of an AltiVec vector type to an equivalent GCC 10187 // vector type and vice versa 10188 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10189 Kind = CK_BitCast; 10190 return Compatible; 10191 } 10192 10193 // If we are allowing lax vector conversions, and LHS and RHS are both 10194 // vectors, the total size only needs to be the same. This is a bitcast; 10195 // no bits are changed but the result type is different. 10196 if (isLaxVectorConversion(RHSType, LHSType)) { 10197 // The default for lax vector conversions with Altivec vectors will 10198 // change, so if we are converting between vector types where 10199 // at least one is an Altivec vector, emit a warning. 10200 if (Context.getTargetInfo().getTriple().isPPC() && 10201 anyAltivecTypes(RHSType, LHSType) && 10202 !Context.areCompatibleVectorTypes(RHSType, LHSType)) 10203 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all) 10204 << RHSType << LHSType; 10205 Kind = CK_BitCast; 10206 return IncompatibleVectors; 10207 } 10208 } 10209 10210 // When the RHS comes from another lax conversion (e.g. binops between 10211 // scalars and vectors) the result is canonicalized as a vector. When the 10212 // LHS is also a vector, the lax is allowed by the condition above. Handle 10213 // the case where LHS is a scalar. 10214 if (LHSType->isScalarType()) { 10215 const VectorType *VecType = RHSType->getAs<VectorType>(); 10216 if (VecType && VecType->getNumElements() == 1 && 10217 isLaxVectorConversion(RHSType, LHSType)) { 10218 if (Context.getTargetInfo().getTriple().isPPC() && 10219 (VecType->getVectorKind() == VectorKind::AltiVecVector || 10220 VecType->getVectorKind() == VectorKind::AltiVecBool || 10221 VecType->getVectorKind() == VectorKind::AltiVecPixel)) 10222 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all) 10223 << RHSType << LHSType; 10224 ExprResult *VecExpr = &RHS; 10225 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 10226 Kind = CK_BitCast; 10227 return Compatible; 10228 } 10229 } 10230 10231 // Allow assignments between fixed-length and sizeless SVE vectors. 10232 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) || 10233 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType())) 10234 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 10235 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 10236 Kind = CK_BitCast; 10237 return Compatible; 10238 } 10239 10240 // Allow assignments between fixed-length and sizeless RVV vectors. 10241 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) || 10242 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) { 10243 if (Context.areCompatibleRVVTypes(LHSType, RHSType) || 10244 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) { 10245 Kind = CK_BitCast; 10246 return Compatible; 10247 } 10248 } 10249 10250 return Incompatible; 10251 } 10252 10253 // Diagnose attempts to convert between __ibm128, __float128 and long double 10254 // where such conversions currently can't be handled. 10255 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 10256 return Incompatible; 10257 10258 // Disallow assigning a _Complex to a real type in C++ mode since it simply 10259 // discards the imaginary part. 10260 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 10261 !LHSType->getAs<ComplexType>()) 10262 return Incompatible; 10263 10264 // Arithmetic conversions. 10265 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 10266 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 10267 if (ConvertRHS) 10268 Kind = PrepareScalarCast(RHS, LHSType); 10269 return Compatible; 10270 } 10271 10272 // Conversions to normal pointers. 10273 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 10274 // U* -> T* 10275 if (isa<PointerType>(RHSType)) { 10276 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 10277 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 10278 if (AddrSpaceL != AddrSpaceR) 10279 Kind = CK_AddressSpaceConversion; 10280 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 10281 Kind = CK_NoOp; 10282 else 10283 Kind = CK_BitCast; 10284 return checkPointerTypesForAssignment(*this, LHSType, RHSType, 10285 RHS.get()->getBeginLoc()); 10286 } 10287 10288 // int -> T* 10289 if (RHSType->isIntegerType()) { 10290 Kind = CK_IntegralToPointer; // FIXME: null? 10291 return IntToPointer; 10292 } 10293 10294 // C pointers are not compatible with ObjC object pointers, 10295 // with two exceptions: 10296 if (isa<ObjCObjectPointerType>(RHSType)) { 10297 // - conversions to void* 10298 if (LHSPointer->getPointeeType()->isVoidType()) { 10299 Kind = CK_BitCast; 10300 return Compatible; 10301 } 10302 10303 // - conversions from 'Class' to the redefinition type 10304 if (RHSType->isObjCClassType() && 10305 Context.hasSameType(LHSType, 10306 Context.getObjCClassRedefinitionType())) { 10307 Kind = CK_BitCast; 10308 return Compatible; 10309 } 10310 10311 Kind = CK_BitCast; 10312 return IncompatiblePointer; 10313 } 10314 10315 // U^ -> void* 10316 if (RHSType->getAs<BlockPointerType>()) { 10317 if (LHSPointer->getPointeeType()->isVoidType()) { 10318 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 10319 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 10320 ->getPointeeType() 10321 .getAddressSpace(); 10322 Kind = 10323 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 10324 return Compatible; 10325 } 10326 } 10327 10328 return Incompatible; 10329 } 10330 10331 // Conversions to block pointers. 10332 if (isa<BlockPointerType>(LHSType)) { 10333 // U^ -> T^ 10334 if (RHSType->isBlockPointerType()) { 10335 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 10336 ->getPointeeType() 10337 .getAddressSpace(); 10338 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 10339 ->getPointeeType() 10340 .getAddressSpace(); 10341 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 10342 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 10343 } 10344 10345 // int or null -> T^ 10346 if (RHSType->isIntegerType()) { 10347 Kind = CK_IntegralToPointer; // FIXME: null 10348 return IntToBlockPointer; 10349 } 10350 10351 // id -> T^ 10352 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 10353 Kind = CK_AnyPointerToBlockPointerCast; 10354 return Compatible; 10355 } 10356 10357 // void* -> T^ 10358 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 10359 if (RHSPT->getPointeeType()->isVoidType()) { 10360 Kind = CK_AnyPointerToBlockPointerCast; 10361 return Compatible; 10362 } 10363 10364 return Incompatible; 10365 } 10366 10367 // Conversions to Objective-C pointers. 10368 if (isa<ObjCObjectPointerType>(LHSType)) { 10369 // A* -> B* 10370 if (RHSType->isObjCObjectPointerType()) { 10371 Kind = CK_BitCast; 10372 Sema::AssignConvertType result = 10373 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 10374 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 10375 result == Compatible && 10376 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 10377 result = IncompatibleObjCWeakRef; 10378 return result; 10379 } 10380 10381 // int or null -> A* 10382 if (RHSType->isIntegerType()) { 10383 Kind = CK_IntegralToPointer; // FIXME: null 10384 return IntToPointer; 10385 } 10386 10387 // In general, C pointers are not compatible with ObjC object pointers, 10388 // with two exceptions: 10389 if (isa<PointerType>(RHSType)) { 10390 Kind = CK_CPointerToObjCPointerCast; 10391 10392 // - conversions from 'void*' 10393 if (RHSType->isVoidPointerType()) { 10394 return Compatible; 10395 } 10396 10397 // - conversions to 'Class' from its redefinition type 10398 if (LHSType->isObjCClassType() && 10399 Context.hasSameType(RHSType, 10400 Context.getObjCClassRedefinitionType())) { 10401 return Compatible; 10402 } 10403 10404 return IncompatiblePointer; 10405 } 10406 10407 // Only under strict condition T^ is compatible with an Objective-C pointer. 10408 if (RHSType->isBlockPointerType() && 10409 LHSType->isBlockCompatibleObjCPointerType(Context)) { 10410 if (ConvertRHS) 10411 maybeExtendBlockObject(RHS); 10412 Kind = CK_BlockPointerToObjCPointerCast; 10413 return Compatible; 10414 } 10415 10416 return Incompatible; 10417 } 10418 10419 // Conversion to nullptr_t (C23 only) 10420 if (getLangOpts().C23 && LHSType->isNullPtrType() && 10421 RHS.get()->isNullPointerConstant(Context, 10422 Expr::NPC_ValueDependentIsNull)) { 10423 // null -> nullptr_t 10424 Kind = CK_NullToPointer; 10425 return Compatible; 10426 } 10427 10428 // Conversions from pointers that are not covered by the above. 10429 if (isa<PointerType>(RHSType)) { 10430 // T* -> _Bool 10431 if (LHSType == Context.BoolTy) { 10432 Kind = CK_PointerToBoolean; 10433 return Compatible; 10434 } 10435 10436 // T* -> int 10437 if (LHSType->isIntegerType()) { 10438 Kind = CK_PointerToIntegral; 10439 return PointerToInt; 10440 } 10441 10442 return Incompatible; 10443 } 10444 10445 // Conversions from Objective-C pointers that are not covered by the above. 10446 if (isa<ObjCObjectPointerType>(RHSType)) { 10447 // T* -> _Bool 10448 if (LHSType == Context.BoolTy) { 10449 Kind = CK_PointerToBoolean; 10450 return Compatible; 10451 } 10452 10453 // T* -> int 10454 if (LHSType->isIntegerType()) { 10455 Kind = CK_PointerToIntegral; 10456 return PointerToInt; 10457 } 10458 10459 return Incompatible; 10460 } 10461 10462 // struct A -> struct B 10463 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 10464 if (Context.typesAreCompatible(LHSType, RHSType)) { 10465 Kind = CK_NoOp; 10466 return Compatible; 10467 } 10468 } 10469 10470 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 10471 Kind = CK_IntToOCLSampler; 10472 return Compatible; 10473 } 10474 10475 return Incompatible; 10476} 10477 10478/// Constructs a transparent union from an expression that is 10479/// used to initialize the transparent union. 10480static void ConstructTransparentUnion(Sema &S, ASTContext &C, 10481 ExprResult &EResult, QualType UnionType, 10482 FieldDecl *Field) { 10483 // Build an initializer list that designates the appropriate member 10484 // of the transparent union. 10485 Expr *E = EResult.get(); 10486 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 10487 E, SourceLocation()); 10488 Initializer->setType(UnionType); 10489 Initializer->setInitializedFieldInUnion(Field); 10490 10491 // Build a compound literal constructing a value of the transparent 10492 // union type from this initializer list. 10493 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 10494 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 10495 VK_PRValue, Initializer, false); 10496} 10497 10498Sema::AssignConvertType 10499Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 10500 ExprResult &RHS) { 10501 QualType RHSType = RHS.get()->getType(); 10502 10503 // If the ArgType is a Union type, we want to handle a potential 10504 // transparent_union GCC extension. 10505 const RecordType *UT = ArgType->getAsUnionType(); 10506 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 10507 return Incompatible; 10508 10509 // The field to initialize within the transparent union. 10510 RecordDecl *UD = UT->getDecl(); 10511 FieldDecl *InitField = nullptr; 10512 // It's compatible if the expression matches any of the fields. 10513 for (auto *it : UD->fields()) { 10514 if (it->getType()->isPointerType()) { 10515 // If the transparent union contains a pointer type, we allow: 10516 // 1) void pointer 10517 // 2) null pointer constant 10518 if (RHSType->isPointerType()) 10519 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 10520 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 10521 InitField = it; 10522 break; 10523 } 10524 10525 if (RHS.get()->isNullPointerConstant(Context, 10526 Expr::NPC_ValueDependentIsNull)) { 10527 RHS = ImpCastExprToType(RHS.get(), it->getType(), 10528 CK_NullToPointer); 10529 InitField = it; 10530 break; 10531 } 10532 } 10533 10534 CastKind Kind; 10535 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 10536 == Compatible) { 10537 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 10538 InitField = it; 10539 break; 10540 } 10541 } 10542 10543 if (!InitField) 10544 return Incompatible; 10545 10546 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 10547 return Compatible; 10548} 10549 10550Sema::AssignConvertType 10551Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 10552 bool Diagnose, 10553 bool DiagnoseCFAudited, 10554 bool ConvertRHS) { 10555 // We need to be able to tell the caller whether we diagnosed a problem, if 10556 // they ask us to issue diagnostics. 10557 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 10558 10559 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 10560 // we can't avoid *all* modifications at the moment, so we need some somewhere 10561 // to put the updated value. 10562 ExprResult LocalRHS = CallerRHS; 10563 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 10564 10565 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 10566 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 10567 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 10568 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 10569 Diag(RHS.get()->getExprLoc(), 10570 diag::warn_noderef_to_dereferenceable_pointer) 10571 << RHS.get()->getSourceRange(); 10572 } 10573 } 10574 } 10575 10576 if (getLangOpts().CPlusPlus) { 10577 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 10578 // C++ 5.17p3: If the left operand is not of class type, the 10579 // expression is implicitly converted (C++ 4) to the 10580 // cv-unqualified type of the left operand. 10581 QualType RHSType = RHS.get()->getType(); 10582 if (Diagnose) { 10583 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 10584 AA_Assigning); 10585 } else { 10586 ImplicitConversionSequence ICS = 10587 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 10588 /*SuppressUserConversions=*/false, 10589 AllowedExplicit::None, 10590 /*InOverloadResolution=*/false, 10591 /*CStyle=*/false, 10592 /*AllowObjCWritebackConversion=*/false); 10593 if (ICS.isFailure()) 10594 return Incompatible; 10595 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 10596 ICS, AA_Assigning); 10597 } 10598 if (RHS.isInvalid()) 10599 return Incompatible; 10600 Sema::AssignConvertType result = Compatible; 10601 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 10602 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 10603 result = IncompatibleObjCWeakRef; 10604 return result; 10605 } 10606 10607 // FIXME: Currently, we fall through and treat C++ classes like C 10608 // structures. 10609 // FIXME: We also fall through for atomics; not sure what should 10610 // happen there, though. 10611 } else if (RHS.get()->getType() == Context.OverloadTy) { 10612 // As a set of extensions to C, we support overloading on functions. These 10613 // functions need to be resolved here. 10614 DeclAccessPair DAP; 10615 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 10616 RHS.get(), LHSType, /*Complain=*/false, DAP)) 10617 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 10618 else 10619 return Incompatible; 10620 } 10621 10622 // This check seems unnatural, however it is necessary to ensure the proper 10623 // conversion of functions/arrays. If the conversion were done for all 10624 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 10625 // expressions that suppress this implicit conversion (&, sizeof). This needs 10626 // to happen before we check for null pointer conversions because C does not 10627 // undergo the same implicit conversions as C++ does above (by the calls to 10628 // TryImplicitConversion() and PerformImplicitConversion()) which insert the 10629 // lvalue to rvalue cast before checking for null pointer constraints. This 10630 // addresses code like: nullptr_t val; int *ptr; ptr = val; 10631 // 10632 // Suppress this for references: C++ 8.5.3p5. 10633 if (!LHSType->isReferenceType()) { 10634 // FIXME: We potentially allocate here even if ConvertRHS is false. 10635 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 10636 if (RHS.isInvalid()) 10637 return Incompatible; 10638 } 10639 10640 // The constraints are expressed in terms of the atomic, qualified, or 10641 // unqualified type of the LHS. 10642 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType(); 10643 10644 // C99 6.5.16.1p1: the left operand is a pointer and the right is 10645 // a null pointer constant <C23>or its type is nullptr_t;</C23>. 10646 if ((LHSTypeAfterConversion->isPointerType() || 10647 LHSTypeAfterConversion->isObjCObjectPointerType() || 10648 LHSTypeAfterConversion->isBlockPointerType()) && 10649 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) || 10650 RHS.get()->isNullPointerConstant(Context, 10651 Expr::NPC_ValueDependentIsNull))) { 10652 if (Diagnose || ConvertRHS) { 10653 CastKind Kind; 10654 CXXCastPath Path; 10655 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 10656 /*IgnoreBaseAccess=*/false, Diagnose); 10657 if (ConvertRHS) 10658 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 10659 } 10660 return Compatible; 10661 } 10662 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or 10663 // unqualified bool, and the right operand is a pointer or its type is 10664 // nullptr_t. 10665 if (getLangOpts().C23 && LHSType->isBooleanType() && 10666 RHS.get()->getType()->isNullPtrType()) { 10667 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only 10668 // only handles nullptr -> _Bool due to needing an extra conversion 10669 // step. 10670 // We model this by converting from nullptr -> void * and then let the 10671 // conversion from void * -> _Bool happen naturally. 10672 if (Diagnose || ConvertRHS) { 10673 CastKind Kind; 10674 CXXCastPath Path; 10675 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path, 10676 /*IgnoreBaseAccess=*/false, Diagnose); 10677 if (ConvertRHS) 10678 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue, 10679 &Path); 10680 } 10681 } 10682 10683 // OpenCL queue_t type assignment. 10684 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 10685 Context, Expr::NPC_ValueDependentIsNull)) { 10686 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10687 return Compatible; 10688 } 10689 10690 CastKind Kind; 10691 Sema::AssignConvertType result = 10692 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 10693 10694 // C99 6.5.16.1p2: The value of the right operand is converted to the 10695 // type of the assignment expression. 10696 // CheckAssignmentConstraints allows the left-hand side to be a reference, 10697 // so that we can use references in built-in functions even in C. 10698 // The getNonReferenceType() call makes sure that the resulting expression 10699 // does not have reference type. 10700 if (result != Incompatible && RHS.get()->getType() != LHSType) { 10701 QualType Ty = LHSType.getNonLValueExprType(Context); 10702 Expr *E = RHS.get(); 10703 10704 // Check for various Objective-C errors. If we are not reporting 10705 // diagnostics and just checking for errors, e.g., during overload 10706 // resolution, return Incompatible to indicate the failure. 10707 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 10708 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 10709 Diagnose, DiagnoseCFAudited) != ACR_okay) { 10710 if (!Diagnose) 10711 return Incompatible; 10712 } 10713 if (getLangOpts().ObjC && 10714 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 10715 E->getType(), E, Diagnose) || 10716 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 10717 if (!Diagnose) 10718 return Incompatible; 10719 // Replace the expression with a corrected version and continue so we 10720 // can find further errors. 10721 RHS = E; 10722 return Compatible; 10723 } 10724 10725 if (ConvertRHS) 10726 RHS = ImpCastExprToType(E, Ty, Kind); 10727 } 10728 10729 return result; 10730} 10731 10732namespace { 10733/// The original operand to an operator, prior to the application of the usual 10734/// arithmetic conversions and converting the arguments of a builtin operator 10735/// candidate. 10736struct OriginalOperand { 10737 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 10738 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 10739 Op = MTE->getSubExpr(); 10740 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 10741 Op = BTE->getSubExpr(); 10742 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 10743 Orig = ICE->getSubExprAsWritten(); 10744 Conversion = ICE->getConversionFunction(); 10745 } 10746 } 10747 10748 QualType getType() const { return Orig->getType(); } 10749 10750 Expr *Orig; 10751 NamedDecl *Conversion; 10752}; 10753} 10754 10755QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 10756 ExprResult &RHS) { 10757 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 10758 10759 Diag(Loc, diag::err_typecheck_invalid_operands) 10760 << OrigLHS.getType() << OrigRHS.getType() 10761 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10762 10763 // If a user-defined conversion was applied to either of the operands prior 10764 // to applying the built-in operator rules, tell the user about it. 10765 if (OrigLHS.Conversion) { 10766 Diag(OrigLHS.Conversion->getLocation(), 10767 diag::note_typecheck_invalid_operands_converted) 10768 << 0 << LHS.get()->getType(); 10769 } 10770 if (OrigRHS.Conversion) { 10771 Diag(OrigRHS.Conversion->getLocation(), 10772 diag::note_typecheck_invalid_operands_converted) 10773 << 1 << RHS.get()->getType(); 10774 } 10775 10776 return QualType(); 10777} 10778 10779// Diagnose cases where a scalar was implicitly converted to a vector and 10780// diagnose the underlying types. Otherwise, diagnose the error 10781// as invalid vector logical operands for non-C++ cases. 10782QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 10783 ExprResult &RHS) { 10784 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 10785 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 10786 10787 bool LHSNatVec = LHSType->isVectorType(); 10788 bool RHSNatVec = RHSType->isVectorType(); 10789 10790 if (!(LHSNatVec && RHSNatVec)) { 10791 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 10792 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 10793 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10794 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 10795 << Vector->getSourceRange(); 10796 return QualType(); 10797 } 10798 10799 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10800 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 10801 << RHS.get()->getSourceRange(); 10802 10803 return QualType(); 10804} 10805 10806/// Try to convert a value of non-vector type to a vector type by converting 10807/// the type to the element type of the vector and then performing a splat. 10808/// If the language is OpenCL, we only use conversions that promote scalar 10809/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 10810/// for float->int. 10811/// 10812/// OpenCL V2.0 6.2.6.p2: 10813/// An error shall occur if any scalar operand type has greater rank 10814/// than the type of the vector element. 10815/// 10816/// \param scalar - if non-null, actually perform the conversions 10817/// \return true if the operation fails (but without diagnosing the failure) 10818static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 10819 QualType scalarTy, 10820 QualType vectorEltTy, 10821 QualType vectorTy, 10822 unsigned &DiagID) { 10823 // The conversion to apply to the scalar before splatting it, 10824 // if necessary. 10825 CastKind scalarCast = CK_NoOp; 10826 10827 if (vectorEltTy->isIntegralType(S.Context)) { 10828 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 10829 (scalarTy->isIntegerType() && 10830 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 10831 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10832 return true; 10833 } 10834 if (!scalarTy->isIntegralType(S.Context)) 10835 return true; 10836 scalarCast = CK_IntegralCast; 10837 } else if (vectorEltTy->isRealFloatingType()) { 10838 if (scalarTy->isRealFloatingType()) { 10839 if (S.getLangOpts().OpenCL && 10840 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 10841 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10842 return true; 10843 } 10844 scalarCast = CK_FloatingCast; 10845 } 10846 else if (scalarTy->isIntegralType(S.Context)) 10847 scalarCast = CK_IntegralToFloating; 10848 else 10849 return true; 10850 } else { 10851 return true; 10852 } 10853 10854 // Adjust scalar if desired. 10855 if (scalar) { 10856 if (scalarCast != CK_NoOp) 10857 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 10858 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 10859 } 10860 return false; 10861} 10862 10863/// Convert vector E to a vector with the same number of elements but different 10864/// element type. 10865static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 10866 const auto *VecTy = E->getType()->getAs<VectorType>(); 10867 assert(VecTy && "Expression E must be a vector"); 10868 QualType NewVecTy = 10869 VecTy->isExtVectorType() 10870 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements()) 10871 : S.Context.getVectorType(ElementType, VecTy->getNumElements(), 10872 VecTy->getVectorKind()); 10873 10874 // Look through the implicit cast. Return the subexpression if its type is 10875 // NewVecTy. 10876 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10877 if (ICE->getSubExpr()->getType() == NewVecTy) 10878 return ICE->getSubExpr(); 10879 10880 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 10881 return S.ImpCastExprToType(E, NewVecTy, Cast); 10882} 10883 10884/// Test if a (constant) integer Int can be casted to another integer type 10885/// IntTy without losing precision. 10886static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 10887 QualType OtherIntTy) { 10888 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10889 10890 // Reject cases where the value of the Int is unknown as that would 10891 // possibly cause truncation, but accept cases where the scalar can be 10892 // demoted without loss of precision. 10893 Expr::EvalResult EVResult; 10894 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10895 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 10896 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 10897 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 10898 10899 if (CstInt) { 10900 // If the scalar is constant and is of a higher order and has more active 10901 // bits that the vector element type, reject it. 10902 llvm::APSInt Result = EVResult.Val.getInt(); 10903 unsigned NumBits = IntSigned 10904 ? (Result.isNegative() ? Result.getSignificantBits() 10905 : Result.getActiveBits()) 10906 : Result.getActiveBits(); 10907 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 10908 return true; 10909 10910 // If the signedness of the scalar type and the vector element type 10911 // differs and the number of bits is greater than that of the vector 10912 // element reject it. 10913 return (IntSigned != OtherIntSigned && 10914 NumBits > S.Context.getIntWidth(OtherIntTy)); 10915 } 10916 10917 // Reject cases where the value of the scalar is not constant and it's 10918 // order is greater than that of the vector element type. 10919 return (Order < 0); 10920} 10921 10922/// Test if a (constant) integer Int can be casted to floating point type 10923/// FloatTy without losing precision. 10924static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 10925 QualType FloatTy) { 10926 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10927 10928 // Determine if the integer constant can be expressed as a floating point 10929 // number of the appropriate type. 10930 Expr::EvalResult EVResult; 10931 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10932 10933 uint64_t Bits = 0; 10934 if (CstInt) { 10935 // Reject constants that would be truncated if they were converted to 10936 // the floating point type. Test by simple to/from conversion. 10937 // FIXME: Ideally the conversion to an APFloat and from an APFloat 10938 // could be avoided if there was a convertFromAPInt method 10939 // which could signal back if implicit truncation occurred. 10940 llvm::APSInt Result = EVResult.Val.getInt(); 10941 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 10942 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 10943 llvm::APFloat::rmTowardZero); 10944 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 10945 !IntTy->hasSignedIntegerRepresentation()); 10946 bool Ignored = false; 10947 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 10948 &Ignored); 10949 if (Result != ConvertBack) 10950 return true; 10951 } else { 10952 // Reject types that cannot be fully encoded into the mantissa of 10953 // the float. 10954 Bits = S.Context.getTypeSize(IntTy); 10955 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 10956 S.Context.getFloatTypeSemantics(FloatTy)); 10957 if (Bits > FloatPrec) 10958 return true; 10959 } 10960 10961 return false; 10962} 10963 10964/// Attempt to convert and splat Scalar into a vector whose types matches 10965/// Vector following GCC conversion rules. The rule is that implicit 10966/// conversion can occur when Scalar can be casted to match Vector's element 10967/// type without causing truncation of Scalar. 10968static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 10969 ExprResult *Vector) { 10970 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 10971 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 10972 QualType VectorEltTy; 10973 10974 if (const auto *VT = VectorTy->getAs<VectorType>()) { 10975 assert(!isa<ExtVectorType>(VT) && 10976 "ExtVectorTypes should not be handled here!"); 10977 VectorEltTy = VT->getElementType(); 10978 } else if (VectorTy->isSveVLSBuiltinType()) { 10979 VectorEltTy = 10980 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext()); 10981 } else { 10982 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here"); 10983 } 10984 10985 // Reject cases where the vector element type or the scalar element type are 10986 // not integral or floating point types. 10987 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 10988 return true; 10989 10990 // The conversion to apply to the scalar before splatting it, 10991 // if necessary. 10992 CastKind ScalarCast = CK_NoOp; 10993 10994 // Accept cases where the vector elements are integers and the scalar is 10995 // an integer. 10996 // FIXME: Notionally if the scalar was a floating point value with a precise 10997 // integral representation, we could cast it to an appropriate integer 10998 // type and then perform the rest of the checks here. GCC will perform 10999 // this conversion in some cases as determined by the input language. 11000 // We should accept it on a language independent basis. 11001 if (VectorEltTy->isIntegralType(S.Context) && 11002 ScalarTy->isIntegralType(S.Context) && 11003 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 11004 11005 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 11006 return true; 11007 11008 ScalarCast = CK_IntegralCast; 11009 } else if (VectorEltTy->isIntegralType(S.Context) && 11010 ScalarTy->isRealFloatingType()) { 11011 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 11012 ScalarCast = CK_FloatingToIntegral; 11013 else 11014 return true; 11015 } else if (VectorEltTy->isRealFloatingType()) { 11016 if (ScalarTy->isRealFloatingType()) { 11017 11018 // Reject cases where the scalar type is not a constant and has a higher 11019 // Order than the vector element type. 11020 llvm::APFloat Result(0.0); 11021 11022 // Determine whether this is a constant scalar. In the event that the 11023 // value is dependent (and thus cannot be evaluated by the constant 11024 // evaluator), skip the evaluation. This will then diagnose once the 11025 // expression is instantiated. 11026 bool CstScalar = Scalar->get()->isValueDependent() || 11027 Scalar->get()->EvaluateAsFloat(Result, S.Context); 11028 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 11029 if (!CstScalar && Order < 0) 11030 return true; 11031 11032 // If the scalar cannot be safely casted to the vector element type, 11033 // reject it. 11034 if (CstScalar) { 11035 bool Truncated = false; 11036 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 11037 llvm::APFloat::rmNearestTiesToEven, &Truncated); 11038 if (Truncated) 11039 return true; 11040 } 11041 11042 ScalarCast = CK_FloatingCast; 11043 } else if (ScalarTy->isIntegralType(S.Context)) { 11044 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 11045 return true; 11046 11047 ScalarCast = CK_IntegralToFloating; 11048 } else 11049 return true; 11050 } else if (ScalarTy->isEnumeralType()) 11051 return true; 11052 11053 // Adjust scalar if desired. 11054 if (ScalarCast != CK_NoOp) 11055 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 11056 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 11057 return false; 11058} 11059 11060QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 11061 SourceLocation Loc, bool IsCompAssign, 11062 bool AllowBothBool, 11063 bool AllowBoolConversions, 11064 bool AllowBoolOperation, 11065 bool ReportInvalid) { 11066 if (!IsCompAssign) { 11067 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11068 if (LHS.isInvalid()) 11069 return QualType(); 11070 } 11071 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11072 if (RHS.isInvalid()) 11073 return QualType(); 11074 11075 // For conversion purposes, we ignore any qualifiers. 11076 // For example, "const float" and "float" are equivalent. 11077 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 11078 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 11079 11080 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 11081 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 11082 assert(LHSVecType || RHSVecType); 11083 11084 // AltiVec-style "vector bool op vector bool" combinations are allowed 11085 // for some operators but not others. 11086 if (!AllowBothBool && LHSVecType && 11087 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType && 11088 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) 11089 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 11090 11091 // This operation may not be performed on boolean vectors. 11092 if (!AllowBoolOperation && 11093 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) 11094 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 11095 11096 // If the vector types are identical, return. 11097 if (Context.hasSameType(LHSType, RHSType)) 11098 return Context.getCommonSugaredType(LHSType, RHSType); 11099 11100 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 11101 if (LHSVecType && RHSVecType && 11102 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 11103 if (isa<ExtVectorType>(LHSVecType)) { 11104 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11105 return LHSType; 11106 } 11107 11108 if (!IsCompAssign) 11109 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11110 return RHSType; 11111 } 11112 11113 // AllowBoolConversions says that bool and non-bool AltiVec vectors 11114 // can be mixed, with the result being the non-bool type. The non-bool 11115 // operand must have integer element type. 11116 if (AllowBoolConversions && LHSVecType && RHSVecType && 11117 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 11118 (Context.getTypeSize(LHSVecType->getElementType()) == 11119 Context.getTypeSize(RHSVecType->getElementType()))) { 11120 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector && 11121 LHSVecType->getElementType()->isIntegerType() && 11122 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) { 11123 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11124 return LHSType; 11125 } 11126 if (!IsCompAssign && 11127 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && 11128 RHSVecType->getVectorKind() == VectorKind::AltiVecVector && 11129 RHSVecType->getElementType()->isIntegerType()) { 11130 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11131 return RHSType; 11132 } 11133 } 11134 11135 // Expressions containing fixed-length and sizeless SVE/RVV vectors are 11136 // invalid since the ambiguity can affect the ABI. 11137 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType, 11138 unsigned &SVEorRVV) { 11139 const VectorType *VecType = SecondType->getAs<VectorType>(); 11140 SVEorRVV = 0; 11141 if (FirstType->isSizelessBuiltinType() && VecType) { 11142 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData || 11143 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate) 11144 return true; 11145 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData || 11146 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask) { 11147 SVEorRVV = 1; 11148 return true; 11149 } 11150 } 11151 11152 return false; 11153 }; 11154 11155 unsigned SVEorRVV; 11156 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) || 11157 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) { 11158 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous) 11159 << SVEorRVV << LHSType << RHSType; 11160 return QualType(); 11161 } 11162 11163 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are 11164 // invalid since the ambiguity can affect the ABI. 11165 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType, 11166 unsigned &SVEorRVV) { 11167 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 11168 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 11169 11170 SVEorRVV = 0; 11171 if (FirstVecType && SecondVecType) { 11172 if (FirstVecType->getVectorKind() == VectorKind::Generic) { 11173 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData || 11174 SecondVecType->getVectorKind() == 11175 VectorKind::SveFixedLengthPredicate) 11176 return true; 11177 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData || 11178 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask) { 11179 SVEorRVV = 1; 11180 return true; 11181 } 11182 } 11183 return false; 11184 } 11185 11186 if (SecondVecType && 11187 SecondVecType->getVectorKind() == VectorKind::Generic) { 11188 if (FirstType->isSVESizelessBuiltinType()) 11189 return true; 11190 if (FirstType->isRVVSizelessBuiltinType()) { 11191 SVEorRVV = 1; 11192 return true; 11193 } 11194 } 11195 11196 return false; 11197 }; 11198 11199 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) || 11200 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) { 11201 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous) 11202 << SVEorRVV << LHSType << RHSType; 11203 return QualType(); 11204 } 11205 11206 // If there's a vector type and a scalar, try to convert the scalar to 11207 // the vector element type and splat. 11208 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 11209 if (!RHSVecType) { 11210 if (isa<ExtVectorType>(LHSVecType)) { 11211 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 11212 LHSVecType->getElementType(), LHSType, 11213 DiagID)) 11214 return LHSType; 11215 } else { 11216 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 11217 return LHSType; 11218 } 11219 } 11220 if (!LHSVecType) { 11221 if (isa<ExtVectorType>(RHSVecType)) { 11222 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 11223 LHSType, RHSVecType->getElementType(), 11224 RHSType, DiagID)) 11225 return RHSType; 11226 } else { 11227 if (LHS.get()->isLValue() || 11228 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 11229 return RHSType; 11230 } 11231 } 11232 11233 // FIXME: The code below also handles conversion between vectors and 11234 // non-scalars, we should break this down into fine grained specific checks 11235 // and emit proper diagnostics. 11236 QualType VecType = LHSVecType ? LHSType : RHSType; 11237 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 11238 QualType OtherType = LHSVecType ? RHSType : LHSType; 11239 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 11240 if (isLaxVectorConversion(OtherType, VecType)) { 11241 if (Context.getTargetInfo().getTriple().isPPC() && 11242 anyAltivecTypes(RHSType, LHSType) && 11243 !Context.areCompatibleVectorTypes(RHSType, LHSType)) 11244 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType; 11245 // If we're allowing lax vector conversions, only the total (data) size 11246 // needs to be the same. For non compound assignment, if one of the types is 11247 // scalar, the result is always the vector type. 11248 if (!IsCompAssign) { 11249 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 11250 return VecType; 11251 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 11252 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 11253 // type. Note that this is already done by non-compound assignments in 11254 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 11255 // <1 x T> -> T. The result is also a vector type. 11256 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 11257 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 11258 ExprResult *RHSExpr = &RHS; 11259 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 11260 return VecType; 11261 } 11262 } 11263 11264 // Okay, the expression is invalid. 11265 11266 // If there's a non-vector, non-real operand, diagnose that. 11267 if ((!RHSVecType && !RHSType->isRealType()) || 11268 (!LHSVecType && !LHSType->isRealType())) { 11269 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 11270 << LHSType << RHSType 11271 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11272 return QualType(); 11273 } 11274 11275 // OpenCL V1.1 6.2.6.p1: 11276 // If the operands are of more than one vector type, then an error shall 11277 // occur. Implicit conversions between vector types are not permitted, per 11278 // section 6.2.1. 11279 if (getLangOpts().OpenCL && 11280 RHSVecType && isa<ExtVectorType>(RHSVecType) && 11281 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 11282 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 11283 << RHSType; 11284 return QualType(); 11285 } 11286 11287 11288 // If there is a vector type that is not a ExtVector and a scalar, we reach 11289 // this point if scalar could not be converted to the vector's element type 11290 // without truncation. 11291 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 11292 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 11293 QualType Scalar = LHSVecType ? RHSType : LHSType; 11294 QualType Vector = LHSVecType ? LHSType : RHSType; 11295 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 11296 Diag(Loc, 11297 diag::err_typecheck_vector_not_convertable_implict_truncation) 11298 << ScalarOrVector << Scalar << Vector; 11299 11300 return QualType(); 11301 } 11302 11303 // Otherwise, use the generic diagnostic. 11304 Diag(Loc, DiagID) 11305 << LHSType << RHSType 11306 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11307 return QualType(); 11308} 11309 11310QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, 11311 SourceLocation Loc, 11312 bool IsCompAssign, 11313 ArithConvKind OperationKind) { 11314 if (!IsCompAssign) { 11315 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11316 if (LHS.isInvalid()) 11317 return QualType(); 11318 } 11319 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11320 if (RHS.isInvalid()) 11321 return QualType(); 11322 11323 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 11324 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 11325 11326 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 11327 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); 11328 11329 unsigned DiagID = diag::err_typecheck_invalid_operands; 11330 if ((OperationKind == ACK_Arithmetic) && 11331 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || 11332 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) { 11333 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11334 << RHS.get()->getSourceRange(); 11335 return QualType(); 11336 } 11337 11338 if (Context.hasSameType(LHSType, RHSType)) 11339 return LHSType; 11340 11341 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) { 11342 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 11343 return LHSType; 11344 } 11345 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) { 11346 if (LHS.get()->isLValue() || 11347 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 11348 return RHSType; 11349 } 11350 11351 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) || 11352 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) { 11353 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 11354 << LHSType << RHSType << LHS.get()->getSourceRange() 11355 << RHS.get()->getSourceRange(); 11356 return QualType(); 11357 } 11358 11359 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() && 11360 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != 11361 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) { 11362 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11363 << LHSType << RHSType << LHS.get()->getSourceRange() 11364 << RHS.get()->getSourceRange(); 11365 return QualType(); 11366 } 11367 11368 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) { 11369 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType; 11370 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType; 11371 bool ScalarOrVector = 11372 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType(); 11373 11374 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation) 11375 << ScalarOrVector << Scalar << Vector; 11376 11377 return QualType(); 11378 } 11379 11380 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11381 << RHS.get()->getSourceRange(); 11382 return QualType(); 11383} 11384 11385// checkArithmeticNull - Detect when a NULL constant is used improperly in an 11386// expression. These are mainly cases where the null pointer is used as an 11387// integer instead of a pointer. 11388static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 11389 SourceLocation Loc, bool IsCompare) { 11390 // The canonical way to check for a GNU null is with isNullPointerConstant, 11391 // but we use a bit of a hack here for speed; this is a relatively 11392 // hot path, and isNullPointerConstant is slow. 11393 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 11394 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 11395 11396 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 11397 11398 // Avoid analyzing cases where the result will either be invalid (and 11399 // diagnosed as such) or entirely valid and not something to warn about. 11400 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 11401 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 11402 return; 11403 11404 // Comparison operations would not make sense with a null pointer no matter 11405 // what the other expression is. 11406 if (!IsCompare) { 11407 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 11408 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 11409 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 11410 return; 11411 } 11412 11413 // The rest of the operations only make sense with a null pointer 11414 // if the other expression is a pointer. 11415 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 11416 NonNullType->canDecayToPointerType()) 11417 return; 11418 11419 S.Diag(Loc, diag::warn_null_in_comparison_operation) 11420 << LHSNull /* LHS is NULL */ << NonNullType 11421 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11422} 11423 11424static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 11425 SourceLocation Loc) { 11426 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 11427 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 11428 if (!LUE || !RUE) 11429 return; 11430 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 11431 RUE->getKind() != UETT_SizeOf) 11432 return; 11433 11434 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 11435 QualType LHSTy = LHSArg->getType(); 11436 QualType RHSTy; 11437 11438 if (RUE->isArgumentType()) 11439 RHSTy = RUE->getArgumentType().getNonReferenceType(); 11440 else 11441 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 11442 11443 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 11444 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 11445 return; 11446 11447 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 11448 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 11449 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 11450 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 11451 << LHSArgDecl; 11452 } 11453 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 11454 QualType ArrayElemTy = ArrayTy->getElementType(); 11455 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 11456 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 11457 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 11458 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 11459 return; 11460 S.Diag(Loc, diag::warn_division_sizeof_array) 11461 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 11462 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 11463 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 11464 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 11465 << LHSArgDecl; 11466 } 11467 11468 S.Diag(Loc, diag::note_precedence_silence) << RHS; 11469 } 11470} 11471 11472static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 11473 ExprResult &RHS, 11474 SourceLocation Loc, bool IsDiv) { 11475 // Check for division/remainder by zero. 11476 Expr::EvalResult RHSValue; 11477 if (!RHS.get()->isValueDependent() && 11478 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 11479 RHSValue.Val.getInt() == 0) 11480 S.DiagRuntimeBehavior(Loc, RHS.get(), 11481 S.PDiag(diag::warn_remainder_division_by_zero) 11482 << IsDiv << RHS.get()->getSourceRange()); 11483} 11484 11485QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 11486 SourceLocation Loc, 11487 bool IsCompAssign, bool IsDiv) { 11488 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11489 11490 QualType LHSTy = LHS.get()->getType(); 11491 QualType RHSTy = RHS.get()->getType(); 11492 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 11493 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11494 /*AllowBothBool*/ getLangOpts().AltiVec, 11495 /*AllowBoolConversions*/ false, 11496 /*AllowBooleanOperation*/ false, 11497 /*ReportInvalid*/ true); 11498 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType()) 11499 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 11500 ACK_Arithmetic); 11501 if (!IsDiv && 11502 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 11503 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 11504 // For division, only matrix-by-scalar is supported. Other combinations with 11505 // matrix types are invalid. 11506 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 11507 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 11508 11509 QualType compType = UsualArithmeticConversions( 11510 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 11511 if (LHS.isInvalid() || RHS.isInvalid()) 11512 return QualType(); 11513 11514 11515 if (compType.isNull() || !compType->isArithmeticType()) 11516 return InvalidOperands(Loc, LHS, RHS); 11517 if (IsDiv) { 11518 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 11519 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 11520 } 11521 return compType; 11522} 11523 11524QualType Sema::CheckRemainderOperands( 11525 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 11526 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11527 11528 if (LHS.get()->getType()->isVectorType() || 11529 RHS.get()->getType()->isVectorType()) { 11530 if (LHS.get()->getType()->hasIntegerRepresentation() && 11531 RHS.get()->getType()->hasIntegerRepresentation()) 11532 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11533 /*AllowBothBool*/ getLangOpts().AltiVec, 11534 /*AllowBoolConversions*/ false, 11535 /*AllowBooleanOperation*/ false, 11536 /*ReportInvalid*/ true); 11537 return InvalidOperands(Loc, LHS, RHS); 11538 } 11539 11540 if (LHS.get()->getType()->isSveVLSBuiltinType() || 11541 RHS.get()->getType()->isSveVLSBuiltinType()) { 11542 if (LHS.get()->getType()->hasIntegerRepresentation() && 11543 RHS.get()->getType()->hasIntegerRepresentation()) 11544 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 11545 ACK_Arithmetic); 11546 11547 return InvalidOperands(Loc, LHS, RHS); 11548 } 11549 11550 QualType compType = UsualArithmeticConversions( 11551 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 11552 if (LHS.isInvalid() || RHS.isInvalid()) 11553 return QualType(); 11554 11555 if (compType.isNull() || !compType->isIntegerType()) 11556 return InvalidOperands(Loc, LHS, RHS); 11557 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 11558 return compType; 11559} 11560 11561/// Diagnose invalid arithmetic on two void pointers. 11562static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 11563 Expr *LHSExpr, Expr *RHSExpr) { 11564 S.Diag(Loc, S.getLangOpts().CPlusPlus 11565 ? diag::err_typecheck_pointer_arith_void_type 11566 : diag::ext_gnu_void_ptr) 11567 << 1 /* two pointers */ << LHSExpr->getSourceRange() 11568 << RHSExpr->getSourceRange(); 11569} 11570 11571/// Diagnose invalid arithmetic on a void pointer. 11572static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 11573 Expr *Pointer) { 11574 S.Diag(Loc, S.getLangOpts().CPlusPlus 11575 ? diag::err_typecheck_pointer_arith_void_type 11576 : diag::ext_gnu_void_ptr) 11577 << 0 /* one pointer */ << Pointer->getSourceRange(); 11578} 11579 11580/// Diagnose invalid arithmetic on a null pointer. 11581/// 11582/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 11583/// idiom, which we recognize as a GNU extension. 11584/// 11585static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 11586 Expr *Pointer, bool IsGNUIdiom) { 11587 if (IsGNUIdiom) 11588 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 11589 << Pointer->getSourceRange(); 11590 else 11591 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 11592 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 11593} 11594 11595/// Diagnose invalid subraction on a null pointer. 11596/// 11597static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 11598 Expr *Pointer, bool BothNull) { 11599 // Null - null is valid in C++ [expr.add]p7 11600 if (BothNull && S.getLangOpts().CPlusPlus) 11601 return; 11602 11603 // Is this s a macro from a system header? 11604 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 11605 return; 11606 11607 S.DiagRuntimeBehavior(Loc, Pointer, 11608 S.PDiag(diag::warn_pointer_sub_null_ptr) 11609 << S.getLangOpts().CPlusPlus 11610 << Pointer->getSourceRange()); 11611} 11612 11613/// Diagnose invalid arithmetic on two function pointers. 11614static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 11615 Expr *LHS, Expr *RHS) { 11616 assert(LHS->getType()->isAnyPointerType()); 11617 assert(RHS->getType()->isAnyPointerType()); 11618 S.Diag(Loc, S.getLangOpts().CPlusPlus 11619 ? diag::err_typecheck_pointer_arith_function_type 11620 : diag::ext_gnu_ptr_func_arith) 11621 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 11622 // We only show the second type if it differs from the first. 11623 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 11624 RHS->getType()) 11625 << RHS->getType()->getPointeeType() 11626 << LHS->getSourceRange() << RHS->getSourceRange(); 11627} 11628 11629/// Diagnose invalid arithmetic on a function pointer. 11630static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 11631 Expr *Pointer) { 11632 assert(Pointer->getType()->isAnyPointerType()); 11633 S.Diag(Loc, S.getLangOpts().CPlusPlus 11634 ? diag::err_typecheck_pointer_arith_function_type 11635 : diag::ext_gnu_ptr_func_arith) 11636 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 11637 << 0 /* one pointer, so only one type */ 11638 << Pointer->getSourceRange(); 11639} 11640 11641/// Emit error if Operand is incomplete pointer type 11642/// 11643/// \returns True if pointer has incomplete type 11644static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 11645 Expr *Operand) { 11646 QualType ResType = Operand->getType(); 11647 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11648 ResType = ResAtomicType->getValueType(); 11649 11650 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 11651 QualType PointeeTy = ResType->getPointeeType(); 11652 return S.RequireCompleteSizedType( 11653 Loc, PointeeTy, 11654 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 11655 Operand->getSourceRange()); 11656} 11657 11658/// Check the validity of an arithmetic pointer operand. 11659/// 11660/// If the operand has pointer type, this code will check for pointer types 11661/// which are invalid in arithmetic operations. These will be diagnosed 11662/// appropriately, including whether or not the use is supported as an 11663/// extension. 11664/// 11665/// \returns True when the operand is valid to use (even if as an extension). 11666static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 11667 Expr *Operand) { 11668 QualType ResType = Operand->getType(); 11669 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11670 ResType = ResAtomicType->getValueType(); 11671 11672 if (!ResType->isAnyPointerType()) return true; 11673 11674 QualType PointeeTy = ResType->getPointeeType(); 11675 if (PointeeTy->isVoidType()) { 11676 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 11677 return !S.getLangOpts().CPlusPlus; 11678 } 11679 if (PointeeTy->isFunctionType()) { 11680 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 11681 return !S.getLangOpts().CPlusPlus; 11682 } 11683 11684 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 11685 11686 return true; 11687} 11688 11689/// Check the validity of a binary arithmetic operation w.r.t. pointer 11690/// operands. 11691/// 11692/// This routine will diagnose any invalid arithmetic on pointer operands much 11693/// like \see checkArithmeticOpPointerOperand. However, it has special logic 11694/// for emitting a single diagnostic even for operations where both LHS and RHS 11695/// are (potentially problematic) pointers. 11696/// 11697/// \returns True when the operand is valid to use (even if as an extension). 11698static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 11699 Expr *LHSExpr, Expr *RHSExpr) { 11700 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 11701 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 11702 if (!isLHSPointer && !isRHSPointer) return true; 11703 11704 QualType LHSPointeeTy, RHSPointeeTy; 11705 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 11706 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 11707 11708 // if both are pointers check if operation is valid wrt address spaces 11709 if (isLHSPointer && isRHSPointer) { 11710 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 11711 S.Diag(Loc, 11712 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11713 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 11714 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11715 return false; 11716 } 11717 } 11718 11719 // Check for arithmetic on pointers to incomplete types. 11720 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 11721 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 11722 if (isLHSVoidPtr || isRHSVoidPtr) { 11723 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 11724 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 11725 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 11726 11727 return !S.getLangOpts().CPlusPlus; 11728 } 11729 11730 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 11731 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 11732 if (isLHSFuncPtr || isRHSFuncPtr) { 11733 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 11734 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 11735 RHSExpr); 11736 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 11737 11738 return !S.getLangOpts().CPlusPlus; 11739 } 11740 11741 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 11742 return false; 11743 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 11744 return false; 11745 11746 return true; 11747} 11748 11749/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 11750/// literal. 11751static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 11752 Expr *LHSExpr, Expr *RHSExpr) { 11753 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 11754 Expr* IndexExpr = RHSExpr; 11755 if (!StrExpr) { 11756 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 11757 IndexExpr = LHSExpr; 11758 } 11759 11760 bool IsStringPlusInt = StrExpr && 11761 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 11762 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 11763 return; 11764 11765 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 11766 Self.Diag(OpLoc, diag::warn_string_plus_int) 11767 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 11768 11769 // Only print a fixit for "str" + int, not for int + "str". 11770 if (IndexExpr == RHSExpr) { 11771 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 11772 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 11773 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 11774 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 11775 << FixItHint::CreateInsertion(EndLoc, "]"); 11776 } else 11777 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 11778} 11779 11780/// Emit a warning when adding a char literal to a string. 11781static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 11782 Expr *LHSExpr, Expr *RHSExpr) { 11783 const Expr *StringRefExpr = LHSExpr; 11784 const CharacterLiteral *CharExpr = 11785 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 11786 11787 if (!CharExpr) { 11788 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 11789 StringRefExpr = RHSExpr; 11790 } 11791 11792 if (!CharExpr || !StringRefExpr) 11793 return; 11794 11795 const QualType StringType = StringRefExpr->getType(); 11796 11797 // Return if not a PointerType. 11798 if (!StringType->isAnyPointerType()) 11799 return; 11800 11801 // Return if not a CharacterType. 11802 if (!StringType->getPointeeType()->isAnyCharacterType()) 11803 return; 11804 11805 ASTContext &Ctx = Self.getASTContext(); 11806 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 11807 11808 const QualType CharType = CharExpr->getType(); 11809 if (!CharType->isAnyCharacterType() && 11810 CharType->isIntegerType() && 11811 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 11812 Self.Diag(OpLoc, diag::warn_string_plus_char) 11813 << DiagRange << Ctx.CharTy; 11814 } else { 11815 Self.Diag(OpLoc, diag::warn_string_plus_char) 11816 << DiagRange << CharExpr->getType(); 11817 } 11818 11819 // Only print a fixit for str + char, not for char + str. 11820 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 11821 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 11822 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 11823 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 11824 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 11825 << FixItHint::CreateInsertion(EndLoc, "]"); 11826 } else { 11827 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 11828 } 11829} 11830 11831/// Emit error when two pointers are incompatible. 11832static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 11833 Expr *LHSExpr, Expr *RHSExpr) { 11834 assert(LHSExpr->getType()->isAnyPointerType()); 11835 assert(RHSExpr->getType()->isAnyPointerType()); 11836 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 11837 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 11838 << RHSExpr->getSourceRange(); 11839} 11840 11841// C99 6.5.6 11842QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 11843 SourceLocation Loc, BinaryOperatorKind Opc, 11844 QualType* CompLHSTy) { 11845 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11846 11847 if (LHS.get()->getType()->isVectorType() || 11848 RHS.get()->getType()->isVectorType()) { 11849 QualType compType = 11850 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11851 /*AllowBothBool*/ getLangOpts().AltiVec, 11852 /*AllowBoolConversions*/ getLangOpts().ZVector, 11853 /*AllowBooleanOperation*/ false, 11854 /*ReportInvalid*/ true); 11855 if (CompLHSTy) *CompLHSTy = compType; 11856 return compType; 11857 } 11858 11859 if (LHS.get()->getType()->isSveVLSBuiltinType() || 11860 RHS.get()->getType()->isSveVLSBuiltinType()) { 11861 QualType compType = 11862 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11863 if (CompLHSTy) 11864 *CompLHSTy = compType; 11865 return compType; 11866 } 11867 11868 if (LHS.get()->getType()->isConstantMatrixType() || 11869 RHS.get()->getType()->isConstantMatrixType()) { 11870 QualType compType = 11871 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11872 if (CompLHSTy) 11873 *CompLHSTy = compType; 11874 return compType; 11875 } 11876 11877 QualType compType = UsualArithmeticConversions( 11878 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11879 if (LHS.isInvalid() || RHS.isInvalid()) 11880 return QualType(); 11881 11882 // Diagnose "string literal" '+' int and string '+' "char literal". 11883 if (Opc == BO_Add) { 11884 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 11885 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 11886 } 11887 11888 // handle the common case first (both operands are arithmetic). 11889 if (!compType.isNull() && compType->isArithmeticType()) { 11890 if (CompLHSTy) *CompLHSTy = compType; 11891 return compType; 11892 } 11893 11894 // Type-checking. Ultimately the pointer's going to be in PExp; 11895 // note that we bias towards the LHS being the pointer. 11896 Expr *PExp = LHS.get(), *IExp = RHS.get(); 11897 11898 bool isObjCPointer; 11899 if (PExp->getType()->isPointerType()) { 11900 isObjCPointer = false; 11901 } else if (PExp->getType()->isObjCObjectPointerType()) { 11902 isObjCPointer = true; 11903 } else { 11904 std::swap(PExp, IExp); 11905 if (PExp->getType()->isPointerType()) { 11906 isObjCPointer = false; 11907 } else if (PExp->getType()->isObjCObjectPointerType()) { 11908 isObjCPointer = true; 11909 } else { 11910 return InvalidOperands(Loc, LHS, RHS); 11911 } 11912 } 11913 assert(PExp->getType()->isAnyPointerType()); 11914 11915 if (!IExp->getType()->isIntegerType()) 11916 return InvalidOperands(Loc, LHS, RHS); 11917 11918 // Adding to a null pointer results in undefined behavior. 11919 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 11920 Context, Expr::NPC_ValueDependentIsNotNull)) { 11921 // In C++ adding zero to a null pointer is defined. 11922 Expr::EvalResult KnownVal; 11923 if (!getLangOpts().CPlusPlus || 11924 (!IExp->isValueDependent() && 11925 (!IExp->EvaluateAsInt(KnownVal, Context) || 11926 KnownVal.Val.getInt() != 0))) { 11927 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 11928 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 11929 Context, BO_Add, PExp, IExp); 11930 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 11931 } 11932 } 11933 11934 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 11935 return QualType(); 11936 11937 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 11938 return QualType(); 11939 11940 // Check array bounds for pointer arithemtic 11941 CheckArrayAccess(PExp, IExp); 11942 11943 if (CompLHSTy) { 11944 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 11945 if (LHSTy.isNull()) { 11946 LHSTy = LHS.get()->getType(); 11947 if (Context.isPromotableIntegerType(LHSTy)) 11948 LHSTy = Context.getPromotedIntegerType(LHSTy); 11949 } 11950 *CompLHSTy = LHSTy; 11951 } 11952 11953 return PExp->getType(); 11954} 11955 11956// C99 6.5.6 11957QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 11958 SourceLocation Loc, 11959 QualType* CompLHSTy) { 11960 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11961 11962 if (LHS.get()->getType()->isVectorType() || 11963 RHS.get()->getType()->isVectorType()) { 11964 QualType compType = 11965 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11966 /*AllowBothBool*/ getLangOpts().AltiVec, 11967 /*AllowBoolConversions*/ getLangOpts().ZVector, 11968 /*AllowBooleanOperation*/ false, 11969 /*ReportInvalid*/ true); 11970 if (CompLHSTy) *CompLHSTy = compType; 11971 return compType; 11972 } 11973 11974 if (LHS.get()->getType()->isSveVLSBuiltinType() || 11975 RHS.get()->getType()->isSveVLSBuiltinType()) { 11976 QualType compType = 11977 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11978 if (CompLHSTy) 11979 *CompLHSTy = compType; 11980 return compType; 11981 } 11982 11983 if (LHS.get()->getType()->isConstantMatrixType() || 11984 RHS.get()->getType()->isConstantMatrixType()) { 11985 QualType compType = 11986 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11987 if (CompLHSTy) 11988 *CompLHSTy = compType; 11989 return compType; 11990 } 11991 11992 QualType compType = UsualArithmeticConversions( 11993 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11994 if (LHS.isInvalid() || RHS.isInvalid()) 11995 return QualType(); 11996 11997 // Enforce type constraints: C99 6.5.6p3. 11998 11999 // Handle the common case first (both operands are arithmetic). 12000 if (!compType.isNull() && compType->isArithmeticType()) { 12001 if (CompLHSTy) *CompLHSTy = compType; 12002 return compType; 12003 } 12004 12005 // Either ptr - int or ptr - ptr. 12006 if (LHS.get()->getType()->isAnyPointerType()) { 12007 QualType lpointee = LHS.get()->getType()->getPointeeType(); 12008 12009 // Diagnose bad cases where we step over interface counts. 12010 if (LHS.get()->getType()->isObjCObjectPointerType() && 12011 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 12012 return QualType(); 12013 12014 // The result type of a pointer-int computation is the pointer type. 12015 if (RHS.get()->getType()->isIntegerType()) { 12016 // Subtracting from a null pointer should produce a warning. 12017 // The last argument to the diagnose call says this doesn't match the 12018 // GNU int-to-pointer idiom. 12019 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 12020 Expr::NPC_ValueDependentIsNotNull)) { 12021 // In C++ adding zero to a null pointer is defined. 12022 Expr::EvalResult KnownVal; 12023 if (!getLangOpts().CPlusPlus || 12024 (!RHS.get()->isValueDependent() && 12025 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 12026 KnownVal.Val.getInt() != 0))) { 12027 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 12028 } 12029 } 12030 12031 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 12032 return QualType(); 12033 12034 // Check array bounds for pointer arithemtic 12035 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 12036 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 12037 12038 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 12039 return LHS.get()->getType(); 12040 } 12041 12042 // Handle pointer-pointer subtractions. 12043 if (const PointerType *RHSPTy 12044 = RHS.get()->getType()->getAs<PointerType>()) { 12045 QualType rpointee = RHSPTy->getPointeeType(); 12046 12047 if (getLangOpts().CPlusPlus) { 12048 // Pointee types must be the same: C++ [expr.add] 12049 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 12050 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 12051 } 12052 } else { 12053 // Pointee types must be compatible C99 6.5.6p3 12054 if (!Context.typesAreCompatible( 12055 Context.getCanonicalType(lpointee).getUnqualifiedType(), 12056 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 12057 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 12058 return QualType(); 12059 } 12060 } 12061 12062 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 12063 LHS.get(), RHS.get())) 12064 return QualType(); 12065 12066 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 12067 Context, Expr::NPC_ValueDependentIsNotNull); 12068 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 12069 Context, Expr::NPC_ValueDependentIsNotNull); 12070 12071 // Subtracting nullptr or from nullptr is suspect 12072 if (LHSIsNullPtr) 12073 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 12074 if (RHSIsNullPtr) 12075 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 12076 12077 // The pointee type may have zero size. As an extension, a structure or 12078 // union may have zero size or an array may have zero length. In this 12079 // case subtraction does not make sense. 12080 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 12081 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 12082 if (ElementSize.isZero()) { 12083 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 12084 << rpointee.getUnqualifiedType() 12085 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12086 } 12087 } 12088 12089 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 12090 return Context.getPointerDiffType(); 12091 } 12092 } 12093 12094 return InvalidOperands(Loc, LHS, RHS); 12095} 12096 12097static bool isScopedEnumerationType(QualType T) { 12098 if (const EnumType *ET = T->getAs<EnumType>()) 12099 return ET->getDecl()->isScoped(); 12100 return false; 12101} 12102 12103static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 12104 SourceLocation Loc, BinaryOperatorKind Opc, 12105 QualType LHSType) { 12106 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 12107 // so skip remaining warnings as we don't want to modify values within Sema. 12108 if (S.getLangOpts().OpenCL) 12109 return; 12110 12111 // Check right/shifter operand 12112 Expr::EvalResult RHSResult; 12113 if (RHS.get()->isValueDependent() || 12114 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 12115 return; 12116 llvm::APSInt Right = RHSResult.Val.getInt(); 12117 12118 if (Right.isNegative()) { 12119 S.DiagRuntimeBehavior(Loc, RHS.get(), 12120 S.PDiag(diag::warn_shift_negative) 12121 << RHS.get()->getSourceRange()); 12122 return; 12123 } 12124 12125 QualType LHSExprType = LHS.get()->getType(); 12126 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 12127 if (LHSExprType->isBitIntType()) 12128 LeftSize = S.Context.getIntWidth(LHSExprType); 12129 else if (LHSExprType->isFixedPointType()) { 12130 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 12131 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 12132 } 12133 if (Right.uge(LeftSize)) { 12134 S.DiagRuntimeBehavior(Loc, RHS.get(), 12135 S.PDiag(diag::warn_shift_gt_typewidth) 12136 << RHS.get()->getSourceRange()); 12137 return; 12138 } 12139 12140 // FIXME: We probably need to handle fixed point types specially here. 12141 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 12142 return; 12143 12144 // When left shifting an ICE which is signed, we can check for overflow which 12145 // according to C++ standards prior to C++2a has undefined behavior 12146 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 12147 // more than the maximum value representable in the result type, so never 12148 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 12149 // expression is still probably a bug.) 12150 Expr::EvalResult LHSResult; 12151 if (LHS.get()->isValueDependent() || 12152 LHSType->hasUnsignedIntegerRepresentation() || 12153 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 12154 return; 12155 llvm::APSInt Left = LHSResult.Val.getInt(); 12156 12157 // Don't warn if signed overflow is defined, then all the rest of the 12158 // diagnostics will not be triggered because the behavior is defined. 12159 // Also don't warn in C++20 mode (and newer), as signed left shifts 12160 // always wrap and never overflow. 12161 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20) 12162 return; 12163 12164 // If LHS does not have a non-negative value then, the 12165 // behavior is undefined before C++2a. Warn about it. 12166 if (Left.isNegative()) { 12167 S.DiagRuntimeBehavior(Loc, LHS.get(), 12168 S.PDiag(diag::warn_shift_lhs_negative) 12169 << LHS.get()->getSourceRange()); 12170 return; 12171 } 12172 12173 llvm::APInt ResultBits = 12174 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits(); 12175 if (ResultBits.ule(LeftSize)) 12176 return; 12177 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 12178 Result = Result.shl(Right); 12179 12180 // Print the bit representation of the signed integer as an unsigned 12181 // hexadecimal number. 12182 SmallString<40> HexResult; 12183 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 12184 12185 // If we are only missing a sign bit, this is less likely to result in actual 12186 // bugs -- if the result is cast back to an unsigned type, it will have the 12187 // expected value. Thus we place this behind a different warning that can be 12188 // turned off separately if needed. 12189 if (ResultBits - 1 == LeftSize) { 12190 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 12191 << HexResult << LHSType 12192 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12193 return; 12194 } 12195 12196 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 12197 << HexResult.str() << Result.getSignificantBits() << LHSType 12198 << Left.getBitWidth() << LHS.get()->getSourceRange() 12199 << RHS.get()->getSourceRange(); 12200} 12201 12202/// Return the resulting type when a vector is shifted 12203/// by a scalar or vector shift amount. 12204static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 12205 SourceLocation Loc, bool IsCompAssign) { 12206 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 12207 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 12208 !LHS.get()->getType()->isVectorType()) { 12209 S.Diag(Loc, diag::err_shift_rhs_only_vector) 12210 << RHS.get()->getType() << LHS.get()->getType() 12211 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12212 return QualType(); 12213 } 12214 12215 if (!IsCompAssign) { 12216 LHS = S.UsualUnaryConversions(LHS.get()); 12217 if (LHS.isInvalid()) return QualType(); 12218 } 12219 12220 RHS = S.UsualUnaryConversions(RHS.get()); 12221 if (RHS.isInvalid()) return QualType(); 12222 12223 QualType LHSType = LHS.get()->getType(); 12224 // Note that LHS might be a scalar because the routine calls not only in 12225 // OpenCL case. 12226 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 12227 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 12228 12229 // Note that RHS might not be a vector. 12230 QualType RHSType = RHS.get()->getType(); 12231 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 12232 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 12233 12234 // Do not allow shifts for boolean vectors. 12235 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || 12236 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { 12237 S.Diag(Loc, diag::err_typecheck_invalid_operands) 12238 << LHS.get()->getType() << RHS.get()->getType() 12239 << LHS.get()->getSourceRange(); 12240 return QualType(); 12241 } 12242 12243 // The operands need to be integers. 12244 if (!LHSEleType->isIntegerType()) { 12245 S.Diag(Loc, diag::err_typecheck_expect_int) 12246 << LHS.get()->getType() << LHS.get()->getSourceRange(); 12247 return QualType(); 12248 } 12249 12250 if (!RHSEleType->isIntegerType()) { 12251 S.Diag(Loc, diag::err_typecheck_expect_int) 12252 << RHS.get()->getType() << RHS.get()->getSourceRange(); 12253 return QualType(); 12254 } 12255 12256 if (!LHSVecTy) { 12257 assert(RHSVecTy); 12258 if (IsCompAssign) 12259 return RHSType; 12260 if (LHSEleType != RHSEleType) { 12261 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 12262 LHSEleType = RHSEleType; 12263 } 12264 QualType VecTy = 12265 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 12266 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 12267 LHSType = VecTy; 12268 } else if (RHSVecTy) { 12269 // OpenCL v1.1 s6.3.j says that for vector types, the operators 12270 // are applied component-wise. So if RHS is a vector, then ensure 12271 // that the number of elements is the same as LHS... 12272 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 12273 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 12274 << LHS.get()->getType() << RHS.get()->getType() 12275 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12276 return QualType(); 12277 } 12278 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 12279 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 12280 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 12281 if (LHSBT != RHSBT && 12282 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 12283 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 12284 << LHS.get()->getType() << RHS.get()->getType() 12285 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12286 } 12287 } 12288 } else { 12289 // ...else expand RHS to match the number of elements in LHS. 12290 QualType VecTy = 12291 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 12292 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 12293 } 12294 12295 return LHSType; 12296} 12297 12298static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, 12299 ExprResult &RHS, SourceLocation Loc, 12300 bool IsCompAssign) { 12301 if (!IsCompAssign) { 12302 LHS = S.UsualUnaryConversions(LHS.get()); 12303 if (LHS.isInvalid()) 12304 return QualType(); 12305 } 12306 12307 RHS = S.UsualUnaryConversions(RHS.get()); 12308 if (RHS.isInvalid()) 12309 return QualType(); 12310 12311 QualType LHSType = LHS.get()->getType(); 12312 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>(); 12313 QualType LHSEleType = LHSType->isSveVLSBuiltinType() 12314 ? LHSBuiltinTy->getSveEltType(S.getASTContext()) 12315 : LHSType; 12316 12317 // Note that RHS might not be a vector 12318 QualType RHSType = RHS.get()->getType(); 12319 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>(); 12320 QualType RHSEleType = RHSType->isSveVLSBuiltinType() 12321 ? RHSBuiltinTy->getSveEltType(S.getASTContext()) 12322 : RHSType; 12323 12324 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || 12325 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) { 12326 S.Diag(Loc, diag::err_typecheck_invalid_operands) 12327 << LHSType << RHSType << LHS.get()->getSourceRange(); 12328 return QualType(); 12329 } 12330 12331 if (!LHSEleType->isIntegerType()) { 12332 S.Diag(Loc, diag::err_typecheck_expect_int) 12333 << LHS.get()->getType() << LHS.get()->getSourceRange(); 12334 return QualType(); 12335 } 12336 12337 if (!RHSEleType->isIntegerType()) { 12338 S.Diag(Loc, diag::err_typecheck_expect_int) 12339 << RHS.get()->getType() << RHS.get()->getSourceRange(); 12340 return QualType(); 12341 } 12342 12343 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() && 12344 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != 12345 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) { 12346 S.Diag(Loc, diag::err_typecheck_invalid_operands) 12347 << LHSType << RHSType << LHS.get()->getSourceRange() 12348 << RHS.get()->getSourceRange(); 12349 return QualType(); 12350 } 12351 12352 if (!LHSType->isSveVLSBuiltinType()) { 12353 assert(RHSType->isSveVLSBuiltinType()); 12354 if (IsCompAssign) 12355 return RHSType; 12356 if (LHSEleType != RHSEleType) { 12357 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast); 12358 LHSEleType = RHSEleType; 12359 } 12360 const llvm::ElementCount VecSize = 12361 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC; 12362 QualType VecTy = 12363 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue()); 12364 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat); 12365 LHSType = VecTy; 12366 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) { 12367 if (S.Context.getTypeSize(RHSBuiltinTy) != 12368 S.Context.getTypeSize(LHSBuiltinTy)) { 12369 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 12370 << LHSType << RHSType << LHS.get()->getSourceRange() 12371 << RHS.get()->getSourceRange(); 12372 return QualType(); 12373 } 12374 } else { 12375 const llvm::ElementCount VecSize = 12376 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC; 12377 if (LHSEleType != RHSEleType) { 12378 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast); 12379 RHSEleType = LHSEleType; 12380 } 12381 QualType VecTy = 12382 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue()); 12383 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 12384 } 12385 12386 return LHSType; 12387} 12388 12389// C99 6.5.7 12390QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 12391 SourceLocation Loc, BinaryOperatorKind Opc, 12392 bool IsCompAssign) { 12393 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12394 12395 // Vector shifts promote their scalar inputs to vector type. 12396 if (LHS.get()->getType()->isVectorType() || 12397 RHS.get()->getType()->isVectorType()) { 12398 if (LangOpts.ZVector) { 12399 // The shift operators for the z vector extensions work basically 12400 // like general shifts, except that neither the LHS nor the RHS is 12401 // allowed to be a "vector bool". 12402 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 12403 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool) 12404 return InvalidOperands(Loc, LHS, RHS); 12405 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 12406 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool) 12407 return InvalidOperands(Loc, LHS, RHS); 12408 } 12409 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 12410 } 12411 12412 if (LHS.get()->getType()->isSveVLSBuiltinType() || 12413 RHS.get()->getType()->isSveVLSBuiltinType()) 12414 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 12415 12416 // Shifts don't perform usual arithmetic conversions, they just do integer 12417 // promotions on each operand. C99 6.5.7p3 12418 12419 // For the LHS, do usual unary conversions, but then reset them away 12420 // if this is a compound assignment. 12421 ExprResult OldLHS = LHS; 12422 LHS = UsualUnaryConversions(LHS.get()); 12423 if (LHS.isInvalid()) 12424 return QualType(); 12425 QualType LHSType = LHS.get()->getType(); 12426 if (IsCompAssign) LHS = OldLHS; 12427 12428 // The RHS is simpler. 12429 RHS = UsualUnaryConversions(RHS.get()); 12430 if (RHS.isInvalid()) 12431 return QualType(); 12432 QualType RHSType = RHS.get()->getType(); 12433 12434 // C99 6.5.7p2: Each of the operands shall have integer type. 12435 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 12436 if ((!LHSType->isFixedPointOrIntegerType() && 12437 !LHSType->hasIntegerRepresentation()) || 12438 !RHSType->hasIntegerRepresentation()) 12439 return InvalidOperands(Loc, LHS, RHS); 12440 12441 // C++0x: Don't allow scoped enums. FIXME: Use something better than 12442 // hasIntegerRepresentation() above instead of this. 12443 if (isScopedEnumerationType(LHSType) || 12444 isScopedEnumerationType(RHSType)) { 12445 return InvalidOperands(Loc, LHS, RHS); 12446 } 12447 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 12448 12449 // "The type of the result is that of the promoted left operand." 12450 return LHSType; 12451} 12452 12453/// Diagnose bad pointer comparisons. 12454static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 12455 ExprResult &LHS, ExprResult &RHS, 12456 bool IsError) { 12457 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 12458 : diag::ext_typecheck_comparison_of_distinct_pointers) 12459 << LHS.get()->getType() << RHS.get()->getType() 12460 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12461} 12462 12463/// Returns false if the pointers are converted to a composite type, 12464/// true otherwise. 12465static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 12466 ExprResult &LHS, ExprResult &RHS) { 12467 // C++ [expr.rel]p2: 12468 // [...] Pointer conversions (4.10) and qualification 12469 // conversions (4.4) are performed on pointer operands (or on 12470 // a pointer operand and a null pointer constant) to bring 12471 // them to their composite pointer type. [...] 12472 // 12473 // C++ [expr.eq]p1 uses the same notion for (in)equality 12474 // comparisons of pointers. 12475 12476 QualType LHSType = LHS.get()->getType(); 12477 QualType RHSType = RHS.get()->getType(); 12478 assert(LHSType->isPointerType() || RHSType->isPointerType() || 12479 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 12480 12481 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 12482 if (T.isNull()) { 12483 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 12484 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 12485 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 12486 else 12487 S.InvalidOperands(Loc, LHS, RHS); 12488 return true; 12489 } 12490 12491 return false; 12492} 12493 12494static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 12495 ExprResult &LHS, 12496 ExprResult &RHS, 12497 bool IsError) { 12498 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 12499 : diag::ext_typecheck_comparison_of_fptr_to_void) 12500 << LHS.get()->getType() << RHS.get()->getType() 12501 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12502} 12503 12504static bool isObjCObjectLiteral(ExprResult &E) { 12505 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 12506 case Stmt::ObjCArrayLiteralClass: 12507 case Stmt::ObjCDictionaryLiteralClass: 12508 case Stmt::ObjCStringLiteralClass: 12509 case Stmt::ObjCBoxedExprClass: 12510 return true; 12511 default: 12512 // Note that ObjCBoolLiteral is NOT an object literal! 12513 return false; 12514 } 12515} 12516 12517static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 12518 const ObjCObjectPointerType *Type = 12519 LHS->getType()->getAs<ObjCObjectPointerType>(); 12520 12521 // If this is not actually an Objective-C object, bail out. 12522 if (!Type) 12523 return false; 12524 12525 // Get the LHS object's interface type. 12526 QualType InterfaceType = Type->getPointeeType(); 12527 12528 // If the RHS isn't an Objective-C object, bail out. 12529 if (!RHS->getType()->isObjCObjectPointerType()) 12530 return false; 12531 12532 // Try to find the -isEqual: method. 12533 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 12534 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 12535 InterfaceType, 12536 /*IsInstance=*/true); 12537 if (!Method) { 12538 if (Type->isObjCIdType()) { 12539 // For 'id', just check the global pool. 12540 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 12541 /*receiverId=*/true); 12542 } else { 12543 // Check protocols. 12544 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 12545 /*IsInstance=*/true); 12546 } 12547 } 12548 12549 if (!Method) 12550 return false; 12551 12552 QualType T = Method->parameters()[0]->getType(); 12553 if (!T->isObjCObjectPointerType()) 12554 return false; 12555 12556 QualType R = Method->getReturnType(); 12557 if (!R->isScalarType()) 12558 return false; 12559 12560 return true; 12561} 12562 12563Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 12564 FromE = FromE->IgnoreParenImpCasts(); 12565 switch (FromE->getStmtClass()) { 12566 default: 12567 break; 12568 case Stmt::ObjCStringLiteralClass: 12569 // "string literal" 12570 return LK_String; 12571 case Stmt::ObjCArrayLiteralClass: 12572 // "array literal" 12573 return LK_Array; 12574 case Stmt::ObjCDictionaryLiteralClass: 12575 // "dictionary literal" 12576 return LK_Dictionary; 12577 case Stmt::BlockExprClass: 12578 return LK_Block; 12579 case Stmt::ObjCBoxedExprClass: { 12580 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 12581 switch (Inner->getStmtClass()) { 12582 case Stmt::IntegerLiteralClass: 12583 case Stmt::FloatingLiteralClass: 12584 case Stmt::CharacterLiteralClass: 12585 case Stmt::ObjCBoolLiteralExprClass: 12586 case Stmt::CXXBoolLiteralExprClass: 12587 // "numeric literal" 12588 return LK_Numeric; 12589 case Stmt::ImplicitCastExprClass: { 12590 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 12591 // Boolean literals can be represented by implicit casts. 12592 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 12593 return LK_Numeric; 12594 break; 12595 } 12596 default: 12597 break; 12598 } 12599 return LK_Boxed; 12600 } 12601 } 12602 return LK_None; 12603} 12604 12605static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 12606 ExprResult &LHS, ExprResult &RHS, 12607 BinaryOperator::Opcode Opc){ 12608 Expr *Literal; 12609 Expr *Other; 12610 if (isObjCObjectLiteral(LHS)) { 12611 Literal = LHS.get(); 12612 Other = RHS.get(); 12613 } else { 12614 Literal = RHS.get(); 12615 Other = LHS.get(); 12616 } 12617 12618 // Don't warn on comparisons against nil. 12619 Other = Other->IgnoreParenCasts(); 12620 if (Other->isNullPointerConstant(S.getASTContext(), 12621 Expr::NPC_ValueDependentIsNotNull)) 12622 return; 12623 12624 // This should be kept in sync with warn_objc_literal_comparison. 12625 // LK_String should always be after the other literals, since it has its own 12626 // warning flag. 12627 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 12628 assert(LiteralKind != Sema::LK_Block); 12629 if (LiteralKind == Sema::LK_None) { 12630 llvm_unreachable("Unknown Objective-C object literal kind"); 12631 } 12632 12633 if (LiteralKind == Sema::LK_String) 12634 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 12635 << Literal->getSourceRange(); 12636 else 12637 S.Diag(Loc, diag::warn_objc_literal_comparison) 12638 << LiteralKind << Literal->getSourceRange(); 12639 12640 if (BinaryOperator::isEqualityOp(Opc) && 12641 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 12642 SourceLocation Start = LHS.get()->getBeginLoc(); 12643 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 12644 CharSourceRange OpRange = 12645 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12646 12647 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 12648 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 12649 << FixItHint::CreateReplacement(OpRange, " isEqual:") 12650 << FixItHint::CreateInsertion(End, "]"); 12651 } 12652} 12653 12654/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 12655static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 12656 ExprResult &RHS, SourceLocation Loc, 12657 BinaryOperatorKind Opc) { 12658 // Check that left hand side is !something. 12659 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 12660 if (!UO || UO->getOpcode() != UO_LNot) return; 12661 12662 // Only check if the right hand side is non-bool arithmetic type. 12663 if (RHS.get()->isKnownToHaveBooleanValue()) return; 12664 12665 // Make sure that the something in !something is not bool. 12666 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 12667 if (SubExpr->isKnownToHaveBooleanValue()) return; 12668 12669 // Emit warning. 12670 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 12671 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 12672 << Loc << IsBitwiseOp; 12673 12674 // First note suggest !(x < y) 12675 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 12676 SourceLocation FirstClose = RHS.get()->getEndLoc(); 12677 FirstClose = S.getLocForEndOfToken(FirstClose); 12678 if (FirstClose.isInvalid()) 12679 FirstOpen = SourceLocation(); 12680 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 12681 << IsBitwiseOp 12682 << FixItHint::CreateInsertion(FirstOpen, "(") 12683 << FixItHint::CreateInsertion(FirstClose, ")"); 12684 12685 // Second note suggests (!x) < y 12686 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 12687 SourceLocation SecondClose = LHS.get()->getEndLoc(); 12688 SecondClose = S.getLocForEndOfToken(SecondClose); 12689 if (SecondClose.isInvalid()) 12690 SecondOpen = SourceLocation(); 12691 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 12692 << FixItHint::CreateInsertion(SecondOpen, "(") 12693 << FixItHint::CreateInsertion(SecondClose, ")"); 12694} 12695 12696// Returns true if E refers to a non-weak array. 12697static bool checkForArray(const Expr *E) { 12698 const ValueDecl *D = nullptr; 12699 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 12700 D = DR->getDecl(); 12701 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 12702 if (Mem->isImplicitAccess()) 12703 D = Mem->getMemberDecl(); 12704 } 12705 if (!D) 12706 return false; 12707 return D->getType()->isArrayType() && !D->isWeak(); 12708} 12709 12710/// Diagnose some forms of syntactically-obvious tautological comparison. 12711static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 12712 Expr *LHS, Expr *RHS, 12713 BinaryOperatorKind Opc) { 12714 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 12715 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 12716 12717 QualType LHSType = LHS->getType(); 12718 QualType RHSType = RHS->getType(); 12719 if (LHSType->hasFloatingRepresentation() || 12720 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 12721 S.inTemplateInstantiation()) 12722 return; 12723 12724 // WebAssembly Tables cannot be compared, therefore shouldn't emit 12725 // Tautological diagnostics. 12726 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType()) 12727 return; 12728 12729 // Comparisons between two array types are ill-formed for operator<=>, so 12730 // we shouldn't emit any additional warnings about it. 12731 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 12732 return; 12733 12734 // For non-floating point types, check for self-comparisons of the form 12735 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12736 // often indicate logic errors in the program. 12737 // 12738 // NOTE: Don't warn about comparison expressions resulting from macro 12739 // expansion. Also don't warn about comparisons which are only self 12740 // comparisons within a template instantiation. The warnings should catch 12741 // obvious cases in the definition of the template anyways. The idea is to 12742 // warn when the typed comparison operator will always evaluate to the same 12743 // result. 12744 12745 // Used for indexing into %select in warn_comparison_always 12746 enum { 12747 AlwaysConstant, 12748 AlwaysTrue, 12749 AlwaysFalse, 12750 AlwaysEqual, // std::strong_ordering::equal from operator<=> 12751 }; 12752 12753 // C++2a [depr.array.comp]: 12754 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 12755 // operands of array type are deprecated. 12756 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 12757 RHSStripped->getType()->isArrayType()) { 12758 S.Diag(Loc, diag::warn_depr_array_comparison) 12759 << LHS->getSourceRange() << RHS->getSourceRange() 12760 << LHSStripped->getType() << RHSStripped->getType(); 12761 // Carry on to produce the tautological comparison warning, if this 12762 // expression is potentially-evaluated, we can resolve the array to a 12763 // non-weak declaration, and so on. 12764 } 12765 12766 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 12767 if (Expr::isSameComparisonOperand(LHS, RHS)) { 12768 unsigned Result; 12769 switch (Opc) { 12770 case BO_EQ: 12771 case BO_LE: 12772 case BO_GE: 12773 Result = AlwaysTrue; 12774 break; 12775 case BO_NE: 12776 case BO_LT: 12777 case BO_GT: 12778 Result = AlwaysFalse; 12779 break; 12780 case BO_Cmp: 12781 Result = AlwaysEqual; 12782 break; 12783 default: 12784 Result = AlwaysConstant; 12785 break; 12786 } 12787 S.DiagRuntimeBehavior(Loc, nullptr, 12788 S.PDiag(diag::warn_comparison_always) 12789 << 0 /*self-comparison*/ 12790 << Result); 12791 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 12792 // What is it always going to evaluate to? 12793 unsigned Result; 12794 switch (Opc) { 12795 case BO_EQ: // e.g. array1 == array2 12796 Result = AlwaysFalse; 12797 break; 12798 case BO_NE: // e.g. array1 != array2 12799 Result = AlwaysTrue; 12800 break; 12801 default: // e.g. array1 <= array2 12802 // The best we can say is 'a constant' 12803 Result = AlwaysConstant; 12804 break; 12805 } 12806 S.DiagRuntimeBehavior(Loc, nullptr, 12807 S.PDiag(diag::warn_comparison_always) 12808 << 1 /*array comparison*/ 12809 << Result); 12810 } 12811 } 12812 12813 if (isa<CastExpr>(LHSStripped)) 12814 LHSStripped = LHSStripped->IgnoreParenCasts(); 12815 if (isa<CastExpr>(RHSStripped)) 12816 RHSStripped = RHSStripped->IgnoreParenCasts(); 12817 12818 // Warn about comparisons against a string constant (unless the other 12819 // operand is null); the user probably wants string comparison function. 12820 Expr *LiteralString = nullptr; 12821 Expr *LiteralStringStripped = nullptr; 12822 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 12823 !RHSStripped->isNullPointerConstant(S.Context, 12824 Expr::NPC_ValueDependentIsNull)) { 12825 LiteralString = LHS; 12826 LiteralStringStripped = LHSStripped; 12827 } else if ((isa<StringLiteral>(RHSStripped) || 12828 isa<ObjCEncodeExpr>(RHSStripped)) && 12829 !LHSStripped->isNullPointerConstant(S.Context, 12830 Expr::NPC_ValueDependentIsNull)) { 12831 LiteralString = RHS; 12832 LiteralStringStripped = RHSStripped; 12833 } 12834 12835 if (LiteralString) { 12836 S.DiagRuntimeBehavior(Loc, nullptr, 12837 S.PDiag(diag::warn_stringcompare) 12838 << isa<ObjCEncodeExpr>(LiteralStringStripped) 12839 << LiteralString->getSourceRange()); 12840 } 12841} 12842 12843static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 12844 switch (CK) { 12845 default: { 12846#ifndef NDEBUG 12847 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 12848 << "\n"; 12849#endif 12850 llvm_unreachable("unhandled cast kind"); 12851 } 12852 case CK_UserDefinedConversion: 12853 return ICK_Identity; 12854 case CK_LValueToRValue: 12855 return ICK_Lvalue_To_Rvalue; 12856 case CK_ArrayToPointerDecay: 12857 return ICK_Array_To_Pointer; 12858 case CK_FunctionToPointerDecay: 12859 return ICK_Function_To_Pointer; 12860 case CK_IntegralCast: 12861 return ICK_Integral_Conversion; 12862 case CK_FloatingCast: 12863 return ICK_Floating_Conversion; 12864 case CK_IntegralToFloating: 12865 case CK_FloatingToIntegral: 12866 return ICK_Floating_Integral; 12867 case CK_IntegralComplexCast: 12868 case CK_FloatingComplexCast: 12869 case CK_FloatingComplexToIntegralComplex: 12870 case CK_IntegralComplexToFloatingComplex: 12871 return ICK_Complex_Conversion; 12872 case CK_FloatingComplexToReal: 12873 case CK_FloatingRealToComplex: 12874 case CK_IntegralComplexToReal: 12875 case CK_IntegralRealToComplex: 12876 return ICK_Complex_Real; 12877 } 12878} 12879 12880static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 12881 QualType FromType, 12882 SourceLocation Loc) { 12883 // Check for a narrowing implicit conversion. 12884 StandardConversionSequence SCS; 12885 SCS.setAsIdentityConversion(); 12886 SCS.setToType(0, FromType); 12887 SCS.setToType(1, ToType); 12888 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 12889 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 12890 12891 APValue PreNarrowingValue; 12892 QualType PreNarrowingType; 12893 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 12894 PreNarrowingType, 12895 /*IgnoreFloatToIntegralConversion*/ true)) { 12896 case NK_Dependent_Narrowing: 12897 // Implicit conversion to a narrower type, but the expression is 12898 // value-dependent so we can't tell whether it's actually narrowing. 12899 case NK_Not_Narrowing: 12900 return false; 12901 12902 case NK_Constant_Narrowing: 12903 // Implicit conversion to a narrower type, and the value is not a constant 12904 // expression. 12905 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12906 << /*Constant*/ 1 12907 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 12908 return true; 12909 12910 case NK_Variable_Narrowing: 12911 // Implicit conversion to a narrower type, and the value is not a constant 12912 // expression. 12913 case NK_Type_Narrowing: 12914 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12915 << /*Constant*/ 0 << FromType << ToType; 12916 // TODO: It's not a constant expression, but what if the user intended it 12917 // to be? Can we produce notes to help them figure out why it isn't? 12918 return true; 12919 } 12920 llvm_unreachable("unhandled case in switch"); 12921} 12922 12923static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 12924 ExprResult &LHS, 12925 ExprResult &RHS, 12926 SourceLocation Loc) { 12927 QualType LHSType = LHS.get()->getType(); 12928 QualType RHSType = RHS.get()->getType(); 12929 // Dig out the original argument type and expression before implicit casts 12930 // were applied. These are the types/expressions we need to check the 12931 // [expr.spaceship] requirements against. 12932 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 12933 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 12934 QualType LHSStrippedType = LHSStripped.get()->getType(); 12935 QualType RHSStrippedType = RHSStripped.get()->getType(); 12936 12937 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 12938 // other is not, the program is ill-formed. 12939 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 12940 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12941 return QualType(); 12942 } 12943 12944 // FIXME: Consider combining this with checkEnumArithmeticConversions. 12945 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 12946 RHSStrippedType->isEnumeralType(); 12947 if (NumEnumArgs == 1) { 12948 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 12949 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 12950 if (OtherTy->hasFloatingRepresentation()) { 12951 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12952 return QualType(); 12953 } 12954 } 12955 if (NumEnumArgs == 2) { 12956 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 12957 // type E, the operator yields the result of converting the operands 12958 // to the underlying type of E and applying <=> to the converted operands. 12959 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 12960 S.InvalidOperands(Loc, LHS, RHS); 12961 return QualType(); 12962 } 12963 QualType IntType = 12964 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 12965 assert(IntType->isArithmeticType()); 12966 12967 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 12968 // promote the boolean type, and all other promotable integer types, to 12969 // avoid this. 12970 if (S.Context.isPromotableIntegerType(IntType)) 12971 IntType = S.Context.getPromotedIntegerType(IntType); 12972 12973 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 12974 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 12975 LHSType = RHSType = IntType; 12976 } 12977 12978 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 12979 // usual arithmetic conversions are applied to the operands. 12980 QualType Type = 12981 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12982 if (LHS.isInvalid() || RHS.isInvalid()) 12983 return QualType(); 12984 if (Type.isNull()) 12985 return S.InvalidOperands(Loc, LHS, RHS); 12986 12987 std::optional<ComparisonCategoryType> CCT = 12988 getComparisonCategoryForBuiltinCmp(Type); 12989 if (!CCT) 12990 return S.InvalidOperands(Loc, LHS, RHS); 12991 12992 bool HasNarrowing = checkThreeWayNarrowingConversion( 12993 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 12994 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 12995 RHS.get()->getBeginLoc()); 12996 if (HasNarrowing) 12997 return QualType(); 12998 12999 assert(!Type.isNull() && "composite type for <=> has not been set"); 13000 13001 return S.CheckComparisonCategoryType( 13002 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 13003} 13004 13005static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 13006 ExprResult &RHS, 13007 SourceLocation Loc, 13008 BinaryOperatorKind Opc) { 13009 if (Opc == BO_Cmp) 13010 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 13011 13012 // C99 6.5.8p3 / C99 6.5.9p4 13013 QualType Type = 13014 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 13015 if (LHS.isInvalid() || RHS.isInvalid()) 13016 return QualType(); 13017 if (Type.isNull()) 13018 return S.InvalidOperands(Loc, LHS, RHS); 13019 assert(Type->isArithmeticType() || Type->isEnumeralType()); 13020 13021 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 13022 return S.InvalidOperands(Loc, LHS, RHS); 13023 13024 // Check for comparisons of floating point operands using != and ==. 13025 if (Type->hasFloatingRepresentation()) 13026 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 13027 13028 // The result of comparisons is 'bool' in C++, 'int' in C. 13029 return S.Context.getLogicalOperationType(); 13030} 13031 13032void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 13033 if (!NullE.get()->getType()->isAnyPointerType()) 13034 return; 13035 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 13036 if (!E.get()->getType()->isAnyPointerType() && 13037 E.get()->isNullPointerConstant(Context, 13038 Expr::NPC_ValueDependentIsNotNull) == 13039 Expr::NPCK_ZeroExpression) { 13040 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 13041 if (CL->getValue() == 0) 13042 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 13043 << NullValue 13044 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 13045 NullValue ? "NULL" : "(void *)0"); 13046 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 13047 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 13048 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 13049 if (T == Context.CharTy) 13050 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 13051 << NullValue 13052 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 13053 NullValue ? "NULL" : "(void *)0"); 13054 } 13055 } 13056} 13057 13058// C99 6.5.8, C++ [expr.rel] 13059QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 13060 SourceLocation Loc, 13061 BinaryOperatorKind Opc) { 13062 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 13063 bool IsThreeWay = Opc == BO_Cmp; 13064 bool IsOrdered = IsRelational || IsThreeWay; 13065 auto IsAnyPointerType = [](ExprResult E) { 13066 QualType Ty = E.get()->getType(); 13067 return Ty->isPointerType() || Ty->isMemberPointerType(); 13068 }; 13069 13070 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 13071 // type, array-to-pointer, ..., conversions are performed on both operands to 13072 // bring them to their composite type. 13073 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 13074 // any type-related checks. 13075 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 13076 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13077 if (LHS.isInvalid()) 13078 return QualType(); 13079 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13080 if (RHS.isInvalid()) 13081 return QualType(); 13082 } else { 13083 LHS = DefaultLvalueConversion(LHS.get()); 13084 if (LHS.isInvalid()) 13085 return QualType(); 13086 RHS = DefaultLvalueConversion(RHS.get()); 13087 if (RHS.isInvalid()) 13088 return QualType(); 13089 } 13090 13091 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 13092 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 13093 CheckPtrComparisonWithNullChar(LHS, RHS); 13094 CheckPtrComparisonWithNullChar(RHS, LHS); 13095 } 13096 13097 // Handle vector comparisons separately. 13098 if (LHS.get()->getType()->isVectorType() || 13099 RHS.get()->getType()->isVectorType()) 13100 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 13101 13102 if (LHS.get()->getType()->isSveVLSBuiltinType() || 13103 RHS.get()->getType()->isSveVLSBuiltinType()) 13104 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc); 13105 13106 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 13107 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 13108 13109 QualType LHSType = LHS.get()->getType(); 13110 QualType RHSType = RHS.get()->getType(); 13111 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 13112 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 13113 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 13114 13115 if ((LHSType->isPointerType() && 13116 LHSType->getPointeeType().isWebAssemblyReferenceType()) || 13117 (RHSType->isPointerType() && 13118 RHSType->getPointeeType().isWebAssemblyReferenceType())) 13119 return InvalidOperands(Loc, LHS, RHS); 13120 13121 const Expr::NullPointerConstantKind LHSNullKind = 13122 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 13123 const Expr::NullPointerConstantKind RHSNullKind = 13124 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 13125 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 13126 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 13127 13128 auto computeResultTy = [&]() { 13129 if (Opc != BO_Cmp) 13130 return Context.getLogicalOperationType(); 13131 assert(getLangOpts().CPlusPlus); 13132 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 13133 13134 QualType CompositeTy = LHS.get()->getType(); 13135 assert(!CompositeTy->isReferenceType()); 13136 13137 std::optional<ComparisonCategoryType> CCT = 13138 getComparisonCategoryForBuiltinCmp(CompositeTy); 13139 if (!CCT) 13140 return InvalidOperands(Loc, LHS, RHS); 13141 13142 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 13143 // P0946R0: Comparisons between a null pointer constant and an object 13144 // pointer result in std::strong_equality, which is ill-formed under 13145 // P1959R0. 13146 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 13147 << (LHSIsNull ? LHS.get()->getSourceRange() 13148 : RHS.get()->getSourceRange()); 13149 return QualType(); 13150 } 13151 13152 return CheckComparisonCategoryType( 13153 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 13154 }; 13155 13156 if (!IsOrdered && LHSIsNull != RHSIsNull) { 13157 bool IsEquality = Opc == BO_EQ; 13158 if (RHSIsNull) 13159 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 13160 RHS.get()->getSourceRange()); 13161 else 13162 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 13163 LHS.get()->getSourceRange()); 13164 } 13165 13166 if (IsOrdered && LHSType->isFunctionPointerType() && 13167 RHSType->isFunctionPointerType()) { 13168 // Valid unless a relational comparison of function pointers 13169 bool IsError = Opc == BO_Cmp; 13170 auto DiagID = 13171 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 13172 : getLangOpts().CPlusPlus 13173 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 13174 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 13175 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 13176 << RHS.get()->getSourceRange(); 13177 if (IsError) 13178 return QualType(); 13179 } 13180 13181 if ((LHSType->isIntegerType() && !LHSIsNull) || 13182 (RHSType->isIntegerType() && !RHSIsNull)) { 13183 // Skip normal pointer conversion checks in this case; we have better 13184 // diagnostics for this below. 13185 } else if (getLangOpts().CPlusPlus) { 13186 // Equality comparison of a function pointer to a void pointer is invalid, 13187 // but we allow it as an extension. 13188 // FIXME: If we really want to allow this, should it be part of composite 13189 // pointer type computation so it works in conditionals too? 13190 if (!IsOrdered && 13191 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 13192 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 13193 // This is a gcc extension compatibility comparison. 13194 // In a SFINAE context, we treat this as a hard error to maintain 13195 // conformance with the C++ standard. 13196 diagnoseFunctionPointerToVoidComparison( 13197 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 13198 13199 if (isSFINAEContext()) 13200 return QualType(); 13201 13202 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 13203 return computeResultTy(); 13204 } 13205 13206 // C++ [expr.eq]p2: 13207 // If at least one operand is a pointer [...] bring them to their 13208 // composite pointer type. 13209 // C++ [expr.spaceship]p6 13210 // If at least one of the operands is of pointer type, [...] bring them 13211 // to their composite pointer type. 13212 // C++ [expr.rel]p2: 13213 // If both operands are pointers, [...] bring them to their composite 13214 // pointer type. 13215 // For <=>, the only valid non-pointer types are arrays and functions, and 13216 // we already decayed those, so this is really the same as the relational 13217 // comparison rule. 13218 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 13219 (IsOrdered ? 2 : 1) && 13220 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 13221 RHSType->isObjCObjectPointerType()))) { 13222 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 13223 return QualType(); 13224 return computeResultTy(); 13225 } 13226 } else if (LHSType->isPointerType() && 13227 RHSType->isPointerType()) { // C99 6.5.8p2 13228 // All of the following pointer-related warnings are GCC extensions, except 13229 // when handling null pointer constants. 13230 QualType LCanPointeeTy = 13231 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 13232 QualType RCanPointeeTy = 13233 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 13234 13235 // C99 6.5.9p2 and C99 6.5.8p2 13236 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 13237 RCanPointeeTy.getUnqualifiedType())) { 13238 if (IsRelational) { 13239 // Pointers both need to point to complete or incomplete types 13240 if ((LCanPointeeTy->isIncompleteType() != 13241 RCanPointeeTy->isIncompleteType()) && 13242 !getLangOpts().C11) { 13243 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 13244 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 13245 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 13246 << RCanPointeeTy->isIncompleteType(); 13247 } 13248 } 13249 } else if (!IsRelational && 13250 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 13251 // Valid unless comparison between non-null pointer and function pointer 13252 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 13253 && !LHSIsNull && !RHSIsNull) 13254 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 13255 /*isError*/false); 13256 } else { 13257 // Invalid 13258 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 13259 } 13260 if (LCanPointeeTy != RCanPointeeTy) { 13261 // Treat NULL constant as a special case in OpenCL. 13262 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 13263 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 13264 Diag(Loc, 13265 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 13266 << LHSType << RHSType << 0 /* comparison */ 13267 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 13268 } 13269 } 13270 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 13271 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 13272 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 13273 : CK_BitCast; 13274 if (LHSIsNull && !RHSIsNull) 13275 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 13276 else 13277 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 13278 } 13279 return computeResultTy(); 13280 } 13281 13282 13283 // C++ [expr.eq]p4: 13284 // Two operands of type std::nullptr_t or one operand of type 13285 // std::nullptr_t and the other a null pointer constant compare 13286 // equal. 13287 // C23 6.5.9p5: 13288 // If both operands have type nullptr_t or one operand has type nullptr_t 13289 // and the other is a null pointer constant, they compare equal if the 13290 // former is a null pointer. 13291 if (!IsOrdered && LHSIsNull && RHSIsNull) { 13292 if (LHSType->isNullPtrType()) { 13293 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 13294 return computeResultTy(); 13295 } 13296 if (RHSType->isNullPtrType()) { 13297 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 13298 return computeResultTy(); 13299 } 13300 } 13301 13302 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) { 13303 // C23 6.5.9p6: 13304 // Otherwise, at least one operand is a pointer. If one is a pointer and 13305 // the other is a null pointer constant or has type nullptr_t, they 13306 // compare equal 13307 if (LHSIsNull && RHSType->isPointerType()) { 13308 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 13309 return computeResultTy(); 13310 } 13311 if (RHSIsNull && LHSType->isPointerType()) { 13312 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 13313 return computeResultTy(); 13314 } 13315 } 13316 13317 // Comparison of Objective-C pointers and block pointers against nullptr_t. 13318 // These aren't covered by the composite pointer type rules. 13319 if (!IsOrdered && RHSType->isNullPtrType() && 13320 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 13321 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 13322 return computeResultTy(); 13323 } 13324 if (!IsOrdered && LHSType->isNullPtrType() && 13325 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 13326 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 13327 return computeResultTy(); 13328 } 13329 13330 if (getLangOpts().CPlusPlus) { 13331 if (IsRelational && 13332 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 13333 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 13334 // HACK: Relational comparison of nullptr_t against a pointer type is 13335 // invalid per DR583, but we allow it within std::less<> and friends, 13336 // since otherwise common uses of it break. 13337 // FIXME: Consider removing this hack once LWG fixes std::less<> and 13338 // friends to have std::nullptr_t overload candidates. 13339 DeclContext *DC = CurContext; 13340 if (isa<FunctionDecl>(DC)) 13341 DC = DC->getParent(); 13342 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 13343 if (CTSD->isInStdNamespace() && 13344 llvm::StringSwitch<bool>(CTSD->getName()) 13345 .Cases("less", "less_equal", "greater", "greater_equal", true) 13346 .Default(false)) { 13347 if (RHSType->isNullPtrType()) 13348 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 13349 else 13350 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 13351 return computeResultTy(); 13352 } 13353 } 13354 } 13355 13356 // C++ [expr.eq]p2: 13357 // If at least one operand is a pointer to member, [...] bring them to 13358 // their composite pointer type. 13359 if (!IsOrdered && 13360 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 13361 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 13362 return QualType(); 13363 else 13364 return computeResultTy(); 13365 } 13366 } 13367 13368 // Handle block pointer types. 13369 if (!IsOrdered && LHSType->isBlockPointerType() && 13370 RHSType->isBlockPointerType()) { 13371 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 13372 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 13373 13374 if (!LHSIsNull && !RHSIsNull && 13375 !Context.typesAreCompatible(lpointee, rpointee)) { 13376 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 13377 << LHSType << RHSType << LHS.get()->getSourceRange() 13378 << RHS.get()->getSourceRange(); 13379 } 13380 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 13381 return computeResultTy(); 13382 } 13383 13384 // Allow block pointers to be compared with null pointer constants. 13385 if (!IsOrdered 13386 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 13387 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 13388 if (!LHSIsNull && !RHSIsNull) { 13389 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 13390 ->getPointeeType()->isVoidType()) 13391 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 13392 ->getPointeeType()->isVoidType()))) 13393 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 13394 << LHSType << RHSType << LHS.get()->getSourceRange() 13395 << RHS.get()->getSourceRange(); 13396 } 13397 if (LHSIsNull && !RHSIsNull) 13398 LHS = ImpCastExprToType(LHS.get(), RHSType, 13399 RHSType->isPointerType() ? CK_BitCast 13400 : CK_AnyPointerToBlockPointerCast); 13401 else 13402 RHS = ImpCastExprToType(RHS.get(), LHSType, 13403 LHSType->isPointerType() ? CK_BitCast 13404 : CK_AnyPointerToBlockPointerCast); 13405 return computeResultTy(); 13406 } 13407 13408 if (LHSType->isObjCObjectPointerType() || 13409 RHSType->isObjCObjectPointerType()) { 13410 const PointerType *LPT = LHSType->getAs<PointerType>(); 13411 const PointerType *RPT = RHSType->getAs<PointerType>(); 13412 if (LPT || RPT) { 13413 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 13414 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 13415 13416 if (!LPtrToVoid && !RPtrToVoid && 13417 !Context.typesAreCompatible(LHSType, RHSType)) { 13418 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 13419 /*isError*/false); 13420 } 13421 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 13422 // the RHS, but we have test coverage for this behavior. 13423 // FIXME: Consider using convertPointersToCompositeType in C++. 13424 if (LHSIsNull && !RHSIsNull) { 13425 Expr *E = LHS.get(); 13426 if (getLangOpts().ObjCAutoRefCount) 13427 CheckObjCConversion(SourceRange(), RHSType, E, 13428 CCK_ImplicitConversion); 13429 LHS = ImpCastExprToType(E, RHSType, 13430 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 13431 } 13432 else { 13433 Expr *E = RHS.get(); 13434 if (getLangOpts().ObjCAutoRefCount) 13435 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 13436 /*Diagnose=*/true, 13437 /*DiagnoseCFAudited=*/false, Opc); 13438 RHS = ImpCastExprToType(E, LHSType, 13439 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 13440 } 13441 return computeResultTy(); 13442 } 13443 if (LHSType->isObjCObjectPointerType() && 13444 RHSType->isObjCObjectPointerType()) { 13445 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 13446 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 13447 /*isError*/false); 13448 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 13449 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 13450 13451 if (LHSIsNull && !RHSIsNull) 13452 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 13453 else 13454 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 13455 return computeResultTy(); 13456 } 13457 13458 if (!IsOrdered && LHSType->isBlockPointerType() && 13459 RHSType->isBlockCompatibleObjCPointerType(Context)) { 13460 LHS = ImpCastExprToType(LHS.get(), RHSType, 13461 CK_BlockPointerToObjCPointerCast); 13462 return computeResultTy(); 13463 } else if (!IsOrdered && 13464 LHSType->isBlockCompatibleObjCPointerType(Context) && 13465 RHSType->isBlockPointerType()) { 13466 RHS = ImpCastExprToType(RHS.get(), LHSType, 13467 CK_BlockPointerToObjCPointerCast); 13468 return computeResultTy(); 13469 } 13470 } 13471 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 13472 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 13473 unsigned DiagID = 0; 13474 bool isError = false; 13475 if (LangOpts.DebuggerSupport) { 13476 // Under a debugger, allow the comparison of pointers to integers, 13477 // since users tend to want to compare addresses. 13478 } else if ((LHSIsNull && LHSType->isIntegerType()) || 13479 (RHSIsNull && RHSType->isIntegerType())) { 13480 if (IsOrdered) { 13481 isError = getLangOpts().CPlusPlus; 13482 DiagID = 13483 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 13484 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 13485 } 13486 } else if (getLangOpts().CPlusPlus) { 13487 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 13488 isError = true; 13489 } else if (IsOrdered) 13490 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 13491 else 13492 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 13493 13494 if (DiagID) { 13495 Diag(Loc, DiagID) 13496 << LHSType << RHSType << LHS.get()->getSourceRange() 13497 << RHS.get()->getSourceRange(); 13498 if (isError) 13499 return QualType(); 13500 } 13501 13502 if (LHSType->isIntegerType()) 13503 LHS = ImpCastExprToType(LHS.get(), RHSType, 13504 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 13505 else 13506 RHS = ImpCastExprToType(RHS.get(), LHSType, 13507 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 13508 return computeResultTy(); 13509 } 13510 13511 // Handle block pointers. 13512 if (!IsOrdered && RHSIsNull 13513 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 13514 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 13515 return computeResultTy(); 13516 } 13517 if (!IsOrdered && LHSIsNull 13518 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 13519 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 13520 return computeResultTy(); 13521 } 13522 13523 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 13524 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 13525 return computeResultTy(); 13526 } 13527 13528 if (LHSType->isQueueT() && RHSType->isQueueT()) { 13529 return computeResultTy(); 13530 } 13531 13532 if (LHSIsNull && RHSType->isQueueT()) { 13533 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 13534 return computeResultTy(); 13535 } 13536 13537 if (LHSType->isQueueT() && RHSIsNull) { 13538 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 13539 return computeResultTy(); 13540 } 13541 } 13542 13543 return InvalidOperands(Loc, LHS, RHS); 13544} 13545 13546// Return a signed ext_vector_type that is of identical size and number of 13547// elements. For floating point vectors, return an integer type of identical 13548// size and number of elements. In the non ext_vector_type case, search from 13549// the largest type to the smallest type to avoid cases where long long == long, 13550// where long gets picked over long long. 13551QualType Sema::GetSignedVectorType(QualType V) { 13552 const VectorType *VTy = V->castAs<VectorType>(); 13553 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 13554 13555 if (isa<ExtVectorType>(VTy)) { 13556 if (VTy->isExtVectorBoolType()) 13557 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements()); 13558 if (TypeSize == Context.getTypeSize(Context.CharTy)) 13559 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 13560 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 13561 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 13562 if (TypeSize == Context.getTypeSize(Context.IntTy)) 13563 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 13564 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 13565 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); 13566 if (TypeSize == Context.getTypeSize(Context.LongTy)) 13567 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 13568 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 13569 "Unhandled vector element size in vector compare"); 13570 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 13571 } 13572 13573 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 13574 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), 13575 VectorKind::Generic); 13576 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 13577 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 13578 VectorKind::Generic); 13579 if (TypeSize == Context.getTypeSize(Context.LongTy)) 13580 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 13581 VectorKind::Generic); 13582 if (TypeSize == Context.getTypeSize(Context.IntTy)) 13583 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 13584 VectorKind::Generic); 13585 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 13586 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 13587 VectorKind::Generic); 13588 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 13589 "Unhandled vector element size in vector compare"); 13590 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 13591 VectorKind::Generic); 13592} 13593 13594QualType Sema::GetSignedSizelessVectorType(QualType V) { 13595 const BuiltinType *VTy = V->castAs<BuiltinType>(); 13596 assert(VTy->isSizelessBuiltinType() && "expected sizeless type"); 13597 13598 const QualType ETy = V->getSveEltType(Context); 13599 const auto TypeSize = Context.getTypeSize(ETy); 13600 13601 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true); 13602 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC; 13603 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue()); 13604} 13605 13606/// CheckVectorCompareOperands - vector comparisons are a clang extension that 13607/// operates on extended vector types. Instead of producing an IntTy result, 13608/// like a scalar comparison, a vector comparison produces a vector of integer 13609/// types. 13610QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 13611 SourceLocation Loc, 13612 BinaryOperatorKind Opc) { 13613 if (Opc == BO_Cmp) { 13614 Diag(Loc, diag::err_three_way_vector_comparison); 13615 return QualType(); 13616 } 13617 13618 // Check to make sure we're operating on vectors of the same type and width, 13619 // Allowing one side to be a scalar of element type. 13620 QualType vType = 13621 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false, 13622 /*AllowBothBool*/ true, 13623 /*AllowBoolConversions*/ getLangOpts().ZVector, 13624 /*AllowBooleanOperation*/ true, 13625 /*ReportInvalid*/ true); 13626 if (vType.isNull()) 13627 return vType; 13628 13629 QualType LHSType = LHS.get()->getType(); 13630 13631 // Determine the return type of a vector compare. By default clang will return 13632 // a scalar for all vector compares except vector bool and vector pixel. 13633 // With the gcc compiler we will always return a vector type and with the xl 13634 // compiler we will always return a scalar type. This switch allows choosing 13635 // which behavior is prefered. 13636 if (getLangOpts().AltiVec) { 13637 switch (getLangOpts().getAltivecSrcCompat()) { 13638 case LangOptions::AltivecSrcCompatKind::Mixed: 13639 // If AltiVec, the comparison results in a numeric type, i.e. 13640 // bool for C++, int for C 13641 if (vType->castAs<VectorType>()->getVectorKind() == 13642 VectorKind::AltiVecVector) 13643 return Context.getLogicalOperationType(); 13644 else 13645 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 13646 break; 13647 case LangOptions::AltivecSrcCompatKind::GCC: 13648 // For GCC we always return the vector type. 13649 break; 13650 case LangOptions::AltivecSrcCompatKind::XL: 13651 return Context.getLogicalOperationType(); 13652 break; 13653 } 13654 } 13655 13656 // For non-floating point types, check for self-comparisons of the form 13657 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 13658 // often indicate logic errors in the program. 13659 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 13660 13661 // Check for comparisons of floating point operands using != and ==. 13662 if (LHSType->hasFloatingRepresentation()) { 13663 assert(RHS.get()->getType()->hasFloatingRepresentation()); 13664 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 13665 } 13666 13667 // Return a signed type for the vector. 13668 return GetSignedVectorType(vType); 13669} 13670 13671QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS, 13672 ExprResult &RHS, 13673 SourceLocation Loc, 13674 BinaryOperatorKind Opc) { 13675 if (Opc == BO_Cmp) { 13676 Diag(Loc, diag::err_three_way_vector_comparison); 13677 return QualType(); 13678 } 13679 13680 // Check to make sure we're operating on vectors of the same type and width, 13681 // Allowing one side to be a scalar of element type. 13682 QualType vType = CheckSizelessVectorOperands( 13683 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison); 13684 13685 if (vType.isNull()) 13686 return vType; 13687 13688 QualType LHSType = LHS.get()->getType(); 13689 13690 // For non-floating point types, check for self-comparisons of the form 13691 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 13692 // often indicate logic errors in the program. 13693 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 13694 13695 // Check for comparisons of floating point operands using != and ==. 13696 if (LHSType->hasFloatingRepresentation()) { 13697 assert(RHS.get()->getType()->hasFloatingRepresentation()); 13698 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 13699 } 13700 13701 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 13702 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>(); 13703 13704 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() && 13705 RHSBuiltinTy->isSVEBool()) 13706 return LHSType; 13707 13708 // Return a signed type for the vector. 13709 return GetSignedSizelessVectorType(vType); 13710} 13711 13712static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 13713 const ExprResult &XorRHS, 13714 const SourceLocation Loc) { 13715 // Do not diagnose macros. 13716 if (Loc.isMacroID()) 13717 return; 13718 13719 // Do not diagnose if both LHS and RHS are macros. 13720 if (XorLHS.get()->getExprLoc().isMacroID() && 13721 XorRHS.get()->getExprLoc().isMacroID()) 13722 return; 13723 13724 bool Negative = false; 13725 bool ExplicitPlus = false; 13726 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 13727 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 13728 13729 if (!LHSInt) 13730 return; 13731 if (!RHSInt) { 13732 // Check negative literals. 13733 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 13734 UnaryOperatorKind Opc = UO->getOpcode(); 13735 if (Opc != UO_Minus && Opc != UO_Plus) 13736 return; 13737 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 13738 if (!RHSInt) 13739 return; 13740 Negative = (Opc == UO_Minus); 13741 ExplicitPlus = !Negative; 13742 } else { 13743 return; 13744 } 13745 } 13746 13747 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 13748 llvm::APInt RightSideValue = RHSInt->getValue(); 13749 if (LeftSideValue != 2 && LeftSideValue != 10) 13750 return; 13751 13752 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 13753 return; 13754 13755 CharSourceRange ExprRange = CharSourceRange::getCharRange( 13756 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 13757 llvm::StringRef ExprStr = 13758 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 13759 13760 CharSourceRange XorRange = 13761 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 13762 llvm::StringRef XorStr = 13763 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 13764 // Do not diagnose if xor keyword/macro is used. 13765 if (XorStr == "xor") 13766 return; 13767 13768 std::string LHSStr = std::string(Lexer::getSourceText( 13769 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 13770 S.getSourceManager(), S.getLangOpts())); 13771 std::string RHSStr = std::string(Lexer::getSourceText( 13772 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 13773 S.getSourceManager(), S.getLangOpts())); 13774 13775 if (Negative) { 13776 RightSideValue = -RightSideValue; 13777 RHSStr = "-" + RHSStr; 13778 } else if (ExplicitPlus) { 13779 RHSStr = "+" + RHSStr; 13780 } 13781 13782 StringRef LHSStrRef = LHSStr; 13783 StringRef RHSStrRef = RHSStr; 13784 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 13785 // literals. 13786 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") || 13787 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") || 13788 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") || 13789 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") || 13790 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) || 13791 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) || 13792 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 13793 return; 13794 13795 bool SuggestXor = 13796 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 13797 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 13798 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 13799 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 13800 std::string SuggestedExpr = "1 << " + RHSStr; 13801 bool Overflow = false; 13802 llvm::APInt One = (LeftSideValue - 1); 13803 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 13804 if (Overflow) { 13805 if (RightSideIntValue < 64) 13806 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 13807 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 13808 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 13809 else if (RightSideIntValue == 64) 13810 S.Diag(Loc, diag::warn_xor_used_as_pow) 13811 << ExprStr << toString(XorValue, 10, true); 13812 else 13813 return; 13814 } else { 13815 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 13816 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 13817 << toString(PowValue, 10, true) 13818 << FixItHint::CreateReplacement( 13819 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 13820 } 13821 13822 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 13823 << ("0x2 ^ " + RHSStr) << SuggestXor; 13824 } else if (LeftSideValue == 10) { 13825 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 13826 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 13827 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 13828 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 13829 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 13830 << ("0xA ^ " + RHSStr) << SuggestXor; 13831 } 13832} 13833 13834QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13835 SourceLocation Loc) { 13836 // Ensure that either both operands are of the same vector type, or 13837 // one operand is of a vector type and the other is of its element type. 13838 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 13839 /*AllowBothBool*/ true, 13840 /*AllowBoolConversions*/ false, 13841 /*AllowBooleanOperation*/ false, 13842 /*ReportInvalid*/ false); 13843 if (vType.isNull()) 13844 return InvalidOperands(Loc, LHS, RHS); 13845 if (getLangOpts().OpenCL && 13846 getLangOpts().getOpenCLCompatibleVersion() < 120 && 13847 vType->hasFloatingRepresentation()) 13848 return InvalidOperands(Loc, LHS, RHS); 13849 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 13850 // usage of the logical operators && and || with vectors in C. This 13851 // check could be notionally dropped. 13852 if (!getLangOpts().CPlusPlus && 13853 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 13854 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 13855 13856 return GetSignedVectorType(LHS.get()->getType()); 13857} 13858 13859QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 13860 SourceLocation Loc, 13861 bool IsCompAssign) { 13862 if (!IsCompAssign) { 13863 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13864 if (LHS.isInvalid()) 13865 return QualType(); 13866 } 13867 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13868 if (RHS.isInvalid()) 13869 return QualType(); 13870 13871 // For conversion purposes, we ignore any qualifiers. 13872 // For example, "const float" and "float" are equivalent. 13873 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 13874 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 13875 13876 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 13877 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 13878 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13879 13880 if (Context.hasSameType(LHSType, RHSType)) 13881 return Context.getCommonSugaredType(LHSType, RHSType); 13882 13883 // Type conversion may change LHS/RHS. Keep copies to the original results, in 13884 // case we have to return InvalidOperands. 13885 ExprResult OriginalLHS = LHS; 13886 ExprResult OriginalRHS = RHS; 13887 if (LHSMatType && !RHSMatType) { 13888 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 13889 if (!RHS.isInvalid()) 13890 return LHSType; 13891 13892 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13893 } 13894 13895 if (!LHSMatType && RHSMatType) { 13896 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 13897 if (!LHS.isInvalid()) 13898 return RHSType; 13899 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13900 } 13901 13902 return InvalidOperands(Loc, LHS, RHS); 13903} 13904 13905QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 13906 SourceLocation Loc, 13907 bool IsCompAssign) { 13908 if (!IsCompAssign) { 13909 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13910 if (LHS.isInvalid()) 13911 return QualType(); 13912 } 13913 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13914 if (RHS.isInvalid()) 13915 return QualType(); 13916 13917 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 13918 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 13919 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13920 13921 if (LHSMatType && RHSMatType) { 13922 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 13923 return InvalidOperands(Loc, LHS, RHS); 13924 13925 if (Context.hasSameType(LHSMatType, RHSMatType)) 13926 return Context.getCommonSugaredType( 13927 LHS.get()->getType().getUnqualifiedType(), 13928 RHS.get()->getType().getUnqualifiedType()); 13929 13930 QualType LHSELTy = LHSMatType->getElementType(), 13931 RHSELTy = RHSMatType->getElementType(); 13932 if (!Context.hasSameType(LHSELTy, RHSELTy)) 13933 return InvalidOperands(Loc, LHS, RHS); 13934 13935 return Context.getConstantMatrixType( 13936 Context.getCommonSugaredType(LHSELTy, RHSELTy), 13937 LHSMatType->getNumRows(), RHSMatType->getNumColumns()); 13938 } 13939 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 13940} 13941 13942static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { 13943 switch (Opc) { 13944 default: 13945 return false; 13946 case BO_And: 13947 case BO_AndAssign: 13948 case BO_Or: 13949 case BO_OrAssign: 13950 case BO_Xor: 13951 case BO_XorAssign: 13952 return true; 13953 } 13954} 13955 13956inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 13957 SourceLocation Loc, 13958 BinaryOperatorKind Opc) { 13959 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 13960 13961 bool IsCompAssign = 13962 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 13963 13964 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); 13965 13966 if (LHS.get()->getType()->isVectorType() || 13967 RHS.get()->getType()->isVectorType()) { 13968 if (LHS.get()->getType()->hasIntegerRepresentation() && 13969 RHS.get()->getType()->hasIntegerRepresentation()) 13970 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 13971 /*AllowBothBool*/ true, 13972 /*AllowBoolConversions*/ getLangOpts().ZVector, 13973 /*AllowBooleanOperation*/ LegalBoolVecOperator, 13974 /*ReportInvalid*/ true); 13975 return InvalidOperands(Loc, LHS, RHS); 13976 } 13977 13978 if (LHS.get()->getType()->isSveVLSBuiltinType() || 13979 RHS.get()->getType()->isSveVLSBuiltinType()) { 13980 if (LHS.get()->getType()->hasIntegerRepresentation() && 13981 RHS.get()->getType()->hasIntegerRepresentation()) 13982 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13983 ACK_BitwiseOp); 13984 return InvalidOperands(Loc, LHS, RHS); 13985 } 13986 13987 if (LHS.get()->getType()->isSveVLSBuiltinType() || 13988 RHS.get()->getType()->isSveVLSBuiltinType()) { 13989 if (LHS.get()->getType()->hasIntegerRepresentation() && 13990 RHS.get()->getType()->hasIntegerRepresentation()) 13991 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13992 ACK_BitwiseOp); 13993 return InvalidOperands(Loc, LHS, RHS); 13994 } 13995 13996 if (Opc == BO_And) 13997 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 13998 13999 if (LHS.get()->getType()->hasFloatingRepresentation() || 14000 RHS.get()->getType()->hasFloatingRepresentation()) 14001 return InvalidOperands(Loc, LHS, RHS); 14002 14003 ExprResult LHSResult = LHS, RHSResult = RHS; 14004 QualType compType = UsualArithmeticConversions( 14005 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 14006 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 14007 return QualType(); 14008 LHS = LHSResult.get(); 14009 RHS = RHSResult.get(); 14010 14011 if (Opc == BO_Xor) 14012 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 14013 14014 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 14015 return compType; 14016 return InvalidOperands(Loc, LHS, RHS); 14017} 14018 14019// C99 6.5.[13,14] 14020inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 14021 SourceLocation Loc, 14022 BinaryOperatorKind Opc) { 14023 // Check vector operands differently. 14024 if (LHS.get()->getType()->isVectorType() || 14025 RHS.get()->getType()->isVectorType()) 14026 return CheckVectorLogicalOperands(LHS, RHS, Loc); 14027 14028 bool EnumConstantInBoolContext = false; 14029 for (const ExprResult &HS : {LHS, RHS}) { 14030 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 14031 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 14032 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 14033 EnumConstantInBoolContext = true; 14034 } 14035 } 14036 14037 if (EnumConstantInBoolContext) 14038 Diag(Loc, diag::warn_enum_constant_in_bool_context); 14039 14040 // WebAssembly tables can't be used with logical operators. 14041 QualType LHSTy = LHS.get()->getType(); 14042 QualType RHSTy = RHS.get()->getType(); 14043 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy); 14044 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy); 14045 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) || 14046 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) { 14047 return InvalidOperands(Loc, LHS, RHS); 14048 } 14049 14050 // Diagnose cases where the user write a logical and/or but probably meant a 14051 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 14052 // is a constant. 14053 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 14054 !LHS.get()->getType()->isBooleanType() && 14055 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 14056 // Don't warn in macros or template instantiations. 14057 !Loc.isMacroID() && !inTemplateInstantiation()) { 14058 // If the RHS can be constant folded, and if it constant folds to something 14059 // that isn't 0 or 1 (which indicate a potential logical operation that 14060 // happened to fold to true/false) then warn. 14061 // Parens on the RHS are ignored. 14062 Expr::EvalResult EVResult; 14063 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 14064 llvm::APSInt Result = EVResult.Val.getInt(); 14065 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() && 14066 !RHS.get()->getExprLoc().isMacroID()) || 14067 (Result != 0 && Result != 1)) { 14068 Diag(Loc, diag::warn_logical_instead_of_bitwise) 14069 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||"); 14070 // Suggest replacing the logical operator with the bitwise version 14071 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 14072 << (Opc == BO_LAnd ? "&" : "|") 14073 << FixItHint::CreateReplacement( 14074 SourceRange(Loc, getLocForEndOfToken(Loc)), 14075 Opc == BO_LAnd ? "&" : "|"); 14076 if (Opc == BO_LAnd) 14077 // Suggest replacing "Foo() && kNonZero" with "Foo()" 14078 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 14079 << FixItHint::CreateRemoval( 14080 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 14081 RHS.get()->getEndLoc())); 14082 } 14083 } 14084 } 14085 14086 if (!Context.getLangOpts().CPlusPlus) { 14087 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 14088 // not operate on the built-in scalar and vector float types. 14089 if (Context.getLangOpts().OpenCL && 14090 Context.getLangOpts().OpenCLVersion < 120) { 14091 if (LHS.get()->getType()->isFloatingType() || 14092 RHS.get()->getType()->isFloatingType()) 14093 return InvalidOperands(Loc, LHS, RHS); 14094 } 14095 14096 LHS = UsualUnaryConversions(LHS.get()); 14097 if (LHS.isInvalid()) 14098 return QualType(); 14099 14100 RHS = UsualUnaryConversions(RHS.get()); 14101 if (RHS.isInvalid()) 14102 return QualType(); 14103 14104 if (!LHS.get()->getType()->isScalarType() || 14105 !RHS.get()->getType()->isScalarType()) 14106 return InvalidOperands(Loc, LHS, RHS); 14107 14108 return Context.IntTy; 14109 } 14110 14111 // The following is safe because we only use this method for 14112 // non-overloadable operands. 14113 14114 // C++ [expr.log.and]p1 14115 // C++ [expr.log.or]p1 14116 // The operands are both contextually converted to type bool. 14117 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 14118 if (LHSRes.isInvalid()) 14119 return InvalidOperands(Loc, LHS, RHS); 14120 LHS = LHSRes; 14121 14122 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 14123 if (RHSRes.isInvalid()) 14124 return InvalidOperands(Loc, LHS, RHS); 14125 RHS = RHSRes; 14126 14127 // C++ [expr.log.and]p2 14128 // C++ [expr.log.or]p2 14129 // The result is a bool. 14130 return Context.BoolTy; 14131} 14132 14133static bool IsReadonlyMessage(Expr *E, Sema &S) { 14134 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14135 if (!ME) return false; 14136 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 14137 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 14138 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 14139 if (!Base) return false; 14140 return Base->getMethodDecl() != nullptr; 14141} 14142 14143/// Is the given expression (which must be 'const') a reference to a 14144/// variable which was originally non-const, but which has become 14145/// 'const' due to being captured within a block? 14146enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 14147static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 14148 assert(E->isLValue() && E->getType().isConstQualified()); 14149 E = E->IgnoreParens(); 14150 14151 // Must be a reference to a declaration from an enclosing scope. 14152 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14153 if (!DRE) return NCCK_None; 14154 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 14155 14156 // The declaration must be a variable which is not declared 'const'. 14157 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 14158 if (!var) return NCCK_None; 14159 if (var->getType().isConstQualified()) return NCCK_None; 14160 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 14161 14162 // Decide whether the first capture was for a block or a lambda. 14163 DeclContext *DC = S.CurContext, *Prev = nullptr; 14164 // Decide whether the first capture was for a block or a lambda. 14165 while (DC) { 14166 // For init-capture, it is possible that the variable belongs to the 14167 // template pattern of the current context. 14168 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 14169 if (var->isInitCapture() && 14170 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 14171 break; 14172 if (DC == var->getDeclContext()) 14173 break; 14174 Prev = DC; 14175 DC = DC->getParent(); 14176 } 14177 // Unless we have an init-capture, we've gone one step too far. 14178 if (!var->isInitCapture()) 14179 DC = Prev; 14180 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 14181} 14182 14183static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 14184 Ty = Ty.getNonReferenceType(); 14185 if (IsDereference && Ty->isPointerType()) 14186 Ty = Ty->getPointeeType(); 14187 return !Ty.isConstQualified(); 14188} 14189 14190// Update err_typecheck_assign_const and note_typecheck_assign_const 14191// when this enum is changed. 14192enum { 14193 ConstFunction, 14194 ConstVariable, 14195 ConstMember, 14196 ConstMethod, 14197 NestedConstMember, 14198 ConstUnknown, // Keep as last element 14199}; 14200 14201/// Emit the "read-only variable not assignable" error and print notes to give 14202/// more information about why the variable is not assignable, such as pointing 14203/// to the declaration of a const variable, showing that a method is const, or 14204/// that the function is returning a const reference. 14205static void DiagnoseConstAssignment(Sema &S, const Expr *E, 14206 SourceLocation Loc) { 14207 SourceRange ExprRange = E->getSourceRange(); 14208 14209 // Only emit one error on the first const found. All other consts will emit 14210 // a note to the error. 14211 bool DiagnosticEmitted = false; 14212 14213 // Track if the current expression is the result of a dereference, and if the 14214 // next checked expression is the result of a dereference. 14215 bool IsDereference = false; 14216 bool NextIsDereference = false; 14217 14218 // Loop to process MemberExpr chains. 14219 while (true) { 14220 IsDereference = NextIsDereference; 14221 14222 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 14223 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14224 NextIsDereference = ME->isArrow(); 14225 const ValueDecl *VD = ME->getMemberDecl(); 14226 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 14227 // Mutable fields can be modified even if the class is const. 14228 if (Field->isMutable()) { 14229 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 14230 break; 14231 } 14232 14233 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 14234 if (!DiagnosticEmitted) { 14235 S.Diag(Loc, diag::err_typecheck_assign_const) 14236 << ExprRange << ConstMember << false /*static*/ << Field 14237 << Field->getType(); 14238 DiagnosticEmitted = true; 14239 } 14240 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 14241 << ConstMember << false /*static*/ << Field << Field->getType() 14242 << Field->getSourceRange(); 14243 } 14244 E = ME->getBase(); 14245 continue; 14246 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 14247 if (VDecl->getType().isConstQualified()) { 14248 if (!DiagnosticEmitted) { 14249 S.Diag(Loc, diag::err_typecheck_assign_const) 14250 << ExprRange << ConstMember << true /*static*/ << VDecl 14251 << VDecl->getType(); 14252 DiagnosticEmitted = true; 14253 } 14254 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 14255 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 14256 << VDecl->getSourceRange(); 14257 } 14258 // Static fields do not inherit constness from parents. 14259 break; 14260 } 14261 break; // End MemberExpr 14262 } else if (const ArraySubscriptExpr *ASE = 14263 dyn_cast<ArraySubscriptExpr>(E)) { 14264 E = ASE->getBase()->IgnoreParenImpCasts(); 14265 continue; 14266 } else if (const ExtVectorElementExpr *EVE = 14267 dyn_cast<ExtVectorElementExpr>(E)) { 14268 E = EVE->getBase()->IgnoreParenImpCasts(); 14269 continue; 14270 } 14271 break; 14272 } 14273 14274 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 14275 // Function calls 14276 const FunctionDecl *FD = CE->getDirectCallee(); 14277 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 14278 if (!DiagnosticEmitted) { 14279 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 14280 << ConstFunction << FD; 14281 DiagnosticEmitted = true; 14282 } 14283 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 14284 diag::note_typecheck_assign_const) 14285 << ConstFunction << FD << FD->getReturnType() 14286 << FD->getReturnTypeSourceRange(); 14287 } 14288 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14289 // Point to variable declaration. 14290 if (const ValueDecl *VD = DRE->getDecl()) { 14291 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 14292 if (!DiagnosticEmitted) { 14293 S.Diag(Loc, diag::err_typecheck_assign_const) 14294 << ExprRange << ConstVariable << VD << VD->getType(); 14295 DiagnosticEmitted = true; 14296 } 14297 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 14298 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 14299 } 14300 } 14301 } else if (isa<CXXThisExpr>(E)) { 14302 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 14303 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 14304 if (MD->isConst()) { 14305 if (!DiagnosticEmitted) { 14306 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 14307 << ConstMethod << MD; 14308 DiagnosticEmitted = true; 14309 } 14310 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 14311 << ConstMethod << MD << MD->getSourceRange(); 14312 } 14313 } 14314 } 14315 } 14316 14317 if (DiagnosticEmitted) 14318 return; 14319 14320 // Can't determine a more specific message, so display the generic error. 14321 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 14322} 14323 14324enum OriginalExprKind { 14325 OEK_Variable, 14326 OEK_Member, 14327 OEK_LValue 14328}; 14329 14330static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 14331 const RecordType *Ty, 14332 SourceLocation Loc, SourceRange Range, 14333 OriginalExprKind OEK, 14334 bool &DiagnosticEmitted) { 14335 std::vector<const RecordType *> RecordTypeList; 14336 RecordTypeList.push_back(Ty); 14337 unsigned NextToCheckIndex = 0; 14338 // We walk the record hierarchy breadth-first to ensure that we print 14339 // diagnostics in field nesting order. 14340 while (RecordTypeList.size() > NextToCheckIndex) { 14341 bool IsNested = NextToCheckIndex > 0; 14342 for (const FieldDecl *Field : 14343 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 14344 // First, check every field for constness. 14345 QualType FieldTy = Field->getType(); 14346 if (FieldTy.isConstQualified()) { 14347 if (!DiagnosticEmitted) { 14348 S.Diag(Loc, diag::err_typecheck_assign_const) 14349 << Range << NestedConstMember << OEK << VD 14350 << IsNested << Field; 14351 DiagnosticEmitted = true; 14352 } 14353 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 14354 << NestedConstMember << IsNested << Field 14355 << FieldTy << Field->getSourceRange(); 14356 } 14357 14358 // Then we append it to the list to check next in order. 14359 FieldTy = FieldTy.getCanonicalType(); 14360 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 14361 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 14362 RecordTypeList.push_back(FieldRecTy); 14363 } 14364 } 14365 ++NextToCheckIndex; 14366 } 14367} 14368 14369/// Emit an error for the case where a record we are trying to assign to has a 14370/// const-qualified field somewhere in its hierarchy. 14371static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 14372 SourceLocation Loc) { 14373 QualType Ty = E->getType(); 14374 assert(Ty->isRecordType() && "lvalue was not record?"); 14375 SourceRange Range = E->getSourceRange(); 14376 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 14377 bool DiagEmitted = false; 14378 14379 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 14380 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 14381 Range, OEK_Member, DiagEmitted); 14382 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 14383 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 14384 Range, OEK_Variable, DiagEmitted); 14385 else 14386 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 14387 Range, OEK_LValue, DiagEmitted); 14388 if (!DiagEmitted) 14389 DiagnoseConstAssignment(S, E, Loc); 14390} 14391 14392/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 14393/// emit an error and return true. If so, return false. 14394static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 14395 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 14396 14397 S.CheckShadowingDeclModification(E, Loc); 14398 14399 SourceLocation OrigLoc = Loc; 14400 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 14401 &Loc); 14402 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 14403 IsLV = Expr::MLV_InvalidMessageExpression; 14404 if (IsLV == Expr::MLV_Valid) 14405 return false; 14406 14407 unsigned DiagID = 0; 14408 bool NeedType = false; 14409 switch (IsLV) { // C99 6.5.16p2 14410 case Expr::MLV_ConstQualified: 14411 // Use a specialized diagnostic when we're assigning to an object 14412 // from an enclosing function or block. 14413 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 14414 if (NCCK == NCCK_Block) 14415 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 14416 else 14417 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 14418 break; 14419 } 14420 14421 // In ARC, use some specialized diagnostics for occasions where we 14422 // infer 'const'. These are always pseudo-strong variables. 14423 if (S.getLangOpts().ObjCAutoRefCount) { 14424 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 14425 if (declRef && isa<VarDecl>(declRef->getDecl())) { 14426 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 14427 14428 // Use the normal diagnostic if it's pseudo-__strong but the 14429 // user actually wrote 'const'. 14430 if (var->isARCPseudoStrong() && 14431 (!var->getTypeSourceInfo() || 14432 !var->getTypeSourceInfo()->getType().isConstQualified())) { 14433 // There are three pseudo-strong cases: 14434 // - self 14435 ObjCMethodDecl *method = S.getCurMethodDecl(); 14436 if (method && var == method->getSelfDecl()) { 14437 DiagID = method->isClassMethod() 14438 ? diag::err_typecheck_arc_assign_self_class_method 14439 : diag::err_typecheck_arc_assign_self; 14440 14441 // - Objective-C externally_retained attribute. 14442 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 14443 isa<ParmVarDecl>(var)) { 14444 DiagID = diag::err_typecheck_arc_assign_externally_retained; 14445 14446 // - fast enumeration variables 14447 } else { 14448 DiagID = diag::err_typecheck_arr_assign_enumeration; 14449 } 14450 14451 SourceRange Assign; 14452 if (Loc != OrigLoc) 14453 Assign = SourceRange(OrigLoc, OrigLoc); 14454 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 14455 // We need to preserve the AST regardless, so migration tool 14456 // can do its job. 14457 return false; 14458 } 14459 } 14460 } 14461 14462 // If none of the special cases above are triggered, then this is a 14463 // simple const assignment. 14464 if (DiagID == 0) { 14465 DiagnoseConstAssignment(S, E, Loc); 14466 return true; 14467 } 14468 14469 break; 14470 case Expr::MLV_ConstAddrSpace: 14471 DiagnoseConstAssignment(S, E, Loc); 14472 return true; 14473 case Expr::MLV_ConstQualifiedField: 14474 DiagnoseRecursiveConstFields(S, E, Loc); 14475 return true; 14476 case Expr::MLV_ArrayType: 14477 case Expr::MLV_ArrayTemporary: 14478 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 14479 NeedType = true; 14480 break; 14481 case Expr::MLV_NotObjectType: 14482 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 14483 NeedType = true; 14484 break; 14485 case Expr::MLV_LValueCast: 14486 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 14487 break; 14488 case Expr::MLV_Valid: 14489 llvm_unreachable("did not take early return for MLV_Valid"); 14490 case Expr::MLV_InvalidExpression: 14491 case Expr::MLV_MemberFunction: 14492 case Expr::MLV_ClassTemporary: 14493 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 14494 break; 14495 case Expr::MLV_IncompleteType: 14496 case Expr::MLV_IncompleteVoidType: 14497 return S.RequireCompleteType(Loc, E->getType(), 14498 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 14499 case Expr::MLV_DuplicateVectorComponents: 14500 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 14501 break; 14502 case Expr::MLV_NoSetterProperty: 14503 llvm_unreachable("readonly properties should be processed differently"); 14504 case Expr::MLV_InvalidMessageExpression: 14505 DiagID = diag::err_readonly_message_assignment; 14506 break; 14507 case Expr::MLV_SubObjCPropertySetting: 14508 DiagID = diag::err_no_subobject_property_setting; 14509 break; 14510 } 14511 14512 SourceRange Assign; 14513 if (Loc != OrigLoc) 14514 Assign = SourceRange(OrigLoc, OrigLoc); 14515 if (NeedType) 14516 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 14517 else 14518 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 14519 return true; 14520} 14521 14522static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 14523 SourceLocation Loc, 14524 Sema &Sema) { 14525 if (Sema.inTemplateInstantiation()) 14526 return; 14527 if (Sema.isUnevaluatedContext()) 14528 return; 14529 if (Loc.isInvalid() || Loc.isMacroID()) 14530 return; 14531 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 14532 return; 14533 14534 // C / C++ fields 14535 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 14536 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 14537 if (ML && MR) { 14538 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 14539 return; 14540 const ValueDecl *LHSDecl = 14541 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 14542 const ValueDecl *RHSDecl = 14543 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 14544 if (LHSDecl != RHSDecl) 14545 return; 14546 if (LHSDecl->getType().isVolatileQualified()) 14547 return; 14548 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 14549 if (RefTy->getPointeeType().isVolatileQualified()) 14550 return; 14551 14552 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 14553 } 14554 14555 // Objective-C instance variables 14556 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 14557 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 14558 if (OL && OR && OL->getDecl() == OR->getDecl()) { 14559 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 14560 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 14561 if (RL && RR && RL->getDecl() == RR->getDecl()) 14562 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 14563 } 14564} 14565 14566// C99 6.5.16.1 14567QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 14568 SourceLocation Loc, 14569 QualType CompoundType, 14570 BinaryOperatorKind Opc) { 14571 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 14572 14573 // Verify that LHS is a modifiable lvalue, and emit error if not. 14574 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 14575 return QualType(); 14576 14577 QualType LHSType = LHSExpr->getType(); 14578 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 14579 CompoundType; 14580 // OpenCL v1.2 s6.1.1.1 p2: 14581 // The half data type can only be used to declare a pointer to a buffer that 14582 // contains half values 14583 if (getLangOpts().OpenCL && 14584 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 14585 LHSType->isHalfType()) { 14586 Diag(Loc, diag::err_opencl_half_load_store) << 1 14587 << LHSType.getUnqualifiedType(); 14588 return QualType(); 14589 } 14590 14591 // WebAssembly tables can't be used on RHS of an assignment expression. 14592 if (RHSType->isWebAssemblyTableType()) { 14593 Diag(Loc, diag::err_wasm_table_art) << 0; 14594 return QualType(); 14595 } 14596 14597 AssignConvertType ConvTy; 14598 if (CompoundType.isNull()) { 14599 Expr *RHSCheck = RHS.get(); 14600 14601 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 14602 14603 QualType LHSTy(LHSType); 14604 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 14605 if (RHS.isInvalid()) 14606 return QualType(); 14607 // Special case of NSObject attributes on c-style pointer types. 14608 if (ConvTy == IncompatiblePointer && 14609 ((Context.isObjCNSObjectType(LHSType) && 14610 RHSType->isObjCObjectPointerType()) || 14611 (Context.isObjCNSObjectType(RHSType) && 14612 LHSType->isObjCObjectPointerType()))) 14613 ConvTy = Compatible; 14614 14615 if (ConvTy == Compatible && 14616 LHSType->isObjCObjectType()) 14617 Diag(Loc, diag::err_objc_object_assignment) 14618 << LHSType; 14619 14620 // If the RHS is a unary plus or minus, check to see if they = and + are 14621 // right next to each other. If so, the user may have typo'd "x =+ 4" 14622 // instead of "x += 4". 14623 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 14624 RHSCheck = ICE->getSubExpr(); 14625 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 14626 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 14627 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 14628 // Only if the two operators are exactly adjacent. 14629 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 14630 // And there is a space or other character before the subexpr of the 14631 // unary +/-. We don't want to warn on "x=-1". 14632 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 14633 UO->getSubExpr()->getBeginLoc().isFileID()) { 14634 Diag(Loc, diag::warn_not_compound_assign) 14635 << (UO->getOpcode() == UO_Plus ? "+" : "-") 14636 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 14637 } 14638 } 14639 14640 if (ConvTy == Compatible) { 14641 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 14642 // Warn about retain cycles where a block captures the LHS, but 14643 // not if the LHS is a simple variable into which the block is 14644 // being stored...unless that variable can be captured by reference! 14645 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 14646 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 14647 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 14648 checkRetainCycles(LHSExpr, RHS.get()); 14649 } 14650 14651 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 14652 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 14653 // It is safe to assign a weak reference into a strong variable. 14654 // Although this code can still have problems: 14655 // id x = self.weakProp; 14656 // id y = self.weakProp; 14657 // we do not warn to warn spuriously when 'x' and 'y' are on separate 14658 // paths through the function. This should be revisited if 14659 // -Wrepeated-use-of-weak is made flow-sensitive. 14660 // For ObjCWeak only, we do not warn if the assign is to a non-weak 14661 // variable, which will be valid for the current autorelease scope. 14662 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 14663 RHS.get()->getBeginLoc())) 14664 getCurFunction()->markSafeWeakUse(RHS.get()); 14665 14666 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 14667 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 14668 } 14669 } 14670 } else { 14671 // Compound assignment "x += y" 14672 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 14673 } 14674 14675 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 14676 RHS.get(), AA_Assigning)) 14677 return QualType(); 14678 14679 CheckForNullPointerDereference(*this, LHSExpr); 14680 14681 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 14682 if (CompoundType.isNull()) { 14683 // C++2a [expr.ass]p5: 14684 // A simple-assignment whose left operand is of a volatile-qualified 14685 // type is deprecated unless the assignment is either a discarded-value 14686 // expression or an unevaluated operand 14687 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 14688 } 14689 } 14690 14691 // C11 6.5.16p3: The type of an assignment expression is the type of the 14692 // left operand would have after lvalue conversion. 14693 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has 14694 // qualified type, the value has the unqualified version of the type of the 14695 // lvalue; additionally, if the lvalue has atomic type, the value has the 14696 // non-atomic version of the type of the lvalue. 14697 // C++ 5.17p1: the type of the assignment expression is that of its left 14698 // operand. 14699 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); 14700} 14701 14702// Scenarios to ignore if expression E is: 14703// 1. an explicit cast expression into void 14704// 2. a function call expression that returns void 14705static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) { 14706 E = E->IgnoreParens(); 14707 14708 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 14709 if (CE->getCastKind() == CK_ToVoid) { 14710 return true; 14711 } 14712 14713 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 14714 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 14715 CE->getSubExpr()->getType()->isDependentType()) { 14716 return true; 14717 } 14718 } 14719 14720 if (const auto *CE = dyn_cast<CallExpr>(E)) 14721 return CE->getCallReturnType(Context)->isVoidType(); 14722 return false; 14723} 14724 14725// Look for instances where it is likely the comma operator is confused with 14726// another operator. There is an explicit list of acceptable expressions for 14727// the left hand side of the comma operator, otherwise emit a warning. 14728void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 14729 // No warnings in macros 14730 if (Loc.isMacroID()) 14731 return; 14732 14733 // Don't warn in template instantiations. 14734 if (inTemplateInstantiation()) 14735 return; 14736 14737 // Scope isn't fine-grained enough to explicitly list the specific cases, so 14738 // instead, skip more than needed, then call back into here with the 14739 // CommaVisitor in SemaStmt.cpp. 14740 // The listed locations are the initialization and increment portions 14741 // of a for loop. The additional checks are on the condition of 14742 // if statements, do/while loops, and for loops. 14743 // Differences in scope flags for C89 mode requires the extra logic. 14744 const unsigned ForIncrementFlags = 14745 getLangOpts().C99 || getLangOpts().CPlusPlus 14746 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 14747 : Scope::ContinueScope | Scope::BreakScope; 14748 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 14749 const unsigned ScopeFlags = getCurScope()->getFlags(); 14750 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 14751 (ScopeFlags & ForInitFlags) == ForInitFlags) 14752 return; 14753 14754 // If there are multiple comma operators used together, get the RHS of the 14755 // of the comma operator as the LHS. 14756 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 14757 if (BO->getOpcode() != BO_Comma) 14758 break; 14759 LHS = BO->getRHS(); 14760 } 14761 14762 // Only allow some expressions on LHS to not warn. 14763 if (IgnoreCommaOperand(LHS, Context)) 14764 return; 14765 14766 Diag(Loc, diag::warn_comma_operator); 14767 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 14768 << LHS->getSourceRange() 14769 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 14770 LangOpts.CPlusPlus ? "static_cast<void>(" 14771 : "(void)(") 14772 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 14773 ")"); 14774} 14775 14776// C99 6.5.17 14777static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 14778 SourceLocation Loc) { 14779 LHS = S.CheckPlaceholderExpr(LHS.get()); 14780 RHS = S.CheckPlaceholderExpr(RHS.get()); 14781 if (LHS.isInvalid() || RHS.isInvalid()) 14782 return QualType(); 14783 14784 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 14785 // operands, but not unary promotions. 14786 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 14787 14788 // So we treat the LHS as a ignored value, and in C++ we allow the 14789 // containing site to determine what should be done with the RHS. 14790 LHS = S.IgnoredValueConversions(LHS.get()); 14791 if (LHS.isInvalid()) 14792 return QualType(); 14793 14794 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 14795 14796 if (!S.getLangOpts().CPlusPlus) { 14797 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 14798 if (RHS.isInvalid()) 14799 return QualType(); 14800 if (!RHS.get()->getType()->isVoidType()) 14801 S.RequireCompleteType(Loc, RHS.get()->getType(), 14802 diag::err_incomplete_type); 14803 } 14804 14805 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 14806 S.DiagnoseCommaOperator(LHS.get(), Loc); 14807 14808 return RHS.get()->getType(); 14809} 14810 14811/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 14812/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 14813static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 14814 ExprValueKind &VK, 14815 ExprObjectKind &OK, 14816 SourceLocation OpLoc, 14817 bool IsInc, bool IsPrefix) { 14818 if (Op->isTypeDependent()) 14819 return S.Context.DependentTy; 14820 14821 QualType ResType = Op->getType(); 14822 // Atomic types can be used for increment / decrement where the non-atomic 14823 // versions can, so ignore the _Atomic() specifier for the purpose of 14824 // checking. 14825 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 14826 ResType = ResAtomicType->getValueType(); 14827 14828 assert(!ResType.isNull() && "no type for increment/decrement expression"); 14829 14830 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 14831 // Decrement of bool is not allowed. 14832 if (!IsInc) { 14833 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 14834 return QualType(); 14835 } 14836 // Increment of bool sets it to true, but is deprecated. 14837 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 14838 : diag::warn_increment_bool) 14839 << Op->getSourceRange(); 14840 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 14841 // Error on enum increments and decrements in C++ mode 14842 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 14843 return QualType(); 14844 } else if (ResType->isRealType()) { 14845 // OK! 14846 } else if (ResType->isPointerType()) { 14847 // C99 6.5.2.4p2, 6.5.6p2 14848 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 14849 return QualType(); 14850 } else if (ResType->isObjCObjectPointerType()) { 14851 // On modern runtimes, ObjC pointer arithmetic is forbidden. 14852 // Otherwise, we just need a complete type. 14853 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 14854 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 14855 return QualType(); 14856 } else if (ResType->isAnyComplexType()) { 14857 // C99 does not support ++/-- on complex types, we allow as an extension. 14858 S.Diag(OpLoc, diag::ext_integer_increment_complex) 14859 << ResType << Op->getSourceRange(); 14860 } else if (ResType->isPlaceholderType()) { 14861 ExprResult PR = S.CheckPlaceholderExpr(Op); 14862 if (PR.isInvalid()) return QualType(); 14863 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 14864 IsInc, IsPrefix); 14865 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 14866 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 14867 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 14868 (ResType->castAs<VectorType>()->getVectorKind() != 14869 VectorKind::AltiVecBool)) { 14870 // The z vector extensions allow ++ and -- for non-bool vectors. 14871 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() && 14872 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 14873 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 14874 } else { 14875 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 14876 << ResType << int(IsInc) << Op->getSourceRange(); 14877 return QualType(); 14878 } 14879 // At this point, we know we have a real, complex or pointer type. 14880 // Now make sure the operand is a modifiable lvalue. 14881 if (CheckForModifiableLvalue(Op, OpLoc, S)) 14882 return QualType(); 14883 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 14884 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 14885 // An operand with volatile-qualified type is deprecated 14886 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 14887 << IsInc << ResType; 14888 } 14889 // In C++, a prefix increment is the same type as the operand. Otherwise 14890 // (in C or with postfix), the increment is the unqualified type of the 14891 // operand. 14892 if (IsPrefix && S.getLangOpts().CPlusPlus) { 14893 VK = VK_LValue; 14894 OK = Op->getObjectKind(); 14895 return ResType; 14896 } else { 14897 VK = VK_PRValue; 14898 return ResType.getUnqualifiedType(); 14899 } 14900} 14901 14902 14903/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 14904/// This routine allows us to typecheck complex/recursive expressions 14905/// where the declaration is needed for type checking. We only need to 14906/// handle cases when the expression references a function designator 14907/// or is an lvalue. Here are some examples: 14908/// - &(x) => x 14909/// - &*****f => f for f a function designator. 14910/// - &s.xx => s 14911/// - &s.zz[1].yy -> s, if zz is an array 14912/// - *(x + 1) -> x, if x is an array 14913/// - &"123"[2] -> 0 14914/// - & __real__ x -> x 14915/// 14916/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 14917/// members. 14918static ValueDecl *getPrimaryDecl(Expr *E) { 14919 switch (E->getStmtClass()) { 14920 case Stmt::DeclRefExprClass: 14921 return cast<DeclRefExpr>(E)->getDecl(); 14922 case Stmt::MemberExprClass: 14923 // If this is an arrow operator, the address is an offset from 14924 // the base's value, so the object the base refers to is 14925 // irrelevant. 14926 if (cast<MemberExpr>(E)->isArrow()) 14927 return nullptr; 14928 // Otherwise, the expression refers to a part of the base 14929 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 14930 case Stmt::ArraySubscriptExprClass: { 14931 // FIXME: This code shouldn't be necessary! We should catch the implicit 14932 // promotion of register arrays earlier. 14933 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 14934 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 14935 if (ICE->getSubExpr()->getType()->isArrayType()) 14936 return getPrimaryDecl(ICE->getSubExpr()); 14937 } 14938 return nullptr; 14939 } 14940 case Stmt::UnaryOperatorClass: { 14941 UnaryOperator *UO = cast<UnaryOperator>(E); 14942 14943 switch(UO->getOpcode()) { 14944 case UO_Real: 14945 case UO_Imag: 14946 case UO_Extension: 14947 return getPrimaryDecl(UO->getSubExpr()); 14948 default: 14949 return nullptr; 14950 } 14951 } 14952 case Stmt::ParenExprClass: 14953 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 14954 case Stmt::ImplicitCastExprClass: 14955 // If the result of an implicit cast is an l-value, we care about 14956 // the sub-expression; otherwise, the result here doesn't matter. 14957 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 14958 case Stmt::CXXUuidofExprClass: 14959 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 14960 default: 14961 return nullptr; 14962 } 14963} 14964 14965namespace { 14966enum { 14967 AO_Bit_Field = 0, 14968 AO_Vector_Element = 1, 14969 AO_Property_Expansion = 2, 14970 AO_Register_Variable = 3, 14971 AO_Matrix_Element = 4, 14972 AO_No_Error = 5 14973}; 14974} 14975/// Diagnose invalid operand for address of operations. 14976/// 14977/// \param Type The type of operand which cannot have its address taken. 14978static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 14979 Expr *E, unsigned Type) { 14980 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 14981} 14982 14983bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, 14984 const Expr *Op, 14985 const CXXMethodDecl *MD) { 14986 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens()); 14987 14988 if (Op != DRE) 14989 return Diag(OpLoc, diag::err_parens_pointer_member_function) 14990 << Op->getSourceRange(); 14991 14992 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 14993 if (isa<CXXDestructorDecl>(MD)) 14994 return Diag(OpLoc, diag::err_typecheck_addrof_dtor) 14995 << DRE->getSourceRange(); 14996 14997 if (DRE->getQualifier()) 14998 return false; 14999 15000 if (MD->getParent()->getName().empty()) 15001 return Diag(OpLoc, diag::err_unqualified_pointer_member_function) 15002 << DRE->getSourceRange(); 15003 15004 SmallString<32> Str; 15005 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 15006 return Diag(OpLoc, diag::err_unqualified_pointer_member_function) 15007 << DRE->getSourceRange() 15008 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual); 15009} 15010 15011/// CheckAddressOfOperand - The operand of & must be either a function 15012/// designator or an lvalue designating an object. If it is an lvalue, the 15013/// object cannot be declared with storage class register or be a bit field. 15014/// Note: The usual conversions are *not* applied to the operand of the & 15015/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 15016/// In C++, the operand might be an overloaded function name, in which case 15017/// we allow the '&' but retain the overloaded-function type. 15018QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 15019 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 15020 if (PTy->getKind() == BuiltinType::Overload) { 15021 Expr *E = OrigOp.get()->IgnoreParens(); 15022 if (!isa<OverloadExpr>(E)) { 15023 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 15024 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 15025 << OrigOp.get()->getSourceRange(); 15026 return QualType(); 15027 } 15028 15029 OverloadExpr *Ovl = cast<OverloadExpr>(E); 15030 if (isa<UnresolvedMemberExpr>(Ovl)) 15031 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 15032 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 15033 << OrigOp.get()->getSourceRange(); 15034 return QualType(); 15035 } 15036 15037 return Context.OverloadTy; 15038 } 15039 15040 if (PTy->getKind() == BuiltinType::UnknownAny) 15041 return Context.UnknownAnyTy; 15042 15043 if (PTy->getKind() == BuiltinType::BoundMember) { 15044 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 15045 << OrigOp.get()->getSourceRange(); 15046 return QualType(); 15047 } 15048 15049 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 15050 if (OrigOp.isInvalid()) return QualType(); 15051 } 15052 15053 if (OrigOp.get()->isTypeDependent()) 15054 return Context.DependentTy; 15055 15056 assert(!OrigOp.get()->hasPlaceholderType()); 15057 15058 // Make sure to ignore parentheses in subsequent checks 15059 Expr *op = OrigOp.get()->IgnoreParens(); 15060 15061 // In OpenCL captures for blocks called as lambda functions 15062 // are located in the private address space. Blocks used in 15063 // enqueue_kernel can be located in a different address space 15064 // depending on a vendor implementation. Thus preventing 15065 // taking an address of the capture to avoid invalid AS casts. 15066 if (LangOpts.OpenCL) { 15067 auto* VarRef = dyn_cast<DeclRefExpr>(op); 15068 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 15069 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 15070 return QualType(); 15071 } 15072 } 15073 15074 if (getLangOpts().C99) { 15075 // Implement C99-only parts of addressof rules. 15076 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 15077 if (uOp->getOpcode() == UO_Deref) 15078 // Per C99 6.5.3.2, the address of a deref always returns a valid result 15079 // (assuming the deref expression is valid). 15080 return uOp->getSubExpr()->getType(); 15081 } 15082 // Technically, there should be a check for array subscript 15083 // expressions here, but the result of one is always an lvalue anyway. 15084 } 15085 ValueDecl *dcl = getPrimaryDecl(op); 15086 15087 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 15088 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 15089 op->getBeginLoc())) 15090 return QualType(); 15091 15092 Expr::LValueClassification lval = op->ClassifyLValue(Context); 15093 unsigned AddressOfError = AO_No_Error; 15094 15095 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 15096 bool sfinae = (bool)isSFINAEContext(); 15097 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 15098 : diag::ext_typecheck_addrof_temporary) 15099 << op->getType() << op->getSourceRange(); 15100 if (sfinae) 15101 return QualType(); 15102 // Materialize the temporary as an lvalue so that we can take its address. 15103 OrigOp = op = 15104 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 15105 } else if (isa<ObjCSelectorExpr>(op)) { 15106 return Context.getPointerType(op->getType()); 15107 } else if (lval == Expr::LV_MemberFunction) { 15108 // If it's an instance method, make a member pointer. 15109 // The expression must have exactly the form &A::foo. 15110 15111 // If the underlying expression isn't a decl ref, give up. 15112 if (!isa<DeclRefExpr>(op)) { 15113 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 15114 << OrigOp.get()->getSourceRange(); 15115 return QualType(); 15116 } 15117 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 15118 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 15119 15120 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD); 15121 15122 QualType MPTy = Context.getMemberPointerType( 15123 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 15124 // Under the MS ABI, lock down the inheritance model now. 15125 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15126 (void)isCompleteType(OpLoc, MPTy); 15127 return MPTy; 15128 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 15129 // C99 6.5.3.2p1 15130 // The operand must be either an l-value or a function designator 15131 if (!op->getType()->isFunctionType()) { 15132 // Use a special diagnostic for loads from property references. 15133 if (isa<PseudoObjectExpr>(op)) { 15134 AddressOfError = AO_Property_Expansion; 15135 } else { 15136 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 15137 << op->getType() << op->getSourceRange(); 15138 return QualType(); 15139 } 15140 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) { 15141 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl())) 15142 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD); 15143 } 15144 15145 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 15146 // The operand cannot be a bit-field 15147 AddressOfError = AO_Bit_Field; 15148 } else if (op->getObjectKind() == OK_VectorComponent) { 15149 // The operand cannot be an element of a vector 15150 AddressOfError = AO_Vector_Element; 15151 } else if (op->getObjectKind() == OK_MatrixComponent) { 15152 // The operand cannot be an element of a matrix. 15153 AddressOfError = AO_Matrix_Element; 15154 } else if (dcl) { // C99 6.5.3.2p1 15155 // We have an lvalue with a decl. Make sure the decl is not declared 15156 // with the register storage-class specifier. 15157 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 15158 // in C++ it is not error to take address of a register 15159 // variable (c++03 7.1.1P3) 15160 if (vd->getStorageClass() == SC_Register && 15161 !getLangOpts().CPlusPlus) { 15162 AddressOfError = AO_Register_Variable; 15163 } 15164 } else if (isa<MSPropertyDecl>(dcl)) { 15165 AddressOfError = AO_Property_Expansion; 15166 } else if (isa<FunctionTemplateDecl>(dcl)) { 15167 return Context.OverloadTy; 15168 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 15169 // Okay: we can take the address of a field. 15170 // Could be a pointer to member, though, if there is an explicit 15171 // scope qualifier for the class. 15172 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 15173 DeclContext *Ctx = dcl->getDeclContext(); 15174 if (Ctx && Ctx->isRecord()) { 15175 if (dcl->getType()->isReferenceType()) { 15176 Diag(OpLoc, 15177 diag::err_cannot_form_pointer_to_member_of_reference_type) 15178 << dcl->getDeclName() << dcl->getType(); 15179 return QualType(); 15180 } 15181 15182 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 15183 Ctx = Ctx->getParent(); 15184 15185 QualType MPTy = Context.getMemberPointerType( 15186 op->getType(), 15187 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 15188 // Under the MS ABI, lock down the inheritance model now. 15189 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15190 (void)isCompleteType(OpLoc, MPTy); 15191 return MPTy; 15192 } 15193 } 15194 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, 15195 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl)) 15196 llvm_unreachable("Unknown/unexpected decl type"); 15197 } 15198 15199 if (AddressOfError != AO_No_Error) { 15200 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 15201 return QualType(); 15202 } 15203 15204 if (lval == Expr::LV_IncompleteVoidType) { 15205 // Taking the address of a void variable is technically illegal, but we 15206 // allow it in cases which are otherwise valid. 15207 // Example: "extern void x; void* y = &x;". 15208 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 15209 } 15210 15211 // If the operand has type "type", the result has type "pointer to type". 15212 if (op->getType()->isObjCObjectType()) 15213 return Context.getObjCObjectPointerType(op->getType()); 15214 15215 // Cannot take the address of WebAssembly references or tables. 15216 if (Context.getTargetInfo().getTriple().isWasm()) { 15217 QualType OpTy = op->getType(); 15218 if (OpTy.isWebAssemblyReferenceType()) { 15219 Diag(OpLoc, diag::err_wasm_ca_reference) 15220 << 1 << OrigOp.get()->getSourceRange(); 15221 return QualType(); 15222 } 15223 if (OpTy->isWebAssemblyTableType()) { 15224 Diag(OpLoc, diag::err_wasm_table_pr) 15225 << 1 << OrigOp.get()->getSourceRange(); 15226 return QualType(); 15227 } 15228 } 15229 15230 CheckAddressOfPackedMember(op); 15231 15232 return Context.getPointerType(op->getType()); 15233} 15234 15235static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 15236 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 15237 if (!DRE) 15238 return; 15239 const Decl *D = DRE->getDecl(); 15240 if (!D) 15241 return; 15242 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 15243 if (!Param) 15244 return; 15245 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 15246 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 15247 return; 15248 if (FunctionScopeInfo *FD = S.getCurFunction()) 15249 FD->ModifiedNonNullParams.insert(Param); 15250} 15251 15252/// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 15253static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 15254 SourceLocation OpLoc, 15255 bool IsAfterAmp = false) { 15256 if (Op->isTypeDependent()) 15257 return S.Context.DependentTy; 15258 15259 ExprResult ConvResult = S.UsualUnaryConversions(Op); 15260 if (ConvResult.isInvalid()) 15261 return QualType(); 15262 Op = ConvResult.get(); 15263 QualType OpTy = Op->getType(); 15264 QualType Result; 15265 15266 if (isa<CXXReinterpretCastExpr>(Op)) { 15267 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 15268 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 15269 Op->getSourceRange()); 15270 } 15271 15272 if (const PointerType *PT = OpTy->getAs<PointerType>()) 15273 { 15274 Result = PT->getPointeeType(); 15275 } 15276 else if (const ObjCObjectPointerType *OPT = 15277 OpTy->getAs<ObjCObjectPointerType>()) 15278 Result = OPT->getPointeeType(); 15279 else { 15280 ExprResult PR = S.CheckPlaceholderExpr(Op); 15281 if (PR.isInvalid()) return QualType(); 15282 if (PR.get() != Op) 15283 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 15284 } 15285 15286 if (Result.isNull()) { 15287 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 15288 << OpTy << Op->getSourceRange(); 15289 return QualType(); 15290 } 15291 15292 if (Result->isVoidType()) { 15293 // C++ [expr.unary.op]p1: 15294 // [...] the expression to which [the unary * operator] is applied shall 15295 // be a pointer to an object type, or a pointer to a function type 15296 LangOptions LO = S.getLangOpts(); 15297 if (LO.CPlusPlus) 15298 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp) 15299 << OpTy << Op->getSourceRange(); 15300 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext()) 15301 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 15302 << OpTy << Op->getSourceRange(); 15303 } 15304 15305 // Dereferences are usually l-values... 15306 VK = VK_LValue; 15307 15308 // ...except that certain expressions are never l-values in C. 15309 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 15310 VK = VK_PRValue; 15311 15312 return Result; 15313} 15314 15315BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 15316 BinaryOperatorKind Opc; 15317 switch (Kind) { 15318 default: llvm_unreachable("Unknown binop!"); 15319 case tok::periodstar: Opc = BO_PtrMemD; break; 15320 case tok::arrowstar: Opc = BO_PtrMemI; break; 15321 case tok::star: Opc = BO_Mul; break; 15322 case tok::slash: Opc = BO_Div; break; 15323 case tok::percent: Opc = BO_Rem; break; 15324 case tok::plus: Opc = BO_Add; break; 15325 case tok::minus: Opc = BO_Sub; break; 15326 case tok::lessless: Opc = BO_Shl; break; 15327 case tok::greatergreater: Opc = BO_Shr; break; 15328 case tok::lessequal: Opc = BO_LE; break; 15329 case tok::less: Opc = BO_LT; break; 15330 case tok::greaterequal: Opc = BO_GE; break; 15331 case tok::greater: Opc = BO_GT; break; 15332 case tok::exclaimequal: Opc = BO_NE; break; 15333 case tok::equalequal: Opc = BO_EQ; break; 15334 case tok::spaceship: Opc = BO_Cmp; break; 15335 case tok::amp: Opc = BO_And; break; 15336 case tok::caret: Opc = BO_Xor; break; 15337 case tok::pipe: Opc = BO_Or; break; 15338 case tok::ampamp: Opc = BO_LAnd; break; 15339 case tok::pipepipe: Opc = BO_LOr; break; 15340 case tok::equal: Opc = BO_Assign; break; 15341 case tok::starequal: Opc = BO_MulAssign; break; 15342 case tok::slashequal: Opc = BO_DivAssign; break; 15343 case tok::percentequal: Opc = BO_RemAssign; break; 15344 case tok::plusequal: Opc = BO_AddAssign; break; 15345 case tok::minusequal: Opc = BO_SubAssign; break; 15346 case tok::lesslessequal: Opc = BO_ShlAssign; break; 15347 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 15348 case tok::ampequal: Opc = BO_AndAssign; break; 15349 case tok::caretequal: Opc = BO_XorAssign; break; 15350 case tok::pipeequal: Opc = BO_OrAssign; break; 15351 case tok::comma: Opc = BO_Comma; break; 15352 } 15353 return Opc; 15354} 15355 15356static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 15357 tok::TokenKind Kind) { 15358 UnaryOperatorKind Opc; 15359 switch (Kind) { 15360 default: llvm_unreachable("Unknown unary op!"); 15361 case tok::plusplus: Opc = UO_PreInc; break; 15362 case tok::minusminus: Opc = UO_PreDec; break; 15363 case tok::amp: Opc = UO_AddrOf; break; 15364 case tok::star: Opc = UO_Deref; break; 15365 case tok::plus: Opc = UO_Plus; break; 15366 case tok::minus: Opc = UO_Minus; break; 15367 case tok::tilde: Opc = UO_Not; break; 15368 case tok::exclaim: Opc = UO_LNot; break; 15369 case tok::kw___real: Opc = UO_Real; break; 15370 case tok::kw___imag: Opc = UO_Imag; break; 15371 case tok::kw___extension__: Opc = UO_Extension; break; 15372 } 15373 return Opc; 15374} 15375 15376const FieldDecl * 15377Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) { 15378 // Explore the case for adding 'this->' to the LHS of a self assignment, very 15379 // common for setters. 15380 // struct A { 15381 // int X; 15382 // -void setX(int X) { X = X; } 15383 // +void setX(int X) { this->X = X; } 15384 // }; 15385 15386 // Only consider parameters for self assignment fixes. 15387 if (!isa<ParmVarDecl>(SelfAssigned)) 15388 return nullptr; 15389 const auto *Method = 15390 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true)); 15391 if (!Method) 15392 return nullptr; 15393 15394 const CXXRecordDecl *Parent = Method->getParent(); 15395 // In theory this is fixable if the lambda explicitly captures this, but 15396 // that's added complexity that's rarely going to be used. 15397 if (Parent->isLambda()) 15398 return nullptr; 15399 15400 // FIXME: Use an actual Lookup operation instead of just traversing fields 15401 // in order to get base class fields. 15402 auto Field = 15403 llvm::find_if(Parent->fields(), 15404 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) { 15405 return F->getDeclName() == Name; 15406 }); 15407 return (Field != Parent->field_end()) ? *Field : nullptr; 15408} 15409 15410/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 15411/// This warning suppressed in the event of macro expansions. 15412static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 15413 SourceLocation OpLoc, bool IsBuiltin) { 15414 if (S.inTemplateInstantiation()) 15415 return; 15416 if (S.isUnevaluatedContext()) 15417 return; 15418 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 15419 return; 15420 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15421 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15422 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15423 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15424 if (!LHSDeclRef || !RHSDeclRef || 15425 LHSDeclRef->getLocation().isMacroID() || 15426 RHSDeclRef->getLocation().isMacroID()) 15427 return; 15428 const ValueDecl *LHSDecl = 15429 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 15430 const ValueDecl *RHSDecl = 15431 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 15432 if (LHSDecl != RHSDecl) 15433 return; 15434 if (LHSDecl->getType().isVolatileQualified()) 15435 return; 15436 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 15437 if (RefTy->getPointeeType().isVolatileQualified()) 15438 return; 15439 15440 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 15441 : diag::warn_self_assignment_overloaded) 15442 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 15443 << RHSExpr->getSourceRange(); 15444 if (const FieldDecl *SelfAssignField = 15445 S.getSelfAssignmentClassMemberCandidate(RHSDecl)) 15446 Diag << 1 << SelfAssignField 15447 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->"); 15448 else 15449 Diag << 0; 15450} 15451 15452/// Check if a bitwise-& is performed on an Objective-C pointer. This 15453/// is usually indicative of introspection within the Objective-C pointer. 15454static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 15455 SourceLocation OpLoc) { 15456 if (!S.getLangOpts().ObjC) 15457 return; 15458 15459 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 15460 const Expr *LHS = L.get(); 15461 const Expr *RHS = R.get(); 15462 15463 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 15464 ObjCPointerExpr = LHS; 15465 OtherExpr = RHS; 15466 } 15467 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 15468 ObjCPointerExpr = RHS; 15469 OtherExpr = LHS; 15470 } 15471 15472 // This warning is deliberately made very specific to reduce false 15473 // positives with logic that uses '&' for hashing. This logic mainly 15474 // looks for code trying to introspect into tagged pointers, which 15475 // code should generally never do. 15476 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 15477 unsigned Diag = diag::warn_objc_pointer_masking; 15478 // Determine if we are introspecting the result of performSelectorXXX. 15479 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 15480 // Special case messages to -performSelector and friends, which 15481 // can return non-pointer values boxed in a pointer value. 15482 // Some clients may wish to silence warnings in this subcase. 15483 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 15484 Selector S = ME->getSelector(); 15485 StringRef SelArg0 = S.getNameForSlot(0); 15486 if (SelArg0.starts_with("performSelector")) 15487 Diag = diag::warn_objc_pointer_masking_performSelector; 15488 } 15489 15490 S.Diag(OpLoc, Diag) 15491 << ObjCPointerExpr->getSourceRange(); 15492 } 15493} 15494 15495static NamedDecl *getDeclFromExpr(Expr *E) { 15496 if (!E) 15497 return nullptr; 15498 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 15499 return DRE->getDecl(); 15500 if (auto *ME = dyn_cast<MemberExpr>(E)) 15501 return ME->getMemberDecl(); 15502 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 15503 return IRE->getDecl(); 15504 return nullptr; 15505} 15506 15507// This helper function promotes a binary operator's operands (which are of a 15508// half vector type) to a vector of floats and then truncates the result to 15509// a vector of either half or short. 15510static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 15511 BinaryOperatorKind Opc, QualType ResultTy, 15512 ExprValueKind VK, ExprObjectKind OK, 15513 bool IsCompAssign, SourceLocation OpLoc, 15514 FPOptionsOverride FPFeatures) { 15515 auto &Context = S.getASTContext(); 15516 assert((isVector(ResultTy, Context.HalfTy) || 15517 isVector(ResultTy, Context.ShortTy)) && 15518 "Result must be a vector of half or short"); 15519 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 15520 isVector(RHS.get()->getType(), Context.HalfTy) && 15521 "both operands expected to be a half vector"); 15522 15523 RHS = convertVector(RHS.get(), Context.FloatTy, S); 15524 QualType BinOpResTy = RHS.get()->getType(); 15525 15526 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 15527 // change BinOpResTy to a vector of ints. 15528 if (isVector(ResultTy, Context.ShortTy)) 15529 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 15530 15531 if (IsCompAssign) 15532 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 15533 ResultTy, VK, OK, OpLoc, FPFeatures, 15534 BinOpResTy, BinOpResTy); 15535 15536 LHS = convertVector(LHS.get(), Context.FloatTy, S); 15537 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 15538 BinOpResTy, VK, OK, OpLoc, FPFeatures); 15539 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 15540} 15541 15542static std::pair<ExprResult, ExprResult> 15543CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 15544 Expr *RHSExpr) { 15545 ExprResult LHS = LHSExpr, RHS = RHSExpr; 15546 if (!S.Context.isDependenceAllowed()) { 15547 // C cannot handle TypoExpr nodes on either side of a binop because it 15548 // doesn't handle dependent types properly, so make sure any TypoExprs have 15549 // been dealt with before checking the operands. 15550 LHS = S.CorrectDelayedTyposInExpr(LHS); 15551 RHS = S.CorrectDelayedTyposInExpr( 15552 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 15553 [Opc, LHS](Expr *E) { 15554 if (Opc != BO_Assign) 15555 return ExprResult(E); 15556 // Avoid correcting the RHS to the same Expr as the LHS. 15557 Decl *D = getDeclFromExpr(E); 15558 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 15559 }); 15560 } 15561 return std::make_pair(LHS, RHS); 15562} 15563 15564/// Returns true if conversion between vectors of halfs and vectors of floats 15565/// is needed. 15566static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 15567 Expr *E0, Expr *E1 = nullptr) { 15568 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 15569 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 15570 return false; 15571 15572 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 15573 QualType Ty = E->IgnoreImplicit()->getType(); 15574 15575 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 15576 // to vectors of floats. Although the element type of the vectors is __fp16, 15577 // the vectors shouldn't be treated as storage-only types. See the 15578 // discussion here: https://reviews.llvm.org/rG825235c140e7 15579 if (const VectorType *VT = Ty->getAs<VectorType>()) { 15580 if (VT->getVectorKind() == VectorKind::Neon) 15581 return false; 15582 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 15583 } 15584 return false; 15585 }; 15586 15587 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 15588} 15589 15590/// CreateBuiltinBinOp - Creates a new built-in binary operation with 15591/// operator @p Opc at location @c TokLoc. This routine only supports 15592/// built-in operations; ActOnBinOp handles overloaded operators. 15593ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 15594 BinaryOperatorKind Opc, 15595 Expr *LHSExpr, Expr *RHSExpr) { 15596 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 15597 // The syntax only allows initializer lists on the RHS of assignment, 15598 // so we don't need to worry about accepting invalid code for 15599 // non-assignment operators. 15600 // C++11 5.17p9: 15601 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 15602 // of x = {} is x = T(). 15603 InitializationKind Kind = InitializationKind::CreateDirectList( 15604 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 15605 InitializedEntity Entity = 15606 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 15607 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 15608 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 15609 if (Init.isInvalid()) 15610 return Init; 15611 RHSExpr = Init.get(); 15612 } 15613 15614 ExprResult LHS = LHSExpr, RHS = RHSExpr; 15615 QualType ResultTy; // Result type of the binary operator. 15616 // The following two variables are used for compound assignment operators 15617 QualType CompLHSTy; // Type of LHS after promotions for computation 15618 QualType CompResultTy; // Type of computation result 15619 ExprValueKind VK = VK_PRValue; 15620 ExprObjectKind OK = OK_Ordinary; 15621 bool ConvertHalfVec = false; 15622 15623 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 15624 if (!LHS.isUsable() || !RHS.isUsable()) 15625 return ExprError(); 15626 15627 if (getLangOpts().OpenCL) { 15628 QualType LHSTy = LHSExpr->getType(); 15629 QualType RHSTy = RHSExpr->getType(); 15630 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 15631 // the ATOMIC_VAR_INIT macro. 15632 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 15633 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 15634 if (BO_Assign == Opc) 15635 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 15636 else 15637 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 15638 return ExprError(); 15639 } 15640 15641 // OpenCL special types - image, sampler, pipe, and blocks are to be used 15642 // only with a builtin functions and therefore should be disallowed here. 15643 if (LHSTy->isImageType() || RHSTy->isImageType() || 15644 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 15645 LHSTy->isPipeType() || RHSTy->isPipeType() || 15646 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 15647 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 15648 return ExprError(); 15649 } 15650 } 15651 15652 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 15653 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 15654 15655 switch (Opc) { 15656 case BO_Assign: 15657 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc); 15658 if (getLangOpts().CPlusPlus && 15659 LHS.get()->getObjectKind() != OK_ObjCProperty) { 15660 VK = LHS.get()->getValueKind(); 15661 OK = LHS.get()->getObjectKind(); 15662 } 15663 if (!ResultTy.isNull()) { 15664 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 15665 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 15666 15667 // Avoid copying a block to the heap if the block is assigned to a local 15668 // auto variable that is declared in the same scope as the block. This 15669 // optimization is unsafe if the local variable is declared in an outer 15670 // scope. For example: 15671 // 15672 // BlockTy b; 15673 // { 15674 // b = ^{...}; 15675 // } 15676 // // It is unsafe to invoke the block here if it wasn't copied to the 15677 // // heap. 15678 // b(); 15679 15680 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 15681 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 15682 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 15683 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 15684 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 15685 15686 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 15687 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 15688 NTCUC_Assignment, NTCUK_Copy); 15689 } 15690 RecordModifiableNonNullParam(*this, LHS.get()); 15691 break; 15692 case BO_PtrMemD: 15693 case BO_PtrMemI: 15694 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 15695 Opc == BO_PtrMemI); 15696 break; 15697 case BO_Mul: 15698 case BO_Div: 15699 ConvertHalfVec = true; 15700 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 15701 Opc == BO_Div); 15702 break; 15703 case BO_Rem: 15704 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 15705 break; 15706 case BO_Add: 15707 ConvertHalfVec = true; 15708 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 15709 break; 15710 case BO_Sub: 15711 ConvertHalfVec = true; 15712 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 15713 break; 15714 case BO_Shl: 15715 case BO_Shr: 15716 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 15717 break; 15718 case BO_LE: 15719 case BO_LT: 15720 case BO_GE: 15721 case BO_GT: 15722 ConvertHalfVec = true; 15723 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 15724 break; 15725 case BO_EQ: 15726 case BO_NE: 15727 ConvertHalfVec = true; 15728 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 15729 break; 15730 case BO_Cmp: 15731 ConvertHalfVec = true; 15732 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 15733 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 15734 break; 15735 case BO_And: 15736 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 15737 [[fallthrough]]; 15738 case BO_Xor: 15739 case BO_Or: 15740 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 15741 break; 15742 case BO_LAnd: 15743 case BO_LOr: 15744 ConvertHalfVec = true; 15745 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 15746 break; 15747 case BO_MulAssign: 15748 case BO_DivAssign: 15749 ConvertHalfVec = true; 15750 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 15751 Opc == BO_DivAssign); 15752 CompLHSTy = CompResultTy; 15753 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15754 ResultTy = 15755 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15756 break; 15757 case BO_RemAssign: 15758 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 15759 CompLHSTy = CompResultTy; 15760 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15761 ResultTy = 15762 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15763 break; 15764 case BO_AddAssign: 15765 ConvertHalfVec = true; 15766 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 15767 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15768 ResultTy = 15769 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15770 break; 15771 case BO_SubAssign: 15772 ConvertHalfVec = true; 15773 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 15774 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15775 ResultTy = 15776 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15777 break; 15778 case BO_ShlAssign: 15779 case BO_ShrAssign: 15780 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 15781 CompLHSTy = CompResultTy; 15782 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15783 ResultTy = 15784 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15785 break; 15786 case BO_AndAssign: 15787 case BO_OrAssign: // fallthrough 15788 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 15789 [[fallthrough]]; 15790 case BO_XorAssign: 15791 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 15792 CompLHSTy = CompResultTy; 15793 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15794 ResultTy = 15795 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15796 break; 15797 case BO_Comma: 15798 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 15799 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 15800 VK = RHS.get()->getValueKind(); 15801 OK = RHS.get()->getObjectKind(); 15802 } 15803 break; 15804 } 15805 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 15806 return ExprError(); 15807 15808 // Some of the binary operations require promoting operands of half vector to 15809 // float vectors and truncating the result back to half vector. For now, we do 15810 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 15811 // arm64). 15812 assert( 15813 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 15814 isVector(LHS.get()->getType(), Context.HalfTy)) && 15815 "both sides are half vectors or neither sides are"); 15816 ConvertHalfVec = 15817 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 15818 15819 // Check for array bounds violations for both sides of the BinaryOperator 15820 CheckArrayAccess(LHS.get()); 15821 CheckArrayAccess(RHS.get()); 15822 15823 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 15824 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 15825 &Context.Idents.get("object_setClass"), 15826 SourceLocation(), LookupOrdinaryName); 15827 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 15828 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 15829 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 15830 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 15831 "object_setClass(") 15832 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 15833 ",") 15834 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 15835 } 15836 else 15837 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 15838 } 15839 else if (const ObjCIvarRefExpr *OIRE = 15840 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 15841 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 15842 15843 // Opc is not a compound assignment if CompResultTy is null. 15844 if (CompResultTy.isNull()) { 15845 if (ConvertHalfVec) 15846 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 15847 OpLoc, CurFPFeatureOverrides()); 15848 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 15849 VK, OK, OpLoc, CurFPFeatureOverrides()); 15850 } 15851 15852 // Handle compound assignments. 15853 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 15854 OK_ObjCProperty) { 15855 VK = VK_LValue; 15856 OK = LHS.get()->getObjectKind(); 15857 } 15858 15859 // The LHS is not converted to the result type for fixed-point compound 15860 // assignment as the common type is computed on demand. Reset the CompLHSTy 15861 // to the LHS type we would have gotten after unary conversions. 15862 if (CompResultTy->isFixedPointType()) 15863 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 15864 15865 if (ConvertHalfVec) 15866 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 15867 OpLoc, CurFPFeatureOverrides()); 15868 15869 return CompoundAssignOperator::Create( 15870 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 15871 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 15872} 15873 15874/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 15875/// operators are mixed in a way that suggests that the programmer forgot that 15876/// comparison operators have higher precedence. The most typical example of 15877/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 15878static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 15879 SourceLocation OpLoc, Expr *LHSExpr, 15880 Expr *RHSExpr) { 15881 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 15882 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 15883 15884 // Check that one of the sides is a comparison operator and the other isn't. 15885 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 15886 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 15887 if (isLeftComp == isRightComp) 15888 return; 15889 15890 // Bitwise operations are sometimes used as eager logical ops. 15891 // Don't diagnose this. 15892 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 15893 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 15894 if (isLeftBitwise || isRightBitwise) 15895 return; 15896 15897 SourceRange DiagRange = isLeftComp 15898 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 15899 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 15900 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 15901 SourceRange ParensRange = 15902 isLeftComp 15903 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 15904 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 15905 15906 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 15907 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 15908 SuggestParentheses(Self, OpLoc, 15909 Self.PDiag(diag::note_precedence_silence) << OpStr, 15910 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 15911 SuggestParentheses(Self, OpLoc, 15912 Self.PDiag(diag::note_precedence_bitwise_first) 15913 << BinaryOperator::getOpcodeStr(Opc), 15914 ParensRange); 15915} 15916 15917/// It accepts a '&&' expr that is inside a '||' one. 15918/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 15919/// in parentheses. 15920static void 15921EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 15922 BinaryOperator *Bop) { 15923 assert(Bop->getOpcode() == BO_LAnd); 15924 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 15925 << Bop->getSourceRange() << OpLoc; 15926 SuggestParentheses(Self, Bop->getOperatorLoc(), 15927 Self.PDiag(diag::note_precedence_silence) 15928 << Bop->getOpcodeStr(), 15929 Bop->getSourceRange()); 15930} 15931 15932/// Look for '&&' in the left hand of a '||' expr. 15933static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 15934 Expr *LHSExpr, Expr *RHSExpr) { 15935 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 15936 if (Bop->getOpcode() == BO_LAnd) { 15937 // If it's "string_literal && a || b" don't warn since the precedence 15938 // doesn't matter. 15939 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts())) 15940 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15941 } else if (Bop->getOpcode() == BO_LOr) { 15942 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 15943 // If it's "a || b && string_literal || c" we didn't warn earlier for 15944 // "a || b && string_literal", but warn now. 15945 if (RBop->getOpcode() == BO_LAnd && 15946 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts())) 15947 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 15948 } 15949 } 15950 } 15951} 15952 15953/// Look for '&&' in the right hand of a '||' expr. 15954static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 15955 Expr *LHSExpr, Expr *RHSExpr) { 15956 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 15957 if (Bop->getOpcode() == BO_LAnd) { 15958 // If it's "a || b && string_literal" don't warn since the precedence 15959 // doesn't matter. 15960 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts())) 15961 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15962 } 15963 } 15964} 15965 15966/// Look for bitwise op in the left or right hand of a bitwise op with 15967/// lower precedence and emit a diagnostic together with a fixit hint that wraps 15968/// the '&' expression in parentheses. 15969static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 15970 SourceLocation OpLoc, Expr *SubExpr) { 15971 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15972 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 15973 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 15974 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 15975 << Bop->getSourceRange() << OpLoc; 15976 SuggestParentheses(S, Bop->getOperatorLoc(), 15977 S.PDiag(diag::note_precedence_silence) 15978 << Bop->getOpcodeStr(), 15979 Bop->getSourceRange()); 15980 } 15981 } 15982} 15983 15984static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 15985 Expr *SubExpr, StringRef Shift) { 15986 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15987 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 15988 StringRef Op = Bop->getOpcodeStr(); 15989 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 15990 << Bop->getSourceRange() << OpLoc << Shift << Op; 15991 SuggestParentheses(S, Bop->getOperatorLoc(), 15992 S.PDiag(diag::note_precedence_silence) << Op, 15993 Bop->getSourceRange()); 15994 } 15995 } 15996} 15997 15998static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 15999 Expr *LHSExpr, Expr *RHSExpr) { 16000 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 16001 if (!OCE) 16002 return; 16003 16004 FunctionDecl *FD = OCE->getDirectCallee(); 16005 if (!FD || !FD->isOverloadedOperator()) 16006 return; 16007 16008 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 16009 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 16010 return; 16011 16012 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 16013 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 16014 << (Kind == OO_LessLess); 16015 SuggestParentheses(S, OCE->getOperatorLoc(), 16016 S.PDiag(diag::note_precedence_silence) 16017 << (Kind == OO_LessLess ? "<<" : ">>"), 16018 OCE->getSourceRange()); 16019 SuggestParentheses( 16020 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 16021 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 16022} 16023 16024/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 16025/// precedence. 16026static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 16027 SourceLocation OpLoc, Expr *LHSExpr, 16028 Expr *RHSExpr){ 16029 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 16030 if (BinaryOperator::isBitwiseOp(Opc)) 16031 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 16032 16033 // Diagnose "arg1 & arg2 | arg3" 16034 if ((Opc == BO_Or || Opc == BO_Xor) && 16035 !OpLoc.isMacroID()/* Don't warn in macros. */) { 16036 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 16037 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 16038 } 16039 16040 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 16041 // We don't warn for 'assert(a || b && "bad")' since this is safe. 16042 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 16043 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 16044 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 16045 } 16046 16047 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 16048 || Opc == BO_Shr) { 16049 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 16050 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 16051 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 16052 } 16053 16054 // Warn on overloaded shift operators and comparisons, such as: 16055 // cout << 5 == 4; 16056 if (BinaryOperator::isComparisonOp(Opc)) 16057 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 16058} 16059 16060// Binary Operators. 'Tok' is the token for the operator. 16061ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 16062 tok::TokenKind Kind, 16063 Expr *LHSExpr, Expr *RHSExpr) { 16064 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 16065 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 16066 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 16067 16068 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 16069 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 16070 16071 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 16072} 16073 16074void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 16075 UnresolvedSetImpl &Functions) { 16076 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 16077 if (OverOp != OO_None && OverOp != OO_Equal) 16078 LookupOverloadedOperatorName(OverOp, S, Functions); 16079 16080 // In C++20 onwards, we may have a second operator to look up. 16081 if (getLangOpts().CPlusPlus20) { 16082 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 16083 LookupOverloadedOperatorName(ExtraOp, S, Functions); 16084 } 16085} 16086 16087/// Build an overloaded binary operator expression in the given scope. 16088static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 16089 BinaryOperatorKind Opc, 16090 Expr *LHS, Expr *RHS) { 16091 switch (Opc) { 16092 case BO_Assign: 16093 // In the non-overloaded case, we warn about self-assignment (x = x) for 16094 // both simple assignment and certain compound assignments where algebra 16095 // tells us the operation yields a constant result. When the operator is 16096 // overloaded, we can't do the latter because we don't want to assume that 16097 // those algebraic identities still apply; for example, a path-building 16098 // library might use operator/= to append paths. But it's still reasonable 16099 // to assume that simple assignment is just moving/copying values around 16100 // and so self-assignment is likely a bug. 16101 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 16102 [[fallthrough]]; 16103 case BO_DivAssign: 16104 case BO_RemAssign: 16105 case BO_SubAssign: 16106 case BO_AndAssign: 16107 case BO_OrAssign: 16108 case BO_XorAssign: 16109 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 16110 break; 16111 default: 16112 break; 16113 } 16114 16115 // Find all of the overloaded operators visible from this point. 16116 UnresolvedSet<16> Functions; 16117 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 16118 16119 // Build the (potentially-overloaded, potentially-dependent) 16120 // binary operation. 16121 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 16122} 16123 16124ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 16125 BinaryOperatorKind Opc, 16126 Expr *LHSExpr, Expr *RHSExpr) { 16127 ExprResult LHS, RHS; 16128 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 16129 if (!LHS.isUsable() || !RHS.isUsable()) 16130 return ExprError(); 16131 LHSExpr = LHS.get(); 16132 RHSExpr = RHS.get(); 16133 16134 // We want to end up calling one of checkPseudoObjectAssignment 16135 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 16136 // both expressions are overloadable or either is type-dependent), 16137 // or CreateBuiltinBinOp (in any other case). We also want to get 16138 // any placeholder types out of the way. 16139 16140 // Handle pseudo-objects in the LHS. 16141 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 16142 // Assignments with a pseudo-object l-value need special analysis. 16143 if (pty->getKind() == BuiltinType::PseudoObject && 16144 BinaryOperator::isAssignmentOp(Opc)) 16145 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 16146 16147 // Don't resolve overloads if the other type is overloadable. 16148 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 16149 // We can't actually test that if we still have a placeholder, 16150 // though. Fortunately, none of the exceptions we see in that 16151 // code below are valid when the LHS is an overload set. Note 16152 // that an overload set can be dependently-typed, but it never 16153 // instantiates to having an overloadable type. 16154 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 16155 if (resolvedRHS.isInvalid()) return ExprError(); 16156 RHSExpr = resolvedRHS.get(); 16157 16158 if (RHSExpr->isTypeDependent() || 16159 RHSExpr->getType()->isOverloadableType()) 16160 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 16161 } 16162 16163 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 16164 // template, diagnose the missing 'template' keyword instead of diagnosing 16165 // an invalid use of a bound member function. 16166 // 16167 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 16168 // to C++1z [over.over]/1.4, but we already checked for that case above. 16169 if (Opc == BO_LT && inTemplateInstantiation() && 16170 (pty->getKind() == BuiltinType::BoundMember || 16171 pty->getKind() == BuiltinType::Overload)) { 16172 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 16173 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 16174 llvm::any_of(OE->decls(), [](NamedDecl *ND) { 16175 return isa<FunctionTemplateDecl>(ND); 16176 })) { 16177 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 16178 : OE->getNameLoc(), 16179 diag::err_template_kw_missing) 16180 << OE->getName().getAsString() << ""; 16181 return ExprError(); 16182 } 16183 } 16184 16185 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 16186 if (LHS.isInvalid()) return ExprError(); 16187 LHSExpr = LHS.get(); 16188 } 16189 16190 // Handle pseudo-objects in the RHS. 16191 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 16192 // An overload in the RHS can potentially be resolved by the type 16193 // being assigned to. 16194 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 16195 if (getLangOpts().CPlusPlus && 16196 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 16197 LHSExpr->getType()->isOverloadableType())) 16198 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 16199 16200 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 16201 } 16202 16203 // Don't resolve overloads if the other type is overloadable. 16204 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 16205 LHSExpr->getType()->isOverloadableType()) 16206 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 16207 16208 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 16209 if (!resolvedRHS.isUsable()) return ExprError(); 16210 RHSExpr = resolvedRHS.get(); 16211 } 16212 16213 if (getLangOpts().CPlusPlus) { 16214 // If either expression is type-dependent, always build an 16215 // overloaded op. 16216 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 16217 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 16218 16219 // Otherwise, build an overloaded op if either expression has an 16220 // overloadable type. 16221 if (LHSExpr->getType()->isOverloadableType() || 16222 RHSExpr->getType()->isOverloadableType()) 16223 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 16224 } 16225 16226 if (getLangOpts().RecoveryAST && 16227 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 16228 assert(!getLangOpts().CPlusPlus); 16229 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 16230 "Should only occur in error-recovery path."); 16231 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 16232 // C [6.15.16] p3: 16233 // An assignment expression has the value of the left operand after the 16234 // assignment, but is not an lvalue. 16235 return CompoundAssignOperator::Create( 16236 Context, LHSExpr, RHSExpr, Opc, 16237 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 16238 OpLoc, CurFPFeatureOverrides()); 16239 QualType ResultType; 16240 switch (Opc) { 16241 case BO_Assign: 16242 ResultType = LHSExpr->getType().getUnqualifiedType(); 16243 break; 16244 case BO_LT: 16245 case BO_GT: 16246 case BO_LE: 16247 case BO_GE: 16248 case BO_EQ: 16249 case BO_NE: 16250 case BO_LAnd: 16251 case BO_LOr: 16252 // These operators have a fixed result type regardless of operands. 16253 ResultType = Context.IntTy; 16254 break; 16255 case BO_Comma: 16256 ResultType = RHSExpr->getType(); 16257 break; 16258 default: 16259 ResultType = Context.DependentTy; 16260 break; 16261 } 16262 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 16263 VK_PRValue, OK_Ordinary, OpLoc, 16264 CurFPFeatureOverrides()); 16265 } 16266 16267 // Build a built-in binary operation. 16268 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 16269} 16270 16271static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 16272 if (T.isNull() || T->isDependentType()) 16273 return false; 16274 16275 if (!Ctx.isPromotableIntegerType(T)) 16276 return true; 16277 16278 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 16279} 16280 16281ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 16282 UnaryOperatorKind Opc, Expr *InputExpr, 16283 bool IsAfterAmp) { 16284 ExprResult Input = InputExpr; 16285 ExprValueKind VK = VK_PRValue; 16286 ExprObjectKind OK = OK_Ordinary; 16287 QualType resultType; 16288 bool CanOverflow = false; 16289 16290 bool ConvertHalfVec = false; 16291 if (getLangOpts().OpenCL) { 16292 QualType Ty = InputExpr->getType(); 16293 // The only legal unary operation for atomics is '&'. 16294 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 16295 // OpenCL special types - image, sampler, pipe, and blocks are to be used 16296 // only with a builtin functions and therefore should be disallowed here. 16297 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 16298 || Ty->isBlockPointerType())) { 16299 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 16300 << InputExpr->getType() 16301 << Input.get()->getSourceRange()); 16302 } 16303 } 16304 16305 if (getLangOpts().HLSL && OpLoc.isValid()) { 16306 if (Opc == UO_AddrOf) 16307 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0); 16308 if (Opc == UO_Deref) 16309 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1); 16310 } 16311 16312 switch (Opc) { 16313 case UO_PreInc: 16314 case UO_PreDec: 16315 case UO_PostInc: 16316 case UO_PostDec: 16317 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 16318 OpLoc, 16319 Opc == UO_PreInc || 16320 Opc == UO_PostInc, 16321 Opc == UO_PreInc || 16322 Opc == UO_PreDec); 16323 CanOverflow = isOverflowingIntegerType(Context, resultType); 16324 break; 16325 case UO_AddrOf: 16326 resultType = CheckAddressOfOperand(Input, OpLoc); 16327 CheckAddressOfNoDeref(InputExpr); 16328 RecordModifiableNonNullParam(*this, InputExpr); 16329 break; 16330 case UO_Deref: { 16331 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 16332 if (Input.isInvalid()) return ExprError(); 16333 resultType = 16334 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp); 16335 break; 16336 } 16337 case UO_Plus: 16338 case UO_Minus: 16339 CanOverflow = Opc == UO_Minus && 16340 isOverflowingIntegerType(Context, Input.get()->getType()); 16341 Input = UsualUnaryConversions(Input.get()); 16342 if (Input.isInvalid()) return ExprError(); 16343 // Unary plus and minus require promoting an operand of half vector to a 16344 // float vector and truncating the result back to a half vector. For now, we 16345 // do this only when HalfArgsAndReturns is set (that is, when the target is 16346 // arm or arm64). 16347 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 16348 16349 // If the operand is a half vector, promote it to a float vector. 16350 if (ConvertHalfVec) 16351 Input = convertVector(Input.get(), Context.FloatTy, *this); 16352 resultType = Input.get()->getType(); 16353 if (resultType->isDependentType()) 16354 break; 16355 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 16356 break; 16357 else if (resultType->isVectorType() && 16358 // The z vector extensions don't allow + or - with bool vectors. 16359 (!Context.getLangOpts().ZVector || 16360 resultType->castAs<VectorType>()->getVectorKind() != 16361 VectorKind::AltiVecBool)) 16362 break; 16363 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and - 16364 break; 16365 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 16366 Opc == UO_Plus && 16367 resultType->isPointerType()) 16368 break; 16369 16370 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 16371 << resultType << Input.get()->getSourceRange()); 16372 16373 case UO_Not: // bitwise complement 16374 Input = UsualUnaryConversions(Input.get()); 16375 if (Input.isInvalid()) 16376 return ExprError(); 16377 resultType = Input.get()->getType(); 16378 if (resultType->isDependentType()) 16379 break; 16380 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 16381 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 16382 // C99 does not support '~' for complex conjugation. 16383 Diag(OpLoc, diag::ext_integer_complement_complex) 16384 << resultType << Input.get()->getSourceRange(); 16385 else if (resultType->hasIntegerRepresentation()) 16386 break; 16387 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 16388 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 16389 // on vector float types. 16390 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 16391 if (!T->isIntegerType()) 16392 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 16393 << resultType << Input.get()->getSourceRange()); 16394 } else { 16395 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 16396 << resultType << Input.get()->getSourceRange()); 16397 } 16398 break; 16399 16400 case UO_LNot: // logical negation 16401 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 16402 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 16403 if (Input.isInvalid()) return ExprError(); 16404 resultType = Input.get()->getType(); 16405 16406 // Though we still have to promote half FP to float... 16407 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 16408 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 16409 resultType = Context.FloatTy; 16410 } 16411 16412 // WebAsembly tables can't be used in unary expressions. 16413 if (resultType->isPointerType() && 16414 resultType->getPointeeType().isWebAssemblyReferenceType()) { 16415 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 16416 << resultType << Input.get()->getSourceRange()); 16417 } 16418 16419 if (resultType->isDependentType()) 16420 break; 16421 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 16422 // C99 6.5.3.3p1: ok, fallthrough; 16423 if (Context.getLangOpts().CPlusPlus) { 16424 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 16425 // operand contextually converted to bool. 16426 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 16427 ScalarTypeToBooleanCastKind(resultType)); 16428 } else if (Context.getLangOpts().OpenCL && 16429 Context.getLangOpts().OpenCLVersion < 120) { 16430 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 16431 // operate on scalar float types. 16432 if (!resultType->isIntegerType() && !resultType->isPointerType()) 16433 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 16434 << resultType << Input.get()->getSourceRange()); 16435 } 16436 } else if (resultType->isExtVectorType()) { 16437 if (Context.getLangOpts().OpenCL && 16438 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 16439 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 16440 // operate on vector float types. 16441 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 16442 if (!T->isIntegerType()) 16443 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 16444 << resultType << Input.get()->getSourceRange()); 16445 } 16446 // Vector logical not returns the signed variant of the operand type. 16447 resultType = GetSignedVectorType(resultType); 16448 break; 16449 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 16450 const VectorType *VTy = resultType->castAs<VectorType>(); 16451 if (VTy->getVectorKind() != VectorKind::Generic) 16452 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 16453 << resultType << Input.get()->getSourceRange()); 16454 16455 // Vector logical not returns the signed variant of the operand type. 16456 resultType = GetSignedVectorType(resultType); 16457 break; 16458 } else { 16459 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 16460 << resultType << Input.get()->getSourceRange()); 16461 } 16462 16463 // LNot always has type int. C99 6.5.3.3p5. 16464 // In C++, it's bool. C++ 5.3.1p8 16465 resultType = Context.getLogicalOperationType(); 16466 break; 16467 case UO_Real: 16468 case UO_Imag: 16469 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 16470 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 16471 // complex l-values to ordinary l-values and all other values to r-values. 16472 if (Input.isInvalid()) return ExprError(); 16473 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 16474 if (Input.get()->isGLValue() && 16475 Input.get()->getObjectKind() == OK_Ordinary) 16476 VK = Input.get()->getValueKind(); 16477 } else if (!getLangOpts().CPlusPlus) { 16478 // In C, a volatile scalar is read by __imag. In C++, it is not. 16479 Input = DefaultLvalueConversion(Input.get()); 16480 } 16481 break; 16482 case UO_Extension: 16483 resultType = Input.get()->getType(); 16484 VK = Input.get()->getValueKind(); 16485 OK = Input.get()->getObjectKind(); 16486 break; 16487 case UO_Coawait: 16488 // It's unnecessary to represent the pass-through operator co_await in the 16489 // AST; just return the input expression instead. 16490 assert(!Input.get()->getType()->isDependentType() && 16491 "the co_await expression must be non-dependant before " 16492 "building operator co_await"); 16493 return Input; 16494 } 16495 if (resultType.isNull() || Input.isInvalid()) 16496 return ExprError(); 16497 16498 // Check for array bounds violations in the operand of the UnaryOperator, 16499 // except for the '*' and '&' operators that have to be handled specially 16500 // by CheckArrayAccess (as there are special cases like &array[arraysize] 16501 // that are explicitly defined as valid by the standard). 16502 if (Opc != UO_AddrOf && Opc != UO_Deref) 16503 CheckArrayAccess(Input.get()); 16504 16505 auto *UO = 16506 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 16507 OpLoc, CanOverflow, CurFPFeatureOverrides()); 16508 16509 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 16510 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 16511 !isUnevaluatedContext()) 16512 ExprEvalContexts.back().PossibleDerefs.insert(UO); 16513 16514 // Convert the result back to a half vector. 16515 if (ConvertHalfVec) 16516 return convertVector(UO, Context.HalfTy, *this); 16517 return UO; 16518} 16519 16520/// Determine whether the given expression is a qualified member 16521/// access expression, of a form that could be turned into a pointer to member 16522/// with the address-of operator. 16523bool Sema::isQualifiedMemberAccess(Expr *E) { 16524 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 16525 if (!DRE->getQualifier()) 16526 return false; 16527 16528 ValueDecl *VD = DRE->getDecl(); 16529 if (!VD->isCXXClassMember()) 16530 return false; 16531 16532 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 16533 return true; 16534 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 16535 return Method->isImplicitObjectMemberFunction(); 16536 16537 return false; 16538 } 16539 16540 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 16541 if (!ULE->getQualifier()) 16542 return false; 16543 16544 for (NamedDecl *D : ULE->decls()) { 16545 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 16546 if (Method->isImplicitObjectMemberFunction()) 16547 return true; 16548 } else { 16549 // Overload set does not contain methods. 16550 break; 16551 } 16552 } 16553 16554 return false; 16555 } 16556 16557 return false; 16558} 16559 16560ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 16561 UnaryOperatorKind Opc, Expr *Input, 16562 bool IsAfterAmp) { 16563 // First things first: handle placeholders so that the 16564 // overloaded-operator check considers the right type. 16565 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 16566 // Increment and decrement of pseudo-object references. 16567 if (pty->getKind() == BuiltinType::PseudoObject && 16568 UnaryOperator::isIncrementDecrementOp(Opc)) 16569 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 16570 16571 // extension is always a builtin operator. 16572 if (Opc == UO_Extension) 16573 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 16574 16575 // & gets special logic for several kinds of placeholder. 16576 // The builtin code knows what to do. 16577 if (Opc == UO_AddrOf && 16578 (pty->getKind() == BuiltinType::Overload || 16579 pty->getKind() == BuiltinType::UnknownAny || 16580 pty->getKind() == BuiltinType::BoundMember)) 16581 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 16582 16583 // Anything else needs to be handled now. 16584 ExprResult Result = CheckPlaceholderExpr(Input); 16585 if (Result.isInvalid()) return ExprError(); 16586 Input = Result.get(); 16587 } 16588 16589 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 16590 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 16591 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 16592 // Find all of the overloaded operators visible from this point. 16593 UnresolvedSet<16> Functions; 16594 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 16595 if (S && OverOp != OO_None) 16596 LookupOverloadedOperatorName(OverOp, S, Functions); 16597 16598 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 16599 } 16600 16601 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp); 16602} 16603 16604// Unary Operators. 'Tok' is the token for the operator. 16605ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, 16606 Expr *Input, bool IsAfterAmp) { 16607 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input, 16608 IsAfterAmp); 16609} 16610 16611/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 16612ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 16613 LabelDecl *TheDecl) { 16614 TheDecl->markUsed(Context); 16615 // Create the AST node. The address of a label always has type 'void*'. 16616 auto *Res = new (Context) AddrLabelExpr( 16617 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy)); 16618 16619 if (getCurFunction()) 16620 getCurFunction()->AddrLabels.push_back(Res); 16621 16622 return Res; 16623} 16624 16625void Sema::ActOnStartStmtExpr() { 16626 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 16627 // Make sure we diagnose jumping into a statement expression. 16628 setFunctionHasBranchProtectedScope(); 16629} 16630 16631void Sema::ActOnStmtExprError() { 16632 // Note that function is also called by TreeTransform when leaving a 16633 // StmtExpr scope without rebuilding anything. 16634 16635 DiscardCleanupsInEvaluationContext(); 16636 PopExpressionEvaluationContext(); 16637} 16638 16639ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 16640 SourceLocation RPLoc) { 16641 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 16642} 16643 16644ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 16645 SourceLocation RPLoc, unsigned TemplateDepth) { 16646 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 16647 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 16648 16649 if (hasAnyUnrecoverableErrorsInThisFunction()) 16650 DiscardCleanupsInEvaluationContext(); 16651 assert(!Cleanup.exprNeedsCleanups() && 16652 "cleanups within StmtExpr not correctly bound!"); 16653 PopExpressionEvaluationContext(); 16654 16655 // FIXME: there are a variety of strange constraints to enforce here, for 16656 // example, it is not possible to goto into a stmt expression apparently. 16657 // More semantic analysis is needed. 16658 16659 // If there are sub-stmts in the compound stmt, take the type of the last one 16660 // as the type of the stmtexpr. 16661 QualType Ty = Context.VoidTy; 16662 bool StmtExprMayBindToTemp = false; 16663 if (!Compound->body_empty()) { 16664 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 16665 if (const auto *LastStmt = 16666 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 16667 if (const Expr *Value = LastStmt->getExprStmt()) { 16668 StmtExprMayBindToTemp = true; 16669 Ty = Value->getType(); 16670 } 16671 } 16672 } 16673 16674 // FIXME: Check that expression type is complete/non-abstract; statement 16675 // expressions are not lvalues. 16676 Expr *ResStmtExpr = 16677 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 16678 if (StmtExprMayBindToTemp) 16679 return MaybeBindToTemporary(ResStmtExpr); 16680 return ResStmtExpr; 16681} 16682 16683ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 16684 if (ER.isInvalid()) 16685 return ExprError(); 16686 16687 // Do function/array conversion on the last expression, but not 16688 // lvalue-to-rvalue. However, initialize an unqualified type. 16689 ER = DefaultFunctionArrayConversion(ER.get()); 16690 if (ER.isInvalid()) 16691 return ExprError(); 16692 Expr *E = ER.get(); 16693 16694 if (E->isTypeDependent()) 16695 return E; 16696 16697 // In ARC, if the final expression ends in a consume, splice 16698 // the consume out and bind it later. In the alternate case 16699 // (when dealing with a retainable type), the result 16700 // initialization will create a produce. In both cases the 16701 // result will be +1, and we'll need to balance that out with 16702 // a bind. 16703 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 16704 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 16705 return Cast->getSubExpr(); 16706 16707 // FIXME: Provide a better location for the initialization. 16708 return PerformCopyInitialization( 16709 InitializedEntity::InitializeStmtExprResult( 16710 E->getBeginLoc(), E->getType().getUnqualifiedType()), 16711 SourceLocation(), E); 16712} 16713 16714ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 16715 TypeSourceInfo *TInfo, 16716 ArrayRef<OffsetOfComponent> Components, 16717 SourceLocation RParenLoc) { 16718 QualType ArgTy = TInfo->getType(); 16719 bool Dependent = ArgTy->isDependentType(); 16720 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 16721 16722 // We must have at least one component that refers to the type, and the first 16723 // one is known to be a field designator. Verify that the ArgTy represents 16724 // a struct/union/class. 16725 if (!Dependent && !ArgTy->isRecordType()) 16726 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 16727 << ArgTy << TypeRange); 16728 16729 // Type must be complete per C99 7.17p3 because a declaring a variable 16730 // with an incomplete type would be ill-formed. 16731 if (!Dependent 16732 && RequireCompleteType(BuiltinLoc, ArgTy, 16733 diag::err_offsetof_incomplete_type, TypeRange)) 16734 return ExprError(); 16735 16736 bool DidWarnAboutNonPOD = false; 16737 QualType CurrentType = ArgTy; 16738 SmallVector<OffsetOfNode, 4> Comps; 16739 SmallVector<Expr*, 4> Exprs; 16740 for (const OffsetOfComponent &OC : Components) { 16741 if (OC.isBrackets) { 16742 // Offset of an array sub-field. TODO: Should we allow vector elements? 16743 if (!CurrentType->isDependentType()) { 16744 const ArrayType *AT = Context.getAsArrayType(CurrentType); 16745 if(!AT) 16746 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 16747 << CurrentType); 16748 CurrentType = AT->getElementType(); 16749 } else 16750 CurrentType = Context.DependentTy; 16751 16752 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 16753 if (IdxRval.isInvalid()) 16754 return ExprError(); 16755 Expr *Idx = IdxRval.get(); 16756 16757 // The expression must be an integral expression. 16758 // FIXME: An integral constant expression? 16759 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 16760 !Idx->getType()->isIntegerType()) 16761 return ExprError( 16762 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 16763 << Idx->getSourceRange()); 16764 16765 // Record this array index. 16766 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 16767 Exprs.push_back(Idx); 16768 continue; 16769 } 16770 16771 // Offset of a field. 16772 if (CurrentType->isDependentType()) { 16773 // We have the offset of a field, but we can't look into the dependent 16774 // type. Just record the identifier of the field. 16775 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 16776 CurrentType = Context.DependentTy; 16777 continue; 16778 } 16779 16780 // We need to have a complete type to look into. 16781 if (RequireCompleteType(OC.LocStart, CurrentType, 16782 diag::err_offsetof_incomplete_type)) 16783 return ExprError(); 16784 16785 // Look for the designated field. 16786 const RecordType *RC = CurrentType->getAs<RecordType>(); 16787 if (!RC) 16788 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 16789 << CurrentType); 16790 RecordDecl *RD = RC->getDecl(); 16791 16792 // C++ [lib.support.types]p5: 16793 // The macro offsetof accepts a restricted set of type arguments in this 16794 // International Standard. type shall be a POD structure or a POD union 16795 // (clause 9). 16796 // C++11 [support.types]p4: 16797 // If type is not a standard-layout class (Clause 9), the results are 16798 // undefined. 16799 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 16800 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 16801 unsigned DiagID = 16802 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 16803 : diag::ext_offsetof_non_pod_type; 16804 16805 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) { 16806 Diag(BuiltinLoc, DiagID) 16807 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType; 16808 DidWarnAboutNonPOD = true; 16809 } 16810 } 16811 16812 // Look for the field. 16813 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 16814 LookupQualifiedName(R, RD); 16815 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 16816 IndirectFieldDecl *IndirectMemberDecl = nullptr; 16817 if (!MemberDecl) { 16818 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 16819 MemberDecl = IndirectMemberDecl->getAnonField(); 16820 } 16821 16822 if (!MemberDecl) { 16823 // Lookup could be ambiguous when looking up a placeholder variable 16824 // __builtin_offsetof(S, _). 16825 // In that case we would already have emitted a diagnostic 16826 if (!R.isAmbiguous()) 16827 Diag(BuiltinLoc, diag::err_no_member) 16828 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd); 16829 return ExprError(); 16830 } 16831 16832 // C99 7.17p3: 16833 // (If the specified member is a bit-field, the behavior is undefined.) 16834 // 16835 // We diagnose this as an error. 16836 if (MemberDecl->isBitField()) { 16837 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 16838 << MemberDecl->getDeclName() 16839 << SourceRange(BuiltinLoc, RParenLoc); 16840 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 16841 return ExprError(); 16842 } 16843 16844 RecordDecl *Parent = MemberDecl->getParent(); 16845 if (IndirectMemberDecl) 16846 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 16847 16848 // If the member was found in a base class, introduce OffsetOfNodes for 16849 // the base class indirections. 16850 CXXBasePaths Paths; 16851 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 16852 Paths)) { 16853 if (Paths.getDetectedVirtual()) { 16854 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 16855 << MemberDecl->getDeclName() 16856 << SourceRange(BuiltinLoc, RParenLoc); 16857 return ExprError(); 16858 } 16859 16860 CXXBasePath &Path = Paths.front(); 16861 for (const CXXBasePathElement &B : Path) 16862 Comps.push_back(OffsetOfNode(B.Base)); 16863 } 16864 16865 if (IndirectMemberDecl) { 16866 for (auto *FI : IndirectMemberDecl->chain()) { 16867 assert(isa<FieldDecl>(FI)); 16868 Comps.push_back(OffsetOfNode(OC.LocStart, 16869 cast<FieldDecl>(FI), OC.LocEnd)); 16870 } 16871 } else 16872 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 16873 16874 CurrentType = MemberDecl->getType().getNonReferenceType(); 16875 } 16876 16877 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 16878 Comps, Exprs, RParenLoc); 16879} 16880 16881ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 16882 SourceLocation BuiltinLoc, 16883 SourceLocation TypeLoc, 16884 ParsedType ParsedArgTy, 16885 ArrayRef<OffsetOfComponent> Components, 16886 SourceLocation RParenLoc) { 16887 16888 TypeSourceInfo *ArgTInfo; 16889 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 16890 if (ArgTy.isNull()) 16891 return ExprError(); 16892 16893 if (!ArgTInfo) 16894 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 16895 16896 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 16897} 16898 16899 16900ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 16901 Expr *CondExpr, 16902 Expr *LHSExpr, Expr *RHSExpr, 16903 SourceLocation RPLoc) { 16904 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 16905 16906 ExprValueKind VK = VK_PRValue; 16907 ExprObjectKind OK = OK_Ordinary; 16908 QualType resType; 16909 bool CondIsTrue = false; 16910 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 16911 resType = Context.DependentTy; 16912 } else { 16913 // The conditional expression is required to be a constant expression. 16914 llvm::APSInt condEval(32); 16915 ExprResult CondICE = VerifyIntegerConstantExpression( 16916 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 16917 if (CondICE.isInvalid()) 16918 return ExprError(); 16919 CondExpr = CondICE.get(); 16920 CondIsTrue = condEval.getZExtValue(); 16921 16922 // If the condition is > zero, then the AST type is the same as the LHSExpr. 16923 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 16924 16925 resType = ActiveExpr->getType(); 16926 VK = ActiveExpr->getValueKind(); 16927 OK = ActiveExpr->getObjectKind(); 16928 } 16929 16930 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 16931 resType, VK, OK, RPLoc, CondIsTrue); 16932} 16933 16934//===----------------------------------------------------------------------===// 16935// Clang Extensions. 16936//===----------------------------------------------------------------------===// 16937 16938/// ActOnBlockStart - This callback is invoked when a block literal is started. 16939void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 16940 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 16941 16942 if (LangOpts.CPlusPlus) { 16943 MangleNumberingContext *MCtx; 16944 Decl *ManglingContextDecl; 16945 std::tie(MCtx, ManglingContextDecl) = 16946 getCurrentMangleNumberContext(Block->getDeclContext()); 16947 if (MCtx) { 16948 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 16949 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 16950 } 16951 } 16952 16953 PushBlockScope(CurScope, Block); 16954 CurContext->addDecl(Block); 16955 if (CurScope) 16956 PushDeclContext(CurScope, Block); 16957 else 16958 CurContext = Block; 16959 16960 getCurBlock()->HasImplicitReturnType = true; 16961 16962 // Enter a new evaluation context to insulate the block from any 16963 // cleanups from the enclosing full-expression. 16964 PushExpressionEvaluationContext( 16965 ExpressionEvaluationContext::PotentiallyEvaluated); 16966} 16967 16968void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 16969 Scope *CurScope) { 16970 assert(ParamInfo.getIdentifier() == nullptr && 16971 "block-id should have no identifier!"); 16972 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 16973 BlockScopeInfo *CurBlock = getCurBlock(); 16974 16975 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo); 16976 QualType T = Sig->getType(); 16977 16978 // FIXME: We should allow unexpanded parameter packs here, but that would, 16979 // in turn, make the block expression contain unexpanded parameter packs. 16980 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 16981 // Drop the parameters. 16982 FunctionProtoType::ExtProtoInfo EPI; 16983 EPI.HasTrailingReturn = false; 16984 EPI.TypeQuals.addConst(); 16985 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI); 16986 Sig = Context.getTrivialTypeSourceInfo(T); 16987 } 16988 16989 // GetTypeForDeclarator always produces a function type for a block 16990 // literal signature. Furthermore, it is always a FunctionProtoType 16991 // unless the function was written with a typedef. 16992 assert(T->isFunctionType() && 16993 "GetTypeForDeclarator made a non-function block signature"); 16994 16995 // Look for an explicit signature in that function type. 16996 FunctionProtoTypeLoc ExplicitSignature; 16997 16998 if ((ExplicitSignature = Sig->getTypeLoc() 16999 .getAsAdjusted<FunctionProtoTypeLoc>())) { 17000 17001 // Check whether that explicit signature was synthesized by 17002 // GetTypeForDeclarator. If so, don't save that as part of the 17003 // written signature. 17004 if (ExplicitSignature.getLocalRangeBegin() == 17005 ExplicitSignature.getLocalRangeEnd()) { 17006 // This would be much cheaper if we stored TypeLocs instead of 17007 // TypeSourceInfos. 17008 TypeLoc Result = ExplicitSignature.getReturnLoc(); 17009 unsigned Size = Result.getFullDataSize(); 17010 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 17011 Sig->getTypeLoc().initializeFullCopy(Result, Size); 17012 17013 ExplicitSignature = FunctionProtoTypeLoc(); 17014 } 17015 } 17016 17017 CurBlock->TheDecl->setSignatureAsWritten(Sig); 17018 CurBlock->FunctionType = T; 17019 17020 const auto *Fn = T->castAs<FunctionType>(); 17021 QualType RetTy = Fn->getReturnType(); 17022 bool isVariadic = 17023 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 17024 17025 CurBlock->TheDecl->setIsVariadic(isVariadic); 17026 17027 // Context.DependentTy is used as a placeholder for a missing block 17028 // return type. TODO: what should we do with declarators like: 17029 // ^ * { ... } 17030 // If the answer is "apply template argument deduction".... 17031 if (RetTy != Context.DependentTy) { 17032 CurBlock->ReturnType = RetTy; 17033 CurBlock->TheDecl->setBlockMissingReturnType(false); 17034 CurBlock->HasImplicitReturnType = false; 17035 } 17036 17037 // Push block parameters from the declarator if we had them. 17038 SmallVector<ParmVarDecl*, 8> Params; 17039 if (ExplicitSignature) { 17040 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 17041 ParmVarDecl *Param = ExplicitSignature.getParam(I); 17042 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 17043 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 17044 // Diagnose this as an extension in C17 and earlier. 17045 if (!getLangOpts().C23) 17046 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23); 17047 } 17048 Params.push_back(Param); 17049 } 17050 17051 // Fake up parameter variables if we have a typedef, like 17052 // ^ fntype { ... } 17053 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 17054 for (const auto &I : Fn->param_types()) { 17055 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 17056 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 17057 Params.push_back(Param); 17058 } 17059 } 17060 17061 // Set the parameters on the block decl. 17062 if (!Params.empty()) { 17063 CurBlock->TheDecl->setParams(Params); 17064 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 17065 /*CheckParameterNames=*/false); 17066 } 17067 17068 // Finally we can process decl attributes. 17069 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 17070 17071 // Put the parameter variables in scope. 17072 for (auto *AI : CurBlock->TheDecl->parameters()) { 17073 AI->setOwningFunction(CurBlock->TheDecl); 17074 17075 // If this has an identifier, add it to the scope stack. 17076 if (AI->getIdentifier()) { 17077 CheckShadow(CurBlock->TheScope, AI); 17078 17079 PushOnScopeChains(AI, CurBlock->TheScope); 17080 } 17081 17082 if (AI->isInvalidDecl()) 17083 CurBlock->TheDecl->setInvalidDecl(); 17084 } 17085} 17086 17087/// ActOnBlockError - If there is an error parsing a block, this callback 17088/// is invoked to pop the information about the block from the action impl. 17089void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 17090 // Leave the expression-evaluation context. 17091 DiscardCleanupsInEvaluationContext(); 17092 PopExpressionEvaluationContext(); 17093 17094 // Pop off CurBlock, handle nested blocks. 17095 PopDeclContext(); 17096 PopFunctionScopeInfo(); 17097} 17098 17099/// ActOnBlockStmtExpr - This is called when the body of a block statement 17100/// literal was successfully completed. ^(int x){...} 17101ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 17102 Stmt *Body, Scope *CurScope) { 17103 // If blocks are disabled, emit an error. 17104 if (!LangOpts.Blocks) 17105 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 17106 17107 // Leave the expression-evaluation context. 17108 if (hasAnyUnrecoverableErrorsInThisFunction()) 17109 DiscardCleanupsInEvaluationContext(); 17110 assert(!Cleanup.exprNeedsCleanups() && 17111 "cleanups within block not correctly bound!"); 17112 PopExpressionEvaluationContext(); 17113 17114 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 17115 BlockDecl *BD = BSI->TheDecl; 17116 17117 if (BSI->HasImplicitReturnType) 17118 deduceClosureReturnType(*BSI); 17119 17120 QualType RetTy = Context.VoidTy; 17121 if (!BSI->ReturnType.isNull()) 17122 RetTy = BSI->ReturnType; 17123 17124 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 17125 QualType BlockTy; 17126 17127 // If the user wrote a function type in some form, try to use that. 17128 if (!BSI->FunctionType.isNull()) { 17129 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 17130 17131 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 17132 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 17133 17134 // Turn protoless block types into nullary block types. 17135 if (isa<FunctionNoProtoType>(FTy)) { 17136 FunctionProtoType::ExtProtoInfo EPI; 17137 EPI.ExtInfo = Ext; 17138 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI); 17139 17140 // Otherwise, if we don't need to change anything about the function type, 17141 // preserve its sugar structure. 17142 } else if (FTy->getReturnType() == RetTy && 17143 (!NoReturn || FTy->getNoReturnAttr())) { 17144 BlockTy = BSI->FunctionType; 17145 17146 // Otherwise, make the minimal modifications to the function type. 17147 } else { 17148 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 17149 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 17150 EPI.TypeQuals = Qualifiers(); 17151 EPI.ExtInfo = Ext; 17152 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 17153 } 17154 17155 // If we don't have a function type, just build one from nothing. 17156 } else { 17157 FunctionProtoType::ExtProtoInfo EPI; 17158 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 17159 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI); 17160 } 17161 17162 DiagnoseUnusedParameters(BD->parameters()); 17163 BlockTy = Context.getBlockPointerType(BlockTy); 17164 17165 // If needed, diagnose invalid gotos and switches in the block. 17166 if (getCurFunction()->NeedsScopeChecking() && 17167 !PP.isCodeCompletionEnabled()) 17168 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 17169 17170 BD->setBody(cast<CompoundStmt>(Body)); 17171 17172 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 17173 DiagnoseUnguardedAvailabilityViolations(BD); 17174 17175 // Try to apply the named return value optimization. We have to check again 17176 // if we can do this, though, because blocks keep return statements around 17177 // to deduce an implicit return type. 17178 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 17179 !BD->isDependentContext()) 17180 computeNRVO(Body, BSI); 17181 17182 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 17183 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 17184 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 17185 NTCUK_Destruct|NTCUK_Copy); 17186 17187 PopDeclContext(); 17188 17189 // Set the captured variables on the block. 17190 SmallVector<BlockDecl::Capture, 4> Captures; 17191 for (Capture &Cap : BSI->Captures) { 17192 if (Cap.isInvalid() || Cap.isThisCapture()) 17193 continue; 17194 // Cap.getVariable() is always a VarDecl because 17195 // blocks cannot capture structured bindings or other ValueDecl kinds. 17196 auto *Var = cast<VarDecl>(Cap.getVariable()); 17197 Expr *CopyExpr = nullptr; 17198 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 17199 if (const RecordType *Record = 17200 Cap.getCaptureType()->getAs<RecordType>()) { 17201 // The capture logic needs the destructor, so make sure we mark it. 17202 // Usually this is unnecessary because most local variables have 17203 // their destructors marked at declaration time, but parameters are 17204 // an exception because it's technically only the call site that 17205 // actually requires the destructor. 17206 if (isa<ParmVarDecl>(Var)) 17207 FinalizeVarWithDestructor(Var, Record); 17208 17209 // Enter a separate potentially-evaluated context while building block 17210 // initializers to isolate their cleanups from those of the block 17211 // itself. 17212 // FIXME: Is this appropriate even when the block itself occurs in an 17213 // unevaluated operand? 17214 EnterExpressionEvaluationContext EvalContext( 17215 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 17216 17217 SourceLocation Loc = Cap.getLocation(); 17218 17219 ExprResult Result = BuildDeclarationNameExpr( 17220 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 17221 17222 // According to the blocks spec, the capture of a variable from 17223 // the stack requires a const copy constructor. This is not true 17224 // of the copy/move done to move a __block variable to the heap. 17225 if (!Result.isInvalid() && 17226 !Result.get()->getType().isConstQualified()) { 17227 Result = ImpCastExprToType(Result.get(), 17228 Result.get()->getType().withConst(), 17229 CK_NoOp, VK_LValue); 17230 } 17231 17232 if (!Result.isInvalid()) { 17233 Result = PerformCopyInitialization( 17234 InitializedEntity::InitializeBlock(Var->getLocation(), 17235 Cap.getCaptureType()), 17236 Loc, Result.get()); 17237 } 17238 17239 // Build a full-expression copy expression if initialization 17240 // succeeded and used a non-trivial constructor. Recover from 17241 // errors by pretending that the copy isn't necessary. 17242 if (!Result.isInvalid() && 17243 !cast<CXXConstructExpr>(Result.get())->getConstructor() 17244 ->isTrivial()) { 17245 Result = MaybeCreateExprWithCleanups(Result); 17246 CopyExpr = Result.get(); 17247 } 17248 } 17249 } 17250 17251 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 17252 CopyExpr); 17253 Captures.push_back(NewCap); 17254 } 17255 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 17256 17257 // Pop the block scope now but keep it alive to the end of this function. 17258 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 17259 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 17260 17261 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 17262 17263 // If the block isn't obviously global, i.e. it captures anything at 17264 // all, then we need to do a few things in the surrounding context: 17265 if (Result->getBlockDecl()->hasCaptures()) { 17266 // First, this expression has a new cleanup object. 17267 ExprCleanupObjects.push_back(Result->getBlockDecl()); 17268 Cleanup.setExprNeedsCleanups(true); 17269 17270 // It also gets a branch-protected scope if any of the captured 17271 // variables needs destruction. 17272 for (const auto &CI : Result->getBlockDecl()->captures()) { 17273 const VarDecl *var = CI.getVariable(); 17274 if (var->getType().isDestructedType() != QualType::DK_none) { 17275 setFunctionHasBranchProtectedScope(); 17276 break; 17277 } 17278 } 17279 } 17280 17281 if (getCurFunction()) 17282 getCurFunction()->addBlock(BD); 17283 17284 if (BD->isInvalidDecl()) 17285 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(), 17286 {Result}, Result->getType()); 17287 return Result; 17288} 17289 17290ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 17291 SourceLocation RPLoc) { 17292 TypeSourceInfo *TInfo; 17293 GetTypeFromParser(Ty, &TInfo); 17294 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 17295} 17296 17297ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 17298 Expr *E, TypeSourceInfo *TInfo, 17299 SourceLocation RPLoc) { 17300 Expr *OrigExpr = E; 17301 bool IsMS = false; 17302 17303 // CUDA device code does not support varargs. 17304 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 17305 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 17306 CUDAFunctionTarget T = IdentifyCUDATarget(F); 17307 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 17308 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 17309 } 17310 } 17311 17312 // NVPTX does not support va_arg expression. 17313 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice && 17314 Context.getTargetInfo().getTriple().isNVPTX()) 17315 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 17316 17317 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 17318 // as Microsoft ABI on an actual Microsoft platform, where 17319 // __builtin_ms_va_list and __builtin_va_list are the same.) 17320 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 17321 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 17322 QualType MSVaListType = Context.getBuiltinMSVaListType(); 17323 if (Context.hasSameType(MSVaListType, E->getType())) { 17324 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 17325 return ExprError(); 17326 IsMS = true; 17327 } 17328 } 17329 17330 // Get the va_list type 17331 QualType VaListType = Context.getBuiltinVaListType(); 17332 if (!IsMS) { 17333 if (VaListType->isArrayType()) { 17334 // Deal with implicit array decay; for example, on x86-64, 17335 // va_list is an array, but it's supposed to decay to 17336 // a pointer for va_arg. 17337 VaListType = Context.getArrayDecayedType(VaListType); 17338 // Make sure the input expression also decays appropriately. 17339 ExprResult Result = UsualUnaryConversions(E); 17340 if (Result.isInvalid()) 17341 return ExprError(); 17342 E = Result.get(); 17343 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 17344 // If va_list is a record type and we are compiling in C++ mode, 17345 // check the argument using reference binding. 17346 InitializedEntity Entity = InitializedEntity::InitializeParameter( 17347 Context, Context.getLValueReferenceType(VaListType), false); 17348 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 17349 if (Init.isInvalid()) 17350 return ExprError(); 17351 E = Init.getAs<Expr>(); 17352 } else { 17353 // Otherwise, the va_list argument must be an l-value because 17354 // it is modified by va_arg. 17355 if (!E->isTypeDependent() && 17356 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 17357 return ExprError(); 17358 } 17359 } 17360 17361 if (!IsMS && !E->isTypeDependent() && 17362 !Context.hasSameType(VaListType, E->getType())) 17363 return ExprError( 17364 Diag(E->getBeginLoc(), 17365 diag::err_first_argument_to_va_arg_not_of_type_va_list) 17366 << OrigExpr->getType() << E->getSourceRange()); 17367 17368 if (!TInfo->getType()->isDependentType()) { 17369 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 17370 diag::err_second_parameter_to_va_arg_incomplete, 17371 TInfo->getTypeLoc())) 17372 return ExprError(); 17373 17374 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 17375 TInfo->getType(), 17376 diag::err_second_parameter_to_va_arg_abstract, 17377 TInfo->getTypeLoc())) 17378 return ExprError(); 17379 17380 if (!TInfo->getType().isPODType(Context)) { 17381 Diag(TInfo->getTypeLoc().getBeginLoc(), 17382 TInfo->getType()->isObjCLifetimeType() 17383 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 17384 : diag::warn_second_parameter_to_va_arg_not_pod) 17385 << TInfo->getType() 17386 << TInfo->getTypeLoc().getSourceRange(); 17387 } 17388 17389 // Check for va_arg where arguments of the given type will be promoted 17390 // (i.e. this va_arg is guaranteed to have undefined behavior). 17391 QualType PromoteType; 17392 if (Context.isPromotableIntegerType(TInfo->getType())) { 17393 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 17394 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 17395 // and C23 7.16.1.1p2 says, in part: 17396 // If type is not compatible with the type of the actual next argument 17397 // (as promoted according to the default argument promotions), the 17398 // behavior is undefined, except for the following cases: 17399 // - both types are pointers to qualified or unqualified versions of 17400 // compatible types; 17401 // - one type is compatible with a signed integer type, the other 17402 // type is compatible with the corresponding unsigned integer type, 17403 // and the value is representable in both types; 17404 // - one type is pointer to qualified or unqualified void and the 17405 // other is a pointer to a qualified or unqualified character type; 17406 // - or, the type of the next argument is nullptr_t and type is a 17407 // pointer type that has the same representation and alignment 17408 // requirements as a pointer to a character type. 17409 // Given that type compatibility is the primary requirement (ignoring 17410 // qualifications), you would think we could call typesAreCompatible() 17411 // directly to test this. However, in C++, that checks for *same type*, 17412 // which causes false positives when passing an enumeration type to 17413 // va_arg. Instead, get the underlying type of the enumeration and pass 17414 // that. 17415 QualType UnderlyingType = TInfo->getType(); 17416 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 17417 UnderlyingType = ET->getDecl()->getIntegerType(); 17418 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 17419 /*CompareUnqualified*/ true)) 17420 PromoteType = QualType(); 17421 17422 // If the types are still not compatible, we need to test whether the 17423 // promoted type and the underlying type are the same except for 17424 // signedness. Ask the AST for the correctly corresponding type and see 17425 // if that's compatible. 17426 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && 17427 PromoteType->isUnsignedIntegerType() != 17428 UnderlyingType->isUnsignedIntegerType()) { 17429 UnderlyingType = 17430 UnderlyingType->isUnsignedIntegerType() 17431 ? Context.getCorrespondingSignedType(UnderlyingType) 17432 : Context.getCorrespondingUnsignedType(UnderlyingType); 17433 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 17434 /*CompareUnqualified*/ true)) 17435 PromoteType = QualType(); 17436 } 17437 } 17438 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 17439 PromoteType = Context.DoubleTy; 17440 if (!PromoteType.isNull()) 17441 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 17442 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 17443 << TInfo->getType() 17444 << PromoteType 17445 << TInfo->getTypeLoc().getSourceRange()); 17446 } 17447 17448 QualType T = TInfo->getType().getNonLValueExprType(Context); 17449 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 17450} 17451 17452ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 17453 // The type of __null will be int or long, depending on the size of 17454 // pointers on the target. 17455 QualType Ty; 17456 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default); 17457 if (pw == Context.getTargetInfo().getIntWidth()) 17458 Ty = Context.IntTy; 17459 else if (pw == Context.getTargetInfo().getLongWidth()) 17460 Ty = Context.LongTy; 17461 else if (pw == Context.getTargetInfo().getLongLongWidth()) 17462 Ty = Context.LongLongTy; 17463 else { 17464 llvm_unreachable("I don't know size of pointer!"); 17465 } 17466 17467 return new (Context) GNUNullExpr(Ty, TokenLoc); 17468} 17469 17470static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { 17471 CXXRecordDecl *ImplDecl = nullptr; 17472 17473 // Fetch the std::source_location::__impl decl. 17474 if (NamespaceDecl *Std = S.getStdNamespace()) { 17475 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"), 17476 Loc, Sema::LookupOrdinaryName); 17477 if (S.LookupQualifiedName(ResultSL, Std)) { 17478 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { 17479 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"), 17480 Loc, Sema::LookupOrdinaryName); 17481 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && 17482 S.LookupQualifiedName(ResultImpl, SLDecl)) { 17483 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); 17484 } 17485 } 17486 } 17487 } 17488 17489 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { 17490 S.Diag(Loc, diag::err_std_source_location_impl_not_found); 17491 return nullptr; 17492 } 17493 17494 // Verify that __impl is a trivial struct type, with no base classes, and with 17495 // only the four expected fields. 17496 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || 17497 ImplDecl->getNumBases() != 0) { 17498 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 17499 return nullptr; 17500 } 17501 17502 unsigned Count = 0; 17503 for (FieldDecl *F : ImplDecl->fields()) { 17504 StringRef Name = F->getName(); 17505 17506 if (Name == "_M_file_name") { 17507 if (F->getType() != 17508 S.Context.getPointerType(S.Context.CharTy.withConst())) 17509 break; 17510 Count++; 17511 } else if (Name == "_M_function_name") { 17512 if (F->getType() != 17513 S.Context.getPointerType(S.Context.CharTy.withConst())) 17514 break; 17515 Count++; 17516 } else if (Name == "_M_line") { 17517 if (!F->getType()->isIntegerType()) 17518 break; 17519 Count++; 17520 } else if (Name == "_M_column") { 17521 if (!F->getType()->isIntegerType()) 17522 break; 17523 Count++; 17524 } else { 17525 Count = 100; // invalid 17526 break; 17527 } 17528 } 17529 if (Count != 4) { 17530 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 17531 return nullptr; 17532 } 17533 17534 return ImplDecl; 17535} 17536 17537ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind, 17538 SourceLocation BuiltinLoc, 17539 SourceLocation RPLoc) { 17540 QualType ResultTy; 17541 switch (Kind) { 17542 case SourceLocIdentKind::File: 17543 case SourceLocIdentKind::FileName: 17544 case SourceLocIdentKind::Function: 17545 case SourceLocIdentKind::FuncSig: { 17546 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0); 17547 ResultTy = 17548 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType()); 17549 break; 17550 } 17551 case SourceLocIdentKind::Line: 17552 case SourceLocIdentKind::Column: 17553 ResultTy = Context.UnsignedIntTy; 17554 break; 17555 case SourceLocIdentKind::SourceLocStruct: 17556 if (!StdSourceLocationImplDecl) { 17557 StdSourceLocationImplDecl = 17558 LookupStdSourceLocationImpl(*this, BuiltinLoc); 17559 if (!StdSourceLocationImplDecl) 17560 return ExprError(); 17561 } 17562 ResultTy = Context.getPointerType( 17563 Context.getRecordType(StdSourceLocationImplDecl).withConst()); 17564 break; 17565 } 17566 17567 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext); 17568} 17569 17570ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, 17571 SourceLocation BuiltinLoc, 17572 SourceLocation RPLoc, 17573 DeclContext *ParentContext) { 17574 return new (Context) 17575 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); 17576} 17577 17578bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 17579 bool Diagnose) { 17580 if (!getLangOpts().ObjC) 17581 return false; 17582 17583 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 17584 if (!PT) 17585 return false; 17586 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 17587 17588 // Ignore any parens, implicit casts (should only be 17589 // array-to-pointer decays), and not-so-opaque values. The last is 17590 // important for making this trigger for property assignments. 17591 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 17592 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 17593 if (OV->getSourceExpr()) 17594 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 17595 17596 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 17597 if (!PT->isObjCIdType() && 17598 !(ID && ID->getIdentifier()->isStr("NSString"))) 17599 return false; 17600 if (!SL->isOrdinary()) 17601 return false; 17602 17603 if (Diagnose) { 17604 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 17605 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 17606 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 17607 } 17608 return true; 17609 } 17610 17611 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 17612 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 17613 isa<CXXBoolLiteralExpr>(SrcExpr)) && 17614 !SrcExpr->isNullPointerConstant( 17615 getASTContext(), Expr::NPC_NeverValueDependent)) { 17616 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 17617 return false; 17618 if (Diagnose) { 17619 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 17620 << /*number*/1 17621 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 17622 Expr *NumLit = 17623 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 17624 if (NumLit) 17625 Exp = NumLit; 17626 } 17627 return true; 17628 } 17629 17630 return false; 17631} 17632 17633static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 17634 const Expr *SrcExpr) { 17635 if (!DstType->isFunctionPointerType() || 17636 !SrcExpr->getType()->isFunctionType()) 17637 return false; 17638 17639 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 17640 if (!DRE) 17641 return false; 17642 17643 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 17644 if (!FD) 17645 return false; 17646 17647 return !S.checkAddressOfFunctionIsAvailable(FD, 17648 /*Complain=*/true, 17649 SrcExpr->getBeginLoc()); 17650} 17651 17652bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 17653 SourceLocation Loc, 17654 QualType DstType, QualType SrcType, 17655 Expr *SrcExpr, AssignmentAction Action, 17656 bool *Complained) { 17657 if (Complained) 17658 *Complained = false; 17659 17660 // Decode the result (notice that AST's are still created for extensions). 17661 bool CheckInferredResultType = false; 17662 bool isInvalid = false; 17663 unsigned DiagKind = 0; 17664 ConversionFixItGenerator ConvHints; 17665 bool MayHaveConvFixit = false; 17666 bool MayHaveFunctionDiff = false; 17667 const ObjCInterfaceDecl *IFace = nullptr; 17668 const ObjCProtocolDecl *PDecl = nullptr; 17669 17670 switch (ConvTy) { 17671 case Compatible: 17672 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 17673 return false; 17674 17675 case PointerToInt: 17676 if (getLangOpts().CPlusPlus) { 17677 DiagKind = diag::err_typecheck_convert_pointer_int; 17678 isInvalid = true; 17679 } else { 17680 DiagKind = diag::ext_typecheck_convert_pointer_int; 17681 } 17682 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17683 MayHaveConvFixit = true; 17684 break; 17685 case IntToPointer: 17686 if (getLangOpts().CPlusPlus) { 17687 DiagKind = diag::err_typecheck_convert_int_pointer; 17688 isInvalid = true; 17689 } else { 17690 DiagKind = diag::ext_typecheck_convert_int_pointer; 17691 } 17692 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17693 MayHaveConvFixit = true; 17694 break; 17695 case IncompatibleFunctionPointerStrict: 17696 DiagKind = 17697 diag::warn_typecheck_convert_incompatible_function_pointer_strict; 17698 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17699 MayHaveConvFixit = true; 17700 break; 17701 case IncompatibleFunctionPointer: 17702 if (getLangOpts().CPlusPlus) { 17703 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 17704 isInvalid = true; 17705 } else { 17706 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 17707 } 17708 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17709 MayHaveConvFixit = true; 17710 break; 17711 case IncompatiblePointer: 17712 if (Action == AA_Passing_CFAudited) { 17713 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 17714 } else if (getLangOpts().CPlusPlus) { 17715 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 17716 isInvalid = true; 17717 } else { 17718 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 17719 } 17720 CheckInferredResultType = DstType->isObjCObjectPointerType() && 17721 SrcType->isObjCObjectPointerType(); 17722 if (!CheckInferredResultType) { 17723 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17724 } else if (CheckInferredResultType) { 17725 SrcType = SrcType.getUnqualifiedType(); 17726 DstType = DstType.getUnqualifiedType(); 17727 } 17728 MayHaveConvFixit = true; 17729 break; 17730 case IncompatiblePointerSign: 17731 if (getLangOpts().CPlusPlus) { 17732 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 17733 isInvalid = true; 17734 } else { 17735 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 17736 } 17737 break; 17738 case FunctionVoidPointer: 17739 if (getLangOpts().CPlusPlus) { 17740 DiagKind = diag::err_typecheck_convert_pointer_void_func; 17741 isInvalid = true; 17742 } else { 17743 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 17744 } 17745 break; 17746 case IncompatiblePointerDiscardsQualifiers: { 17747 // Perform array-to-pointer decay if necessary. 17748 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 17749 17750 isInvalid = true; 17751 17752 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 17753 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 17754 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 17755 DiagKind = diag::err_typecheck_incompatible_address_space; 17756 break; 17757 17758 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 17759 DiagKind = diag::err_typecheck_incompatible_ownership; 17760 break; 17761 } 17762 17763 llvm_unreachable("unknown error case for discarding qualifiers!"); 17764 // fallthrough 17765 } 17766 case CompatiblePointerDiscardsQualifiers: 17767 // If the qualifiers lost were because we were applying the 17768 // (deprecated) C++ conversion from a string literal to a char* 17769 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 17770 // Ideally, this check would be performed in 17771 // checkPointerTypesForAssignment. However, that would require a 17772 // bit of refactoring (so that the second argument is an 17773 // expression, rather than a type), which should be done as part 17774 // of a larger effort to fix checkPointerTypesForAssignment for 17775 // C++ semantics. 17776 if (getLangOpts().CPlusPlus && 17777 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 17778 return false; 17779 if (getLangOpts().CPlusPlus) { 17780 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 17781 isInvalid = true; 17782 } else { 17783 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 17784 } 17785 17786 break; 17787 case IncompatibleNestedPointerQualifiers: 17788 if (getLangOpts().CPlusPlus) { 17789 isInvalid = true; 17790 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 17791 } else { 17792 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 17793 } 17794 break; 17795 case IncompatibleNestedPointerAddressSpaceMismatch: 17796 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 17797 isInvalid = true; 17798 break; 17799 case IntToBlockPointer: 17800 DiagKind = diag::err_int_to_block_pointer; 17801 isInvalid = true; 17802 break; 17803 case IncompatibleBlockPointer: 17804 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 17805 isInvalid = true; 17806 break; 17807 case IncompatibleObjCQualifiedId: { 17808 if (SrcType->isObjCQualifiedIdType()) { 17809 const ObjCObjectPointerType *srcOPT = 17810 SrcType->castAs<ObjCObjectPointerType>(); 17811 for (auto *srcProto : srcOPT->quals()) { 17812 PDecl = srcProto; 17813 break; 17814 } 17815 if (const ObjCInterfaceType *IFaceT = 17816 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 17817 IFace = IFaceT->getDecl(); 17818 } 17819 else if (DstType->isObjCQualifiedIdType()) { 17820 const ObjCObjectPointerType *dstOPT = 17821 DstType->castAs<ObjCObjectPointerType>(); 17822 for (auto *dstProto : dstOPT->quals()) { 17823 PDecl = dstProto; 17824 break; 17825 } 17826 if (const ObjCInterfaceType *IFaceT = 17827 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 17828 IFace = IFaceT->getDecl(); 17829 } 17830 if (getLangOpts().CPlusPlus) { 17831 DiagKind = diag::err_incompatible_qualified_id; 17832 isInvalid = true; 17833 } else { 17834 DiagKind = diag::warn_incompatible_qualified_id; 17835 } 17836 break; 17837 } 17838 case IncompatibleVectors: 17839 if (getLangOpts().CPlusPlus) { 17840 DiagKind = diag::err_incompatible_vectors; 17841 isInvalid = true; 17842 } else { 17843 DiagKind = diag::warn_incompatible_vectors; 17844 } 17845 break; 17846 case IncompatibleObjCWeakRef: 17847 DiagKind = diag::err_arc_weak_unavailable_assign; 17848 isInvalid = true; 17849 break; 17850 case Incompatible: 17851 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 17852 if (Complained) 17853 *Complained = true; 17854 return true; 17855 } 17856 17857 DiagKind = diag::err_typecheck_convert_incompatible; 17858 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17859 MayHaveConvFixit = true; 17860 isInvalid = true; 17861 MayHaveFunctionDiff = true; 17862 break; 17863 } 17864 17865 QualType FirstType, SecondType; 17866 switch (Action) { 17867 case AA_Assigning: 17868 case AA_Initializing: 17869 // The destination type comes first. 17870 FirstType = DstType; 17871 SecondType = SrcType; 17872 break; 17873 17874 case AA_Returning: 17875 case AA_Passing: 17876 case AA_Passing_CFAudited: 17877 case AA_Converting: 17878 case AA_Sending: 17879 case AA_Casting: 17880 // The source type comes first. 17881 FirstType = SrcType; 17882 SecondType = DstType; 17883 break; 17884 } 17885 17886 PartialDiagnostic FDiag = PDiag(DiagKind); 17887 AssignmentAction ActionForDiag = Action; 17888 if (Action == AA_Passing_CFAudited) 17889 ActionForDiag = AA_Passing; 17890 17891 FDiag << FirstType << SecondType << ActionForDiag 17892 << SrcExpr->getSourceRange(); 17893 17894 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 17895 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 17896 auto isPlainChar = [](const clang::Type *Type) { 17897 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 17898 Type->isSpecificBuiltinType(BuiltinType::Char_U); 17899 }; 17900 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 17901 isPlainChar(SecondType->getPointeeOrArrayElementType())); 17902 } 17903 17904 // If we can fix the conversion, suggest the FixIts. 17905 if (!ConvHints.isNull()) { 17906 for (FixItHint &H : ConvHints.Hints) 17907 FDiag << H; 17908 } 17909 17910 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 17911 17912 if (MayHaveFunctionDiff) 17913 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 17914 17915 Diag(Loc, FDiag); 17916 if ((DiagKind == diag::warn_incompatible_qualified_id || 17917 DiagKind == diag::err_incompatible_qualified_id) && 17918 PDecl && IFace && !IFace->hasDefinition()) 17919 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 17920 << IFace << PDecl; 17921 17922 if (SecondType == Context.OverloadTy) 17923 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 17924 FirstType, /*TakingAddress=*/true); 17925 17926 if (CheckInferredResultType) 17927 EmitRelatedResultTypeNote(SrcExpr); 17928 17929 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 17930 EmitRelatedResultTypeNoteForReturn(DstType); 17931 17932 if (Complained) 17933 *Complained = true; 17934 return isInvalid; 17935} 17936 17937ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 17938 llvm::APSInt *Result, 17939 AllowFoldKind CanFold) { 17940 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 17941 public: 17942 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 17943 QualType T) override { 17944 return S.Diag(Loc, diag::err_ice_not_integral) 17945 << T << S.LangOpts.CPlusPlus; 17946 } 17947 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 17948 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 17949 } 17950 } Diagnoser; 17951 17952 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 17953} 17954 17955ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 17956 llvm::APSInt *Result, 17957 unsigned DiagID, 17958 AllowFoldKind CanFold) { 17959 class IDDiagnoser : public VerifyICEDiagnoser { 17960 unsigned DiagID; 17961 17962 public: 17963 IDDiagnoser(unsigned DiagID) 17964 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 17965 17966 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 17967 return S.Diag(Loc, DiagID); 17968 } 17969 } Diagnoser(DiagID); 17970 17971 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 17972} 17973 17974Sema::SemaDiagnosticBuilder 17975Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 17976 QualType T) { 17977 return diagnoseNotICE(S, Loc); 17978} 17979 17980Sema::SemaDiagnosticBuilder 17981Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 17982 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 17983} 17984 17985ExprResult 17986Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 17987 VerifyICEDiagnoser &Diagnoser, 17988 AllowFoldKind CanFold) { 17989 SourceLocation DiagLoc = E->getBeginLoc(); 17990 17991 if (getLangOpts().CPlusPlus11) { 17992 // C++11 [expr.const]p5: 17993 // If an expression of literal class type is used in a context where an 17994 // integral constant expression is required, then that class type shall 17995 // have a single non-explicit conversion function to an integral or 17996 // unscoped enumeration type 17997 ExprResult Converted; 17998 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 17999 VerifyICEDiagnoser &BaseDiagnoser; 18000 public: 18001 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 18002 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 18003 BaseDiagnoser.Suppress, true), 18004 BaseDiagnoser(BaseDiagnoser) {} 18005 18006 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 18007 QualType T) override { 18008 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 18009 } 18010 18011 SemaDiagnosticBuilder diagnoseIncomplete( 18012 Sema &S, SourceLocation Loc, QualType T) override { 18013 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 18014 } 18015 18016 SemaDiagnosticBuilder diagnoseExplicitConv( 18017 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 18018 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 18019 } 18020 18021 SemaDiagnosticBuilder noteExplicitConv( 18022 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 18023 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 18024 << ConvTy->isEnumeralType() << ConvTy; 18025 } 18026 18027 SemaDiagnosticBuilder diagnoseAmbiguous( 18028 Sema &S, SourceLocation Loc, QualType T) override { 18029 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 18030 } 18031 18032 SemaDiagnosticBuilder noteAmbiguous( 18033 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 18034 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 18035 << ConvTy->isEnumeralType() << ConvTy; 18036 } 18037 18038 SemaDiagnosticBuilder diagnoseConversion( 18039 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 18040 llvm_unreachable("conversion functions are permitted"); 18041 } 18042 } ConvertDiagnoser(Diagnoser); 18043 18044 Converted = PerformContextualImplicitConversion(DiagLoc, E, 18045 ConvertDiagnoser); 18046 if (Converted.isInvalid()) 18047 return Converted; 18048 E = Converted.get(); 18049 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 18050 return ExprError(); 18051 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 18052 // An ICE must be of integral or unscoped enumeration type. 18053 if (!Diagnoser.Suppress) 18054 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 18055 << E->getSourceRange(); 18056 return ExprError(); 18057 } 18058 18059 ExprResult RValueExpr = DefaultLvalueConversion(E); 18060 if (RValueExpr.isInvalid()) 18061 return ExprError(); 18062 18063 E = RValueExpr.get(); 18064 18065 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 18066 // in the non-ICE case. 18067 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 18068 if (Result) 18069 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 18070 if (!isa<ConstantExpr>(E)) 18071 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 18072 : ConstantExpr::Create(Context, E); 18073 return E; 18074 } 18075 18076 Expr::EvalResult EvalResult; 18077 SmallVector<PartialDiagnosticAt, 8> Notes; 18078 EvalResult.Diag = &Notes; 18079 18080 // Try to evaluate the expression, and produce diagnostics explaining why it's 18081 // not a constant expression as a side-effect. 18082 bool Folded = 18083 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 18084 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 18085 18086 if (!isa<ConstantExpr>(E)) 18087 E = ConstantExpr::Create(Context, E, EvalResult.Val); 18088 18089 // In C++11, we can rely on diagnostics being produced for any expression 18090 // which is not a constant expression. If no diagnostics were produced, then 18091 // this is a constant expression. 18092 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 18093 if (Result) 18094 *Result = EvalResult.Val.getInt(); 18095 return E; 18096 } 18097 18098 // If our only note is the usual "invalid subexpression" note, just point 18099 // the caret at its location rather than producing an essentially 18100 // redundant note. 18101 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 18102 diag::note_invalid_subexpr_in_const_expr) { 18103 DiagLoc = Notes[0].first; 18104 Notes.clear(); 18105 } 18106 18107 if (!Folded || !CanFold) { 18108 if (!Diagnoser.Suppress) { 18109 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 18110 for (const PartialDiagnosticAt &Note : Notes) 18111 Diag(Note.first, Note.second); 18112 } 18113 18114 return ExprError(); 18115 } 18116 18117 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 18118 for (const PartialDiagnosticAt &Note : Notes) 18119 Diag(Note.first, Note.second); 18120 18121 if (Result) 18122 *Result = EvalResult.Val.getInt(); 18123 return E; 18124} 18125 18126namespace { 18127 // Handle the case where we conclude a expression which we speculatively 18128 // considered to be unevaluated is actually evaluated. 18129 class TransformToPE : public TreeTransform<TransformToPE> { 18130 typedef TreeTransform<TransformToPE> BaseTransform; 18131 18132 public: 18133 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 18134 18135 // Make sure we redo semantic analysis 18136 bool AlwaysRebuild() { return true; } 18137 bool ReplacingOriginal() { return true; } 18138 18139 // We need to special-case DeclRefExprs referring to FieldDecls which 18140 // are not part of a member pointer formation; normal TreeTransforming 18141 // doesn't catch this case because of the way we represent them in the AST. 18142 // FIXME: This is a bit ugly; is it really the best way to handle this 18143 // case? 18144 // 18145 // Error on DeclRefExprs referring to FieldDecls. 18146 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 18147 if (isa<FieldDecl>(E->getDecl()) && 18148 !SemaRef.isUnevaluatedContext()) 18149 return SemaRef.Diag(E->getLocation(), 18150 diag::err_invalid_non_static_member_use) 18151 << E->getDecl() << E->getSourceRange(); 18152 18153 return BaseTransform::TransformDeclRefExpr(E); 18154 } 18155 18156 // Exception: filter out member pointer formation 18157 ExprResult TransformUnaryOperator(UnaryOperator *E) { 18158 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 18159 return E; 18160 18161 return BaseTransform::TransformUnaryOperator(E); 18162 } 18163 18164 // The body of a lambda-expression is in a separate expression evaluation 18165 // context so never needs to be transformed. 18166 // FIXME: Ideally we wouldn't transform the closure type either, and would 18167 // just recreate the capture expressions and lambda expression. 18168 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 18169 return SkipLambdaBody(E, Body); 18170 } 18171 }; 18172} 18173 18174ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 18175 assert(isUnevaluatedContext() && 18176 "Should only transform unevaluated expressions"); 18177 ExprEvalContexts.back().Context = 18178 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 18179 if (isUnevaluatedContext()) 18180 return E; 18181 return TransformToPE(*this).TransformExpr(E); 18182} 18183 18184TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { 18185 assert(isUnevaluatedContext() && 18186 "Should only transform unevaluated expressions"); 18187 ExprEvalContexts.back().Context = 18188 ExprEvalContexts[ExprEvalContexts.size() - 2].Context; 18189 if (isUnevaluatedContext()) 18190 return TInfo; 18191 return TransformToPE(*this).TransformType(TInfo); 18192} 18193 18194void 18195Sema::PushExpressionEvaluationContext( 18196 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 18197 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 18198 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 18199 LambdaContextDecl, ExprContext); 18200 18201 // Discarded statements and immediate contexts nested in other 18202 // discarded statements or immediate context are themselves 18203 // a discarded statement or an immediate context, respectively. 18204 ExprEvalContexts.back().InDiscardedStatement = 18205 ExprEvalContexts[ExprEvalContexts.size() - 2] 18206 .isDiscardedStatementContext(); 18207 18208 // C++23 [expr.const]/p15 18209 // An expression or conversion is in an immediate function context if [...] 18210 // it is a subexpression of a manifestly constant-evaluated expression or 18211 // conversion. 18212 const auto &Prev = ExprEvalContexts[ExprEvalContexts.size() - 2]; 18213 ExprEvalContexts.back().InImmediateFunctionContext = 18214 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated(); 18215 18216 ExprEvalContexts.back().InImmediateEscalatingFunctionContext = 18217 Prev.InImmediateEscalatingFunctionContext; 18218 18219 Cleanup.reset(); 18220 if (!MaybeODRUseExprs.empty()) 18221 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 18222} 18223 18224void 18225Sema::PushExpressionEvaluationContext( 18226 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 18227 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 18228 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 18229 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 18230} 18231 18232namespace { 18233 18234const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 18235 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 18236 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 18237 if (E->getOpcode() == UO_Deref) 18238 return CheckPossibleDeref(S, E->getSubExpr()); 18239 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 18240 return CheckPossibleDeref(S, E->getBase()); 18241 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 18242 return CheckPossibleDeref(S, E->getBase()); 18243 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 18244 QualType Inner; 18245 QualType Ty = E->getType(); 18246 if (const auto *Ptr = Ty->getAs<PointerType>()) 18247 Inner = Ptr->getPointeeType(); 18248 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 18249 Inner = Arr->getElementType(); 18250 else 18251 return nullptr; 18252 18253 if (Inner->hasAttr(attr::NoDeref)) 18254 return E; 18255 } 18256 return nullptr; 18257} 18258 18259} // namespace 18260 18261void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 18262 for (const Expr *E : Rec.PossibleDerefs) { 18263 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 18264 if (DeclRef) { 18265 const ValueDecl *Decl = DeclRef->getDecl(); 18266 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 18267 << Decl->getName() << E->getSourceRange(); 18268 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 18269 } else { 18270 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 18271 << E->getSourceRange(); 18272 } 18273 } 18274 Rec.PossibleDerefs.clear(); 18275} 18276 18277/// Check whether E, which is either a discarded-value expression or an 18278/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 18279/// and if so, remove it from the list of volatile-qualified assignments that 18280/// we are going to warn are deprecated. 18281void Sema::CheckUnusedVolatileAssignment(Expr *E) { 18282 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 18283 return; 18284 18285 // Note: ignoring parens here is not justified by the standard rules, but 18286 // ignoring parentheses seems like a more reasonable approach, and this only 18287 // drives a deprecation warning so doesn't affect conformance. 18288 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 18289 if (BO->getOpcode() == BO_Assign) { 18290 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 18291 llvm::erase(LHSs, BO->getLHS()); 18292 } 18293 } 18294} 18295 18296void Sema::MarkExpressionAsImmediateEscalating(Expr *E) { 18297 assert(getLangOpts().CPlusPlus20 && 18298 ExprEvalContexts.back().InImmediateEscalatingFunctionContext && 18299 "Cannot mark an immediate escalating expression outside of an " 18300 "immediate escalating context"); 18301 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit()); 18302 Call && Call->getCallee()) { 18303 if (auto *DeclRef = 18304 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 18305 DeclRef->setIsImmediateEscalating(true); 18306 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) { 18307 Ctr->setIsImmediateEscalating(true); 18308 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) { 18309 DeclRef->setIsImmediateEscalating(true); 18310 } else { 18311 assert(false && "expected an immediately escalating expression"); 18312 } 18313 if (FunctionScopeInfo *FI = getCurFunction()) 18314 FI->FoundImmediateEscalatingExpression = true; 18315} 18316 18317ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 18318 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 18319 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() || 18320 isCheckingDefaultArgumentOrInitializer() || 18321 RebuildingImmediateInvocation || isImmediateFunctionContext()) 18322 return E; 18323 18324 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 18325 /// It's OK if this fails; we'll also remove this in 18326 /// HandleImmediateInvocations, but catching it here allows us to avoid 18327 /// walking the AST looking for it in simple cases. 18328 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 18329 if (auto *DeclRef = 18330 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 18331 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 18332 18333 // C++23 [expr.const]/p16 18334 // An expression or conversion is immediate-escalating if it is not initially 18335 // in an immediate function context and it is [...] an immediate invocation 18336 // that is not a constant expression and is not a subexpression of an 18337 // immediate invocation. 18338 APValue Cached; 18339 auto CheckConstantExpressionAndKeepResult = [&]() { 18340 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 18341 Expr::EvalResult Eval; 18342 Eval.Diag = &Notes; 18343 bool Res = E.get()->EvaluateAsConstantExpr( 18344 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation); 18345 if (Res && Notes.empty()) { 18346 Cached = std::move(Eval.Val); 18347 return true; 18348 } 18349 return false; 18350 }; 18351 18352 if (!E.get()->isValueDependent() && 18353 ExprEvalContexts.back().InImmediateEscalatingFunctionContext && 18354 !CheckConstantExpressionAndKeepResult()) { 18355 MarkExpressionAsImmediateEscalating(E.get()); 18356 return E; 18357 } 18358 18359 if (Cleanup.exprNeedsCleanups()) { 18360 // Since an immediate invocation is a full expression itself - it requires 18361 // an additional ExprWithCleanups node, but it can participate to a bigger 18362 // full expression which actually requires cleanups to be run after so 18363 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it 18364 // may discard cleanups for outer expression too early. 18365 18366 // Note that ExprWithCleanups created here must always have empty cleanup 18367 // objects: 18368 // - compound literals do not create cleanup objects in C++ and immediate 18369 // invocations are C++-only. 18370 // - blocks are not allowed inside constant expressions and compiler will 18371 // issue an error if they appear there. 18372 // 18373 // Hence, in correct code any cleanup objects created inside current 18374 // evaluation context must be outside the immediate invocation. 18375 E = ExprWithCleanups::Create(getASTContext(), E.get(), 18376 Cleanup.cleanupsHaveSideEffects(), {}); 18377 } 18378 18379 ConstantExpr *Res = ConstantExpr::Create( 18380 getASTContext(), E.get(), 18381 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 18382 getASTContext()), 18383 /*IsImmediateInvocation*/ true); 18384 if (Cached.hasValue()) 18385 Res->MoveIntoResult(Cached, getASTContext()); 18386 /// Value-dependent constant expressions should not be immediately 18387 /// evaluated until they are instantiated. 18388 if (!Res->isValueDependent()) 18389 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 18390 return Res; 18391} 18392 18393static void EvaluateAndDiagnoseImmediateInvocation( 18394 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 18395 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 18396 Expr::EvalResult Eval; 18397 Eval.Diag = &Notes; 18398 ConstantExpr *CE = Candidate.getPointer(); 18399 bool Result = CE->EvaluateAsConstantExpr( 18400 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 18401 if (!Result || !Notes.empty()) { 18402 SemaRef.FailedImmediateInvocations.insert(CE); 18403 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 18404 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 18405 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit(); 18406 FunctionDecl *FD = nullptr; 18407 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 18408 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 18409 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 18410 FD = Call->getConstructor(); 18411 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr)) 18412 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction()); 18413 18414 assert(FD && FD->isImmediateFunction() && 18415 "could not find an immediate function in this expression"); 18416 if (FD->isInvalidDecl()) 18417 return; 18418 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) 18419 << FD << FD->isConsteval(); 18420 if (auto Context = 18421 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) { 18422 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer) 18423 << Context->Decl; 18424 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at); 18425 } 18426 if (!FD->isConsteval()) 18427 SemaRef.DiagnoseImmediateEscalatingReason(FD); 18428 for (auto &Note : Notes) 18429 SemaRef.Diag(Note.first, Note.second); 18430 return; 18431 } 18432 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 18433} 18434 18435static void RemoveNestedImmediateInvocation( 18436 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 18437 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 18438 struct ComplexRemove : TreeTransform<ComplexRemove> { 18439 using Base = TreeTransform<ComplexRemove>; 18440 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 18441 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 18442 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 18443 CurrentII; 18444 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 18445 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 18446 SmallVector<Sema::ImmediateInvocationCandidate, 18447 4>::reverse_iterator Current) 18448 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 18449 void RemoveImmediateInvocation(ConstantExpr* E) { 18450 auto It = std::find_if(CurrentII, IISet.rend(), 18451 [E](Sema::ImmediateInvocationCandidate Elem) { 18452 return Elem.getPointer() == E; 18453 }); 18454 // It is possible that some subexpression of the current immediate 18455 // invocation was handled from another expression evaluation context. Do 18456 // not handle the current immediate invocation if some of its 18457 // subexpressions failed before. 18458 if (It == IISet.rend()) { 18459 if (SemaRef.FailedImmediateInvocations.contains(E)) 18460 CurrentII->setInt(1); 18461 } else { 18462 It->setInt(1); // Mark as deleted 18463 } 18464 } 18465 ExprResult TransformConstantExpr(ConstantExpr *E) { 18466 if (!E->isImmediateInvocation()) 18467 return Base::TransformConstantExpr(E); 18468 RemoveImmediateInvocation(E); 18469 return Base::TransformExpr(E->getSubExpr()); 18470 } 18471 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 18472 /// we need to remove its DeclRefExpr from the DRSet. 18473 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 18474 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 18475 return Base::TransformCXXOperatorCallExpr(E); 18476 } 18477 /// Base::TransformUserDefinedLiteral doesn't preserve the 18478 /// UserDefinedLiteral node. 18479 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; } 18480 /// Base::TransformInitializer skips ConstantExpr so we need to visit them 18481 /// here. 18482 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 18483 if (!Init) 18484 return Init; 18485 /// ConstantExpr are the first layer of implicit node to be removed so if 18486 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 18487 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 18488 if (CE->isImmediateInvocation()) 18489 RemoveImmediateInvocation(CE); 18490 return Base::TransformInitializer(Init, NotCopyInit); 18491 } 18492 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 18493 DRSet.erase(E); 18494 return E; 18495 } 18496 ExprResult TransformLambdaExpr(LambdaExpr *E) { 18497 // Do not rebuild lambdas to avoid creating a new type. 18498 // Lambdas have already been processed inside their eval context. 18499 return E; 18500 } 18501 bool AlwaysRebuild() { return false; } 18502 bool ReplacingOriginal() { return true; } 18503 bool AllowSkippingCXXConstructExpr() { 18504 bool Res = AllowSkippingFirstCXXConstructExpr; 18505 AllowSkippingFirstCXXConstructExpr = true; 18506 return Res; 18507 } 18508 bool AllowSkippingFirstCXXConstructExpr = true; 18509 } Transformer(SemaRef, Rec.ReferenceToConsteval, 18510 Rec.ImmediateInvocationCandidates, It); 18511 18512 /// CXXConstructExpr with a single argument are getting skipped by 18513 /// TreeTransform in some situtation because they could be implicit. This 18514 /// can only occur for the top-level CXXConstructExpr because it is used 18515 /// nowhere in the expression being transformed therefore will not be rebuilt. 18516 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 18517 /// skipping the first CXXConstructExpr. 18518 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 18519 Transformer.AllowSkippingFirstCXXConstructExpr = false; 18520 18521 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 18522 // The result may not be usable in case of previous compilation errors. 18523 // In this case evaluation of the expression may result in crash so just 18524 // don't do anything further with the result. 18525 if (Res.isUsable()) { 18526 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 18527 It->getPointer()->setSubExpr(Res.get()); 18528 } 18529} 18530 18531static void 18532HandleImmediateInvocations(Sema &SemaRef, 18533 Sema::ExpressionEvaluationContextRecord &Rec) { 18534 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 18535 Rec.ReferenceToConsteval.size() == 0) || 18536 SemaRef.RebuildingImmediateInvocation) 18537 return; 18538 18539 /// When we have more than 1 ImmediateInvocationCandidates or previously 18540 /// failed immediate invocations, we need to check for nested 18541 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics. 18542 /// Otherwise we only need to remove ReferenceToConsteval in the immediate 18543 /// invocation. 18544 if (Rec.ImmediateInvocationCandidates.size() > 1 || 18545 !SemaRef.FailedImmediateInvocations.empty()) { 18546 18547 /// Prevent sema calls during the tree transform from adding pointers that 18548 /// are already in the sets. 18549 llvm::SaveAndRestore DisableIITracking( 18550 SemaRef.RebuildingImmediateInvocation, true); 18551 18552 /// Prevent diagnostic during tree transfrom as they are duplicates 18553 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 18554 18555 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 18556 It != Rec.ImmediateInvocationCandidates.rend(); It++) 18557 if (!It->getInt()) 18558 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 18559 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 18560 Rec.ReferenceToConsteval.size()) { 18561 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 18562 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 18563 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 18564 bool VisitDeclRefExpr(DeclRefExpr *E) { 18565 DRSet.erase(E); 18566 return DRSet.size(); 18567 } 18568 } Visitor(Rec.ReferenceToConsteval); 18569 Visitor.TraverseStmt( 18570 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 18571 } 18572 for (auto CE : Rec.ImmediateInvocationCandidates) 18573 if (!CE.getInt()) 18574 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 18575 for (auto *DR : Rec.ReferenceToConsteval) { 18576 // If the expression is immediate escalating, it is not an error; 18577 // The outer context itself becomes immediate and further errors, 18578 // if any, will be handled by DiagnoseImmediateEscalatingReason. 18579 if (DR->isImmediateEscalating()) 18580 continue; 18581 auto *FD = cast<FunctionDecl>(DR->getDecl()); 18582 const NamedDecl *ND = FD; 18583 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND); 18584 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD))) 18585 ND = MD->getParent(); 18586 18587 // C++23 [expr.const]/p16 18588 // An expression or conversion is immediate-escalating if it is not 18589 // initially in an immediate function context and it is [...] a 18590 // potentially-evaluated id-expression that denotes an immediate function 18591 // that is not a subexpression of an immediate invocation. 18592 bool ImmediateEscalating = false; 18593 bool IsPotentiallyEvaluated = 18594 Rec.Context == 18595 Sema::ExpressionEvaluationContext::PotentiallyEvaluated || 18596 Rec.Context == 18597 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed; 18598 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated) 18599 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext; 18600 18601 if (!Rec.InImmediateEscalatingFunctionContext || 18602 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) { 18603 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 18604 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval(); 18605 SemaRef.Diag(ND->getLocation(), diag::note_declared_at); 18606 if (auto Context = 18607 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) { 18608 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer) 18609 << Context->Decl; 18610 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at); 18611 } 18612 if (FD->isImmediateEscalating() && !FD->isConsteval()) 18613 SemaRef.DiagnoseImmediateEscalatingReason(FD); 18614 18615 } else { 18616 SemaRef.MarkExpressionAsImmediateEscalating(DR); 18617 } 18618 } 18619} 18620 18621void Sema::PopExpressionEvaluationContext() { 18622 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 18623 unsigned NumTypos = Rec.NumTypos; 18624 18625 if (!Rec.Lambdas.empty()) { 18626 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 18627 if (!getLangOpts().CPlusPlus20 && 18628 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 18629 Rec.isUnevaluated() || 18630 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 18631 unsigned D; 18632 if (Rec.isUnevaluated()) { 18633 // C++11 [expr.prim.lambda]p2: 18634 // A lambda-expression shall not appear in an unevaluated operand 18635 // (Clause 5). 18636 D = diag::err_lambda_unevaluated_operand; 18637 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 18638 // C++1y [expr.const]p2: 18639 // A conditional-expression e is a core constant expression unless the 18640 // evaluation of e, following the rules of the abstract machine, would 18641 // evaluate [...] a lambda-expression. 18642 D = diag::err_lambda_in_constant_expression; 18643 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 18644 // C++17 [expr.prim.lamda]p2: 18645 // A lambda-expression shall not appear [...] in a template-argument. 18646 D = diag::err_lambda_in_invalid_context; 18647 } else 18648 llvm_unreachable("Couldn't infer lambda error message."); 18649 18650 for (const auto *L : Rec.Lambdas) 18651 Diag(L->getBeginLoc(), D); 18652 } 18653 } 18654 18655 WarnOnPendingNoDerefs(Rec); 18656 HandleImmediateInvocations(*this, Rec); 18657 18658 // Warn on any volatile-qualified simple-assignments that are not discarded- 18659 // value expressions nor unevaluated operands (those cases get removed from 18660 // this list by CheckUnusedVolatileAssignment). 18661 for (auto *BO : Rec.VolatileAssignmentLHSs) 18662 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 18663 << BO->getType(); 18664 18665 // When are coming out of an unevaluated context, clear out any 18666 // temporaries that we may have created as part of the evaluation of 18667 // the expression in that context: they aren't relevant because they 18668 // will never be constructed. 18669 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 18670 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 18671 ExprCleanupObjects.end()); 18672 Cleanup = Rec.ParentCleanup; 18673 CleanupVarDeclMarking(); 18674 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 18675 // Otherwise, merge the contexts together. 18676 } else { 18677 Cleanup.mergeFrom(Rec.ParentCleanup); 18678 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 18679 Rec.SavedMaybeODRUseExprs.end()); 18680 } 18681 18682 // Pop the current expression evaluation context off the stack. 18683 ExprEvalContexts.pop_back(); 18684 18685 // The global expression evaluation context record is never popped. 18686 ExprEvalContexts.back().NumTypos += NumTypos; 18687} 18688 18689void Sema::DiscardCleanupsInEvaluationContext() { 18690 ExprCleanupObjects.erase( 18691 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 18692 ExprCleanupObjects.end()); 18693 Cleanup.reset(); 18694 MaybeODRUseExprs.clear(); 18695} 18696 18697ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 18698 ExprResult Result = CheckPlaceholderExpr(E); 18699 if (Result.isInvalid()) 18700 return ExprError(); 18701 E = Result.get(); 18702 if (!E->getType()->isVariablyModifiedType()) 18703 return E; 18704 return TransformToPotentiallyEvaluated(E); 18705} 18706 18707/// Are we in a context that is potentially constant evaluated per C++20 18708/// [expr.const]p12? 18709static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 18710 /// C++2a [expr.const]p12: 18711 // An expression or conversion is potentially constant evaluated if it is 18712 switch (SemaRef.ExprEvalContexts.back().Context) { 18713 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 18714 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 18715 18716 // -- a manifestly constant-evaluated expression, 18717 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 18718 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18719 case Sema::ExpressionEvaluationContext::DiscardedStatement: 18720 // -- a potentially-evaluated expression, 18721 case Sema::ExpressionEvaluationContext::UnevaluatedList: 18722 // -- an immediate subexpression of a braced-init-list, 18723 18724 // -- [FIXME] an expression of the form & cast-expression that occurs 18725 // within a templated entity 18726 // -- a subexpression of one of the above that is not a subexpression of 18727 // a nested unevaluated operand. 18728 return true; 18729 18730 case Sema::ExpressionEvaluationContext::Unevaluated: 18731 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 18732 // Expressions in this context are never evaluated. 18733 return false; 18734 } 18735 llvm_unreachable("Invalid context"); 18736} 18737 18738/// Return true if this function has a calling convention that requires mangling 18739/// in the size of the parameter pack. 18740static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 18741 // These manglings don't do anything on non-Windows or non-x86 platforms, so 18742 // we don't need parameter type sizes. 18743 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 18744 if (!TT.isOSWindows() || !TT.isX86()) 18745 return false; 18746 18747 // If this is C++ and this isn't an extern "C" function, parameters do not 18748 // need to be complete. In this case, C++ mangling will apply, which doesn't 18749 // use the size of the parameters. 18750 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 18751 return false; 18752 18753 // Stdcall, fastcall, and vectorcall need this special treatment. 18754 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 18755 switch (CC) { 18756 case CC_X86StdCall: 18757 case CC_X86FastCall: 18758 case CC_X86VectorCall: 18759 return true; 18760 default: 18761 break; 18762 } 18763 return false; 18764} 18765 18766/// Require that all of the parameter types of function be complete. Normally, 18767/// parameter types are only required to be complete when a function is called 18768/// or defined, but to mangle functions with certain calling conventions, the 18769/// mangler needs to know the size of the parameter list. In this situation, 18770/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 18771/// the function as _foo@0, i.e. zero bytes of parameters, which will usually 18772/// result in a linker error. Clang doesn't implement this behavior, and instead 18773/// attempts to error at compile time. 18774static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 18775 SourceLocation Loc) { 18776 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 18777 FunctionDecl *FD; 18778 ParmVarDecl *Param; 18779 18780 public: 18781 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 18782 : FD(FD), Param(Param) {} 18783 18784 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18785 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 18786 StringRef CCName; 18787 switch (CC) { 18788 case CC_X86StdCall: 18789 CCName = "stdcall"; 18790 break; 18791 case CC_X86FastCall: 18792 CCName = "fastcall"; 18793 break; 18794 case CC_X86VectorCall: 18795 CCName = "vectorcall"; 18796 break; 18797 default: 18798 llvm_unreachable("CC does not need mangling"); 18799 } 18800 18801 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 18802 << Param->getDeclName() << FD->getDeclName() << CCName; 18803 } 18804 }; 18805 18806 for (ParmVarDecl *Param : FD->parameters()) { 18807 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 18808 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 18809 } 18810} 18811 18812namespace { 18813enum class OdrUseContext { 18814 /// Declarations in this context are not odr-used. 18815 None, 18816 /// Declarations in this context are formally odr-used, but this is a 18817 /// dependent context. 18818 Dependent, 18819 /// Declarations in this context are odr-used but not actually used (yet). 18820 FormallyOdrUsed, 18821 /// Declarations in this context are used. 18822 Used 18823}; 18824} 18825 18826/// Are we within a context in which references to resolved functions or to 18827/// variables result in odr-use? 18828static OdrUseContext isOdrUseContext(Sema &SemaRef) { 18829 OdrUseContext Result; 18830 18831 switch (SemaRef.ExprEvalContexts.back().Context) { 18832 case Sema::ExpressionEvaluationContext::Unevaluated: 18833 case Sema::ExpressionEvaluationContext::UnevaluatedList: 18834 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 18835 return OdrUseContext::None; 18836 18837 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 18838 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 18839 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 18840 Result = OdrUseContext::Used; 18841 break; 18842 18843 case Sema::ExpressionEvaluationContext::DiscardedStatement: 18844 Result = OdrUseContext::FormallyOdrUsed; 18845 break; 18846 18847 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18848 // A default argument formally results in odr-use, but doesn't actually 18849 // result in a use in any real sense until it itself is used. 18850 Result = OdrUseContext::FormallyOdrUsed; 18851 break; 18852 } 18853 18854 if (SemaRef.CurContext->isDependentContext()) 18855 return OdrUseContext::Dependent; 18856 18857 return Result; 18858} 18859 18860static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 18861 if (!Func->isConstexpr()) 18862 return false; 18863 18864 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 18865 return true; 18866 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 18867 return CCD && CCD->getInheritedConstructor(); 18868} 18869 18870/// Mark a function referenced, and check whether it is odr-used 18871/// (C++ [basic.def.odr]p2, C99 6.9p3) 18872void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 18873 bool MightBeOdrUse) { 18874 assert(Func && "No function?"); 18875 18876 Func->setReferenced(); 18877 18878 // Recursive functions aren't really used until they're used from some other 18879 // context. 18880 bool IsRecursiveCall = CurContext == Func; 18881 18882 // C++11 [basic.def.odr]p3: 18883 // A function whose name appears as a potentially-evaluated expression is 18884 // odr-used if it is the unique lookup result or the selected member of a 18885 // set of overloaded functions [...]. 18886 // 18887 // We (incorrectly) mark overload resolution as an unevaluated context, so we 18888 // can just check that here. 18889 OdrUseContext OdrUse = 18890 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 18891 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 18892 OdrUse = OdrUseContext::FormallyOdrUsed; 18893 18894 // Trivial default constructors and destructors are never actually used. 18895 // FIXME: What about other special members? 18896 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 18897 OdrUse == OdrUseContext::Used) { 18898 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 18899 if (Constructor->isDefaultConstructor()) 18900 OdrUse = OdrUseContext::FormallyOdrUsed; 18901 if (isa<CXXDestructorDecl>(Func)) 18902 OdrUse = OdrUseContext::FormallyOdrUsed; 18903 } 18904 18905 // C++20 [expr.const]p12: 18906 // A function [...] is needed for constant evaluation if it is [...] a 18907 // constexpr function that is named by an expression that is potentially 18908 // constant evaluated 18909 bool NeededForConstantEvaluation = 18910 isPotentiallyConstantEvaluatedContext(*this) && 18911 isImplicitlyDefinableConstexprFunction(Func); 18912 18913 // Determine whether we require a function definition to exist, per 18914 // C++11 [temp.inst]p3: 18915 // Unless a function template specialization has been explicitly 18916 // instantiated or explicitly specialized, the function template 18917 // specialization is implicitly instantiated when the specialization is 18918 // referenced in a context that requires a function definition to exist. 18919 // C++20 [temp.inst]p7: 18920 // The existence of a definition of a [...] function is considered to 18921 // affect the semantics of the program if the [...] function is needed for 18922 // constant evaluation by an expression 18923 // C++20 [basic.def.odr]p10: 18924 // Every program shall contain exactly one definition of every non-inline 18925 // function or variable that is odr-used in that program outside of a 18926 // discarded statement 18927 // C++20 [special]p1: 18928 // The implementation will implicitly define [defaulted special members] 18929 // if they are odr-used or needed for constant evaluation. 18930 // 18931 // Note that we skip the implicit instantiation of templates that are only 18932 // used in unused default arguments or by recursive calls to themselves. 18933 // This is formally non-conforming, but seems reasonable in practice. 18934 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 18935 NeededForConstantEvaluation); 18936 18937 // C++14 [temp.expl.spec]p6: 18938 // If a template [...] is explicitly specialized then that specialization 18939 // shall be declared before the first use of that specialization that would 18940 // cause an implicit instantiation to take place, in every translation unit 18941 // in which such a use occurs 18942 if (NeedDefinition && 18943 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 18944 Func->getMemberSpecializationInfo())) 18945 checkSpecializationReachability(Loc, Func); 18946 18947 if (getLangOpts().CUDA) 18948 CheckCUDACall(Loc, Func); 18949 18950 // If we need a definition, try to create one. 18951 if (NeedDefinition && !Func->getBody()) { 18952 runWithSufficientStackSpace(Loc, [&] { 18953 if (CXXConstructorDecl *Constructor = 18954 dyn_cast<CXXConstructorDecl>(Func)) { 18955 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 18956 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 18957 if (Constructor->isDefaultConstructor()) { 18958 if (Constructor->isTrivial() && 18959 !Constructor->hasAttr<DLLExportAttr>()) 18960 return; 18961 DefineImplicitDefaultConstructor(Loc, Constructor); 18962 } else if (Constructor->isCopyConstructor()) { 18963 DefineImplicitCopyConstructor(Loc, Constructor); 18964 } else if (Constructor->isMoveConstructor()) { 18965 DefineImplicitMoveConstructor(Loc, Constructor); 18966 } 18967 } else if (Constructor->getInheritedConstructor()) { 18968 DefineInheritingConstructor(Loc, Constructor); 18969 } 18970 } else if (CXXDestructorDecl *Destructor = 18971 dyn_cast<CXXDestructorDecl>(Func)) { 18972 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 18973 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 18974 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 18975 return; 18976 DefineImplicitDestructor(Loc, Destructor); 18977 } 18978 if (Destructor->isVirtual() && getLangOpts().AppleKext) 18979 MarkVTableUsed(Loc, Destructor->getParent()); 18980 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 18981 if (MethodDecl->isOverloadedOperator() && 18982 MethodDecl->getOverloadedOperator() == OO_Equal) { 18983 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 18984 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 18985 if (MethodDecl->isCopyAssignmentOperator()) 18986 DefineImplicitCopyAssignment(Loc, MethodDecl); 18987 else if (MethodDecl->isMoveAssignmentOperator()) 18988 DefineImplicitMoveAssignment(Loc, MethodDecl); 18989 } 18990 } else if (isa<CXXConversionDecl>(MethodDecl) && 18991 MethodDecl->getParent()->isLambda()) { 18992 CXXConversionDecl *Conversion = 18993 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 18994 if (Conversion->isLambdaToBlockPointerConversion()) 18995 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 18996 else 18997 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 18998 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 18999 MarkVTableUsed(Loc, MethodDecl->getParent()); 19000 } 19001 19002 if (Func->isDefaulted() && !Func->isDeleted()) { 19003 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 19004 if (DCK != DefaultedComparisonKind::None) 19005 DefineDefaultedComparison(Loc, Func, DCK); 19006 } 19007 19008 // Implicit instantiation of function templates and member functions of 19009 // class templates. 19010 if (Func->isImplicitlyInstantiable()) { 19011 TemplateSpecializationKind TSK = 19012 Func->getTemplateSpecializationKindForInstantiation(); 19013 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 19014 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 19015 if (FirstInstantiation) { 19016 PointOfInstantiation = Loc; 19017 if (auto *MSI = Func->getMemberSpecializationInfo()) 19018 MSI->setPointOfInstantiation(Loc); 19019 // FIXME: Notify listener. 19020 else 19021 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 19022 } else if (TSK != TSK_ImplicitInstantiation) { 19023 // Use the point of use as the point of instantiation, instead of the 19024 // point of explicit instantiation (which we track as the actual point 19025 // of instantiation). This gives better backtraces in diagnostics. 19026 PointOfInstantiation = Loc; 19027 } 19028 19029 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 19030 Func->isConstexpr()) { 19031 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 19032 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 19033 CodeSynthesisContexts.size()) 19034 PendingLocalImplicitInstantiations.push_back( 19035 std::make_pair(Func, PointOfInstantiation)); 19036 else if (Func->isConstexpr()) 19037 // Do not defer instantiations of constexpr functions, to avoid the 19038 // expression evaluator needing to call back into Sema if it sees a 19039 // call to such a function. 19040 InstantiateFunctionDefinition(PointOfInstantiation, Func); 19041 else { 19042 Func->setInstantiationIsPending(true); 19043 PendingInstantiations.push_back( 19044 std::make_pair(Func, PointOfInstantiation)); 19045 // Notify the consumer that a function was implicitly instantiated. 19046 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 19047 } 19048 } 19049 } else { 19050 // Walk redefinitions, as some of them may be instantiable. 19051 for (auto *i : Func->redecls()) { 19052 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 19053 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 19054 } 19055 } 19056 }); 19057 } 19058 19059 // If a constructor was defined in the context of a default parameter 19060 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed 19061 // context), its initializers may not be referenced yet. 19062 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 19063 EnterExpressionEvaluationContext EvalContext( 19064 *this, 19065 Constructor->isImmediateFunction() 19066 ? ExpressionEvaluationContext::ImmediateFunctionContext 19067 : ExpressionEvaluationContext::PotentiallyEvaluated, 19068 Constructor); 19069 for (CXXCtorInitializer *Init : Constructor->inits()) { 19070 if (Init->isInClassMemberInitializer()) 19071 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() { 19072 MarkDeclarationsReferencedInExpr(Init->getInit()); 19073 }); 19074 } 19075 } 19076 19077 // C++14 [except.spec]p17: 19078 // An exception-specification is considered to be needed when: 19079 // - the function is odr-used or, if it appears in an unevaluated operand, 19080 // would be odr-used if the expression were potentially-evaluated; 19081 // 19082 // Note, we do this even if MightBeOdrUse is false. That indicates that the 19083 // function is a pure virtual function we're calling, and in that case the 19084 // function was selected by overload resolution and we need to resolve its 19085 // exception specification for a different reason. 19086 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 19087 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 19088 ResolveExceptionSpec(Loc, FPT); 19089 19090 // A callee could be called by a host function then by a device function. 19091 // If we only try recording once, we will miss recording the use on device 19092 // side. Therefore keep trying until it is recorded. 19093 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice && 19094 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func)) 19095 CUDARecordImplicitHostDeviceFuncUsedByDevice(Func); 19096 19097 // If this is the first "real" use, act on that. 19098 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 19099 // Keep track of used but undefined functions. 19100 if (!Func->isDefined()) { 19101 if (mightHaveNonExternalLinkage(Func)) 19102 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 19103 else if (Func->getMostRecentDecl()->isInlined() && 19104 !LangOpts.GNUInline && 19105 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 19106 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 19107 else if (isExternalWithNoLinkageType(Func)) 19108 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 19109 } 19110 19111 // Some x86 Windows calling conventions mangle the size of the parameter 19112 // pack into the name. Computing the size of the parameters requires the 19113 // parameter types to be complete. Check that now. 19114 if (funcHasParameterSizeMangling(*this, Func)) 19115 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 19116 19117 // In the MS C++ ABI, the compiler emits destructor variants where they are 19118 // used. If the destructor is used here but defined elsewhere, mark the 19119 // virtual base destructors referenced. If those virtual base destructors 19120 // are inline, this will ensure they are defined when emitting the complete 19121 // destructor variant. This checking may be redundant if the destructor is 19122 // provided later in this TU. 19123 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 19124 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 19125 CXXRecordDecl *Parent = Dtor->getParent(); 19126 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 19127 CheckCompleteDestructorVariant(Loc, Dtor); 19128 } 19129 } 19130 19131 Func->markUsed(Context); 19132 } 19133} 19134 19135/// Directly mark a variable odr-used. Given a choice, prefer to use 19136/// MarkVariableReferenced since it does additional checks and then 19137/// calls MarkVarDeclODRUsed. 19138/// If the variable must be captured: 19139/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 19140/// - else capture it in the DeclContext that maps to the 19141/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 19142static void 19143MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, 19144 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 19145 // Keep track of used but undefined variables. 19146 // FIXME: We shouldn't suppress this warning for static data members. 19147 VarDecl *Var = V->getPotentiallyDecomposedVarDecl(); 19148 assert(Var && "expected a capturable variable"); 19149 19150 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 19151 (!Var->isExternallyVisible() || Var->isInline() || 19152 SemaRef.isExternalWithNoLinkageType(Var)) && 19153 !(Var->isStaticDataMember() && Var->hasInit())) { 19154 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 19155 if (old.isInvalid()) 19156 old = Loc; 19157 } 19158 QualType CaptureType, DeclRefType; 19159 if (SemaRef.LangOpts.OpenMP) 19160 SemaRef.tryCaptureOpenMPLambdas(V); 19161 SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit, 19162 /*EllipsisLoc*/ SourceLocation(), 19163 /*BuildAndDiagnose*/ true, CaptureType, 19164 DeclRefType, FunctionScopeIndexToStopAt); 19165 19166 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { 19167 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 19168 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 19169 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 19170 if (VarTarget == Sema::CVT_Host && 19171 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 19172 UserTarget == Sema::CFT_Global)) { 19173 // Diagnose ODR-use of host global variables in device functions. 19174 // Reference of device global variables in host functions is allowed 19175 // through shadow variables therefore it is not diagnosed. 19176 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) { 19177 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 19178 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 19179 SemaRef.targetDiag(Var->getLocation(), 19180 Var->getType().isConstQualified() 19181 ? diag::note_cuda_const_var_unpromoted 19182 : diag::note_cuda_host_var); 19183 } 19184 } else if (VarTarget == Sema::CVT_Device && 19185 !Var->hasAttr<CUDASharedAttr>() && 19186 (UserTarget == Sema::CFT_Host || 19187 UserTarget == Sema::CFT_HostDevice)) { 19188 // Record a CUDA/HIP device side variable if it is ODR-used 19189 // by host code. This is done conservatively, when the variable is 19190 // referenced in any of the following contexts: 19191 // - a non-function context 19192 // - a host function 19193 // - a host device function 19194 // This makes the ODR-use of the device side variable by host code to 19195 // be visible in the device compilation for the compiler to be able to 19196 // emit template variables instantiated by host code only and to 19197 // externalize the static device side variable ODR-used by host code. 19198 if (!Var->hasExternalStorage()) 19199 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 19200 else if (SemaRef.LangOpts.GPURelocatableDeviceCode) 19201 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var); 19202 } 19203 } 19204 19205 V->markUsed(SemaRef.Context); 19206} 19207 19208void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, 19209 SourceLocation Loc, 19210 unsigned CapturingScopeIndex) { 19211 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 19212} 19213 19214void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, 19215 ValueDecl *var) { 19216 DeclContext *VarDC = var->getDeclContext(); 19217 19218 // If the parameter still belongs to the translation unit, then 19219 // we're actually just using one parameter in the declaration of 19220 // the next. 19221 if (isa<ParmVarDecl>(var) && 19222 isa<TranslationUnitDecl>(VarDC)) 19223 return; 19224 19225 // For C code, don't diagnose about capture if we're not actually in code 19226 // right now; it's impossible to write a non-constant expression outside of 19227 // function context, so we'll get other (more useful) diagnostics later. 19228 // 19229 // For C++, things get a bit more nasty... it would be nice to suppress this 19230 // diagnostic for certain cases like using a local variable in an array bound 19231 // for a member of a local class, but the correct predicate is not obvious. 19232 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 19233 return; 19234 19235 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 19236 unsigned ContextKind = 3; // unknown 19237 if (isa<CXXMethodDecl>(VarDC) && 19238 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 19239 ContextKind = 2; 19240 } else if (isa<FunctionDecl>(VarDC)) { 19241 ContextKind = 0; 19242 } else if (isa<BlockDecl>(VarDC)) { 19243 ContextKind = 1; 19244 } 19245 19246 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 19247 << var << ValueKind << ContextKind << VarDC; 19248 S.Diag(var->getLocation(), diag::note_entity_declared_at) 19249 << var; 19250 19251 // FIXME: Add additional diagnostic info about class etc. which prevents 19252 // capture. 19253} 19254 19255static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, 19256 ValueDecl *Var, 19257 bool &SubCapturesAreNested, 19258 QualType &CaptureType, 19259 QualType &DeclRefType) { 19260 // Check whether we've already captured it. 19261 if (CSI->CaptureMap.count(Var)) { 19262 // If we found a capture, any subcaptures are nested. 19263 SubCapturesAreNested = true; 19264 19265 // Retrieve the capture type for this variable. 19266 CaptureType = CSI->getCapture(Var).getCaptureType(); 19267 19268 // Compute the type of an expression that refers to this variable. 19269 DeclRefType = CaptureType.getNonReferenceType(); 19270 19271 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 19272 // are mutable in the sense that user can change their value - they are 19273 // private instances of the captured declarations. 19274 const Capture &Cap = CSI->getCapture(Var); 19275 if (Cap.isCopyCapture() && 19276 !(isa<LambdaScopeInfo>(CSI) && 19277 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) && 19278 !(isa<CapturedRegionScopeInfo>(CSI) && 19279 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 19280 DeclRefType.addConst(); 19281 return true; 19282 } 19283 return false; 19284} 19285 19286// Only block literals, captured statements, and lambda expressions can 19287// capture; other scopes don't work. 19288static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, 19289 ValueDecl *Var, 19290 SourceLocation Loc, 19291 const bool Diagnose, 19292 Sema &S) { 19293 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 19294 return getLambdaAwareParentOfDeclContext(DC); 19295 19296 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl(); 19297 if (Underlying) { 19298 if (Underlying->hasLocalStorage() && Diagnose) 19299 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var); 19300 } 19301 return nullptr; 19302} 19303 19304// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 19305// certain types of variables (unnamed, variably modified types etc.) 19306// so check for eligibility. 19307static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, 19308 SourceLocation Loc, const bool Diagnose, 19309 Sema &S) { 19310 19311 assert((isa<VarDecl, BindingDecl>(Var)) && 19312 "Only variables and structured bindings can be captured"); 19313 19314 bool IsBlock = isa<BlockScopeInfo>(CSI); 19315 bool IsLambda = isa<LambdaScopeInfo>(CSI); 19316 19317 // Lambdas are not allowed to capture unnamed variables 19318 // (e.g. anonymous unions). 19319 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 19320 // assuming that's the intent. 19321 if (IsLambda && !Var->getDeclName()) { 19322 if (Diagnose) { 19323 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 19324 S.Diag(Var->getLocation(), diag::note_declared_at); 19325 } 19326 return false; 19327 } 19328 19329 // Prohibit variably-modified types in blocks; they're difficult to deal with. 19330 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 19331 if (Diagnose) { 19332 S.Diag(Loc, diag::err_ref_vm_type); 19333 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 19334 } 19335 return false; 19336 } 19337 // Prohibit structs with flexible array members too. 19338 // We cannot capture what is in the tail end of the struct. 19339 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 19340 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 19341 if (Diagnose) { 19342 if (IsBlock) 19343 S.Diag(Loc, diag::err_ref_flexarray_type); 19344 else 19345 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 19346 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 19347 } 19348 return false; 19349 } 19350 } 19351 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 19352 // Lambdas and captured statements are not allowed to capture __block 19353 // variables; they don't support the expected semantics. 19354 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 19355 if (Diagnose) { 19356 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 19357 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 19358 } 19359 return false; 19360 } 19361 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 19362 if (S.getLangOpts().OpenCL && IsBlock && 19363 Var->getType()->isBlockPointerType()) { 19364 if (Diagnose) 19365 S.Diag(Loc, diag::err_opencl_block_ref_block); 19366 return false; 19367 } 19368 19369 if (isa<BindingDecl>(Var)) { 19370 if (!IsLambda || !S.getLangOpts().CPlusPlus) { 19371 if (Diagnose) 19372 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var); 19373 return false; 19374 } else if (Diagnose && S.getLangOpts().CPlusPlus) { 19375 S.Diag(Loc, S.LangOpts.CPlusPlus20 19376 ? diag::warn_cxx17_compat_capture_binding 19377 : diag::ext_capture_binding) 19378 << Var; 19379 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var; 19380 } 19381 } 19382 19383 return true; 19384} 19385 19386// Returns true if the capture by block was successful. 19387static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, 19388 SourceLocation Loc, const bool BuildAndDiagnose, 19389 QualType &CaptureType, QualType &DeclRefType, 19390 const bool Nested, Sema &S, bool Invalid) { 19391 bool ByRef = false; 19392 19393 // Blocks are not allowed to capture arrays, excepting OpenCL. 19394 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 19395 // (decayed to pointers). 19396 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 19397 if (BuildAndDiagnose) { 19398 S.Diag(Loc, diag::err_ref_array_type); 19399 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 19400 Invalid = true; 19401 } else { 19402 return false; 19403 } 19404 } 19405 19406 // Forbid the block-capture of autoreleasing variables. 19407 if (!Invalid && 19408 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 19409 if (BuildAndDiagnose) { 19410 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 19411 << /*block*/ 0; 19412 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 19413 Invalid = true; 19414 } else { 19415 return false; 19416 } 19417 } 19418 19419 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 19420 if (const auto *PT = CaptureType->getAs<PointerType>()) { 19421 QualType PointeeTy = PT->getPointeeType(); 19422 19423 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 19424 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 19425 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 19426 if (BuildAndDiagnose) { 19427 SourceLocation VarLoc = Var->getLocation(); 19428 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 19429 S.Diag(VarLoc, diag::note_declare_parameter_strong); 19430 } 19431 } 19432 } 19433 19434 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 19435 if (HasBlocksAttr || CaptureType->isReferenceType() || 19436 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 19437 // Block capture by reference does not change the capture or 19438 // declaration reference types. 19439 ByRef = true; 19440 } else { 19441 // Block capture by copy introduces 'const'. 19442 CaptureType = CaptureType.getNonReferenceType().withConst(); 19443 DeclRefType = CaptureType; 19444 } 19445 19446 // Actually capture the variable. 19447 if (BuildAndDiagnose) 19448 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 19449 CaptureType, Invalid); 19450 19451 return !Invalid; 19452} 19453 19454/// Capture the given variable in the captured region. 19455static bool captureInCapturedRegion( 19456 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, 19457 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 19458 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 19459 bool IsTopScope, Sema &S, bool Invalid) { 19460 // By default, capture variables by reference. 19461 bool ByRef = true; 19462 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 19463 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 19464 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 19465 // Using an LValue reference type is consistent with Lambdas (see below). 19466 if (S.isOpenMPCapturedDecl(Var)) { 19467 bool HasConst = DeclRefType.isConstQualified(); 19468 DeclRefType = DeclRefType.getUnqualifiedType(); 19469 // Don't lose diagnostics about assignments to const. 19470 if (HasConst) 19471 DeclRefType.addConst(); 19472 } 19473 // Do not capture firstprivates in tasks. 19474 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 19475 OMPC_unknown) 19476 return true; 19477 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 19478 RSI->OpenMPCaptureLevel); 19479 } 19480 19481 if (ByRef) 19482 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 19483 else 19484 CaptureType = DeclRefType; 19485 19486 // Actually capture the variable. 19487 if (BuildAndDiagnose) 19488 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 19489 Loc, SourceLocation(), CaptureType, Invalid); 19490 19491 return !Invalid; 19492} 19493 19494/// Capture the given variable in the lambda. 19495static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, 19496 SourceLocation Loc, const bool BuildAndDiagnose, 19497 QualType &CaptureType, QualType &DeclRefType, 19498 const bool RefersToCapturedVariable, 19499 const Sema::TryCaptureKind Kind, 19500 SourceLocation EllipsisLoc, const bool IsTopScope, 19501 Sema &S, bool Invalid) { 19502 // Determine whether we are capturing by reference or by value. 19503 bool ByRef = false; 19504 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 19505 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 19506 } else { 19507 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 19508 } 19509 19510 BindingDecl *BD = dyn_cast<BindingDecl>(Var); 19511 // FIXME: We should support capturing structured bindings in OpenMP. 19512 if (!Invalid && BD && S.LangOpts.OpenMP) { 19513 if (BuildAndDiagnose) { 19514 S.Diag(Loc, diag::err_capture_binding_openmp) << Var; 19515 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var; 19516 } 19517 Invalid = true; 19518 } 19519 19520 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() && 19521 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) { 19522 S.Diag(Loc, diag::err_wasm_ca_reference) << 0; 19523 Invalid = true; 19524 } 19525 19526 // Compute the type of the field that will capture this variable. 19527 if (ByRef) { 19528 // C++11 [expr.prim.lambda]p15: 19529 // An entity is captured by reference if it is implicitly or 19530 // explicitly captured but not captured by copy. It is 19531 // unspecified whether additional unnamed non-static data 19532 // members are declared in the closure type for entities 19533 // captured by reference. 19534 // 19535 // FIXME: It is not clear whether we want to build an lvalue reference 19536 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 19537 // to do the former, while EDG does the latter. Core issue 1249 will 19538 // clarify, but for now we follow GCC because it's a more permissive and 19539 // easily defensible position. 19540 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 19541 } else { 19542 // C++11 [expr.prim.lambda]p14: 19543 // For each entity captured by copy, an unnamed non-static 19544 // data member is declared in the closure type. The 19545 // declaration order of these members is unspecified. The type 19546 // of such a data member is the type of the corresponding 19547 // captured entity if the entity is not a reference to an 19548 // object, or the referenced type otherwise. [Note: If the 19549 // captured entity is a reference to a function, the 19550 // corresponding data member is also a reference to a 19551 // function. - end note ] 19552 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 19553 if (!RefType->getPointeeType()->isFunctionType()) 19554 CaptureType = RefType->getPointeeType(); 19555 } 19556 19557 // Forbid the lambda copy-capture of autoreleasing variables. 19558 if (!Invalid && 19559 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 19560 if (BuildAndDiagnose) { 19561 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 19562 S.Diag(Var->getLocation(), diag::note_previous_decl) 19563 << Var->getDeclName(); 19564 Invalid = true; 19565 } else { 19566 return false; 19567 } 19568 } 19569 19570 // Make sure that by-copy captures are of a complete and non-abstract type. 19571 if (!Invalid && BuildAndDiagnose) { 19572 if (!CaptureType->isDependentType() && 19573 S.RequireCompleteSizedType( 19574 Loc, CaptureType, 19575 diag::err_capture_of_incomplete_or_sizeless_type, 19576 Var->getDeclName())) 19577 Invalid = true; 19578 else if (S.RequireNonAbstractType(Loc, CaptureType, 19579 diag::err_capture_of_abstract_type)) 19580 Invalid = true; 19581 } 19582 } 19583 19584 // Compute the type of a reference to this captured variable. 19585 if (ByRef) 19586 DeclRefType = CaptureType.getNonReferenceType(); 19587 else { 19588 // C++ [expr.prim.lambda]p5: 19589 // The closure type for a lambda-expression has a public inline 19590 // function call operator [...]. This function call operator is 19591 // declared const (9.3.1) if and only if the lambda-expression's 19592 // parameter-declaration-clause is not followed by mutable. 19593 DeclRefType = CaptureType.getNonReferenceType(); 19594 bool Const = LSI->lambdaCaptureShouldBeConst(); 19595 if (Const && !CaptureType->isReferenceType()) 19596 DeclRefType.addConst(); 19597 } 19598 19599 // Add the capture. 19600 if (BuildAndDiagnose) 19601 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 19602 Loc, EllipsisLoc, CaptureType, Invalid); 19603 19604 return !Invalid; 19605} 19606 19607static bool canCaptureVariableByCopy(ValueDecl *Var, 19608 const ASTContext &Context) { 19609 // Offer a Copy fix even if the type is dependent. 19610 if (Var->getType()->isDependentType()) 19611 return true; 19612 QualType T = Var->getType().getNonReferenceType(); 19613 if (T.isTriviallyCopyableType(Context)) 19614 return true; 19615 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 19616 19617 if (!(RD = RD->getDefinition())) 19618 return false; 19619 if (RD->hasSimpleCopyConstructor()) 19620 return true; 19621 if (RD->hasUserDeclaredCopyConstructor()) 19622 for (CXXConstructorDecl *Ctor : RD->ctors()) 19623 if (Ctor->isCopyConstructor()) 19624 return !Ctor->isDeleted(); 19625 } 19626 return false; 19627} 19628 19629/// Create up to 4 fix-its for explicit reference and value capture of \p Var or 19630/// default capture. Fixes may be omitted if they aren't allowed by the 19631/// standard, for example we can't emit a default copy capture fix-it if we 19632/// already explicitly copy capture capture another variable. 19633static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 19634 ValueDecl *Var) { 19635 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 19636 // Don't offer Capture by copy of default capture by copy fixes if Var is 19637 // known not to be copy constructible. 19638 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 19639 19640 SmallString<32> FixBuffer; 19641 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 19642 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 19643 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 19644 if (ShouldOfferCopyFix) { 19645 // Offer fixes to insert an explicit capture for the variable. 19646 // [] -> [VarName] 19647 // [OtherCapture] -> [OtherCapture, VarName] 19648 FixBuffer.assign({Separator, Var->getName()}); 19649 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 19650 << Var << /*value*/ 0 19651 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 19652 } 19653 // As above but capture by reference. 19654 FixBuffer.assign({Separator, "&", Var->getName()}); 19655 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 19656 << Var << /*reference*/ 1 19657 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 19658 } 19659 19660 // Only try to offer default capture if there are no captures excluding this 19661 // and init captures. 19662 // [this]: OK. 19663 // [X = Y]: OK. 19664 // [&A, &B]: Don't offer. 19665 // [A, B]: Don't offer. 19666 if (llvm::any_of(LSI->Captures, [](Capture &C) { 19667 return !C.isThisCapture() && !C.isInitCapture(); 19668 })) 19669 return; 19670 19671 // The default capture specifiers, '=' or '&', must appear first in the 19672 // capture body. 19673 SourceLocation DefaultInsertLoc = 19674 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 19675 19676 if (ShouldOfferCopyFix) { 19677 bool CanDefaultCopyCapture = true; 19678 // [=, *this] OK since c++17 19679 // [=, this] OK since c++20 19680 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 19681 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 19682 ? LSI->getCXXThisCapture().isCopyCapture() 19683 : false; 19684 // We can't use default capture by copy if any captures already specified 19685 // capture by copy. 19686 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 19687 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 19688 })) { 19689 FixBuffer.assign({"=", Separator}); 19690 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 19691 << /*value*/ 0 19692 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 19693 } 19694 } 19695 19696 // We can't use default capture by reference if any captures already specified 19697 // capture by reference. 19698 if (llvm::none_of(LSI->Captures, [](Capture &C) { 19699 return !C.isInitCapture() && C.isReferenceCapture() && 19700 !C.isThisCapture(); 19701 })) { 19702 FixBuffer.assign({"&", Separator}); 19703 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 19704 << /*reference*/ 1 19705 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 19706 } 19707} 19708 19709bool Sema::tryCaptureVariable( 19710 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 19711 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 19712 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 19713 // An init-capture is notionally from the context surrounding its 19714 // declaration, but its parent DC is the lambda class. 19715 DeclContext *VarDC = Var->getDeclContext(); 19716 DeclContext *DC = CurContext; 19717 19718 // tryCaptureVariable is called every time a DeclRef is formed, 19719 // it can therefore have non-negigible impact on performances. 19720 // For local variables and when there is no capturing scope, 19721 // we can bailout early. 19722 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC)) 19723 return true; 19724 19725 const auto *VD = dyn_cast<VarDecl>(Var); 19726 if (VD) { 19727 if (VD->isInitCapture()) 19728 VarDC = VarDC->getParent(); 19729 } else { 19730 VD = Var->getPotentiallyDecomposedVarDecl(); 19731 } 19732 assert(VD && "Cannot capture a null variable"); 19733 19734 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 19735 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 19736 // We need to sync up the Declaration Context with the 19737 // FunctionScopeIndexToStopAt 19738 if (FunctionScopeIndexToStopAt) { 19739 unsigned FSIndex = FunctionScopes.size() - 1; 19740 while (FSIndex != MaxFunctionScopesIndex) { 19741 DC = getLambdaAwareParentOfDeclContext(DC); 19742 --FSIndex; 19743 } 19744 } 19745 19746 // Capture global variables if it is required to use private copy of this 19747 // variable. 19748 bool IsGlobal = !VD->hasLocalStorage(); 19749 if (IsGlobal && 19750 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 19751 MaxFunctionScopesIndex))) 19752 return true; 19753 19754 if (isa<VarDecl>(Var)) 19755 Var = cast<VarDecl>(Var->getCanonicalDecl()); 19756 19757 // Walk up the stack to determine whether we can capture the variable, 19758 // performing the "simple" checks that don't depend on type. We stop when 19759 // we've either hit the declared scope of the variable or find an existing 19760 // capture of that variable. We start from the innermost capturing-entity 19761 // (the DC) and ensure that all intervening capturing-entities 19762 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 19763 // declcontext can either capture the variable or have already captured 19764 // the variable. 19765 CaptureType = Var->getType(); 19766 DeclRefType = CaptureType.getNonReferenceType(); 19767 bool Nested = false; 19768 bool Explicit = (Kind != TryCapture_Implicit); 19769 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 19770 do { 19771 19772 LambdaScopeInfo *LSI = nullptr; 19773 if (!FunctionScopes.empty()) 19774 LSI = dyn_cast_or_null<LambdaScopeInfo>( 19775 FunctionScopes[FunctionScopesIndex]); 19776 19777 bool IsInScopeDeclarationContext = 19778 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator; 19779 19780 if (LSI && !LSI->AfterParameterList) { 19781 // This allows capturing parameters from a default value which does not 19782 // seems correct 19783 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod()) 19784 return true; 19785 } 19786 // If the variable is declared in the current context, there is no need to 19787 // capture it. 19788 if (IsInScopeDeclarationContext && 19789 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC) 19790 return true; 19791 19792 // Only block literals, captured statements, and lambda expressions can 19793 // capture; other scopes don't work. 19794 DeclContext *ParentDC = 19795 !IsInScopeDeclarationContext 19796 ? DC->getParent() 19797 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc, 19798 BuildAndDiagnose, *this); 19799 // We need to check for the parent *first* because, if we *have* 19800 // private-captured a global variable, we need to recursively capture it in 19801 // intermediate blocks, lambdas, etc. 19802 if (!ParentDC) { 19803 if (IsGlobal) { 19804 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 19805 break; 19806 } 19807 return true; 19808 } 19809 19810 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 19811 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 19812 19813 // Check whether we've already captured it. 19814 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 19815 DeclRefType)) { 19816 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 19817 break; 19818 } 19819 19820 // When evaluating some attributes (like enable_if) we might refer to a 19821 // function parameter appertaining to the same declaration as that 19822 // attribute. 19823 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var); 19824 Parm && Parm->getDeclContext() == DC) 19825 return true; 19826 19827 // If we are instantiating a generic lambda call operator body, 19828 // we do not want to capture new variables. What was captured 19829 // during either a lambdas transformation or initial parsing 19830 // should be used. 19831 if (isGenericLambdaCallOperatorSpecialization(DC)) { 19832 if (BuildAndDiagnose) { 19833 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 19834 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 19835 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 19836 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 19837 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 19838 buildLambdaCaptureFixit(*this, LSI, Var); 19839 } else 19840 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var); 19841 } 19842 return true; 19843 } 19844 19845 // Try to capture variable-length arrays types. 19846 if (Var->getType()->isVariablyModifiedType()) { 19847 // We're going to walk down into the type and look for VLA 19848 // expressions. 19849 QualType QTy = Var->getType(); 19850 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 19851 QTy = PVD->getOriginalType(); 19852 captureVariablyModifiedType(Context, QTy, CSI); 19853 } 19854 19855 if (getLangOpts().OpenMP) { 19856 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 19857 // OpenMP private variables should not be captured in outer scope, so 19858 // just break here. Similarly, global variables that are captured in a 19859 // target region should not be captured outside the scope of the region. 19860 if (RSI->CapRegionKind == CR_OpenMP) { 19861 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 19862 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 19863 // If the variable is private (i.e. not captured) and has variably 19864 // modified type, we still need to capture the type for correct 19865 // codegen in all regions, associated with the construct. Currently, 19866 // it is captured in the innermost captured region only. 19867 if (IsOpenMPPrivateDecl != OMPC_unknown && 19868 Var->getType()->isVariablyModifiedType()) { 19869 QualType QTy = Var->getType(); 19870 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 19871 QTy = PVD->getOriginalType(); 19872 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 19873 I < E; ++I) { 19874 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 19875 FunctionScopes[FunctionScopesIndex - I]); 19876 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 19877 "Wrong number of captured regions associated with the " 19878 "OpenMP construct."); 19879 captureVariablyModifiedType(Context, QTy, OuterRSI); 19880 } 19881 } 19882 bool IsTargetCap = 19883 IsOpenMPPrivateDecl != OMPC_private && 19884 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 19885 RSI->OpenMPCaptureLevel); 19886 // Do not capture global if it is not privatized in outer regions. 19887 bool IsGlobalCap = 19888 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 19889 RSI->OpenMPCaptureLevel); 19890 19891 // When we detect target captures we are looking from inside the 19892 // target region, therefore we need to propagate the capture from the 19893 // enclosing region. Therefore, the capture is not initially nested. 19894 if (IsTargetCap) 19895 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 19896 19897 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 19898 (IsGlobal && !IsGlobalCap)) { 19899 Nested = !IsTargetCap; 19900 bool HasConst = DeclRefType.isConstQualified(); 19901 DeclRefType = DeclRefType.getUnqualifiedType(); 19902 // Don't lose diagnostics about assignments to const. 19903 if (HasConst) 19904 DeclRefType.addConst(); 19905 CaptureType = Context.getLValueReferenceType(DeclRefType); 19906 break; 19907 } 19908 } 19909 } 19910 } 19911 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 19912 // No capture-default, and this is not an explicit capture 19913 // so cannot capture this variable. 19914 if (BuildAndDiagnose) { 19915 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 19916 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 19917 auto *LSI = cast<LambdaScopeInfo>(CSI); 19918 if (LSI->Lambda) { 19919 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 19920 buildLambdaCaptureFixit(*this, LSI, Var); 19921 } 19922 // FIXME: If we error out because an outer lambda can not implicitly 19923 // capture a variable that an inner lambda explicitly captures, we 19924 // should have the inner lambda do the explicit capture - because 19925 // it makes for cleaner diagnostics later. This would purely be done 19926 // so that the diagnostic does not misleadingly claim that a variable 19927 // can not be captured by a lambda implicitly even though it is captured 19928 // explicitly. Suggestion: 19929 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 19930 // at the function head 19931 // - cache the StartingDeclContext - this must be a lambda 19932 // - captureInLambda in the innermost lambda the variable. 19933 } 19934 return true; 19935 } 19936 Explicit = false; 19937 FunctionScopesIndex--; 19938 if (IsInScopeDeclarationContext) 19939 DC = ParentDC; 19940 } while (!VarDC->Equals(DC)); 19941 19942 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 19943 // computing the type of the capture at each step, checking type-specific 19944 // requirements, and adding captures if requested. 19945 // If the variable had already been captured previously, we start capturing 19946 // at the lambda nested within that one. 19947 bool Invalid = false; 19948 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 19949 ++I) { 19950 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 19951 19952 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 19953 // certain types of variables (unnamed, variably modified types etc.) 19954 // so check for eligibility. 19955 if (!Invalid) 19956 Invalid = 19957 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 19958 19959 // After encountering an error, if we're actually supposed to capture, keep 19960 // capturing in nested contexts to suppress any follow-on diagnostics. 19961 if (Invalid && !BuildAndDiagnose) 19962 return true; 19963 19964 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 19965 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 19966 DeclRefType, Nested, *this, Invalid); 19967 Nested = true; 19968 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 19969 Invalid = !captureInCapturedRegion( 19970 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 19971 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 19972 Nested = true; 19973 } else { 19974 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 19975 Invalid = 19976 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 19977 DeclRefType, Nested, Kind, EllipsisLoc, 19978 /*IsTopScope*/ I == N - 1, *this, Invalid); 19979 Nested = true; 19980 } 19981 19982 if (Invalid && !BuildAndDiagnose) 19983 return true; 19984 } 19985 return Invalid; 19986} 19987 19988bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, 19989 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 19990 QualType CaptureType; 19991 QualType DeclRefType; 19992 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 19993 /*BuildAndDiagnose=*/true, CaptureType, 19994 DeclRefType, nullptr); 19995} 19996 19997bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) { 19998 QualType CaptureType; 19999 QualType DeclRefType; 20000 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 20001 /*BuildAndDiagnose=*/false, CaptureType, 20002 DeclRefType, nullptr); 20003} 20004 20005QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) { 20006 QualType CaptureType; 20007 QualType DeclRefType; 20008 20009 // Determine whether we can capture this variable. 20010 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 20011 /*BuildAndDiagnose=*/false, CaptureType, 20012 DeclRefType, nullptr)) 20013 return QualType(); 20014 20015 return DeclRefType; 20016} 20017 20018namespace { 20019// Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 20020// The produced TemplateArgumentListInfo* points to data stored within this 20021// object, so should only be used in contexts where the pointer will not be 20022// used after the CopiedTemplateArgs object is destroyed. 20023class CopiedTemplateArgs { 20024 bool HasArgs; 20025 TemplateArgumentListInfo TemplateArgStorage; 20026public: 20027 template<typename RefExpr> 20028 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 20029 if (HasArgs) 20030 E->copyTemplateArgumentsInto(TemplateArgStorage); 20031 } 20032 operator TemplateArgumentListInfo*() 20033#ifdef __has_cpp_attribute 20034#if __has_cpp_attribute(clang::lifetimebound) 20035 [[clang::lifetimebound]] 20036#endif 20037#endif 20038 { 20039 return HasArgs ? &TemplateArgStorage : nullptr; 20040 } 20041}; 20042} 20043 20044/// Walk the set of potential results of an expression and mark them all as 20045/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 20046/// 20047/// \return A new expression if we found any potential results, ExprEmpty() if 20048/// not, and ExprError() if we diagnosed an error. 20049static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 20050 NonOdrUseReason NOUR) { 20051 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 20052 // an object that satisfies the requirements for appearing in a 20053 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 20054 // is immediately applied." This function handles the lvalue-to-rvalue 20055 // conversion part. 20056 // 20057 // If we encounter a node that claims to be an odr-use but shouldn't be, we 20058 // transform it into the relevant kind of non-odr-use node and rebuild the 20059 // tree of nodes leading to it. 20060 // 20061 // This is a mini-TreeTransform that only transforms a restricted subset of 20062 // nodes (and only certain operands of them). 20063 20064 // Rebuild a subexpression. 20065 auto Rebuild = [&](Expr *Sub) { 20066 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 20067 }; 20068 20069 // Check whether a potential result satisfies the requirements of NOUR. 20070 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 20071 // Any entity other than a VarDecl is always odr-used whenever it's named 20072 // in a potentially-evaluated expression. 20073 auto *VD = dyn_cast<VarDecl>(D); 20074 if (!VD) 20075 return true; 20076 20077 // C++2a [basic.def.odr]p4: 20078 // A variable x whose name appears as a potentially-evalauted expression 20079 // e is odr-used by e unless 20080 // -- x is a reference that is usable in constant expressions, or 20081 // -- x is a variable of non-reference type that is usable in constant 20082 // expressions and has no mutable subobjects, and e is an element of 20083 // the set of potential results of an expression of 20084 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 20085 // conversion is applied, or 20086 // -- x is a variable of non-reference type, and e is an element of the 20087 // set of potential results of a discarded-value expression to which 20088 // the lvalue-to-rvalue conversion is not applied 20089 // 20090 // We check the first bullet and the "potentially-evaluated" condition in 20091 // BuildDeclRefExpr. We check the type requirements in the second bullet 20092 // in CheckLValueToRValueConversionOperand below. 20093 switch (NOUR) { 20094 case NOUR_None: 20095 case NOUR_Unevaluated: 20096 llvm_unreachable("unexpected non-odr-use-reason"); 20097 20098 case NOUR_Constant: 20099 // Constant references were handled when they were built. 20100 if (VD->getType()->isReferenceType()) 20101 return true; 20102 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 20103 if (RD->hasMutableFields()) 20104 return true; 20105 if (!VD->isUsableInConstantExpressions(S.Context)) 20106 return true; 20107 break; 20108 20109 case NOUR_Discarded: 20110 if (VD->getType()->isReferenceType()) 20111 return true; 20112 break; 20113 } 20114 return false; 20115 }; 20116 20117 // Mark that this expression does not constitute an odr-use. 20118 auto MarkNotOdrUsed = [&] { 20119 S.MaybeODRUseExprs.remove(E); 20120 if (LambdaScopeInfo *LSI = S.getCurLambda()) 20121 LSI->markVariableExprAsNonODRUsed(E); 20122 }; 20123 20124 // C++2a [basic.def.odr]p2: 20125 // The set of potential results of an expression e is defined as follows: 20126 switch (E->getStmtClass()) { 20127 // -- If e is an id-expression, ... 20128 case Expr::DeclRefExprClass: { 20129 auto *DRE = cast<DeclRefExpr>(E); 20130 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 20131 break; 20132 20133 // Rebuild as a non-odr-use DeclRefExpr. 20134 MarkNotOdrUsed(); 20135 return DeclRefExpr::Create( 20136 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 20137 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 20138 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 20139 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 20140 } 20141 20142 case Expr::FunctionParmPackExprClass: { 20143 auto *FPPE = cast<FunctionParmPackExpr>(E); 20144 // If any of the declarations in the pack is odr-used, then the expression 20145 // as a whole constitutes an odr-use. 20146 for (VarDecl *D : *FPPE) 20147 if (IsPotentialResultOdrUsed(D)) 20148 return ExprEmpty(); 20149 20150 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 20151 // nothing cares about whether we marked this as an odr-use, but it might 20152 // be useful for non-compiler tools. 20153 MarkNotOdrUsed(); 20154 break; 20155 } 20156 20157 // -- If e is a subscripting operation with an array operand... 20158 case Expr::ArraySubscriptExprClass: { 20159 auto *ASE = cast<ArraySubscriptExpr>(E); 20160 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 20161 if (!OldBase->getType()->isArrayType()) 20162 break; 20163 ExprResult Base = Rebuild(OldBase); 20164 if (!Base.isUsable()) 20165 return Base; 20166 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 20167 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 20168 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 20169 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 20170 ASE->getRBracketLoc()); 20171 } 20172 20173 case Expr::MemberExprClass: { 20174 auto *ME = cast<MemberExpr>(E); 20175 // -- If e is a class member access expression [...] naming a non-static 20176 // data member... 20177 if (isa<FieldDecl>(ME->getMemberDecl())) { 20178 ExprResult Base = Rebuild(ME->getBase()); 20179 if (!Base.isUsable()) 20180 return Base; 20181 return MemberExpr::Create( 20182 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 20183 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 20184 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 20185 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 20186 ME->getObjectKind(), ME->isNonOdrUse()); 20187 } 20188 20189 if (ME->getMemberDecl()->isCXXInstanceMember()) 20190 break; 20191 20192 // -- If e is a class member access expression naming a static data member, 20193 // ... 20194 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 20195 break; 20196 20197 // Rebuild as a non-odr-use MemberExpr. 20198 MarkNotOdrUsed(); 20199 return MemberExpr::Create( 20200 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 20201 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 20202 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 20203 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 20204 } 20205 20206 case Expr::BinaryOperatorClass: { 20207 auto *BO = cast<BinaryOperator>(E); 20208 Expr *LHS = BO->getLHS(); 20209 Expr *RHS = BO->getRHS(); 20210 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 20211 if (BO->getOpcode() == BO_PtrMemD) { 20212 ExprResult Sub = Rebuild(LHS); 20213 if (!Sub.isUsable()) 20214 return Sub; 20215 LHS = Sub.get(); 20216 // -- If e is a comma expression, ... 20217 } else if (BO->getOpcode() == BO_Comma) { 20218 ExprResult Sub = Rebuild(RHS); 20219 if (!Sub.isUsable()) 20220 return Sub; 20221 RHS = Sub.get(); 20222 } else { 20223 break; 20224 } 20225 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 20226 LHS, RHS); 20227 } 20228 20229 // -- If e has the form (e1)... 20230 case Expr::ParenExprClass: { 20231 auto *PE = cast<ParenExpr>(E); 20232 ExprResult Sub = Rebuild(PE->getSubExpr()); 20233 if (!Sub.isUsable()) 20234 return Sub; 20235 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 20236 } 20237 20238 // -- If e is a glvalue conditional expression, ... 20239 // We don't apply this to a binary conditional operator. FIXME: Should we? 20240 case Expr::ConditionalOperatorClass: { 20241 auto *CO = cast<ConditionalOperator>(E); 20242 ExprResult LHS = Rebuild(CO->getLHS()); 20243 if (LHS.isInvalid()) 20244 return ExprError(); 20245 ExprResult RHS = Rebuild(CO->getRHS()); 20246 if (RHS.isInvalid()) 20247 return ExprError(); 20248 if (!LHS.isUsable() && !RHS.isUsable()) 20249 return ExprEmpty(); 20250 if (!LHS.isUsable()) 20251 LHS = CO->getLHS(); 20252 if (!RHS.isUsable()) 20253 RHS = CO->getRHS(); 20254 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 20255 CO->getCond(), LHS.get(), RHS.get()); 20256 } 20257 20258 // [Clang extension] 20259 // -- If e has the form __extension__ e1... 20260 case Expr::UnaryOperatorClass: { 20261 auto *UO = cast<UnaryOperator>(E); 20262 if (UO->getOpcode() != UO_Extension) 20263 break; 20264 ExprResult Sub = Rebuild(UO->getSubExpr()); 20265 if (!Sub.isUsable()) 20266 return Sub; 20267 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 20268 Sub.get()); 20269 } 20270 20271 // [Clang extension] 20272 // -- If e has the form _Generic(...), the set of potential results is the 20273 // union of the sets of potential results of the associated expressions. 20274 case Expr::GenericSelectionExprClass: { 20275 auto *GSE = cast<GenericSelectionExpr>(E); 20276 20277 SmallVector<Expr *, 4> AssocExprs; 20278 bool AnyChanged = false; 20279 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 20280 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 20281 if (AssocExpr.isInvalid()) 20282 return ExprError(); 20283 if (AssocExpr.isUsable()) { 20284 AssocExprs.push_back(AssocExpr.get()); 20285 AnyChanged = true; 20286 } else { 20287 AssocExprs.push_back(OrigAssocExpr); 20288 } 20289 } 20290 20291 void *ExOrTy = nullptr; 20292 bool IsExpr = GSE->isExprPredicate(); 20293 if (IsExpr) 20294 ExOrTy = GSE->getControllingExpr(); 20295 else 20296 ExOrTy = GSE->getControllingType(); 20297 return AnyChanged ? S.CreateGenericSelectionExpr( 20298 GSE->getGenericLoc(), GSE->getDefaultLoc(), 20299 GSE->getRParenLoc(), IsExpr, ExOrTy, 20300 GSE->getAssocTypeSourceInfos(), AssocExprs) 20301 : ExprEmpty(); 20302 } 20303 20304 // [Clang extension] 20305 // -- If e has the form __builtin_choose_expr(...), the set of potential 20306 // results is the union of the sets of potential results of the 20307 // second and third subexpressions. 20308 case Expr::ChooseExprClass: { 20309 auto *CE = cast<ChooseExpr>(E); 20310 20311 ExprResult LHS = Rebuild(CE->getLHS()); 20312 if (LHS.isInvalid()) 20313 return ExprError(); 20314 20315 ExprResult RHS = Rebuild(CE->getLHS()); 20316 if (RHS.isInvalid()) 20317 return ExprError(); 20318 20319 if (!LHS.get() && !RHS.get()) 20320 return ExprEmpty(); 20321 if (!LHS.isUsable()) 20322 LHS = CE->getLHS(); 20323 if (!RHS.isUsable()) 20324 RHS = CE->getRHS(); 20325 20326 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 20327 RHS.get(), CE->getRParenLoc()); 20328 } 20329 20330 // Step through non-syntactic nodes. 20331 case Expr::ConstantExprClass: { 20332 auto *CE = cast<ConstantExpr>(E); 20333 ExprResult Sub = Rebuild(CE->getSubExpr()); 20334 if (!Sub.isUsable()) 20335 return Sub; 20336 return ConstantExpr::Create(S.Context, Sub.get()); 20337 } 20338 20339 // We could mostly rely on the recursive rebuilding to rebuild implicit 20340 // casts, but not at the top level, so rebuild them here. 20341 case Expr::ImplicitCastExprClass: { 20342 auto *ICE = cast<ImplicitCastExpr>(E); 20343 // Only step through the narrow set of cast kinds we expect to encounter. 20344 // Anything else suggests we've left the region in which potential results 20345 // can be found. 20346 switch (ICE->getCastKind()) { 20347 case CK_NoOp: 20348 case CK_DerivedToBase: 20349 case CK_UncheckedDerivedToBase: { 20350 ExprResult Sub = Rebuild(ICE->getSubExpr()); 20351 if (!Sub.isUsable()) 20352 return Sub; 20353 CXXCastPath Path(ICE->path()); 20354 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 20355 ICE->getValueKind(), &Path); 20356 } 20357 20358 default: 20359 break; 20360 } 20361 break; 20362 } 20363 20364 default: 20365 break; 20366 } 20367 20368 // Can't traverse through this node. Nothing to do. 20369 return ExprEmpty(); 20370} 20371 20372ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 20373 // Check whether the operand is or contains an object of non-trivial C union 20374 // type. 20375 if (E->getType().isVolatileQualified() && 20376 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 20377 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 20378 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 20379 Sema::NTCUC_LValueToRValueVolatile, 20380 NTCUK_Destruct|NTCUK_Copy); 20381 20382 // C++2a [basic.def.odr]p4: 20383 // [...] an expression of non-volatile-qualified non-class type to which 20384 // the lvalue-to-rvalue conversion is applied [...] 20385 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 20386 return E; 20387 20388 ExprResult Result = 20389 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 20390 if (Result.isInvalid()) 20391 return ExprError(); 20392 return Result.get() ? Result : E; 20393} 20394 20395ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 20396 Res = CorrectDelayedTyposInExpr(Res); 20397 20398 if (!Res.isUsable()) 20399 return Res; 20400 20401 // If a constant-expression is a reference to a variable where we delay 20402 // deciding whether it is an odr-use, just assume we will apply the 20403 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 20404 // (a non-type template argument), we have special handling anyway. 20405 return CheckLValueToRValueConversionOperand(Res.get()); 20406} 20407 20408void Sema::CleanupVarDeclMarking() { 20409 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 20410 // call. 20411 MaybeODRUseExprSet LocalMaybeODRUseExprs; 20412 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 20413 20414 for (Expr *E : LocalMaybeODRUseExprs) { 20415 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 20416 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 20417 DRE->getLocation(), *this); 20418 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 20419 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 20420 *this); 20421 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 20422 for (VarDecl *VD : *FP) 20423 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 20424 } else { 20425 llvm_unreachable("Unexpected expression"); 20426 } 20427 } 20428 20429 assert(MaybeODRUseExprs.empty() && 20430 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 20431} 20432 20433static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, 20434 ValueDecl *Var, Expr *E) { 20435 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl(); 20436 if (!VD) 20437 return; 20438 20439 const bool RefersToEnclosingScope = 20440 (SemaRef.CurContext != VD->getDeclContext() && 20441 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage()); 20442 if (RefersToEnclosingScope) { 20443 LambdaScopeInfo *const LSI = 20444 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 20445 if (LSI && (!LSI->CallOperator || 20446 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 20447 // If a variable could potentially be odr-used, defer marking it so 20448 // until we finish analyzing the full expression for any 20449 // lvalue-to-rvalue 20450 // or discarded value conversions that would obviate odr-use. 20451 // Add it to the list of potential captures that will be analyzed 20452 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 20453 // unless the variable is a reference that was initialized by a constant 20454 // expression (this will never need to be captured or odr-used). 20455 // 20456 // FIXME: We can simplify this a lot after implementing P0588R1. 20457 assert(E && "Capture variable should be used in an expression."); 20458 if (!Var->getType()->isReferenceType() || 20459 !VD->isUsableInConstantExpressions(SemaRef.Context)) 20460 LSI->addPotentialCapture(E->IgnoreParens()); 20461 } 20462 } 20463} 20464 20465static void DoMarkVarDeclReferenced( 20466 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 20467 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 20468 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 20469 isa<FunctionParmPackExpr>(E)) && 20470 "Invalid Expr argument to DoMarkVarDeclReferenced"); 20471 Var->setReferenced(); 20472 20473 if (Var->isInvalidDecl()) 20474 return; 20475 20476 auto *MSI = Var->getMemberSpecializationInfo(); 20477 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 20478 : Var->getTemplateSpecializationKind(); 20479 20480 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 20481 bool UsableInConstantExpr = 20482 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 20483 20484 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 20485 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 20486 } 20487 20488 // C++20 [expr.const]p12: 20489 // A variable [...] is needed for constant evaluation if it is [...] a 20490 // variable whose name appears as a potentially constant evaluated 20491 // expression that is either a contexpr variable or is of non-volatile 20492 // const-qualified integral type or of reference type 20493 bool NeededForConstantEvaluation = 20494 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 20495 20496 bool NeedDefinition = 20497 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 20498 20499 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 20500 "Can't instantiate a partial template specialization."); 20501 20502 // If this might be a member specialization of a static data member, check 20503 // the specialization is visible. We already did the checks for variable 20504 // template specializations when we created them. 20505 if (NeedDefinition && TSK != TSK_Undeclared && 20506 !isa<VarTemplateSpecializationDecl>(Var)) 20507 SemaRef.checkSpecializationVisibility(Loc, Var); 20508 20509 // Perform implicit instantiation of static data members, static data member 20510 // templates of class templates, and variable template specializations. Delay 20511 // instantiations of variable templates, except for those that could be used 20512 // in a constant expression. 20513 if (NeedDefinition && isTemplateInstantiation(TSK)) { 20514 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 20515 // instantiation declaration if a variable is usable in a constant 20516 // expression (among other cases). 20517 bool TryInstantiating = 20518 TSK == TSK_ImplicitInstantiation || 20519 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 20520 20521 if (TryInstantiating) { 20522 SourceLocation PointOfInstantiation = 20523 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 20524 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 20525 if (FirstInstantiation) { 20526 PointOfInstantiation = Loc; 20527 if (MSI) 20528 MSI->setPointOfInstantiation(PointOfInstantiation); 20529 // FIXME: Notify listener. 20530 else 20531 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 20532 } 20533 20534 if (UsableInConstantExpr) { 20535 // Do not defer instantiations of variables that could be used in a 20536 // constant expression. 20537 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 20538 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 20539 }); 20540 20541 // Re-set the member to trigger a recomputation of the dependence bits 20542 // for the expression. 20543 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 20544 DRE->setDecl(DRE->getDecl()); 20545 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 20546 ME->setMemberDecl(ME->getMemberDecl()); 20547 } else if (FirstInstantiation) { 20548 SemaRef.PendingInstantiations 20549 .push_back(std::make_pair(Var, PointOfInstantiation)); 20550 } else { 20551 bool Inserted = false; 20552 for (auto &I : SemaRef.SavedPendingInstantiations) { 20553 auto Iter = llvm::find_if( 20554 I, [Var](const Sema::PendingImplicitInstantiation &P) { 20555 return P.first == Var; 20556 }); 20557 if (Iter != I.end()) { 20558 SemaRef.PendingInstantiations.push_back(*Iter); 20559 I.erase(Iter); 20560 Inserted = true; 20561 break; 20562 } 20563 } 20564 20565 // FIXME: For a specialization of a variable template, we don't 20566 // distinguish between "declaration and type implicitly instantiated" 20567 // and "implicit instantiation of definition requested", so we have 20568 // no direct way to avoid enqueueing the pending instantiation 20569 // multiple times. 20570 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted) 20571 SemaRef.PendingInstantiations 20572 .push_back(std::make_pair(Var, PointOfInstantiation)); 20573 } 20574 } 20575 } 20576 20577 // C++2a [basic.def.odr]p4: 20578 // A variable x whose name appears as a potentially-evaluated expression e 20579 // is odr-used by e unless 20580 // -- x is a reference that is usable in constant expressions 20581 // -- x is a variable of non-reference type that is usable in constant 20582 // expressions and has no mutable subobjects [FIXME], and e is an 20583 // element of the set of potential results of an expression of 20584 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 20585 // conversion is applied 20586 // -- x is a variable of non-reference type, and e is an element of the set 20587 // of potential results of a discarded-value expression to which the 20588 // lvalue-to-rvalue conversion is not applied [FIXME] 20589 // 20590 // We check the first part of the second bullet here, and 20591 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 20592 // FIXME: To get the third bullet right, we need to delay this even for 20593 // variables that are not usable in constant expressions. 20594 20595 // If we already know this isn't an odr-use, there's nothing more to do. 20596 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 20597 if (DRE->isNonOdrUse()) 20598 return; 20599 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 20600 if (ME->isNonOdrUse()) 20601 return; 20602 20603 switch (OdrUse) { 20604 case OdrUseContext::None: 20605 // In some cases, a variable may not have been marked unevaluated, if it 20606 // appears in a defaukt initializer. 20607 assert((!E || isa<FunctionParmPackExpr>(E) || 20608 SemaRef.isUnevaluatedContext()) && 20609 "missing non-odr-use marking for unevaluated decl ref"); 20610 break; 20611 20612 case OdrUseContext::FormallyOdrUsed: 20613 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 20614 // behavior. 20615 break; 20616 20617 case OdrUseContext::Used: 20618 // If we might later find that this expression isn't actually an odr-use, 20619 // delay the marking. 20620 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 20621 SemaRef.MaybeODRUseExprs.insert(E); 20622 else 20623 MarkVarDeclODRUsed(Var, Loc, SemaRef); 20624 break; 20625 20626 case OdrUseContext::Dependent: 20627 // If this is a dependent context, we don't need to mark variables as 20628 // odr-used, but we may still need to track them for lambda capture. 20629 // FIXME: Do we also need to do this inside dependent typeid expressions 20630 // (which are modeled as unevaluated at this point)? 20631 DoMarkPotentialCapture(SemaRef, Loc, Var, E); 20632 break; 20633 } 20634} 20635 20636static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, 20637 BindingDecl *BD, Expr *E) { 20638 BD->setReferenced(); 20639 20640 if (BD->isInvalidDecl()) 20641 return; 20642 20643 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 20644 if (OdrUse == OdrUseContext::Used) { 20645 QualType CaptureType, DeclRefType; 20646 SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit, 20647 /*EllipsisLoc*/ SourceLocation(), 20648 /*BuildAndDiagnose*/ true, CaptureType, 20649 DeclRefType, 20650 /*FunctionScopeIndexToStopAt*/ nullptr); 20651 } else if (OdrUse == OdrUseContext::Dependent) { 20652 DoMarkPotentialCapture(SemaRef, Loc, BD, E); 20653 } 20654} 20655 20656/// Mark a variable referenced, and check whether it is odr-used 20657/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 20658/// used directly for normal expressions referring to VarDecl. 20659void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 20660 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 20661} 20662 20663// C++ [temp.dep.expr]p3: 20664// An id-expression is type-dependent if it contains: 20665// - an identifier associated by name lookup with an entity captured by copy 20666// in a lambda-expression that has an explicit object parameter whose type 20667// is dependent ([dcl.fct]), 20668static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter( 20669 Sema &SemaRef, ValueDecl *D, Expr *E) { 20670 auto *ID = dyn_cast<DeclRefExpr>(E); 20671 if (!ID || ID->isTypeDependent()) 20672 return; 20673 20674 auto IsDependent = [&]() { 20675 const LambdaScopeInfo *LSI = SemaRef.getCurLambda(); 20676 if (!LSI) 20677 return false; 20678 if (!LSI->ExplicitObjectParameter || 20679 !LSI->ExplicitObjectParameter->getType()->isDependentType()) 20680 return false; 20681 if (!LSI->CaptureMap.count(D)) 20682 return false; 20683 const Capture &Cap = LSI->getCapture(D); 20684 return !Cap.isCopyCapture(); 20685 }(); 20686 20687 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter( 20688 IsDependent, SemaRef.getASTContext()); 20689} 20690 20691static void 20692MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 20693 bool MightBeOdrUse, 20694 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 20695 if (SemaRef.isInOpenMPDeclareTargetContext()) 20696 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 20697 20698 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 20699 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 20700 if (SemaRef.getLangOpts().CPlusPlus) 20701 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef, 20702 Var, E); 20703 return; 20704 } 20705 20706 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) { 20707 DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E); 20708 if (SemaRef.getLangOpts().CPlusPlus) 20709 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef, 20710 Decl, E); 20711 return; 20712 } 20713 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 20714 20715 // If this is a call to a method via a cast, also mark the method in the 20716 // derived class used in case codegen can devirtualize the call. 20717 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 20718 if (!ME) 20719 return; 20720 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 20721 if (!MD) 20722 return; 20723 // Only attempt to devirtualize if this is truly a virtual call. 20724 bool IsVirtualCall = MD->isVirtual() && 20725 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 20726 if (!IsVirtualCall) 20727 return; 20728 20729 // If it's possible to devirtualize the call, mark the called function 20730 // referenced. 20731 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 20732 ME->getBase(), SemaRef.getLangOpts().AppleKext); 20733 if (DM) 20734 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 20735} 20736 20737/// Perform reference-marking and odr-use handling for a DeclRefExpr. 20738/// 20739/// Note, this may change the dependence of the DeclRefExpr, and so needs to be 20740/// handled with care if the DeclRefExpr is not newly-created. 20741void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 20742 // TODO: update this with DR# once a defect report is filed. 20743 // C++11 defect. The address of a pure member should not be an ODR use, even 20744 // if it's a qualified reference. 20745 bool OdrUse = true; 20746 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 20747 if (Method->isVirtual() && 20748 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 20749 OdrUse = false; 20750 20751 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) { 20752 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() && 20753 !isImmediateFunctionContext() && 20754 !isCheckingDefaultArgumentOrInitializer() && 20755 FD->isImmediateFunction() && !RebuildingImmediateInvocation && 20756 !FD->isDependentContext()) 20757 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 20758 } 20759 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 20760 RefsMinusAssignments); 20761} 20762 20763/// Perform reference-marking and odr-use handling for a MemberExpr. 20764void Sema::MarkMemberReferenced(MemberExpr *E) { 20765 // C++11 [basic.def.odr]p2: 20766 // A non-overloaded function whose name appears as a potentially-evaluated 20767 // expression or a member of a set of candidate functions, if selected by 20768 // overload resolution when referred to from a potentially-evaluated 20769 // expression, is odr-used, unless it is a pure virtual function and its 20770 // name is not explicitly qualified. 20771 bool MightBeOdrUse = true; 20772 if (E->performsVirtualDispatch(getLangOpts())) { 20773 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 20774 if (Method->isPureVirtual()) 20775 MightBeOdrUse = false; 20776 } 20777 SourceLocation Loc = 20778 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 20779 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 20780 RefsMinusAssignments); 20781} 20782 20783/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 20784void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 20785 for (VarDecl *VD : *E) 20786 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 20787 RefsMinusAssignments); 20788} 20789 20790/// Perform marking for a reference to an arbitrary declaration. It 20791/// marks the declaration referenced, and performs odr-use checking for 20792/// functions and variables. This method should not be used when building a 20793/// normal expression which refers to a variable. 20794void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 20795 bool MightBeOdrUse) { 20796 if (MightBeOdrUse) { 20797 if (auto *VD = dyn_cast<VarDecl>(D)) { 20798 MarkVariableReferenced(Loc, VD); 20799 return; 20800 } 20801 } 20802 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 20803 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 20804 return; 20805 } 20806 D->setReferenced(); 20807} 20808 20809namespace { 20810 // Mark all of the declarations used by a type as referenced. 20811 // FIXME: Not fully implemented yet! We need to have a better understanding 20812 // of when we're entering a context we should not recurse into. 20813 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 20814 // TreeTransforms rebuilding the type in a new context. Rather than 20815 // duplicating the TreeTransform logic, we should consider reusing it here. 20816 // Currently that causes problems when rebuilding LambdaExprs. 20817 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 20818 Sema &S; 20819 SourceLocation Loc; 20820 20821 public: 20822 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 20823 20824 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 20825 20826 bool TraverseTemplateArgument(const TemplateArgument &Arg); 20827 }; 20828} 20829 20830bool MarkReferencedDecls::TraverseTemplateArgument( 20831 const TemplateArgument &Arg) { 20832 { 20833 // A non-type template argument is a constant-evaluated context. 20834 EnterExpressionEvaluationContext Evaluated( 20835 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 20836 if (Arg.getKind() == TemplateArgument::Declaration) { 20837 if (Decl *D = Arg.getAsDecl()) 20838 S.MarkAnyDeclReferenced(Loc, D, true); 20839 } else if (Arg.getKind() == TemplateArgument::Expression) { 20840 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 20841 } 20842 } 20843 20844 return Inherited::TraverseTemplateArgument(Arg); 20845} 20846 20847void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 20848 MarkReferencedDecls Marker(*this, Loc); 20849 Marker.TraverseType(T); 20850} 20851 20852namespace { 20853/// Helper class that marks all of the declarations referenced by 20854/// potentially-evaluated subexpressions as "referenced". 20855class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 20856public: 20857 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 20858 bool SkipLocalVariables; 20859 ArrayRef<const Expr *> StopAt; 20860 20861 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 20862 ArrayRef<const Expr *> StopAt) 20863 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 20864 20865 void visitUsedDecl(SourceLocation Loc, Decl *D) { 20866 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 20867 } 20868 20869 void Visit(Expr *E) { 20870 if (llvm::is_contained(StopAt, E)) 20871 return; 20872 Inherited::Visit(E); 20873 } 20874 20875 void VisitConstantExpr(ConstantExpr *E) { 20876 // Don't mark declarations within a ConstantExpression, as this expression 20877 // will be evaluated and folded to a value. 20878 } 20879 20880 void VisitDeclRefExpr(DeclRefExpr *E) { 20881 // If we were asked not to visit local variables, don't. 20882 if (SkipLocalVariables) { 20883 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 20884 if (VD->hasLocalStorage()) 20885 return; 20886 } 20887 20888 // FIXME: This can trigger the instantiation of the initializer of a 20889 // variable, which can cause the expression to become value-dependent 20890 // or error-dependent. Do we need to propagate the new dependence bits? 20891 S.MarkDeclRefReferenced(E); 20892 } 20893 20894 void VisitMemberExpr(MemberExpr *E) { 20895 S.MarkMemberReferenced(E); 20896 Visit(E->getBase()); 20897 } 20898}; 20899} // namespace 20900 20901/// Mark any declarations that appear within this expression or any 20902/// potentially-evaluated subexpressions as "referenced". 20903/// 20904/// \param SkipLocalVariables If true, don't mark local variables as 20905/// 'referenced'. 20906/// \param StopAt Subexpressions that we shouldn't recurse into. 20907void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 20908 bool SkipLocalVariables, 20909 ArrayRef<const Expr*> StopAt) { 20910 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 20911} 20912 20913/// Emit a diagnostic when statements are reachable. 20914/// FIXME: check for reachability even in expressions for which we don't build a 20915/// CFG (eg, in the initializer of a global or in a constant expression). 20916/// For example, 20917/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 20918bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 20919 const PartialDiagnostic &PD) { 20920 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 20921 if (!FunctionScopes.empty()) 20922 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 20923 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 20924 return true; 20925 } 20926 20927 // The initializer of a constexpr variable or of the first declaration of a 20928 // static data member is not syntactically a constant evaluated constant, 20929 // but nonetheless is always required to be a constant expression, so we 20930 // can skip diagnosing. 20931 // FIXME: Using the mangling context here is a hack. 20932 if (auto *VD = dyn_cast_or_null<VarDecl>( 20933 ExprEvalContexts.back().ManglingContextDecl)) { 20934 if (VD->isConstexpr() || 20935 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 20936 return false; 20937 // FIXME: For any other kind of variable, we should build a CFG for its 20938 // initializer and check whether the context in question is reachable. 20939 } 20940 20941 Diag(Loc, PD); 20942 return true; 20943} 20944 20945/// Emit a diagnostic that describes an effect on the run-time behavior 20946/// of the program being compiled. 20947/// 20948/// This routine emits the given diagnostic when the code currently being 20949/// type-checked is "potentially evaluated", meaning that there is a 20950/// possibility that the code will actually be executable. Code in sizeof() 20951/// expressions, code used only during overload resolution, etc., are not 20952/// potentially evaluated. This routine will suppress such diagnostics or, 20953/// in the absolutely nutty case of potentially potentially evaluated 20954/// expressions (C++ typeid), queue the diagnostic to potentially emit it 20955/// later. 20956/// 20957/// This routine should be used for all diagnostics that describe the run-time 20958/// behavior of a program, such as passing a non-POD value through an ellipsis. 20959/// Failure to do so will likely result in spurious diagnostics or failures 20960/// during overload resolution or within sizeof/alignof/typeof/typeid. 20961bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 20962 const PartialDiagnostic &PD) { 20963 20964 if (ExprEvalContexts.back().isDiscardedStatementContext()) 20965 return false; 20966 20967 switch (ExprEvalContexts.back().Context) { 20968 case ExpressionEvaluationContext::Unevaluated: 20969 case ExpressionEvaluationContext::UnevaluatedList: 20970 case ExpressionEvaluationContext::UnevaluatedAbstract: 20971 case ExpressionEvaluationContext::DiscardedStatement: 20972 // The argument will never be evaluated, so don't complain. 20973 break; 20974 20975 case ExpressionEvaluationContext::ConstantEvaluated: 20976 case ExpressionEvaluationContext::ImmediateFunctionContext: 20977 // Relevant diagnostics should be produced by constant evaluation. 20978 break; 20979 20980 case ExpressionEvaluationContext::PotentiallyEvaluated: 20981 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 20982 return DiagIfReachable(Loc, Stmts, PD); 20983 } 20984 20985 return false; 20986} 20987 20988bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 20989 const PartialDiagnostic &PD) { 20990 return DiagRuntimeBehavior( 20991 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD); 20992} 20993 20994bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 20995 CallExpr *CE, FunctionDecl *FD) { 20996 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 20997 return false; 20998 20999 // If we're inside a decltype's expression, don't check for a valid return 21000 // type or construct temporaries until we know whether this is the last call. 21001 if (ExprEvalContexts.back().ExprContext == 21002 ExpressionEvaluationContextRecord::EK_Decltype) { 21003 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 21004 return false; 21005 } 21006 21007 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 21008 FunctionDecl *FD; 21009 CallExpr *CE; 21010 21011 public: 21012 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 21013 : FD(FD), CE(CE) { } 21014 21015 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 21016 if (!FD) { 21017 S.Diag(Loc, diag::err_call_incomplete_return) 21018 << T << CE->getSourceRange(); 21019 return; 21020 } 21021 21022 S.Diag(Loc, diag::err_call_function_incomplete_return) 21023 << CE->getSourceRange() << FD << T; 21024 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 21025 << FD->getDeclName(); 21026 } 21027 } Diagnoser(FD, CE); 21028 21029 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 21030 return true; 21031 21032 return false; 21033} 21034 21035// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 21036// will prevent this condition from triggering, which is what we want. 21037void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 21038 SourceLocation Loc; 21039 21040 unsigned diagnostic = diag::warn_condition_is_assignment; 21041 bool IsOrAssign = false; 21042 21043 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 21044 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 21045 return; 21046 21047 IsOrAssign = Op->getOpcode() == BO_OrAssign; 21048 21049 // Greylist some idioms by putting them into a warning subcategory. 21050 if (ObjCMessageExpr *ME 21051 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 21052 Selector Sel = ME->getSelector(); 21053 21054 // self = [<foo> init...] 21055 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 21056 diagnostic = diag::warn_condition_is_idiomatic_assignment; 21057 21058 // <foo> = [<bar> nextObject] 21059 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 21060 diagnostic = diag::warn_condition_is_idiomatic_assignment; 21061 } 21062 21063 Loc = Op->getOperatorLoc(); 21064 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 21065 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 21066 return; 21067 21068 IsOrAssign = Op->getOperator() == OO_PipeEqual; 21069 Loc = Op->getOperatorLoc(); 21070 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 21071 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 21072 else { 21073 // Not an assignment. 21074 return; 21075 } 21076 21077 Diag(Loc, diagnostic) << E->getSourceRange(); 21078 21079 SourceLocation Open = E->getBeginLoc(); 21080 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 21081 Diag(Loc, diag::note_condition_assign_silence) 21082 << FixItHint::CreateInsertion(Open, "(") 21083 << FixItHint::CreateInsertion(Close, ")"); 21084 21085 if (IsOrAssign) 21086 Diag(Loc, diag::note_condition_or_assign_to_comparison) 21087 << FixItHint::CreateReplacement(Loc, "!="); 21088 else 21089 Diag(Loc, diag::note_condition_assign_to_comparison) 21090 << FixItHint::CreateReplacement(Loc, "=="); 21091} 21092 21093/// Redundant parentheses over an equality comparison can indicate 21094/// that the user intended an assignment used as condition. 21095void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 21096 // Don't warn if the parens came from a macro. 21097 SourceLocation parenLoc = ParenE->getBeginLoc(); 21098 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 21099 return; 21100 // Don't warn for dependent expressions. 21101 if (ParenE->isTypeDependent()) 21102 return; 21103 21104 Expr *E = ParenE->IgnoreParens(); 21105 21106 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 21107 if (opE->getOpcode() == BO_EQ && 21108 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 21109 == Expr::MLV_Valid) { 21110 SourceLocation Loc = opE->getOperatorLoc(); 21111 21112 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 21113 SourceRange ParenERange = ParenE->getSourceRange(); 21114 Diag(Loc, diag::note_equality_comparison_silence) 21115 << FixItHint::CreateRemoval(ParenERange.getBegin()) 21116 << FixItHint::CreateRemoval(ParenERange.getEnd()); 21117 Diag(Loc, diag::note_equality_comparison_to_assign) 21118 << FixItHint::CreateReplacement(Loc, "="); 21119 } 21120} 21121 21122ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 21123 bool IsConstexpr) { 21124 DiagnoseAssignmentAsCondition(E); 21125 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 21126 DiagnoseEqualityWithExtraParens(parenE); 21127 21128 ExprResult result = CheckPlaceholderExpr(E); 21129 if (result.isInvalid()) return ExprError(); 21130 E = result.get(); 21131 21132 if (!E->isTypeDependent()) { 21133 if (getLangOpts().CPlusPlus) 21134 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 21135 21136 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 21137 if (ERes.isInvalid()) 21138 return ExprError(); 21139 E = ERes.get(); 21140 21141 QualType T = E->getType(); 21142 if (!T->isScalarType()) { // C99 6.8.4.1p1 21143 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 21144 << T << E->getSourceRange(); 21145 return ExprError(); 21146 } 21147 CheckBoolLikeConversion(E, Loc); 21148 } 21149 21150 return E; 21151} 21152 21153Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 21154 Expr *SubExpr, ConditionKind CK, 21155 bool MissingOK) { 21156 // MissingOK indicates whether having no condition expression is valid 21157 // (for loop) or invalid (e.g. while loop). 21158 if (!SubExpr) 21159 return MissingOK ? ConditionResult() : ConditionError(); 21160 21161 ExprResult Cond; 21162 switch (CK) { 21163 case ConditionKind::Boolean: 21164 Cond = CheckBooleanCondition(Loc, SubExpr); 21165 break; 21166 21167 case ConditionKind::ConstexprIf: 21168 Cond = CheckBooleanCondition(Loc, SubExpr, true); 21169 break; 21170 21171 case ConditionKind::Switch: 21172 Cond = CheckSwitchCondition(Loc, SubExpr); 21173 break; 21174 } 21175 if (Cond.isInvalid()) { 21176 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 21177 {SubExpr}, PreferredConditionType(CK)); 21178 if (!Cond.get()) 21179 return ConditionError(); 21180 } 21181 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 21182 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 21183 if (!FullExpr.get()) 21184 return ConditionError(); 21185 21186 return ConditionResult(*this, nullptr, FullExpr, 21187 CK == ConditionKind::ConstexprIf); 21188} 21189 21190namespace { 21191 /// A visitor for rebuilding a call to an __unknown_any expression 21192 /// to have an appropriate type. 21193 struct RebuildUnknownAnyFunction 21194 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 21195 21196 Sema &S; 21197 21198 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 21199 21200 ExprResult VisitStmt(Stmt *S) { 21201 llvm_unreachable("unexpected statement!"); 21202 } 21203 21204 ExprResult VisitExpr(Expr *E) { 21205 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 21206 << E->getSourceRange(); 21207 return ExprError(); 21208 } 21209 21210 /// Rebuild an expression which simply semantically wraps another 21211 /// expression which it shares the type and value kind of. 21212 template <class T> ExprResult rebuildSugarExpr(T *E) { 21213 ExprResult SubResult = Visit(E->getSubExpr()); 21214 if (SubResult.isInvalid()) return ExprError(); 21215 21216 Expr *SubExpr = SubResult.get(); 21217 E->setSubExpr(SubExpr); 21218 E->setType(SubExpr->getType()); 21219 E->setValueKind(SubExpr->getValueKind()); 21220 assert(E->getObjectKind() == OK_Ordinary); 21221 return E; 21222 } 21223 21224 ExprResult VisitParenExpr(ParenExpr *E) { 21225 return rebuildSugarExpr(E); 21226 } 21227 21228 ExprResult VisitUnaryExtension(UnaryOperator *E) { 21229 return rebuildSugarExpr(E); 21230 } 21231 21232 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 21233 ExprResult SubResult = Visit(E->getSubExpr()); 21234 if (SubResult.isInvalid()) return ExprError(); 21235 21236 Expr *SubExpr = SubResult.get(); 21237 E->setSubExpr(SubExpr); 21238 E->setType(S.Context.getPointerType(SubExpr->getType())); 21239 assert(E->isPRValue()); 21240 assert(E->getObjectKind() == OK_Ordinary); 21241 return E; 21242 } 21243 21244 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 21245 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 21246 21247 E->setType(VD->getType()); 21248 21249 assert(E->isPRValue()); 21250 if (S.getLangOpts().CPlusPlus && 21251 !(isa<CXXMethodDecl>(VD) && 21252 cast<CXXMethodDecl>(VD)->isInstance())) 21253 E->setValueKind(VK_LValue); 21254 21255 return E; 21256 } 21257 21258 ExprResult VisitMemberExpr(MemberExpr *E) { 21259 return resolveDecl(E, E->getMemberDecl()); 21260 } 21261 21262 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 21263 return resolveDecl(E, E->getDecl()); 21264 } 21265 }; 21266} 21267 21268/// Given a function expression of unknown-any type, try to rebuild it 21269/// to have a function type. 21270static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 21271 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 21272 if (Result.isInvalid()) return ExprError(); 21273 return S.DefaultFunctionArrayConversion(Result.get()); 21274} 21275 21276namespace { 21277 /// A visitor for rebuilding an expression of type __unknown_anytype 21278 /// into one which resolves the type directly on the referring 21279 /// expression. Strict preservation of the original source 21280 /// structure is not a goal. 21281 struct RebuildUnknownAnyExpr 21282 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 21283 21284 Sema &S; 21285 21286 /// The current destination type. 21287 QualType DestType; 21288 21289 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 21290 : S(S), DestType(CastType) {} 21291 21292 ExprResult VisitStmt(Stmt *S) { 21293 llvm_unreachable("unexpected statement!"); 21294 } 21295 21296 ExprResult VisitExpr(Expr *E) { 21297 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 21298 << E->getSourceRange(); 21299 return ExprError(); 21300 } 21301 21302 ExprResult VisitCallExpr(CallExpr *E); 21303 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 21304 21305 /// Rebuild an expression which simply semantically wraps another 21306 /// expression which it shares the type and value kind of. 21307 template <class T> ExprResult rebuildSugarExpr(T *E) { 21308 ExprResult SubResult = Visit(E->getSubExpr()); 21309 if (SubResult.isInvalid()) return ExprError(); 21310 Expr *SubExpr = SubResult.get(); 21311 E->setSubExpr(SubExpr); 21312 E->setType(SubExpr->getType()); 21313 E->setValueKind(SubExpr->getValueKind()); 21314 assert(E->getObjectKind() == OK_Ordinary); 21315 return E; 21316 } 21317 21318 ExprResult VisitParenExpr(ParenExpr *E) { 21319 return rebuildSugarExpr(E); 21320 } 21321 21322 ExprResult VisitUnaryExtension(UnaryOperator *E) { 21323 return rebuildSugarExpr(E); 21324 } 21325 21326 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 21327 const PointerType *Ptr = DestType->getAs<PointerType>(); 21328 if (!Ptr) { 21329 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 21330 << E->getSourceRange(); 21331 return ExprError(); 21332 } 21333 21334 if (isa<CallExpr>(E->getSubExpr())) { 21335 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 21336 << E->getSourceRange(); 21337 return ExprError(); 21338 } 21339 21340 assert(E->isPRValue()); 21341 assert(E->getObjectKind() == OK_Ordinary); 21342 E->setType(DestType); 21343 21344 // Build the sub-expression as if it were an object of the pointee type. 21345 DestType = Ptr->getPointeeType(); 21346 ExprResult SubResult = Visit(E->getSubExpr()); 21347 if (SubResult.isInvalid()) return ExprError(); 21348 E->setSubExpr(SubResult.get()); 21349 return E; 21350 } 21351 21352 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 21353 21354 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 21355 21356 ExprResult VisitMemberExpr(MemberExpr *E) { 21357 return resolveDecl(E, E->getMemberDecl()); 21358 } 21359 21360 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 21361 return resolveDecl(E, E->getDecl()); 21362 } 21363 }; 21364} 21365 21366/// Rebuilds a call expression which yielded __unknown_anytype. 21367ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 21368 Expr *CalleeExpr = E->getCallee(); 21369 21370 enum FnKind { 21371 FK_MemberFunction, 21372 FK_FunctionPointer, 21373 FK_BlockPointer 21374 }; 21375 21376 FnKind Kind; 21377 QualType CalleeType = CalleeExpr->getType(); 21378 if (CalleeType == S.Context.BoundMemberTy) { 21379 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 21380 Kind = FK_MemberFunction; 21381 CalleeType = Expr::findBoundMemberType(CalleeExpr); 21382 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 21383 CalleeType = Ptr->getPointeeType(); 21384 Kind = FK_FunctionPointer; 21385 } else { 21386 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 21387 Kind = FK_BlockPointer; 21388 } 21389 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 21390 21391 // Verify that this is a legal result type of a function. 21392 if (DestType->isArrayType() || DestType->isFunctionType()) { 21393 unsigned diagID = diag::err_func_returning_array_function; 21394 if (Kind == FK_BlockPointer) 21395 diagID = diag::err_block_returning_array_function; 21396 21397 S.Diag(E->getExprLoc(), diagID) 21398 << DestType->isFunctionType() << DestType; 21399 return ExprError(); 21400 } 21401 21402 // Otherwise, go ahead and set DestType as the call's result. 21403 E->setType(DestType.getNonLValueExprType(S.Context)); 21404 E->setValueKind(Expr::getValueKindForType(DestType)); 21405 assert(E->getObjectKind() == OK_Ordinary); 21406 21407 // Rebuild the function type, replacing the result type with DestType. 21408 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 21409 if (Proto) { 21410 // __unknown_anytype(...) is a special case used by the debugger when 21411 // it has no idea what a function's signature is. 21412 // 21413 // We want to build this call essentially under the K&R 21414 // unprototyped rules, but making a FunctionNoProtoType in C++ 21415 // would foul up all sorts of assumptions. However, we cannot 21416 // simply pass all arguments as variadic arguments, nor can we 21417 // portably just call the function under a non-variadic type; see 21418 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 21419 // However, it turns out that in practice it is generally safe to 21420 // call a function declared as "A foo(B,C,D);" under the prototype 21421 // "A foo(B,C,D,...);". The only known exception is with the 21422 // Windows ABI, where any variadic function is implicitly cdecl 21423 // regardless of its normal CC. Therefore we change the parameter 21424 // types to match the types of the arguments. 21425 // 21426 // This is a hack, but it is far superior to moving the 21427 // corresponding target-specific code from IR-gen to Sema/AST. 21428 21429 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 21430 SmallVector<QualType, 8> ArgTypes; 21431 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 21432 ArgTypes.reserve(E->getNumArgs()); 21433 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 21434 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 21435 } 21436 ParamTypes = ArgTypes; 21437 } 21438 DestType = S.Context.getFunctionType(DestType, ParamTypes, 21439 Proto->getExtProtoInfo()); 21440 } else { 21441 DestType = S.Context.getFunctionNoProtoType(DestType, 21442 FnType->getExtInfo()); 21443 } 21444 21445 // Rebuild the appropriate pointer-to-function type. 21446 switch (Kind) { 21447 case FK_MemberFunction: 21448 // Nothing to do. 21449 break; 21450 21451 case FK_FunctionPointer: 21452 DestType = S.Context.getPointerType(DestType); 21453 break; 21454 21455 case FK_BlockPointer: 21456 DestType = S.Context.getBlockPointerType(DestType); 21457 break; 21458 } 21459 21460 // Finally, we can recurse. 21461 ExprResult CalleeResult = Visit(CalleeExpr); 21462 if (!CalleeResult.isUsable()) return ExprError(); 21463 E->setCallee(CalleeResult.get()); 21464 21465 // Bind a temporary if necessary. 21466 return S.MaybeBindToTemporary(E); 21467} 21468 21469ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 21470 // Verify that this is a legal result type of a call. 21471 if (DestType->isArrayType() || DestType->isFunctionType()) { 21472 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 21473 << DestType->isFunctionType() << DestType; 21474 return ExprError(); 21475 } 21476 21477 // Rewrite the method result type if available. 21478 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 21479 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 21480 Method->setReturnType(DestType); 21481 } 21482 21483 // Change the type of the message. 21484 E->setType(DestType.getNonReferenceType()); 21485 E->setValueKind(Expr::getValueKindForType(DestType)); 21486 21487 return S.MaybeBindToTemporary(E); 21488} 21489 21490ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 21491 // The only case we should ever see here is a function-to-pointer decay. 21492 if (E->getCastKind() == CK_FunctionToPointerDecay) { 21493 assert(E->isPRValue()); 21494 assert(E->getObjectKind() == OK_Ordinary); 21495 21496 E->setType(DestType); 21497 21498 // Rebuild the sub-expression as the pointee (function) type. 21499 DestType = DestType->castAs<PointerType>()->getPointeeType(); 21500 21501 ExprResult Result = Visit(E->getSubExpr()); 21502 if (!Result.isUsable()) return ExprError(); 21503 21504 E->setSubExpr(Result.get()); 21505 return E; 21506 } else if (E->getCastKind() == CK_LValueToRValue) { 21507 assert(E->isPRValue()); 21508 assert(E->getObjectKind() == OK_Ordinary); 21509 21510 assert(isa<BlockPointerType>(E->getType())); 21511 21512 E->setType(DestType); 21513 21514 // The sub-expression has to be a lvalue reference, so rebuild it as such. 21515 DestType = S.Context.getLValueReferenceType(DestType); 21516 21517 ExprResult Result = Visit(E->getSubExpr()); 21518 if (!Result.isUsable()) return ExprError(); 21519 21520 E->setSubExpr(Result.get()); 21521 return E; 21522 } else { 21523 llvm_unreachable("Unhandled cast type!"); 21524 } 21525} 21526 21527ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 21528 ExprValueKind ValueKind = VK_LValue; 21529 QualType Type = DestType; 21530 21531 // We know how to make this work for certain kinds of decls: 21532 21533 // - functions 21534 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 21535 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 21536 DestType = Ptr->getPointeeType(); 21537 ExprResult Result = resolveDecl(E, VD); 21538 if (Result.isInvalid()) return ExprError(); 21539 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 21540 VK_PRValue); 21541 } 21542 21543 if (!Type->isFunctionType()) { 21544 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 21545 << VD << E->getSourceRange(); 21546 return ExprError(); 21547 } 21548 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 21549 // We must match the FunctionDecl's type to the hack introduced in 21550 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 21551 // type. See the lengthy commentary in that routine. 21552 QualType FDT = FD->getType(); 21553 const FunctionType *FnType = FDT->castAs<FunctionType>(); 21554 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 21555 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 21556 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 21557 SourceLocation Loc = FD->getLocation(); 21558 FunctionDecl *NewFD = FunctionDecl::Create( 21559 S.Context, FD->getDeclContext(), Loc, Loc, 21560 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 21561 SC_None, S.getCurFPFeatures().isFPConstrained(), 21562 false /*isInlineSpecified*/, FD->hasPrototype(), 21563 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 21564 21565 if (FD->getQualifier()) 21566 NewFD->setQualifierInfo(FD->getQualifierLoc()); 21567 21568 SmallVector<ParmVarDecl*, 16> Params; 21569 for (const auto &AI : FT->param_types()) { 21570 ParmVarDecl *Param = 21571 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 21572 Param->setScopeInfo(0, Params.size()); 21573 Params.push_back(Param); 21574 } 21575 NewFD->setParams(Params); 21576 DRE->setDecl(NewFD); 21577 VD = DRE->getDecl(); 21578 } 21579 } 21580 21581 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 21582 if (MD->isInstance()) { 21583 ValueKind = VK_PRValue; 21584 Type = S.Context.BoundMemberTy; 21585 } 21586 21587 // Function references aren't l-values in C. 21588 if (!S.getLangOpts().CPlusPlus) 21589 ValueKind = VK_PRValue; 21590 21591 // - variables 21592 } else if (isa<VarDecl>(VD)) { 21593 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 21594 Type = RefTy->getPointeeType(); 21595 } else if (Type->isFunctionType()) { 21596 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 21597 << VD << E->getSourceRange(); 21598 return ExprError(); 21599 } 21600 21601 // - nothing else 21602 } else { 21603 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 21604 << VD << E->getSourceRange(); 21605 return ExprError(); 21606 } 21607 21608 // Modifying the declaration like this is friendly to IR-gen but 21609 // also really dangerous. 21610 VD->setType(DestType); 21611 E->setType(Type); 21612 E->setValueKind(ValueKind); 21613 return E; 21614} 21615 21616/// Check a cast of an unknown-any type. We intentionally only 21617/// trigger this for C-style casts. 21618ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 21619 Expr *CastExpr, CastKind &CastKind, 21620 ExprValueKind &VK, CXXCastPath &Path) { 21621 // The type we're casting to must be either void or complete. 21622 if (!CastType->isVoidType() && 21623 RequireCompleteType(TypeRange.getBegin(), CastType, 21624 diag::err_typecheck_cast_to_incomplete)) 21625 return ExprError(); 21626 21627 // Rewrite the casted expression from scratch. 21628 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 21629 if (!result.isUsable()) return ExprError(); 21630 21631 CastExpr = result.get(); 21632 VK = CastExpr->getValueKind(); 21633 CastKind = CK_NoOp; 21634 21635 return CastExpr; 21636} 21637 21638ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 21639 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 21640} 21641 21642ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 21643 Expr *arg, QualType ¶mType) { 21644 // If the syntactic form of the argument is not an explicit cast of 21645 // any sort, just do default argument promotion. 21646 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 21647 if (!castArg) { 21648 ExprResult result = DefaultArgumentPromotion(arg); 21649 if (result.isInvalid()) return ExprError(); 21650 paramType = result.get()->getType(); 21651 return result; 21652 } 21653 21654 // Otherwise, use the type that was written in the explicit cast. 21655 assert(!arg->hasPlaceholderType()); 21656 paramType = castArg->getTypeAsWritten(); 21657 21658 // Copy-initialize a parameter of that type. 21659 InitializedEntity entity = 21660 InitializedEntity::InitializeParameter(Context, paramType, 21661 /*consumed*/ false); 21662 return PerformCopyInitialization(entity, callLoc, arg); 21663} 21664 21665static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 21666 Expr *orig = E; 21667 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 21668 while (true) { 21669 E = E->IgnoreParenImpCasts(); 21670 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 21671 E = call->getCallee(); 21672 diagID = diag::err_uncasted_call_of_unknown_any; 21673 } else { 21674 break; 21675 } 21676 } 21677 21678 SourceLocation loc; 21679 NamedDecl *d; 21680 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 21681 loc = ref->getLocation(); 21682 d = ref->getDecl(); 21683 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 21684 loc = mem->getMemberLoc(); 21685 d = mem->getMemberDecl(); 21686 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 21687 diagID = diag::err_uncasted_call_of_unknown_any; 21688 loc = msg->getSelectorStartLoc(); 21689 d = msg->getMethodDecl(); 21690 if (!d) { 21691 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 21692 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 21693 << orig->getSourceRange(); 21694 return ExprError(); 21695 } 21696 } else { 21697 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 21698 << E->getSourceRange(); 21699 return ExprError(); 21700 } 21701 21702 S.Diag(loc, diagID) << d << orig->getSourceRange(); 21703 21704 // Never recoverable. 21705 return ExprError(); 21706} 21707 21708/// Check for operands with placeholder types and complain if found. 21709/// Returns ExprError() if there was an error and no recovery was possible. 21710ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 21711 if (!Context.isDependenceAllowed()) { 21712 // C cannot handle TypoExpr nodes on either side of a binop because it 21713 // doesn't handle dependent types properly, so make sure any TypoExprs have 21714 // been dealt with before checking the operands. 21715 ExprResult Result = CorrectDelayedTyposInExpr(E); 21716 if (!Result.isUsable()) return ExprError(); 21717 E = Result.get(); 21718 } 21719 21720 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 21721 if (!placeholderType) return E; 21722 21723 switch (placeholderType->getKind()) { 21724 21725 // Overloaded expressions. 21726 case BuiltinType::Overload: { 21727 // Try to resolve a single function template specialization. 21728 // This is obligatory. 21729 ExprResult Result = E; 21730 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 21731 return Result; 21732 21733 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 21734 // leaves Result unchanged on failure. 21735 Result = E; 21736 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 21737 return Result; 21738 21739 // If that failed, try to recover with a call. 21740 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 21741 /*complain*/ true); 21742 return Result; 21743 } 21744 21745 // Bound member functions. 21746 case BuiltinType::BoundMember: { 21747 ExprResult result = E; 21748 const Expr *BME = E->IgnoreParens(); 21749 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 21750 // Try to give a nicer diagnostic if it is a bound member that we recognize. 21751 if (isa<CXXPseudoDestructorExpr>(BME)) { 21752 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 21753 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 21754 if (ME->getMemberNameInfo().getName().getNameKind() == 21755 DeclarationName::CXXDestructorName) 21756 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 21757 } 21758 tryToRecoverWithCall(result, PD, 21759 /*complain*/ true); 21760 return result; 21761 } 21762 21763 // ARC unbridged casts. 21764 case BuiltinType::ARCUnbridgedCast: { 21765 Expr *realCast = stripARCUnbridgedCast(E); 21766 diagnoseARCUnbridgedCast(realCast); 21767 return realCast; 21768 } 21769 21770 // Expressions of unknown type. 21771 case BuiltinType::UnknownAny: 21772 return diagnoseUnknownAnyExpr(*this, E); 21773 21774 // Pseudo-objects. 21775 case BuiltinType::PseudoObject: 21776 return checkPseudoObjectRValue(E); 21777 21778 case BuiltinType::BuiltinFn: { 21779 // Accept __noop without parens by implicitly converting it to a call expr. 21780 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 21781 if (DRE) { 21782 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 21783 unsigned BuiltinID = FD->getBuiltinID(); 21784 if (BuiltinID == Builtin::BI__noop) { 21785 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 21786 CK_BuiltinFnToFnPtr) 21787 .get(); 21788 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 21789 VK_PRValue, SourceLocation(), 21790 FPOptionsOverride()); 21791 } 21792 21793 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) { 21794 // Any use of these other than a direct call is ill-formed as of C++20, 21795 // because they are not addressable functions. In earlier language 21796 // modes, warn and force an instantiation of the real body. 21797 Diag(E->getBeginLoc(), 21798 getLangOpts().CPlusPlus20 21799 ? diag::err_use_of_unaddressable_function 21800 : diag::warn_cxx20_compat_use_of_unaddressable_function); 21801 if (FD->isImplicitlyInstantiable()) { 21802 // Require a definition here because a normal attempt at 21803 // instantiation for a builtin will be ignored, and we won't try 21804 // again later. We assume that the definition of the template 21805 // precedes this use. 21806 InstantiateFunctionDefinition(E->getBeginLoc(), FD, 21807 /*Recursive=*/false, 21808 /*DefinitionRequired=*/true, 21809 /*AtEndOfTU=*/false); 21810 } 21811 // Produce a properly-typed reference to the function. 21812 CXXScopeSpec SS; 21813 SS.Adopt(DRE->getQualifierLoc()); 21814 TemplateArgumentListInfo TemplateArgs; 21815 DRE->copyTemplateArgumentsInto(TemplateArgs); 21816 return BuildDeclRefExpr( 21817 FD, FD->getType(), VK_LValue, DRE->getNameInfo(), 21818 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(), 21819 DRE->getTemplateKeywordLoc(), 21820 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr); 21821 } 21822 } 21823 21824 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 21825 return ExprError(); 21826 } 21827 21828 case BuiltinType::IncompleteMatrixIdx: 21829 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 21830 ->getRowIdx() 21831 ->getBeginLoc(), 21832 diag::err_matrix_incomplete_index); 21833 return ExprError(); 21834 21835 // Expressions of unknown type. 21836 case BuiltinType::OMPArraySection: 21837 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 21838 return ExprError(); 21839 21840 // Expressions of unknown type. 21841 case BuiltinType::OMPArrayShaping: 21842 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 21843 21844 case BuiltinType::OMPIterator: 21845 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 21846 21847 // Everything else should be impossible. 21848#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 21849 case BuiltinType::Id: 21850#include "clang/Basic/OpenCLImageTypes.def" 21851#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 21852 case BuiltinType::Id: 21853#include "clang/Basic/OpenCLExtensionTypes.def" 21854#define SVE_TYPE(Name, Id, SingletonId) \ 21855 case BuiltinType::Id: 21856#include "clang/Basic/AArch64SVEACLETypes.def" 21857#define PPC_VECTOR_TYPE(Name, Id, Size) \ 21858 case BuiltinType::Id: 21859#include "clang/Basic/PPCTypes.def" 21860#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 21861#include "clang/Basic/RISCVVTypes.def" 21862#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 21863#include "clang/Basic/WebAssemblyReferenceTypes.def" 21864#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 21865#define PLACEHOLDER_TYPE(Id, SingletonId) 21866#include "clang/AST/BuiltinTypes.def" 21867 break; 21868 } 21869 21870 llvm_unreachable("invalid placeholder type!"); 21871} 21872 21873bool Sema::CheckCaseExpression(Expr *E) { 21874 if (E->isTypeDependent()) 21875 return true; 21876 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 21877 return E->getType()->isIntegralOrEnumerationType(); 21878 return false; 21879} 21880 21881/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 21882ExprResult 21883Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 21884 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 21885 "Unknown Objective-C Boolean value!"); 21886 QualType BoolT = Context.ObjCBuiltinBoolTy; 21887 if (!Context.getBOOLDecl()) { 21888 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 21889 Sema::LookupOrdinaryName); 21890 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 21891 NamedDecl *ND = Result.getFoundDecl(); 21892 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 21893 Context.setBOOLDecl(TD); 21894 } 21895 } 21896 if (Context.getBOOLDecl()) 21897 BoolT = Context.getBOOLType(); 21898 return new (Context) 21899 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 21900} 21901 21902ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 21903 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 21904 SourceLocation RParen) { 21905 auto FindSpecVersion = 21906 [&](StringRef Platform) -> std::optional<VersionTuple> { 21907 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 21908 return Spec.getPlatform() == Platform; 21909 }); 21910 // Transcribe the "ios" availability check to "maccatalyst" when compiling 21911 // for "maccatalyst" if "maccatalyst" is not specified. 21912 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 21913 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 21914 return Spec.getPlatform() == "ios"; 21915 }); 21916 } 21917 if (Spec == AvailSpecs.end()) 21918 return std::nullopt; 21919 return Spec->getVersion(); 21920 }; 21921 21922 VersionTuple Version; 21923 if (auto MaybeVersion = 21924 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 21925 Version = *MaybeVersion; 21926 21927 // The use of `@available` in the enclosing context should be analyzed to 21928 // warn when it's used inappropriately (i.e. not if(@available)). 21929 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 21930 Context->HasPotentialAvailabilityViolations = true; 21931 21932 return new (Context) 21933 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 21934} 21935 21936ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 21937 ArrayRef<Expr *> SubExprs, QualType T) { 21938 if (!Context.getLangOpts().RecoveryAST) 21939 return ExprError(); 21940 21941 if (isSFINAEContext()) 21942 return ExprError(); 21943 21944 if (T.isNull() || T->isUndeducedType() || 21945 !Context.getLangOpts().RecoveryASTType) 21946 // We don't know the concrete type, fallback to dependent type. 21947 T = Context.DependentTy; 21948 21949 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 21950} 21951