1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/OperationKinds.h" 28 #include "clang/AST/ParentMapContext.h" 29 #include "clang/AST/RecursiveASTVisitor.h" 30 #include "clang/AST/Type.h" 31 #include "clang/AST/TypeLoc.h" 32 #include "clang/Basic/Builtins.h" 33 #include "clang/Basic/DiagnosticSema.h" 34 #include "clang/Basic/PartialDiagnostic.h" 35 #include "clang/Basic/SourceManager.h" 36 #include "clang/Basic/Specifiers.h" 37 #include "clang/Basic/TargetInfo.h" 38 #include "clang/Lex/LiteralSupport.h" 39 #include "clang/Lex/Preprocessor.h" 40 #include "clang/Sema/AnalysisBasedWarnings.h" 41 #include "clang/Sema/DeclSpec.h" 42 #include "clang/Sema/DelayedDiagnostic.h" 43 #include "clang/Sema/Designator.h" 44 #include "clang/Sema/Initialization.h" 45 #include "clang/Sema/Lookup.h" 46 #include "clang/Sema/Overload.h" 47 #include "clang/Sema/ParsedTemplate.h" 48 #include "clang/Sema/Scope.h" 49 #include "clang/Sema/ScopeInfo.h" 50 #include "clang/Sema/SemaFixItUtils.h" 51 #include "clang/Sema/SemaInternal.h" 52 #include "clang/Sema/Template.h" 53 #include "llvm/ADT/STLExtras.h" 54 #include "llvm/ADT/StringExtras.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/ConvertUTF.h" 57 #include "llvm/Support/SaveAndRestore.h" 58 #include "llvm/Support/TypeSize.h" 59 60 using namespace clang; 61 using namespace sema; 62 63 /// Determine whether the use of this declaration is valid, without 64 /// emitting diagnostics. 65 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 66 // See if this is an auto-typed variable whose initializer we are parsing. 67 if (ParsingInitForAutoVars.count(D)) 68 return false; 69 70 // See if this is a deleted function. 71 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 72 if (FD->isDeleted()) 73 return false; 74 75 // If the function has a deduced return type, and we can't deduce it, 76 // then we can't use it either. 77 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 78 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 79 return false; 80 81 // See if this is an aligned allocation/deallocation function that is 82 // unavailable. 83 if (TreatUnavailableAsInvalid && 84 isUnavailableAlignedAllocationFunction(*FD)) 85 return false; 86 } 87 88 // See if this function is unavailable. 89 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 90 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 91 return false; 92 93 if (isa<UnresolvedUsingIfExistsDecl>(D)) 94 return false; 95 96 return true; 97 } 98 99 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 100 // Warn if this is used but marked unused. 101 if (const auto *A = D->getAttr<UnusedAttr>()) { 102 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 103 // should diagnose them. 104 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 105 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 106 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 107 if (DC && !DC->hasAttr<UnusedAttr>()) 108 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 109 } 110 } 111 } 112 113 /// Emit a note explaining that this function is deleted. 114 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 115 assert(Decl && Decl->isDeleted()); 116 117 if (Decl->isDefaulted()) { 118 // If the method was explicitly defaulted, point at that declaration. 119 if (!Decl->isImplicit()) 120 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 121 122 // Try to diagnose why this special member function was implicitly 123 // deleted. This might fail, if that reason no longer applies. 124 DiagnoseDeletedDefaultedFunction(Decl); 125 return; 126 } 127 128 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 129 if (Ctor && Ctor->isInheritingConstructor()) 130 return NoteDeletedInheritingConstructor(Ctor); 131 132 Diag(Decl->getLocation(), diag::note_availability_specified_here) 133 << Decl << 1; 134 } 135 136 /// Determine whether a FunctionDecl was ever declared with an 137 /// explicit storage class. 138 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 139 for (auto I : D->redecls()) { 140 if (I->getStorageClass() != SC_None) 141 return true; 142 } 143 return false; 144 } 145 146 /// Check whether we're in an extern inline function and referring to a 147 /// variable or function with internal linkage (C11 6.7.4p3). 148 /// 149 /// This is only a warning because we used to silently accept this code, but 150 /// in many cases it will not behave correctly. This is not enabled in C++ mode 151 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 152 /// and so while there may still be user mistakes, most of the time we can't 153 /// prove that there are errors. 154 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 155 const NamedDecl *D, 156 SourceLocation Loc) { 157 // This is disabled under C++; there are too many ways for this to fire in 158 // contexts where the warning is a false positive, or where it is technically 159 // correct but benign. 160 if (S.getLangOpts().CPlusPlus) 161 return; 162 163 // Check if this is an inlined function or method. 164 FunctionDecl *Current = S.getCurFunctionDecl(); 165 if (!Current) 166 return; 167 if (!Current->isInlined()) 168 return; 169 if (!Current->isExternallyVisible()) 170 return; 171 172 // Check if the decl has internal linkage. 173 if (D->getFormalLinkage() != InternalLinkage) 174 return; 175 176 // Downgrade from ExtWarn to Extension if 177 // (1) the supposedly external inline function is in the main file, 178 // and probably won't be included anywhere else. 179 // (2) the thing we're referencing is a pure function. 180 // (3) the thing we're referencing is another inline function. 181 // This last can give us false negatives, but it's better than warning on 182 // wrappers for simple C library functions. 183 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 184 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 185 if (!DowngradeWarning && UsedFn) 186 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 187 188 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 189 : diag::ext_internal_in_extern_inline) 190 << /*IsVar=*/!UsedFn << D; 191 192 S.MaybeSuggestAddingStaticToDecl(Current); 193 194 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 195 << D; 196 } 197 198 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 199 const FunctionDecl *First = Cur->getFirstDecl(); 200 201 // Suggest "static" on the function, if possible. 202 if (!hasAnyExplicitStorageClass(First)) { 203 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 204 Diag(DeclBegin, diag::note_convert_inline_to_static) 205 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 206 } 207 } 208 209 /// Determine whether the use of this declaration is valid, and 210 /// emit any corresponding diagnostics. 211 /// 212 /// This routine diagnoses various problems with referencing 213 /// declarations that can occur when using a declaration. For example, 214 /// it might warn if a deprecated or unavailable declaration is being 215 /// used, or produce an error (and return true) if a C++0x deleted 216 /// function is being used. 217 /// 218 /// \returns true if there was an error (this declaration cannot be 219 /// referenced), false otherwise. 220 /// 221 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 222 const ObjCInterfaceDecl *UnknownObjCClass, 223 bool ObjCPropertyAccess, 224 bool AvoidPartialAvailabilityChecks, 225 ObjCInterfaceDecl *ClassReceiver) { 226 SourceLocation Loc = Locs.front(); 227 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 228 // If there were any diagnostics suppressed by template argument deduction, 229 // emit them now. 230 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 231 if (Pos != SuppressedDiagnostics.end()) { 232 for (const PartialDiagnosticAt &Suppressed : Pos->second) 233 Diag(Suppressed.first, Suppressed.second); 234 235 // Clear out the list of suppressed diagnostics, so that we don't emit 236 // them again for this specialization. However, we don't obsolete this 237 // entry from the table, because we want to avoid ever emitting these 238 // diagnostics again. 239 Pos->second.clear(); 240 } 241 242 // C++ [basic.start.main]p3: 243 // The function 'main' shall not be used within a program. 244 if (cast<FunctionDecl>(D)->isMain()) 245 Diag(Loc, diag::ext_main_used); 246 247 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 248 } 249 250 // See if this is an auto-typed variable whose initializer we are parsing. 251 if (ParsingInitForAutoVars.count(D)) { 252 if (isa<BindingDecl>(D)) { 253 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 254 << D->getDeclName(); 255 } else { 256 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 257 << D->getDeclName() << cast<VarDecl>(D)->getType(); 258 } 259 return true; 260 } 261 262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 263 // See if this is a deleted function. 264 if (FD->isDeleted()) { 265 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 266 if (Ctor && Ctor->isInheritingConstructor()) 267 Diag(Loc, diag::err_deleted_inherited_ctor_use) 268 << Ctor->getParent() 269 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 270 else 271 Diag(Loc, diag::err_deleted_function_use); 272 NoteDeletedFunction(FD); 273 return true; 274 } 275 276 // [expr.prim.id]p4 277 // A program that refers explicitly or implicitly to a function with a 278 // trailing requires-clause whose constraint-expression is not satisfied, 279 // other than to declare it, is ill-formed. [...] 280 // 281 // See if this is a function with constraints that need to be satisfied. 282 // Check this before deducing the return type, as it might instantiate the 283 // definition. 284 if (FD->getTrailingRequiresClause()) { 285 ConstraintSatisfaction Satisfaction; 286 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 287 // A diagnostic will have already been generated (non-constant 288 // constraint expression, for example) 289 return true; 290 if (!Satisfaction.IsSatisfied) { 291 Diag(Loc, 292 diag::err_reference_to_function_with_unsatisfied_constraints) 293 << D; 294 DiagnoseUnsatisfiedConstraint(Satisfaction); 295 return true; 296 } 297 } 298 299 // If the function has a deduced return type, and we can't deduce it, 300 // then we can't use it either. 301 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 302 DeduceReturnType(FD, Loc)) 303 return true; 304 305 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 306 return true; 307 308 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 309 return true; 310 } 311 312 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 313 // Lambdas are only default-constructible or assignable in C++2a onwards. 314 if (MD->getParent()->isLambda() && 315 ((isa<CXXConstructorDecl>(MD) && 316 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 317 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 318 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 319 << !isa<CXXConstructorDecl>(MD); 320 } 321 } 322 323 auto getReferencedObjCProp = [](const NamedDecl *D) -> 324 const ObjCPropertyDecl * { 325 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 326 return MD->findPropertyDecl(); 327 return nullptr; 328 }; 329 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 330 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 331 return true; 332 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 333 return true; 334 } 335 336 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 337 // Only the variables omp_in and omp_out are allowed in the combiner. 338 // Only the variables omp_priv and omp_orig are allowed in the 339 // initializer-clause. 340 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 341 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 342 isa<VarDecl>(D)) { 343 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 344 << getCurFunction()->HasOMPDeclareReductionCombiner; 345 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 346 return true; 347 } 348 349 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 350 // List-items in map clauses on this construct may only refer to the declared 351 // variable var and entities that could be referenced by a procedure defined 352 // at the same location 353 if (LangOpts.OpenMP && isa<VarDecl>(D) && 354 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 355 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 356 << getOpenMPDeclareMapperVarName(); 357 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 358 return true; 359 } 360 361 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 362 Diag(Loc, diag::err_use_of_empty_using_if_exists); 363 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 364 return true; 365 } 366 367 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 368 AvoidPartialAvailabilityChecks, ClassReceiver); 369 370 DiagnoseUnusedOfDecl(*this, D, Loc); 371 372 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 373 374 if (auto *VD = dyn_cast<ValueDecl>(D)) 375 checkTypeSupport(VD->getType(), Loc, VD); 376 377 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 378 if (!Context.getTargetInfo().isTLSSupported()) 379 if (const auto *VD = dyn_cast<VarDecl>(D)) 380 if (VD->getTLSKind() != VarDecl::TLS_None) 381 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 382 } 383 384 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 385 !isUnevaluatedContext()) { 386 // C++ [expr.prim.req.nested] p3 387 // A local parameter shall only appear as an unevaluated operand 388 // (Clause 8) within the constraint-expression. 389 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 390 << D; 391 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 392 return true; 393 } 394 395 return false; 396 } 397 398 /// DiagnoseSentinelCalls - This routine checks whether a call or 399 /// message-send is to a declaration with the sentinel attribute, and 400 /// if so, it checks that the requirements of the sentinel are 401 /// satisfied. 402 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 403 ArrayRef<Expr *> Args) { 404 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 405 if (!attr) 406 return; 407 408 // The number of formal parameters of the declaration. 409 unsigned numFormalParams; 410 411 // The kind of declaration. This is also an index into a %select in 412 // the diagnostic. 413 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 414 415 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 416 numFormalParams = MD->param_size(); 417 calleeType = CT_Method; 418 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 419 numFormalParams = FD->param_size(); 420 calleeType = CT_Function; 421 } else if (isa<VarDecl>(D)) { 422 QualType type = cast<ValueDecl>(D)->getType(); 423 const FunctionType *fn = nullptr; 424 if (const PointerType *ptr = type->getAs<PointerType>()) { 425 fn = ptr->getPointeeType()->getAs<FunctionType>(); 426 if (!fn) return; 427 calleeType = CT_Function; 428 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 429 fn = ptr->getPointeeType()->castAs<FunctionType>(); 430 calleeType = CT_Block; 431 } else { 432 return; 433 } 434 435 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 436 numFormalParams = proto->getNumParams(); 437 } else { 438 numFormalParams = 0; 439 } 440 } else { 441 return; 442 } 443 444 // "nullPos" is the number of formal parameters at the end which 445 // effectively count as part of the variadic arguments. This is 446 // useful if you would prefer to not have *any* formal parameters, 447 // but the language forces you to have at least one. 448 unsigned nullPos = attr->getNullPos(); 449 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 450 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 451 452 // The number of arguments which should follow the sentinel. 453 unsigned numArgsAfterSentinel = attr->getSentinel(); 454 455 // If there aren't enough arguments for all the formal parameters, 456 // the sentinel, and the args after the sentinel, complain. 457 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 458 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 459 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 460 return; 461 } 462 463 // Otherwise, find the sentinel expression. 464 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 465 if (!sentinelExpr) return; 466 if (sentinelExpr->isValueDependent()) return; 467 if (Context.isSentinelNullExpr(sentinelExpr)) return; 468 469 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 470 // or 'NULL' if those are actually defined in the context. Only use 471 // 'nil' for ObjC methods, where it's much more likely that the 472 // variadic arguments form a list of object pointers. 473 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 474 std::string NullValue; 475 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 476 NullValue = "nil"; 477 else if (getLangOpts().CPlusPlus11) 478 NullValue = "nullptr"; 479 else if (PP.isMacroDefined("NULL")) 480 NullValue = "NULL"; 481 else 482 NullValue = "(void*) 0"; 483 484 if (MissingNilLoc.isInvalid()) 485 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 486 else 487 Diag(MissingNilLoc, diag::warn_missing_sentinel) 488 << int(calleeType) 489 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 490 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 491 } 492 493 SourceRange Sema::getExprRange(Expr *E) const { 494 return E ? E->getSourceRange() : SourceRange(); 495 } 496 497 //===----------------------------------------------------------------------===// 498 // Standard Promotions and Conversions 499 //===----------------------------------------------------------------------===// 500 501 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 502 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 503 // Handle any placeholder expressions which made it here. 504 if (E->hasPlaceholderType()) { 505 ExprResult result = CheckPlaceholderExpr(E); 506 if (result.isInvalid()) return ExprError(); 507 E = result.get(); 508 } 509 510 QualType Ty = E->getType(); 511 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 512 513 if (Ty->isFunctionType()) { 514 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 515 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 516 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 517 return ExprError(); 518 519 E = ImpCastExprToType(E, Context.getPointerType(Ty), 520 CK_FunctionToPointerDecay).get(); 521 } else if (Ty->isArrayType()) { 522 // In C90 mode, arrays only promote to pointers if the array expression is 523 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 524 // type 'array of type' is converted to an expression that has type 'pointer 525 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 526 // that has type 'array of type' ...". The relevant change is "an lvalue" 527 // (C90) to "an expression" (C99). 528 // 529 // C++ 4.2p1: 530 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 531 // T" can be converted to an rvalue of type "pointer to T". 532 // 533 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 534 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 535 CK_ArrayToPointerDecay); 536 if (Res.isInvalid()) 537 return ExprError(); 538 E = Res.get(); 539 } 540 } 541 return E; 542 } 543 544 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 545 // Check to see if we are dereferencing a null pointer. If so, 546 // and if not volatile-qualified, this is undefined behavior that the 547 // optimizer will delete, so warn about it. People sometimes try to use this 548 // to get a deterministic trap and are surprised by clang's behavior. This 549 // only handles the pattern "*null", which is a very syntactic check. 550 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 551 if (UO && UO->getOpcode() == UO_Deref && 552 UO->getSubExpr()->getType()->isPointerType()) { 553 const LangAS AS = 554 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 555 if ((!isTargetAddressSpace(AS) || 556 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 557 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 558 S.Context, Expr::NPC_ValueDependentIsNotNull) && 559 !UO->getType().isVolatileQualified()) { 560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 561 S.PDiag(diag::warn_indirection_through_null) 562 << UO->getSubExpr()->getSourceRange()); 563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 564 S.PDiag(diag::note_indirection_through_null)); 565 } 566 } 567 } 568 569 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 570 SourceLocation AssignLoc, 571 const Expr* RHS) { 572 const ObjCIvarDecl *IV = OIRE->getDecl(); 573 if (!IV) 574 return; 575 576 DeclarationName MemberName = IV->getDeclName(); 577 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 578 if (!Member || !Member->isStr("isa")) 579 return; 580 581 const Expr *Base = OIRE->getBase(); 582 QualType BaseType = Base->getType(); 583 if (OIRE->isArrow()) 584 BaseType = BaseType->getPointeeType(); 585 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 586 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 587 ObjCInterfaceDecl *ClassDeclared = nullptr; 588 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 589 if (!ClassDeclared->getSuperClass() 590 && (*ClassDeclared->ivar_begin()) == IV) { 591 if (RHS) { 592 NamedDecl *ObjectSetClass = 593 S.LookupSingleName(S.TUScope, 594 &S.Context.Idents.get("object_setClass"), 595 SourceLocation(), S.LookupOrdinaryName); 596 if (ObjectSetClass) { 597 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 598 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 599 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 600 "object_setClass(") 601 << FixItHint::CreateReplacement( 602 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 603 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 604 } 605 else 606 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 607 } else { 608 NamedDecl *ObjectGetClass = 609 S.LookupSingleName(S.TUScope, 610 &S.Context.Idents.get("object_getClass"), 611 SourceLocation(), S.LookupOrdinaryName); 612 if (ObjectGetClass) 613 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 614 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 615 "object_getClass(") 616 << FixItHint::CreateReplacement( 617 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 618 else 619 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 620 } 621 S.Diag(IV->getLocation(), diag::note_ivar_decl); 622 } 623 } 624 } 625 626 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 627 // Handle any placeholder expressions which made it here. 628 if (E->hasPlaceholderType()) { 629 ExprResult result = CheckPlaceholderExpr(E); 630 if (result.isInvalid()) return ExprError(); 631 E = result.get(); 632 } 633 634 // C++ [conv.lval]p1: 635 // A glvalue of a non-function, non-array type T can be 636 // converted to a prvalue. 637 if (!E->isGLValue()) return E; 638 639 QualType T = E->getType(); 640 assert(!T.isNull() && "r-value conversion on typeless expression?"); 641 642 // lvalue-to-rvalue conversion cannot be applied to function or array types. 643 if (T->isFunctionType() || T->isArrayType()) 644 return E; 645 646 // We don't want to throw lvalue-to-rvalue casts on top of 647 // expressions of certain types in C++. 648 if (getLangOpts().CPlusPlus && 649 (E->getType() == Context.OverloadTy || 650 T->isDependentType() || 651 T->isRecordType())) 652 return E; 653 654 // The C standard is actually really unclear on this point, and 655 // DR106 tells us what the result should be but not why. It's 656 // generally best to say that void types just doesn't undergo 657 // lvalue-to-rvalue at all. Note that expressions of unqualified 658 // 'void' type are never l-values, but qualified void can be. 659 if (T->isVoidType()) 660 return E; 661 662 // OpenCL usually rejects direct accesses to values of 'half' type. 663 if (getLangOpts().OpenCL && 664 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 665 T->isHalfType()) { 666 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 667 << 0 << T; 668 return ExprError(); 669 } 670 671 CheckForNullPointerDereference(*this, E); 672 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 673 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 674 &Context.Idents.get("object_getClass"), 675 SourceLocation(), LookupOrdinaryName); 676 if (ObjectGetClass) 677 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 678 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 679 << FixItHint::CreateReplacement( 680 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 681 else 682 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 683 } 684 else if (const ObjCIvarRefExpr *OIRE = 685 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 686 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 687 688 // C++ [conv.lval]p1: 689 // [...] If T is a non-class type, the type of the prvalue is the 690 // cv-unqualified version of T. Otherwise, the type of the 691 // rvalue is T. 692 // 693 // C99 6.3.2.1p2: 694 // If the lvalue has qualified type, the value has the unqualified 695 // version of the type of the lvalue; otherwise, the value has the 696 // type of the lvalue. 697 if (T.hasQualifiers()) 698 T = T.getUnqualifiedType(); 699 700 // Under the MS ABI, lock down the inheritance model now. 701 if (T->isMemberPointerType() && 702 Context.getTargetInfo().getCXXABI().isMicrosoft()) 703 (void)isCompleteType(E->getExprLoc(), T); 704 705 ExprResult Res = CheckLValueToRValueConversionOperand(E); 706 if (Res.isInvalid()) 707 return Res; 708 E = Res.get(); 709 710 // Loading a __weak object implicitly retains the value, so we need a cleanup to 711 // balance that. 712 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 713 Cleanup.setExprNeedsCleanups(true); 714 715 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 716 Cleanup.setExprNeedsCleanups(true); 717 718 // C++ [conv.lval]p3: 719 // If T is cv std::nullptr_t, the result is a null pointer constant. 720 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 721 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 722 CurFPFeatureOverrides()); 723 724 // C11 6.3.2.1p2: 725 // ... if the lvalue has atomic type, the value has the non-atomic version 726 // of the type of the lvalue ... 727 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 728 T = Atomic->getValueType().getUnqualifiedType(); 729 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 730 nullptr, VK_PRValue, FPOptionsOverride()); 731 } 732 733 return Res; 734 } 735 736 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 737 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 738 if (Res.isInvalid()) 739 return ExprError(); 740 Res = DefaultLvalueConversion(Res.get()); 741 if (Res.isInvalid()) 742 return ExprError(); 743 return Res; 744 } 745 746 /// CallExprUnaryConversions - a special case of an unary conversion 747 /// performed on a function designator of a call expression. 748 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 749 QualType Ty = E->getType(); 750 ExprResult Res = E; 751 // Only do implicit cast for a function type, but not for a pointer 752 // to function type. 753 if (Ty->isFunctionType()) { 754 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 755 CK_FunctionToPointerDecay); 756 if (Res.isInvalid()) 757 return ExprError(); 758 } 759 Res = DefaultLvalueConversion(Res.get()); 760 if (Res.isInvalid()) 761 return ExprError(); 762 return Res.get(); 763 } 764 765 /// UsualUnaryConversions - Performs various conversions that are common to most 766 /// operators (C99 6.3). The conversions of array and function types are 767 /// sometimes suppressed. For example, the array->pointer conversion doesn't 768 /// apply if the array is an argument to the sizeof or address (&) operators. 769 /// In these instances, this routine should *not* be called. 770 ExprResult Sema::UsualUnaryConversions(Expr *E) { 771 // First, convert to an r-value. 772 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 773 if (Res.isInvalid()) 774 return ExprError(); 775 E = Res.get(); 776 777 QualType Ty = E->getType(); 778 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 779 780 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); 781 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() && 782 (getLangOpts().getFPEvalMethod() != 783 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine || 784 PP.getLastFPEvalPragmaLocation().isValid())) { 785 switch (EvalMethod) { 786 default: 787 llvm_unreachable("Unrecognized float evaluation method"); 788 break; 789 case LangOptions::FEM_UnsetOnCommandLine: 790 llvm_unreachable("Float evaluation method should be set by now"); 791 break; 792 case LangOptions::FEM_Double: 793 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0) 794 // Widen the expression to double. 795 return Ty->isComplexType() 796 ? ImpCastExprToType(E, 797 Context.getComplexType(Context.DoubleTy), 798 CK_FloatingComplexCast) 799 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast); 800 break; 801 case LangOptions::FEM_Extended: 802 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0) 803 // Widen the expression to long double. 804 return Ty->isComplexType() 805 ? ImpCastExprToType( 806 E, Context.getComplexType(Context.LongDoubleTy), 807 CK_FloatingComplexCast) 808 : ImpCastExprToType(E, Context.LongDoubleTy, 809 CK_FloatingCast); 810 break; 811 } 812 } 813 814 // Half FP have to be promoted to float unless it is natively supported 815 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 816 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 817 818 // Try to perform integral promotions if the object has a theoretically 819 // promotable type. 820 if (Ty->isIntegralOrUnscopedEnumerationType()) { 821 // C99 6.3.1.1p2: 822 // 823 // The following may be used in an expression wherever an int or 824 // unsigned int may be used: 825 // - an object or expression with an integer type whose integer 826 // conversion rank is less than or equal to the rank of int 827 // and unsigned int. 828 // - A bit-field of type _Bool, int, signed int, or unsigned int. 829 // 830 // If an int can represent all values of the original type, the 831 // value is converted to an int; otherwise, it is converted to an 832 // unsigned int. These are called the integer promotions. All 833 // other types are unchanged by the integer promotions. 834 835 QualType PTy = Context.isPromotableBitField(E); 836 if (!PTy.isNull()) { 837 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 838 return E; 839 } 840 if (Ty->isPromotableIntegerType()) { 841 QualType PT = Context.getPromotedIntegerType(Ty); 842 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 843 return E; 844 } 845 } 846 return E; 847 } 848 849 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 850 /// do not have a prototype. Arguments that have type float or __fp16 851 /// are promoted to double. All other argument types are converted by 852 /// UsualUnaryConversions(). 853 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 854 QualType Ty = E->getType(); 855 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 856 857 ExprResult Res = UsualUnaryConversions(E); 858 if (Res.isInvalid()) 859 return ExprError(); 860 E = Res.get(); 861 862 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 863 // promote to double. 864 // Note that default argument promotion applies only to float (and 865 // half/fp16); it does not apply to _Float16. 866 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 867 if (BTy && (BTy->getKind() == BuiltinType::Half || 868 BTy->getKind() == BuiltinType::Float)) { 869 if (getLangOpts().OpenCL && 870 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 871 if (BTy->getKind() == BuiltinType::Half) { 872 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 873 } 874 } else { 875 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 876 } 877 } 878 if (BTy && 879 getLangOpts().getExtendIntArgs() == 880 LangOptions::ExtendArgsKind::ExtendTo64 && 881 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 882 Context.getTypeSizeInChars(BTy) < 883 Context.getTypeSizeInChars(Context.LongLongTy)) { 884 E = (Ty->isUnsignedIntegerType()) 885 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 886 .get() 887 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 888 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 889 "Unexpected typesize for LongLongTy"); 890 } 891 892 // C++ performs lvalue-to-rvalue conversion as a default argument 893 // promotion, even on class types, but note: 894 // C++11 [conv.lval]p2: 895 // When an lvalue-to-rvalue conversion occurs in an unevaluated 896 // operand or a subexpression thereof the value contained in the 897 // referenced object is not accessed. Otherwise, if the glvalue 898 // has a class type, the conversion copy-initializes a temporary 899 // of type T from the glvalue and the result of the conversion 900 // is a prvalue for the temporary. 901 // FIXME: add some way to gate this entire thing for correctness in 902 // potentially potentially evaluated contexts. 903 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 904 ExprResult Temp = PerformCopyInitialization( 905 InitializedEntity::InitializeTemporary(E->getType()), 906 E->getExprLoc(), E); 907 if (Temp.isInvalid()) 908 return ExprError(); 909 E = Temp.get(); 910 } 911 912 return E; 913 } 914 915 /// Determine the degree of POD-ness for an expression. 916 /// Incomplete types are considered POD, since this check can be performed 917 /// when we're in an unevaluated context. 918 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 919 if (Ty->isIncompleteType()) { 920 // C++11 [expr.call]p7: 921 // After these conversions, if the argument does not have arithmetic, 922 // enumeration, pointer, pointer to member, or class type, the program 923 // is ill-formed. 924 // 925 // Since we've already performed array-to-pointer and function-to-pointer 926 // decay, the only such type in C++ is cv void. This also handles 927 // initializer lists as variadic arguments. 928 if (Ty->isVoidType()) 929 return VAK_Invalid; 930 931 if (Ty->isObjCObjectType()) 932 return VAK_Invalid; 933 return VAK_Valid; 934 } 935 936 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 937 return VAK_Invalid; 938 939 if (Ty.isCXX98PODType(Context)) 940 return VAK_Valid; 941 942 // C++11 [expr.call]p7: 943 // Passing a potentially-evaluated argument of class type (Clause 9) 944 // having a non-trivial copy constructor, a non-trivial move constructor, 945 // or a non-trivial destructor, with no corresponding parameter, 946 // is conditionally-supported with implementation-defined semantics. 947 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 948 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 949 if (!Record->hasNonTrivialCopyConstructor() && 950 !Record->hasNonTrivialMoveConstructor() && 951 !Record->hasNonTrivialDestructor()) 952 return VAK_ValidInCXX11; 953 954 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 955 return VAK_Valid; 956 957 if (Ty->isObjCObjectType()) 958 return VAK_Invalid; 959 960 if (getLangOpts().MSVCCompat) 961 return VAK_MSVCUndefined; 962 963 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 964 // permitted to reject them. We should consider doing so. 965 return VAK_Undefined; 966 } 967 968 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 969 // Don't allow one to pass an Objective-C interface to a vararg. 970 const QualType &Ty = E->getType(); 971 VarArgKind VAK = isValidVarArgType(Ty); 972 973 // Complain about passing non-POD types through varargs. 974 switch (VAK) { 975 case VAK_ValidInCXX11: 976 DiagRuntimeBehavior( 977 E->getBeginLoc(), nullptr, 978 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 979 LLVM_FALLTHROUGH; 980 case VAK_Valid: 981 if (Ty->isRecordType()) { 982 // This is unlikely to be what the user intended. If the class has a 983 // 'c_str' member function, the user probably meant to call that. 984 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 985 PDiag(diag::warn_pass_class_arg_to_vararg) 986 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 987 } 988 break; 989 990 case VAK_Undefined: 991 case VAK_MSVCUndefined: 992 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 993 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 994 << getLangOpts().CPlusPlus11 << Ty << CT); 995 break; 996 997 case VAK_Invalid: 998 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 999 Diag(E->getBeginLoc(), 1000 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 1001 << Ty << CT; 1002 else if (Ty->isObjCObjectType()) 1003 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 1004 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 1005 << Ty << CT); 1006 else 1007 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 1008 << isa<InitListExpr>(E) << Ty << CT; 1009 break; 1010 } 1011 } 1012 1013 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 1014 /// will create a trap if the resulting type is not a POD type. 1015 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 1016 FunctionDecl *FDecl) { 1017 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 1018 // Strip the unbridged-cast placeholder expression off, if applicable. 1019 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 1020 (CT == VariadicMethod || 1021 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 1022 E = stripARCUnbridgedCast(E); 1023 1024 // Otherwise, do normal placeholder checking. 1025 } else { 1026 ExprResult ExprRes = CheckPlaceholderExpr(E); 1027 if (ExprRes.isInvalid()) 1028 return ExprError(); 1029 E = ExprRes.get(); 1030 } 1031 } 1032 1033 ExprResult ExprRes = DefaultArgumentPromotion(E); 1034 if (ExprRes.isInvalid()) 1035 return ExprError(); 1036 1037 // Copy blocks to the heap. 1038 if (ExprRes.get()->getType()->isBlockPointerType()) 1039 maybeExtendBlockObject(ExprRes); 1040 1041 E = ExprRes.get(); 1042 1043 // Diagnostics regarding non-POD argument types are 1044 // emitted along with format string checking in Sema::CheckFunctionCall(). 1045 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1046 // Turn this into a trap. 1047 CXXScopeSpec SS; 1048 SourceLocation TemplateKWLoc; 1049 UnqualifiedId Name; 1050 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1051 E->getBeginLoc()); 1052 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1053 /*HasTrailingLParen=*/true, 1054 /*IsAddressOfOperand=*/false); 1055 if (TrapFn.isInvalid()) 1056 return ExprError(); 1057 1058 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1059 None, E->getEndLoc()); 1060 if (Call.isInvalid()) 1061 return ExprError(); 1062 1063 ExprResult Comma = 1064 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1065 if (Comma.isInvalid()) 1066 return ExprError(); 1067 return Comma.get(); 1068 } 1069 1070 if (!getLangOpts().CPlusPlus && 1071 RequireCompleteType(E->getExprLoc(), E->getType(), 1072 diag::err_call_incomplete_argument)) 1073 return ExprError(); 1074 1075 return E; 1076 } 1077 1078 /// Converts an integer to complex float type. Helper function of 1079 /// UsualArithmeticConversions() 1080 /// 1081 /// \return false if the integer expression is an integer type and is 1082 /// successfully converted to the complex type. 1083 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1084 ExprResult &ComplexExpr, 1085 QualType IntTy, 1086 QualType ComplexTy, 1087 bool SkipCast) { 1088 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1089 if (SkipCast) return false; 1090 if (IntTy->isIntegerType()) { 1091 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1092 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1093 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1094 CK_FloatingRealToComplex); 1095 } else { 1096 assert(IntTy->isComplexIntegerType()); 1097 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1098 CK_IntegralComplexToFloatingComplex); 1099 } 1100 return false; 1101 } 1102 1103 /// Handle arithmetic conversion with complex types. Helper function of 1104 /// UsualArithmeticConversions() 1105 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1106 ExprResult &RHS, QualType LHSType, 1107 QualType RHSType, 1108 bool IsCompAssign) { 1109 // if we have an integer operand, the result is the complex type. 1110 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1111 /*skipCast*/false)) 1112 return LHSType; 1113 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1114 /*skipCast*/IsCompAssign)) 1115 return RHSType; 1116 1117 // This handles complex/complex, complex/float, or float/complex. 1118 // When both operands are complex, the shorter operand is converted to the 1119 // type of the longer, and that is the type of the result. This corresponds 1120 // to what is done when combining two real floating-point operands. 1121 // The fun begins when size promotion occur across type domains. 1122 // From H&S 6.3.4: When one operand is complex and the other is a real 1123 // floating-point type, the less precise type is converted, within it's 1124 // real or complex domain, to the precision of the other type. For example, 1125 // when combining a "long double" with a "double _Complex", the 1126 // "double _Complex" is promoted to "long double _Complex". 1127 1128 // Compute the rank of the two types, regardless of whether they are complex. 1129 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1130 1131 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1132 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1133 QualType LHSElementType = 1134 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1135 QualType RHSElementType = 1136 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1137 1138 QualType ResultType = S.Context.getComplexType(LHSElementType); 1139 if (Order < 0) { 1140 // Promote the precision of the LHS if not an assignment. 1141 ResultType = S.Context.getComplexType(RHSElementType); 1142 if (!IsCompAssign) { 1143 if (LHSComplexType) 1144 LHS = 1145 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1146 else 1147 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1148 } 1149 } else if (Order > 0) { 1150 // Promote the precision of the RHS. 1151 if (RHSComplexType) 1152 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1153 else 1154 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1155 } 1156 return ResultType; 1157 } 1158 1159 /// Handle arithmetic conversion from integer to float. Helper function 1160 /// of UsualArithmeticConversions() 1161 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1162 ExprResult &IntExpr, 1163 QualType FloatTy, QualType IntTy, 1164 bool ConvertFloat, bool ConvertInt) { 1165 if (IntTy->isIntegerType()) { 1166 if (ConvertInt) 1167 // Convert intExpr to the lhs floating point type. 1168 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1169 CK_IntegralToFloating); 1170 return FloatTy; 1171 } 1172 1173 // Convert both sides to the appropriate complex float. 1174 assert(IntTy->isComplexIntegerType()); 1175 QualType result = S.Context.getComplexType(FloatTy); 1176 1177 // _Complex int -> _Complex float 1178 if (ConvertInt) 1179 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1180 CK_IntegralComplexToFloatingComplex); 1181 1182 // float -> _Complex float 1183 if (ConvertFloat) 1184 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1185 CK_FloatingRealToComplex); 1186 1187 return result; 1188 } 1189 1190 /// Handle arithmethic conversion with floating point types. Helper 1191 /// function of UsualArithmeticConversions() 1192 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1193 ExprResult &RHS, QualType LHSType, 1194 QualType RHSType, bool IsCompAssign) { 1195 bool LHSFloat = LHSType->isRealFloatingType(); 1196 bool RHSFloat = RHSType->isRealFloatingType(); 1197 1198 // N1169 4.1.4: If one of the operands has a floating type and the other 1199 // operand has a fixed-point type, the fixed-point operand 1200 // is converted to the floating type [...] 1201 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1202 if (LHSFloat) 1203 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1204 else if (!IsCompAssign) 1205 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1206 return LHSFloat ? LHSType : RHSType; 1207 } 1208 1209 // If we have two real floating types, convert the smaller operand 1210 // to the bigger result. 1211 if (LHSFloat && RHSFloat) { 1212 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1213 if (order > 0) { 1214 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1215 return LHSType; 1216 } 1217 1218 assert(order < 0 && "illegal float comparison"); 1219 if (!IsCompAssign) 1220 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1221 return RHSType; 1222 } 1223 1224 if (LHSFloat) { 1225 // Half FP has to be promoted to float unless it is natively supported 1226 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1227 LHSType = S.Context.FloatTy; 1228 1229 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1230 /*ConvertFloat=*/!IsCompAssign, 1231 /*ConvertInt=*/ true); 1232 } 1233 assert(RHSFloat); 1234 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1235 /*ConvertFloat=*/ true, 1236 /*ConvertInt=*/!IsCompAssign); 1237 } 1238 1239 /// Diagnose attempts to convert between __float128, __ibm128 and 1240 /// long double if there is no support for such conversion. 1241 /// Helper function of UsualArithmeticConversions(). 1242 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1243 QualType RHSType) { 1244 // No issue if either is not a floating point type. 1245 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1246 return false; 1247 1248 // No issue if both have the same 128-bit float semantics. 1249 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1250 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1251 1252 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1253 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1254 1255 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1256 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1257 1258 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1259 &RHSSem != &llvm::APFloat::IEEEquad()) && 1260 (&LHSSem != &llvm::APFloat::IEEEquad() || 1261 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1262 return false; 1263 1264 return true; 1265 } 1266 1267 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1268 1269 namespace { 1270 /// These helper callbacks are placed in an anonymous namespace to 1271 /// permit their use as function template parameters. 1272 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1273 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1274 } 1275 1276 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1277 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1278 CK_IntegralComplexCast); 1279 } 1280 } 1281 1282 /// Handle integer arithmetic conversions. Helper function of 1283 /// UsualArithmeticConversions() 1284 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1285 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1286 ExprResult &RHS, QualType LHSType, 1287 QualType RHSType, bool IsCompAssign) { 1288 // The rules for this case are in C99 6.3.1.8 1289 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1290 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1291 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1292 if (LHSSigned == RHSSigned) { 1293 // Same signedness; use the higher-ranked type 1294 if (order >= 0) { 1295 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1296 return LHSType; 1297 } else if (!IsCompAssign) 1298 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1299 return RHSType; 1300 } else if (order != (LHSSigned ? 1 : -1)) { 1301 // The unsigned type has greater than or equal rank to the 1302 // signed type, so use the unsigned type 1303 if (RHSSigned) { 1304 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1305 return LHSType; 1306 } else if (!IsCompAssign) 1307 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1308 return RHSType; 1309 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1310 // The two types are different widths; if we are here, that 1311 // means the signed type is larger than the unsigned type, so 1312 // use the signed type. 1313 if (LHSSigned) { 1314 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1315 return LHSType; 1316 } else if (!IsCompAssign) 1317 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1318 return RHSType; 1319 } else { 1320 // The signed type is higher-ranked than the unsigned type, 1321 // but isn't actually any bigger (like unsigned int and long 1322 // on most 32-bit systems). Use the unsigned type corresponding 1323 // to the signed type. 1324 QualType result = 1325 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1326 RHS = (*doRHSCast)(S, RHS.get(), result); 1327 if (!IsCompAssign) 1328 LHS = (*doLHSCast)(S, LHS.get(), result); 1329 return result; 1330 } 1331 } 1332 1333 /// Handle conversions with GCC complex int extension. Helper function 1334 /// of UsualArithmeticConversions() 1335 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1336 ExprResult &RHS, QualType LHSType, 1337 QualType RHSType, 1338 bool IsCompAssign) { 1339 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1340 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1341 1342 if (LHSComplexInt && RHSComplexInt) { 1343 QualType LHSEltType = LHSComplexInt->getElementType(); 1344 QualType RHSEltType = RHSComplexInt->getElementType(); 1345 QualType ScalarType = 1346 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1347 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1348 1349 return S.Context.getComplexType(ScalarType); 1350 } 1351 1352 if (LHSComplexInt) { 1353 QualType LHSEltType = LHSComplexInt->getElementType(); 1354 QualType ScalarType = 1355 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1356 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1357 QualType ComplexType = S.Context.getComplexType(ScalarType); 1358 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1359 CK_IntegralRealToComplex); 1360 1361 return ComplexType; 1362 } 1363 1364 assert(RHSComplexInt); 1365 1366 QualType RHSEltType = RHSComplexInt->getElementType(); 1367 QualType ScalarType = 1368 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1369 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1370 QualType ComplexType = S.Context.getComplexType(ScalarType); 1371 1372 if (!IsCompAssign) 1373 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1374 CK_IntegralRealToComplex); 1375 return ComplexType; 1376 } 1377 1378 /// Return the rank of a given fixed point or integer type. The value itself 1379 /// doesn't matter, but the values must be increasing with proper increasing 1380 /// rank as described in N1169 4.1.1. 1381 static unsigned GetFixedPointRank(QualType Ty) { 1382 const auto *BTy = Ty->getAs<BuiltinType>(); 1383 assert(BTy && "Expected a builtin type."); 1384 1385 switch (BTy->getKind()) { 1386 case BuiltinType::ShortFract: 1387 case BuiltinType::UShortFract: 1388 case BuiltinType::SatShortFract: 1389 case BuiltinType::SatUShortFract: 1390 return 1; 1391 case BuiltinType::Fract: 1392 case BuiltinType::UFract: 1393 case BuiltinType::SatFract: 1394 case BuiltinType::SatUFract: 1395 return 2; 1396 case BuiltinType::LongFract: 1397 case BuiltinType::ULongFract: 1398 case BuiltinType::SatLongFract: 1399 case BuiltinType::SatULongFract: 1400 return 3; 1401 case BuiltinType::ShortAccum: 1402 case BuiltinType::UShortAccum: 1403 case BuiltinType::SatShortAccum: 1404 case BuiltinType::SatUShortAccum: 1405 return 4; 1406 case BuiltinType::Accum: 1407 case BuiltinType::UAccum: 1408 case BuiltinType::SatAccum: 1409 case BuiltinType::SatUAccum: 1410 return 5; 1411 case BuiltinType::LongAccum: 1412 case BuiltinType::ULongAccum: 1413 case BuiltinType::SatLongAccum: 1414 case BuiltinType::SatULongAccum: 1415 return 6; 1416 default: 1417 if (BTy->isInteger()) 1418 return 0; 1419 llvm_unreachable("Unexpected fixed point or integer type"); 1420 } 1421 } 1422 1423 /// handleFixedPointConversion - Fixed point operations between fixed 1424 /// point types and integers or other fixed point types do not fall under 1425 /// usual arithmetic conversion since these conversions could result in loss 1426 /// of precsision (N1169 4.1.4). These operations should be calculated with 1427 /// the full precision of their result type (N1169 4.1.6.2.1). 1428 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1429 QualType RHSTy) { 1430 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1431 "Expected at least one of the operands to be a fixed point type"); 1432 assert((LHSTy->isFixedPointOrIntegerType() || 1433 RHSTy->isFixedPointOrIntegerType()) && 1434 "Special fixed point arithmetic operation conversions are only " 1435 "applied to ints or other fixed point types"); 1436 1437 // If one operand has signed fixed-point type and the other operand has 1438 // unsigned fixed-point type, then the unsigned fixed-point operand is 1439 // converted to its corresponding signed fixed-point type and the resulting 1440 // type is the type of the converted operand. 1441 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1442 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1443 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1444 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1445 1446 // The result type is the type with the highest rank, whereby a fixed-point 1447 // conversion rank is always greater than an integer conversion rank; if the 1448 // type of either of the operands is a saturating fixedpoint type, the result 1449 // type shall be the saturating fixed-point type corresponding to the type 1450 // with the highest rank; the resulting value is converted (taking into 1451 // account rounding and overflow) to the precision of the resulting type. 1452 // Same ranks between signed and unsigned types are resolved earlier, so both 1453 // types are either signed or both unsigned at this point. 1454 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1455 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1456 1457 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1458 1459 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1460 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1461 1462 return ResultTy; 1463 } 1464 1465 /// Check that the usual arithmetic conversions can be performed on this pair of 1466 /// expressions that might be of enumeration type. 1467 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1468 SourceLocation Loc, 1469 Sema::ArithConvKind ACK) { 1470 // C++2a [expr.arith.conv]p1: 1471 // If one operand is of enumeration type and the other operand is of a 1472 // different enumeration type or a floating-point type, this behavior is 1473 // deprecated ([depr.arith.conv.enum]). 1474 // 1475 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1476 // Eventually we will presumably reject these cases (in C++23 onwards?). 1477 QualType L = LHS->getType(), R = RHS->getType(); 1478 bool LEnum = L->isUnscopedEnumerationType(), 1479 REnum = R->isUnscopedEnumerationType(); 1480 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1481 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1482 (REnum && L->isFloatingType())) { 1483 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1484 ? diag::warn_arith_conv_enum_float_cxx20 1485 : diag::warn_arith_conv_enum_float) 1486 << LHS->getSourceRange() << RHS->getSourceRange() 1487 << (int)ACK << LEnum << L << R; 1488 } else if (!IsCompAssign && LEnum && REnum && 1489 !S.Context.hasSameUnqualifiedType(L, R)) { 1490 unsigned DiagID; 1491 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1492 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1493 // If either enumeration type is unnamed, it's less likely that the 1494 // user cares about this, but this situation is still deprecated in 1495 // C++2a. Use a different warning group. 1496 DiagID = S.getLangOpts().CPlusPlus20 1497 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1498 : diag::warn_arith_conv_mixed_anon_enum_types; 1499 } else if (ACK == Sema::ACK_Conditional) { 1500 // Conditional expressions are separated out because they have 1501 // historically had a different warning flag. 1502 DiagID = S.getLangOpts().CPlusPlus20 1503 ? diag::warn_conditional_mixed_enum_types_cxx20 1504 : diag::warn_conditional_mixed_enum_types; 1505 } else if (ACK == Sema::ACK_Comparison) { 1506 // Comparison expressions are separated out because they have 1507 // historically had a different warning flag. 1508 DiagID = S.getLangOpts().CPlusPlus20 1509 ? diag::warn_comparison_mixed_enum_types_cxx20 1510 : diag::warn_comparison_mixed_enum_types; 1511 } else { 1512 DiagID = S.getLangOpts().CPlusPlus20 1513 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1514 : diag::warn_arith_conv_mixed_enum_types; 1515 } 1516 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1517 << (int)ACK << L << R; 1518 } 1519 } 1520 1521 /// UsualArithmeticConversions - Performs various conversions that are common to 1522 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1523 /// routine returns the first non-arithmetic type found. The client is 1524 /// responsible for emitting appropriate error diagnostics. 1525 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1526 SourceLocation Loc, 1527 ArithConvKind ACK) { 1528 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1529 1530 if (ACK != ACK_CompAssign) { 1531 LHS = UsualUnaryConversions(LHS.get()); 1532 if (LHS.isInvalid()) 1533 return QualType(); 1534 } 1535 1536 RHS = UsualUnaryConversions(RHS.get()); 1537 if (RHS.isInvalid()) 1538 return QualType(); 1539 1540 // For conversion purposes, we ignore any qualifiers. 1541 // For example, "const float" and "float" are equivalent. 1542 QualType LHSType = 1543 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1544 QualType RHSType = 1545 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1546 1547 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1548 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1549 LHSType = AtomicLHS->getValueType(); 1550 1551 // If both types are identical, no conversion is needed. 1552 if (LHSType == RHSType) 1553 return LHSType; 1554 1555 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1556 // The caller can deal with this (e.g. pointer + int). 1557 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1558 return QualType(); 1559 1560 // Apply unary and bitfield promotions to the LHS's type. 1561 QualType LHSUnpromotedType = LHSType; 1562 if (LHSType->isPromotableIntegerType()) 1563 LHSType = Context.getPromotedIntegerType(LHSType); 1564 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1565 if (!LHSBitfieldPromoteTy.isNull()) 1566 LHSType = LHSBitfieldPromoteTy; 1567 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1568 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1569 1570 // If both types are identical, no conversion is needed. 1571 if (LHSType == RHSType) 1572 return LHSType; 1573 1574 // At this point, we have two different arithmetic types. 1575 1576 // Diagnose attempts to convert between __ibm128, __float128 and long double 1577 // where such conversions currently can't be handled. 1578 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1579 return QualType(); 1580 1581 // Handle complex types first (C99 6.3.1.8p1). 1582 if (LHSType->isComplexType() || RHSType->isComplexType()) 1583 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1584 ACK == ACK_CompAssign); 1585 1586 // Now handle "real" floating types (i.e. float, double, long double). 1587 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1588 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1589 ACK == ACK_CompAssign); 1590 1591 // Handle GCC complex int extension. 1592 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1593 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1594 ACK == ACK_CompAssign); 1595 1596 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1597 return handleFixedPointConversion(*this, LHSType, RHSType); 1598 1599 // Finally, we have two differing integer types. 1600 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1601 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1602 } 1603 1604 //===----------------------------------------------------------------------===// 1605 // Semantic Analysis for various Expression Types 1606 //===----------------------------------------------------------------------===// 1607 1608 1609 ExprResult 1610 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1611 SourceLocation DefaultLoc, 1612 SourceLocation RParenLoc, 1613 Expr *ControllingExpr, 1614 ArrayRef<ParsedType> ArgTypes, 1615 ArrayRef<Expr *> ArgExprs) { 1616 unsigned NumAssocs = ArgTypes.size(); 1617 assert(NumAssocs == ArgExprs.size()); 1618 1619 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1620 for (unsigned i = 0; i < NumAssocs; ++i) { 1621 if (ArgTypes[i]) 1622 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1623 else 1624 Types[i] = nullptr; 1625 } 1626 1627 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1628 ControllingExpr, 1629 llvm::makeArrayRef(Types, NumAssocs), 1630 ArgExprs); 1631 delete [] Types; 1632 return ER; 1633 } 1634 1635 ExprResult 1636 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1637 SourceLocation DefaultLoc, 1638 SourceLocation RParenLoc, 1639 Expr *ControllingExpr, 1640 ArrayRef<TypeSourceInfo *> Types, 1641 ArrayRef<Expr *> Exprs) { 1642 unsigned NumAssocs = Types.size(); 1643 assert(NumAssocs == Exprs.size()); 1644 1645 // Decay and strip qualifiers for the controlling expression type, and handle 1646 // placeholder type replacement. See committee discussion from WG14 DR423. 1647 { 1648 EnterExpressionEvaluationContext Unevaluated( 1649 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1650 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1651 if (R.isInvalid()) 1652 return ExprError(); 1653 ControllingExpr = R.get(); 1654 } 1655 1656 // The controlling expression is an unevaluated operand, so side effects are 1657 // likely unintended. 1658 if (!inTemplateInstantiation() && 1659 ControllingExpr->HasSideEffects(Context, false)) 1660 Diag(ControllingExpr->getExprLoc(), 1661 diag::warn_side_effects_unevaluated_context); 1662 1663 bool TypeErrorFound = false, 1664 IsResultDependent = ControllingExpr->isTypeDependent(), 1665 ContainsUnexpandedParameterPack 1666 = ControllingExpr->containsUnexpandedParameterPack(); 1667 1668 for (unsigned i = 0; i < NumAssocs; ++i) { 1669 if (Exprs[i]->containsUnexpandedParameterPack()) 1670 ContainsUnexpandedParameterPack = true; 1671 1672 if (Types[i]) { 1673 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1674 ContainsUnexpandedParameterPack = true; 1675 1676 if (Types[i]->getType()->isDependentType()) { 1677 IsResultDependent = true; 1678 } else { 1679 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1680 // complete object type other than a variably modified type." 1681 unsigned D = 0; 1682 if (Types[i]->getType()->isIncompleteType()) 1683 D = diag::err_assoc_type_incomplete; 1684 else if (!Types[i]->getType()->isObjectType()) 1685 D = diag::err_assoc_type_nonobject; 1686 else if (Types[i]->getType()->isVariablyModifiedType()) 1687 D = diag::err_assoc_type_variably_modified; 1688 1689 if (D != 0) { 1690 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1691 << Types[i]->getTypeLoc().getSourceRange() 1692 << Types[i]->getType(); 1693 TypeErrorFound = true; 1694 } 1695 1696 // C11 6.5.1.1p2 "No two generic associations in the same generic 1697 // selection shall specify compatible types." 1698 for (unsigned j = i+1; j < NumAssocs; ++j) 1699 if (Types[j] && !Types[j]->getType()->isDependentType() && 1700 Context.typesAreCompatible(Types[i]->getType(), 1701 Types[j]->getType())) { 1702 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1703 diag::err_assoc_compatible_types) 1704 << Types[j]->getTypeLoc().getSourceRange() 1705 << Types[j]->getType() 1706 << Types[i]->getType(); 1707 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1708 diag::note_compat_assoc) 1709 << Types[i]->getTypeLoc().getSourceRange() 1710 << Types[i]->getType(); 1711 TypeErrorFound = true; 1712 } 1713 } 1714 } 1715 } 1716 if (TypeErrorFound) 1717 return ExprError(); 1718 1719 // If we determined that the generic selection is result-dependent, don't 1720 // try to compute the result expression. 1721 if (IsResultDependent) 1722 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1723 Exprs, DefaultLoc, RParenLoc, 1724 ContainsUnexpandedParameterPack); 1725 1726 SmallVector<unsigned, 1> CompatIndices; 1727 unsigned DefaultIndex = -1U; 1728 for (unsigned i = 0; i < NumAssocs; ++i) { 1729 if (!Types[i]) 1730 DefaultIndex = i; 1731 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1732 Types[i]->getType())) 1733 CompatIndices.push_back(i); 1734 } 1735 1736 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1737 // type compatible with at most one of the types named in its generic 1738 // association list." 1739 if (CompatIndices.size() > 1) { 1740 // We strip parens here because the controlling expression is typically 1741 // parenthesized in macro definitions. 1742 ControllingExpr = ControllingExpr->IgnoreParens(); 1743 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1744 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1745 << (unsigned)CompatIndices.size(); 1746 for (unsigned I : CompatIndices) { 1747 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1748 diag::note_compat_assoc) 1749 << Types[I]->getTypeLoc().getSourceRange() 1750 << Types[I]->getType(); 1751 } 1752 return ExprError(); 1753 } 1754 1755 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1756 // its controlling expression shall have type compatible with exactly one of 1757 // the types named in its generic association list." 1758 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1759 // We strip parens here because the controlling expression is typically 1760 // parenthesized in macro definitions. 1761 ControllingExpr = ControllingExpr->IgnoreParens(); 1762 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1763 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1764 return ExprError(); 1765 } 1766 1767 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1768 // type name that is compatible with the type of the controlling expression, 1769 // then the result expression of the generic selection is the expression 1770 // in that generic association. Otherwise, the result expression of the 1771 // generic selection is the expression in the default generic association." 1772 unsigned ResultIndex = 1773 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1774 1775 return GenericSelectionExpr::Create( 1776 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1777 ContainsUnexpandedParameterPack, ResultIndex); 1778 } 1779 1780 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1781 /// location of the token and the offset of the ud-suffix within it. 1782 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1783 unsigned Offset) { 1784 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1785 S.getLangOpts()); 1786 } 1787 1788 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1789 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1790 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1791 IdentifierInfo *UDSuffix, 1792 SourceLocation UDSuffixLoc, 1793 ArrayRef<Expr*> Args, 1794 SourceLocation LitEndLoc) { 1795 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1796 1797 QualType ArgTy[2]; 1798 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1799 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1800 if (ArgTy[ArgIdx]->isArrayType()) 1801 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1802 } 1803 1804 DeclarationName OpName = 1805 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1806 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1807 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1808 1809 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1810 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1811 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1812 /*AllowStringTemplatePack*/ false, 1813 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1814 return ExprError(); 1815 1816 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1817 } 1818 1819 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1820 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1821 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1822 /// multiple tokens. However, the common case is that StringToks points to one 1823 /// string. 1824 /// 1825 ExprResult 1826 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1827 assert(!StringToks.empty() && "Must have at least one string!"); 1828 1829 StringLiteralParser Literal(StringToks, PP); 1830 if (Literal.hadError) 1831 return ExprError(); 1832 1833 SmallVector<SourceLocation, 4> StringTokLocs; 1834 for (const Token &Tok : StringToks) 1835 StringTokLocs.push_back(Tok.getLocation()); 1836 1837 QualType CharTy = Context.CharTy; 1838 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1839 if (Literal.isWide()) { 1840 CharTy = Context.getWideCharType(); 1841 Kind = StringLiteral::Wide; 1842 } else if (Literal.isUTF8()) { 1843 if (getLangOpts().Char8) 1844 CharTy = Context.Char8Ty; 1845 Kind = StringLiteral::UTF8; 1846 } else if (Literal.isUTF16()) { 1847 CharTy = Context.Char16Ty; 1848 Kind = StringLiteral::UTF16; 1849 } else if (Literal.isUTF32()) { 1850 CharTy = Context.Char32Ty; 1851 Kind = StringLiteral::UTF32; 1852 } else if (Literal.isPascal()) { 1853 CharTy = Context.UnsignedCharTy; 1854 } 1855 1856 // Warn on initializing an array of char from a u8 string literal; this 1857 // becomes ill-formed in C++2a. 1858 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1859 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1860 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1861 1862 // Create removals for all 'u8' prefixes in the string literal(s). This 1863 // ensures C++2a compatibility (but may change the program behavior when 1864 // built by non-Clang compilers for which the execution character set is 1865 // not always UTF-8). 1866 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1867 SourceLocation RemovalDiagLoc; 1868 for (const Token &Tok : StringToks) { 1869 if (Tok.getKind() == tok::utf8_string_literal) { 1870 if (RemovalDiagLoc.isInvalid()) 1871 RemovalDiagLoc = Tok.getLocation(); 1872 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1873 Tok.getLocation(), 1874 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1875 getSourceManager(), getLangOpts()))); 1876 } 1877 } 1878 Diag(RemovalDiagLoc, RemovalDiag); 1879 } 1880 1881 QualType StrTy = 1882 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1883 1884 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1885 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1886 Kind, Literal.Pascal, StrTy, 1887 &StringTokLocs[0], 1888 StringTokLocs.size()); 1889 if (Literal.getUDSuffix().empty()) 1890 return Lit; 1891 1892 // We're building a user-defined literal. 1893 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1894 SourceLocation UDSuffixLoc = 1895 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1896 Literal.getUDSuffixOffset()); 1897 1898 // Make sure we're allowed user-defined literals here. 1899 if (!UDLScope) 1900 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1901 1902 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1903 // operator "" X (str, len) 1904 QualType SizeType = Context.getSizeType(); 1905 1906 DeclarationName OpName = 1907 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1908 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1909 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1910 1911 QualType ArgTy[] = { 1912 Context.getArrayDecayedType(StrTy), SizeType 1913 }; 1914 1915 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1916 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1917 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1918 /*AllowStringTemplatePack*/ true, 1919 /*DiagnoseMissing*/ true, Lit)) { 1920 1921 case LOLR_Cooked: { 1922 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1923 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1924 StringTokLocs[0]); 1925 Expr *Args[] = { Lit, LenArg }; 1926 1927 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1928 } 1929 1930 case LOLR_Template: { 1931 TemplateArgumentListInfo ExplicitArgs; 1932 TemplateArgument Arg(Lit); 1933 TemplateArgumentLocInfo ArgInfo(Lit); 1934 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1935 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1936 &ExplicitArgs); 1937 } 1938 1939 case LOLR_StringTemplatePack: { 1940 TemplateArgumentListInfo ExplicitArgs; 1941 1942 unsigned CharBits = Context.getIntWidth(CharTy); 1943 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1944 llvm::APSInt Value(CharBits, CharIsUnsigned); 1945 1946 TemplateArgument TypeArg(CharTy); 1947 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1948 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1949 1950 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1951 Value = Lit->getCodeUnit(I); 1952 TemplateArgument Arg(Context, Value, CharTy); 1953 TemplateArgumentLocInfo ArgInfo; 1954 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1955 } 1956 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1957 &ExplicitArgs); 1958 } 1959 case LOLR_Raw: 1960 case LOLR_ErrorNoDiagnostic: 1961 llvm_unreachable("unexpected literal operator lookup result"); 1962 case LOLR_Error: 1963 return ExprError(); 1964 } 1965 llvm_unreachable("unexpected literal operator lookup result"); 1966 } 1967 1968 DeclRefExpr * 1969 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1970 SourceLocation Loc, 1971 const CXXScopeSpec *SS) { 1972 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1973 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1974 } 1975 1976 DeclRefExpr * 1977 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1978 const DeclarationNameInfo &NameInfo, 1979 const CXXScopeSpec *SS, NamedDecl *FoundD, 1980 SourceLocation TemplateKWLoc, 1981 const TemplateArgumentListInfo *TemplateArgs) { 1982 NestedNameSpecifierLoc NNS = 1983 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1984 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1985 TemplateArgs); 1986 } 1987 1988 // CUDA/HIP: Check whether a captured reference variable is referencing a 1989 // host variable in a device or host device lambda. 1990 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1991 VarDecl *VD) { 1992 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1993 return false; 1994 assert(VD->getType()->isReferenceType()); 1995 1996 // Check whether the reference variable is referencing a host variable. 1997 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1998 if (!DRE) 1999 return false; 2000 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 2001 if (!Referee || !Referee->hasGlobalStorage() || 2002 Referee->hasAttr<CUDADeviceAttr>()) 2003 return false; 2004 2005 // Check whether the current function is a device or host device lambda. 2006 // Check whether the reference variable is a capture by getDeclContext() 2007 // since refersToEnclosingVariableOrCapture() is not ready at this point. 2008 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 2009 if (MD && MD->getParent()->isLambda() && 2010 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 2011 VD->getDeclContext() != MD) 2012 return true; 2013 2014 return false; 2015 } 2016 2017 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 2018 // A declaration named in an unevaluated operand never constitutes an odr-use. 2019 if (isUnevaluatedContext()) 2020 return NOUR_Unevaluated; 2021 2022 // C++2a [basic.def.odr]p4: 2023 // A variable x whose name appears as a potentially-evaluated expression e 2024 // is odr-used by e unless [...] x is a reference that is usable in 2025 // constant expressions. 2026 // CUDA/HIP: 2027 // If a reference variable referencing a host variable is captured in a 2028 // device or host device lambda, the value of the referee must be copied 2029 // to the capture and the reference variable must be treated as odr-use 2030 // since the value of the referee is not known at compile time and must 2031 // be loaded from the captured. 2032 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2033 if (VD->getType()->isReferenceType() && 2034 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2035 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2036 VD->isUsableInConstantExpressions(Context)) 2037 return NOUR_Constant; 2038 } 2039 2040 // All remaining non-variable cases constitute an odr-use. For variables, we 2041 // need to wait and see how the expression is used. 2042 return NOUR_None; 2043 } 2044 2045 /// BuildDeclRefExpr - Build an expression that references a 2046 /// declaration that does not require a closure capture. 2047 DeclRefExpr * 2048 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2049 const DeclarationNameInfo &NameInfo, 2050 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2051 SourceLocation TemplateKWLoc, 2052 const TemplateArgumentListInfo *TemplateArgs) { 2053 bool RefersToCapturedVariable = 2054 isa<VarDecl>(D) && 2055 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2056 2057 DeclRefExpr *E = DeclRefExpr::Create( 2058 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2059 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2060 MarkDeclRefReferenced(E); 2061 2062 // C++ [except.spec]p17: 2063 // An exception-specification is considered to be needed when: 2064 // - in an expression, the function is the unique lookup result or 2065 // the selected member of a set of overloaded functions. 2066 // 2067 // We delay doing this until after we've built the function reference and 2068 // marked it as used so that: 2069 // a) if the function is defaulted, we get errors from defining it before / 2070 // instead of errors from computing its exception specification, and 2071 // b) if the function is a defaulted comparison, we can use the body we 2072 // build when defining it as input to the exception specification 2073 // computation rather than computing a new body. 2074 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2075 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2076 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2077 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2078 } 2079 } 2080 2081 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2082 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2083 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2084 getCurFunction()->recordUseOfWeak(E); 2085 2086 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2087 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2088 FD = IFD->getAnonField(); 2089 if (FD) { 2090 UnusedPrivateFields.remove(FD); 2091 // Just in case we're building an illegal pointer-to-member. 2092 if (FD->isBitField()) 2093 E->setObjectKind(OK_BitField); 2094 } 2095 2096 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2097 // designates a bit-field. 2098 if (auto *BD = dyn_cast<BindingDecl>(D)) 2099 if (auto *BE = BD->getBinding()) 2100 E->setObjectKind(BE->getObjectKind()); 2101 2102 return E; 2103 } 2104 2105 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2106 /// possibly a list of template arguments. 2107 /// 2108 /// If this produces template arguments, it is permitted to call 2109 /// DecomposeTemplateName. 2110 /// 2111 /// This actually loses a lot of source location information for 2112 /// non-standard name kinds; we should consider preserving that in 2113 /// some way. 2114 void 2115 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2116 TemplateArgumentListInfo &Buffer, 2117 DeclarationNameInfo &NameInfo, 2118 const TemplateArgumentListInfo *&TemplateArgs) { 2119 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2120 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2121 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2122 2123 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2124 Id.TemplateId->NumArgs); 2125 translateTemplateArguments(TemplateArgsPtr, Buffer); 2126 2127 TemplateName TName = Id.TemplateId->Template.get(); 2128 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2129 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2130 TemplateArgs = &Buffer; 2131 } else { 2132 NameInfo = GetNameFromUnqualifiedId(Id); 2133 TemplateArgs = nullptr; 2134 } 2135 } 2136 2137 static void emitEmptyLookupTypoDiagnostic( 2138 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2139 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2140 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2141 DeclContext *Ctx = 2142 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2143 if (!TC) { 2144 // Emit a special diagnostic for failed member lookups. 2145 // FIXME: computing the declaration context might fail here (?) 2146 if (Ctx) 2147 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2148 << SS.getRange(); 2149 else 2150 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2151 return; 2152 } 2153 2154 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2155 bool DroppedSpecifier = 2156 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2157 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2158 ? diag::note_implicit_param_decl 2159 : diag::note_previous_decl; 2160 if (!Ctx) 2161 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2162 SemaRef.PDiag(NoteID)); 2163 else 2164 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2165 << Typo << Ctx << DroppedSpecifier 2166 << SS.getRange(), 2167 SemaRef.PDiag(NoteID)); 2168 } 2169 2170 /// Diagnose a lookup that found results in an enclosing class during error 2171 /// recovery. This usually indicates that the results were found in a dependent 2172 /// base class that could not be searched as part of a template definition. 2173 /// Always issues a diagnostic (though this may be only a warning in MS 2174 /// compatibility mode). 2175 /// 2176 /// Return \c true if the error is unrecoverable, or \c false if the caller 2177 /// should attempt to recover using these lookup results. 2178 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2179 // During a default argument instantiation the CurContext points 2180 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2181 // function parameter list, hence add an explicit check. 2182 bool isDefaultArgument = 2183 !CodeSynthesisContexts.empty() && 2184 CodeSynthesisContexts.back().Kind == 2185 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2186 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2187 bool isInstance = CurMethod && CurMethod->isInstance() && 2188 R.getNamingClass() == CurMethod->getParent() && 2189 !isDefaultArgument; 2190 2191 // There are two ways we can find a class-scope declaration during template 2192 // instantiation that we did not find in the template definition: if it is a 2193 // member of a dependent base class, or if it is declared after the point of 2194 // use in the same class. Distinguish these by comparing the class in which 2195 // the member was found to the naming class of the lookup. 2196 unsigned DiagID = diag::err_found_in_dependent_base; 2197 unsigned NoteID = diag::note_member_declared_at; 2198 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2199 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2200 : diag::err_found_later_in_class; 2201 } else if (getLangOpts().MSVCCompat) { 2202 DiagID = diag::ext_found_in_dependent_base; 2203 NoteID = diag::note_dependent_member_use; 2204 } 2205 2206 if (isInstance) { 2207 // Give a code modification hint to insert 'this->'. 2208 Diag(R.getNameLoc(), DiagID) 2209 << R.getLookupName() 2210 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2211 CheckCXXThisCapture(R.getNameLoc()); 2212 } else { 2213 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2214 // they're not shadowed). 2215 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2216 } 2217 2218 for (NamedDecl *D : R) 2219 Diag(D->getLocation(), NoteID); 2220 2221 // Return true if we are inside a default argument instantiation 2222 // and the found name refers to an instance member function, otherwise 2223 // the caller will try to create an implicit member call and this is wrong 2224 // for default arguments. 2225 // 2226 // FIXME: Is this special case necessary? We could allow the caller to 2227 // diagnose this. 2228 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2229 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2230 return true; 2231 } 2232 2233 // Tell the callee to try to recover. 2234 return false; 2235 } 2236 2237 /// Diagnose an empty lookup. 2238 /// 2239 /// \return false if new lookup candidates were found 2240 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2241 CorrectionCandidateCallback &CCC, 2242 TemplateArgumentListInfo *ExplicitTemplateArgs, 2243 ArrayRef<Expr *> Args, TypoExpr **Out) { 2244 DeclarationName Name = R.getLookupName(); 2245 2246 unsigned diagnostic = diag::err_undeclared_var_use; 2247 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2248 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2249 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2250 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2251 diagnostic = diag::err_undeclared_use; 2252 diagnostic_suggest = diag::err_undeclared_use_suggest; 2253 } 2254 2255 // If the original lookup was an unqualified lookup, fake an 2256 // unqualified lookup. This is useful when (for example) the 2257 // original lookup would not have found something because it was a 2258 // dependent name. 2259 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2260 while (DC) { 2261 if (isa<CXXRecordDecl>(DC)) { 2262 LookupQualifiedName(R, DC); 2263 2264 if (!R.empty()) { 2265 // Don't give errors about ambiguities in this lookup. 2266 R.suppressDiagnostics(); 2267 2268 // If there's a best viable function among the results, only mention 2269 // that one in the notes. 2270 OverloadCandidateSet Candidates(R.getNameLoc(), 2271 OverloadCandidateSet::CSK_Normal); 2272 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2273 OverloadCandidateSet::iterator Best; 2274 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2275 OR_Success) { 2276 R.clear(); 2277 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2278 R.resolveKind(); 2279 } 2280 2281 return DiagnoseDependentMemberLookup(R); 2282 } 2283 2284 R.clear(); 2285 } 2286 2287 DC = DC->getLookupParent(); 2288 } 2289 2290 // We didn't find anything, so try to correct for a typo. 2291 TypoCorrection Corrected; 2292 if (S && Out) { 2293 SourceLocation TypoLoc = R.getNameLoc(); 2294 assert(!ExplicitTemplateArgs && 2295 "Diagnosing an empty lookup with explicit template args!"); 2296 *Out = CorrectTypoDelayed( 2297 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2298 [=](const TypoCorrection &TC) { 2299 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2300 diagnostic, diagnostic_suggest); 2301 }, 2302 nullptr, CTK_ErrorRecovery); 2303 if (*Out) 2304 return true; 2305 } else if (S && 2306 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2307 S, &SS, CCC, CTK_ErrorRecovery))) { 2308 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2309 bool DroppedSpecifier = 2310 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2311 R.setLookupName(Corrected.getCorrection()); 2312 2313 bool AcceptableWithRecovery = false; 2314 bool AcceptableWithoutRecovery = false; 2315 NamedDecl *ND = Corrected.getFoundDecl(); 2316 if (ND) { 2317 if (Corrected.isOverloaded()) { 2318 OverloadCandidateSet OCS(R.getNameLoc(), 2319 OverloadCandidateSet::CSK_Normal); 2320 OverloadCandidateSet::iterator Best; 2321 for (NamedDecl *CD : Corrected) { 2322 if (FunctionTemplateDecl *FTD = 2323 dyn_cast<FunctionTemplateDecl>(CD)) 2324 AddTemplateOverloadCandidate( 2325 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2326 Args, OCS); 2327 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2328 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2329 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2330 Args, OCS); 2331 } 2332 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2333 case OR_Success: 2334 ND = Best->FoundDecl; 2335 Corrected.setCorrectionDecl(ND); 2336 break; 2337 default: 2338 // FIXME: Arbitrarily pick the first declaration for the note. 2339 Corrected.setCorrectionDecl(ND); 2340 break; 2341 } 2342 } 2343 R.addDecl(ND); 2344 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2345 CXXRecordDecl *Record = nullptr; 2346 if (Corrected.getCorrectionSpecifier()) { 2347 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2348 Record = Ty->getAsCXXRecordDecl(); 2349 } 2350 if (!Record) 2351 Record = cast<CXXRecordDecl>( 2352 ND->getDeclContext()->getRedeclContext()); 2353 R.setNamingClass(Record); 2354 } 2355 2356 auto *UnderlyingND = ND->getUnderlyingDecl(); 2357 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2358 isa<FunctionTemplateDecl>(UnderlyingND); 2359 // FIXME: If we ended up with a typo for a type name or 2360 // Objective-C class name, we're in trouble because the parser 2361 // is in the wrong place to recover. Suggest the typo 2362 // correction, but don't make it a fix-it since we're not going 2363 // to recover well anyway. 2364 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2365 getAsTypeTemplateDecl(UnderlyingND) || 2366 isa<ObjCInterfaceDecl>(UnderlyingND); 2367 } else { 2368 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2369 // because we aren't able to recover. 2370 AcceptableWithoutRecovery = true; 2371 } 2372 2373 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2374 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2375 ? diag::note_implicit_param_decl 2376 : diag::note_previous_decl; 2377 if (SS.isEmpty()) 2378 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2379 PDiag(NoteID), AcceptableWithRecovery); 2380 else 2381 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2382 << Name << computeDeclContext(SS, false) 2383 << DroppedSpecifier << SS.getRange(), 2384 PDiag(NoteID), AcceptableWithRecovery); 2385 2386 // Tell the callee whether to try to recover. 2387 return !AcceptableWithRecovery; 2388 } 2389 } 2390 R.clear(); 2391 2392 // Emit a special diagnostic for failed member lookups. 2393 // FIXME: computing the declaration context might fail here (?) 2394 if (!SS.isEmpty()) { 2395 Diag(R.getNameLoc(), diag::err_no_member) 2396 << Name << computeDeclContext(SS, false) 2397 << SS.getRange(); 2398 return true; 2399 } 2400 2401 // Give up, we can't recover. 2402 Diag(R.getNameLoc(), diagnostic) << Name; 2403 return true; 2404 } 2405 2406 /// In Microsoft mode, if we are inside a template class whose parent class has 2407 /// dependent base classes, and we can't resolve an unqualified identifier, then 2408 /// assume the identifier is a member of a dependent base class. We can only 2409 /// recover successfully in static methods, instance methods, and other contexts 2410 /// where 'this' is available. This doesn't precisely match MSVC's 2411 /// instantiation model, but it's close enough. 2412 static Expr * 2413 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2414 DeclarationNameInfo &NameInfo, 2415 SourceLocation TemplateKWLoc, 2416 const TemplateArgumentListInfo *TemplateArgs) { 2417 // Only try to recover from lookup into dependent bases in static methods or 2418 // contexts where 'this' is available. 2419 QualType ThisType = S.getCurrentThisType(); 2420 const CXXRecordDecl *RD = nullptr; 2421 if (!ThisType.isNull()) 2422 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2423 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2424 RD = MD->getParent(); 2425 if (!RD || !RD->hasAnyDependentBases()) 2426 return nullptr; 2427 2428 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2429 // is available, suggest inserting 'this->' as a fixit. 2430 SourceLocation Loc = NameInfo.getLoc(); 2431 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2432 DB << NameInfo.getName() << RD; 2433 2434 if (!ThisType.isNull()) { 2435 DB << FixItHint::CreateInsertion(Loc, "this->"); 2436 return CXXDependentScopeMemberExpr::Create( 2437 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2438 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2439 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2440 } 2441 2442 // Synthesize a fake NNS that points to the derived class. This will 2443 // perform name lookup during template instantiation. 2444 CXXScopeSpec SS; 2445 auto *NNS = 2446 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2447 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2448 return DependentScopeDeclRefExpr::Create( 2449 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2450 TemplateArgs); 2451 } 2452 2453 ExprResult 2454 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2455 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2456 bool HasTrailingLParen, bool IsAddressOfOperand, 2457 CorrectionCandidateCallback *CCC, 2458 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2459 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2460 "cannot be direct & operand and have a trailing lparen"); 2461 if (SS.isInvalid()) 2462 return ExprError(); 2463 2464 TemplateArgumentListInfo TemplateArgsBuffer; 2465 2466 // Decompose the UnqualifiedId into the following data. 2467 DeclarationNameInfo NameInfo; 2468 const TemplateArgumentListInfo *TemplateArgs; 2469 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2470 2471 DeclarationName Name = NameInfo.getName(); 2472 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2473 SourceLocation NameLoc = NameInfo.getLoc(); 2474 2475 if (II && II->isEditorPlaceholder()) { 2476 // FIXME: When typed placeholders are supported we can create a typed 2477 // placeholder expression node. 2478 return ExprError(); 2479 } 2480 2481 // C++ [temp.dep.expr]p3: 2482 // An id-expression is type-dependent if it contains: 2483 // -- an identifier that was declared with a dependent type, 2484 // (note: handled after lookup) 2485 // -- a template-id that is dependent, 2486 // (note: handled in BuildTemplateIdExpr) 2487 // -- a conversion-function-id that specifies a dependent type, 2488 // -- a nested-name-specifier that contains a class-name that 2489 // names a dependent type. 2490 // Determine whether this is a member of an unknown specialization; 2491 // we need to handle these differently. 2492 bool DependentID = false; 2493 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2494 Name.getCXXNameType()->isDependentType()) { 2495 DependentID = true; 2496 } else if (SS.isSet()) { 2497 if (DeclContext *DC = computeDeclContext(SS, false)) { 2498 if (RequireCompleteDeclContext(SS, DC)) 2499 return ExprError(); 2500 } else { 2501 DependentID = true; 2502 } 2503 } 2504 2505 if (DependentID) 2506 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2507 IsAddressOfOperand, TemplateArgs); 2508 2509 // Perform the required lookup. 2510 LookupResult R(*this, NameInfo, 2511 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2512 ? LookupObjCImplicitSelfParam 2513 : LookupOrdinaryName); 2514 if (TemplateKWLoc.isValid() || TemplateArgs) { 2515 // Lookup the template name again to correctly establish the context in 2516 // which it was found. This is really unfortunate as we already did the 2517 // lookup to determine that it was a template name in the first place. If 2518 // this becomes a performance hit, we can work harder to preserve those 2519 // results until we get here but it's likely not worth it. 2520 bool MemberOfUnknownSpecialization; 2521 AssumedTemplateKind AssumedTemplate; 2522 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2523 MemberOfUnknownSpecialization, TemplateKWLoc, 2524 &AssumedTemplate)) 2525 return ExprError(); 2526 2527 if (MemberOfUnknownSpecialization || 2528 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2529 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2530 IsAddressOfOperand, TemplateArgs); 2531 } else { 2532 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2533 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2534 2535 // If the result might be in a dependent base class, this is a dependent 2536 // id-expression. 2537 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2538 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2539 IsAddressOfOperand, TemplateArgs); 2540 2541 // If this reference is in an Objective-C method, then we need to do 2542 // some special Objective-C lookup, too. 2543 if (IvarLookupFollowUp) { 2544 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2545 if (E.isInvalid()) 2546 return ExprError(); 2547 2548 if (Expr *Ex = E.getAs<Expr>()) 2549 return Ex; 2550 } 2551 } 2552 2553 if (R.isAmbiguous()) 2554 return ExprError(); 2555 2556 // This could be an implicitly declared function reference (legal in C90, 2557 // extension in C99, forbidden in C++). 2558 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2559 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2560 if (D) R.addDecl(D); 2561 } 2562 2563 // Determine whether this name might be a candidate for 2564 // argument-dependent lookup. 2565 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2566 2567 if (R.empty() && !ADL) { 2568 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2569 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2570 TemplateKWLoc, TemplateArgs)) 2571 return E; 2572 } 2573 2574 // Don't diagnose an empty lookup for inline assembly. 2575 if (IsInlineAsmIdentifier) 2576 return ExprError(); 2577 2578 // If this name wasn't predeclared and if this is not a function 2579 // call, diagnose the problem. 2580 TypoExpr *TE = nullptr; 2581 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2582 : nullptr); 2583 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2584 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2585 "Typo correction callback misconfigured"); 2586 if (CCC) { 2587 // Make sure the callback knows what the typo being diagnosed is. 2588 CCC->setTypoName(II); 2589 if (SS.isValid()) 2590 CCC->setTypoNNS(SS.getScopeRep()); 2591 } 2592 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2593 // a template name, but we happen to have always already looked up the name 2594 // before we get here if it must be a template name. 2595 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2596 None, &TE)) { 2597 if (TE && KeywordReplacement) { 2598 auto &State = getTypoExprState(TE); 2599 auto BestTC = State.Consumer->getNextCorrection(); 2600 if (BestTC.isKeyword()) { 2601 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2602 if (State.DiagHandler) 2603 State.DiagHandler(BestTC); 2604 KeywordReplacement->startToken(); 2605 KeywordReplacement->setKind(II->getTokenID()); 2606 KeywordReplacement->setIdentifierInfo(II); 2607 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2608 // Clean up the state associated with the TypoExpr, since it has 2609 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2610 clearDelayedTypo(TE); 2611 // Signal that a correction to a keyword was performed by returning a 2612 // valid-but-null ExprResult. 2613 return (Expr*)nullptr; 2614 } 2615 State.Consumer->resetCorrectionStream(); 2616 } 2617 return TE ? TE : ExprError(); 2618 } 2619 2620 assert(!R.empty() && 2621 "DiagnoseEmptyLookup returned false but added no results"); 2622 2623 // If we found an Objective-C instance variable, let 2624 // LookupInObjCMethod build the appropriate expression to 2625 // reference the ivar. 2626 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2627 R.clear(); 2628 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2629 // In a hopelessly buggy code, Objective-C instance variable 2630 // lookup fails and no expression will be built to reference it. 2631 if (!E.isInvalid() && !E.get()) 2632 return ExprError(); 2633 return E; 2634 } 2635 } 2636 2637 // This is guaranteed from this point on. 2638 assert(!R.empty() || ADL); 2639 2640 // Check whether this might be a C++ implicit instance member access. 2641 // C++ [class.mfct.non-static]p3: 2642 // When an id-expression that is not part of a class member access 2643 // syntax and not used to form a pointer to member is used in the 2644 // body of a non-static member function of class X, if name lookup 2645 // resolves the name in the id-expression to a non-static non-type 2646 // member of some class C, the id-expression is transformed into a 2647 // class member access expression using (*this) as the 2648 // postfix-expression to the left of the . operator. 2649 // 2650 // But we don't actually need to do this for '&' operands if R 2651 // resolved to a function or overloaded function set, because the 2652 // expression is ill-formed if it actually works out to be a 2653 // non-static member function: 2654 // 2655 // C++ [expr.ref]p4: 2656 // Otherwise, if E1.E2 refers to a non-static member function. . . 2657 // [t]he expression can be used only as the left-hand operand of a 2658 // member function call. 2659 // 2660 // There are other safeguards against such uses, but it's important 2661 // to get this right here so that we don't end up making a 2662 // spuriously dependent expression if we're inside a dependent 2663 // instance method. 2664 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2665 bool MightBeImplicitMember; 2666 if (!IsAddressOfOperand) 2667 MightBeImplicitMember = true; 2668 else if (!SS.isEmpty()) 2669 MightBeImplicitMember = false; 2670 else if (R.isOverloadedResult()) 2671 MightBeImplicitMember = false; 2672 else if (R.isUnresolvableResult()) 2673 MightBeImplicitMember = true; 2674 else 2675 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2676 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2677 isa<MSPropertyDecl>(R.getFoundDecl()); 2678 2679 if (MightBeImplicitMember) 2680 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2681 R, TemplateArgs, S); 2682 } 2683 2684 if (TemplateArgs || TemplateKWLoc.isValid()) { 2685 2686 // In C++1y, if this is a variable template id, then check it 2687 // in BuildTemplateIdExpr(). 2688 // The single lookup result must be a variable template declaration. 2689 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2690 Id.TemplateId->Kind == TNK_Var_template) { 2691 assert(R.getAsSingle<VarTemplateDecl>() && 2692 "There should only be one declaration found."); 2693 } 2694 2695 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2696 } 2697 2698 return BuildDeclarationNameExpr(SS, R, ADL); 2699 } 2700 2701 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2702 /// declaration name, generally during template instantiation. 2703 /// There's a large number of things which don't need to be done along 2704 /// this path. 2705 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2706 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2707 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2708 DeclContext *DC = computeDeclContext(SS, false); 2709 if (!DC) 2710 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2711 NameInfo, /*TemplateArgs=*/nullptr); 2712 2713 if (RequireCompleteDeclContext(SS, DC)) 2714 return ExprError(); 2715 2716 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2717 LookupQualifiedName(R, DC); 2718 2719 if (R.isAmbiguous()) 2720 return ExprError(); 2721 2722 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2723 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2724 NameInfo, /*TemplateArgs=*/nullptr); 2725 2726 if (R.empty()) { 2727 // Don't diagnose problems with invalid record decl, the secondary no_member 2728 // diagnostic during template instantiation is likely bogus, e.g. if a class 2729 // is invalid because it's derived from an invalid base class, then missing 2730 // members were likely supposed to be inherited. 2731 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2732 if (CD->isInvalidDecl()) 2733 return ExprError(); 2734 Diag(NameInfo.getLoc(), diag::err_no_member) 2735 << NameInfo.getName() << DC << SS.getRange(); 2736 return ExprError(); 2737 } 2738 2739 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2740 // Diagnose a missing typename if this resolved unambiguously to a type in 2741 // a dependent context. If we can recover with a type, downgrade this to 2742 // a warning in Microsoft compatibility mode. 2743 unsigned DiagID = diag::err_typename_missing; 2744 if (RecoveryTSI && getLangOpts().MSVCCompat) 2745 DiagID = diag::ext_typename_missing; 2746 SourceLocation Loc = SS.getBeginLoc(); 2747 auto D = Diag(Loc, DiagID); 2748 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2749 << SourceRange(Loc, NameInfo.getEndLoc()); 2750 2751 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2752 // context. 2753 if (!RecoveryTSI) 2754 return ExprError(); 2755 2756 // Only issue the fixit if we're prepared to recover. 2757 D << FixItHint::CreateInsertion(Loc, "typename "); 2758 2759 // Recover by pretending this was an elaborated type. 2760 QualType Ty = Context.getTypeDeclType(TD); 2761 TypeLocBuilder TLB; 2762 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2763 2764 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2765 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2766 QTL.setElaboratedKeywordLoc(SourceLocation()); 2767 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2768 2769 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2770 2771 return ExprEmpty(); 2772 } 2773 2774 // Defend against this resolving to an implicit member access. We usually 2775 // won't get here if this might be a legitimate a class member (we end up in 2776 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2777 // a pointer-to-member or in an unevaluated context in C++11. 2778 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2779 return BuildPossibleImplicitMemberExpr(SS, 2780 /*TemplateKWLoc=*/SourceLocation(), 2781 R, /*TemplateArgs=*/nullptr, S); 2782 2783 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2784 } 2785 2786 /// The parser has read a name in, and Sema has detected that we're currently 2787 /// inside an ObjC method. Perform some additional checks and determine if we 2788 /// should form a reference to an ivar. 2789 /// 2790 /// Ideally, most of this would be done by lookup, but there's 2791 /// actually quite a lot of extra work involved. 2792 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2793 IdentifierInfo *II) { 2794 SourceLocation Loc = Lookup.getNameLoc(); 2795 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2796 2797 // Check for error condition which is already reported. 2798 if (!CurMethod) 2799 return DeclResult(true); 2800 2801 // There are two cases to handle here. 1) scoped lookup could have failed, 2802 // in which case we should look for an ivar. 2) scoped lookup could have 2803 // found a decl, but that decl is outside the current instance method (i.e. 2804 // a global variable). In these two cases, we do a lookup for an ivar with 2805 // this name, if the lookup sucedes, we replace it our current decl. 2806 2807 // If we're in a class method, we don't normally want to look for 2808 // ivars. But if we don't find anything else, and there's an 2809 // ivar, that's an error. 2810 bool IsClassMethod = CurMethod->isClassMethod(); 2811 2812 bool LookForIvars; 2813 if (Lookup.empty()) 2814 LookForIvars = true; 2815 else if (IsClassMethod) 2816 LookForIvars = false; 2817 else 2818 LookForIvars = (Lookup.isSingleResult() && 2819 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2820 ObjCInterfaceDecl *IFace = nullptr; 2821 if (LookForIvars) { 2822 IFace = CurMethod->getClassInterface(); 2823 ObjCInterfaceDecl *ClassDeclared; 2824 ObjCIvarDecl *IV = nullptr; 2825 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2826 // Diagnose using an ivar in a class method. 2827 if (IsClassMethod) { 2828 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2829 return DeclResult(true); 2830 } 2831 2832 // Diagnose the use of an ivar outside of the declaring class. 2833 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2834 !declaresSameEntity(ClassDeclared, IFace) && 2835 !getLangOpts().DebuggerSupport) 2836 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2837 2838 // Success. 2839 return IV; 2840 } 2841 } else if (CurMethod->isInstanceMethod()) { 2842 // We should warn if a local variable hides an ivar. 2843 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2844 ObjCInterfaceDecl *ClassDeclared; 2845 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2846 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2847 declaresSameEntity(IFace, ClassDeclared)) 2848 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2849 } 2850 } 2851 } else if (Lookup.isSingleResult() && 2852 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2853 // If accessing a stand-alone ivar in a class method, this is an error. 2854 if (const ObjCIvarDecl *IV = 2855 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2856 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2857 return DeclResult(true); 2858 } 2859 } 2860 2861 // Didn't encounter an error, didn't find an ivar. 2862 return DeclResult(false); 2863 } 2864 2865 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2866 ObjCIvarDecl *IV) { 2867 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2868 assert(CurMethod && CurMethod->isInstanceMethod() && 2869 "should not reference ivar from this context"); 2870 2871 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2872 assert(IFace && "should not reference ivar from this context"); 2873 2874 // If we're referencing an invalid decl, just return this as a silent 2875 // error node. The error diagnostic was already emitted on the decl. 2876 if (IV->isInvalidDecl()) 2877 return ExprError(); 2878 2879 // Check if referencing a field with __attribute__((deprecated)). 2880 if (DiagnoseUseOfDecl(IV, Loc)) 2881 return ExprError(); 2882 2883 // FIXME: This should use a new expr for a direct reference, don't 2884 // turn this into Self->ivar, just return a BareIVarExpr or something. 2885 IdentifierInfo &II = Context.Idents.get("self"); 2886 UnqualifiedId SelfName; 2887 SelfName.setImplicitSelfParam(&II); 2888 CXXScopeSpec SelfScopeSpec; 2889 SourceLocation TemplateKWLoc; 2890 ExprResult SelfExpr = 2891 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2892 /*HasTrailingLParen=*/false, 2893 /*IsAddressOfOperand=*/false); 2894 if (SelfExpr.isInvalid()) 2895 return ExprError(); 2896 2897 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2898 if (SelfExpr.isInvalid()) 2899 return ExprError(); 2900 2901 MarkAnyDeclReferenced(Loc, IV, true); 2902 2903 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2904 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2905 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2906 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2907 2908 ObjCIvarRefExpr *Result = new (Context) 2909 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2910 IV->getLocation(), SelfExpr.get(), true, true); 2911 2912 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2913 if (!isUnevaluatedContext() && 2914 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2915 getCurFunction()->recordUseOfWeak(Result); 2916 } 2917 if (getLangOpts().ObjCAutoRefCount) 2918 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2919 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2920 2921 return Result; 2922 } 2923 2924 /// The parser has read a name in, and Sema has detected that we're currently 2925 /// inside an ObjC method. Perform some additional checks and determine if we 2926 /// should form a reference to an ivar. If so, build an expression referencing 2927 /// that ivar. 2928 ExprResult 2929 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2930 IdentifierInfo *II, bool AllowBuiltinCreation) { 2931 // FIXME: Integrate this lookup step into LookupParsedName. 2932 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2933 if (Ivar.isInvalid()) 2934 return ExprError(); 2935 if (Ivar.isUsable()) 2936 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2937 cast<ObjCIvarDecl>(Ivar.get())); 2938 2939 if (Lookup.empty() && II && AllowBuiltinCreation) 2940 LookupBuiltin(Lookup); 2941 2942 // Sentinel value saying that we didn't do anything special. 2943 return ExprResult(false); 2944 } 2945 2946 /// Cast a base object to a member's actual type. 2947 /// 2948 /// There are two relevant checks: 2949 /// 2950 /// C++ [class.access.base]p7: 2951 /// 2952 /// If a class member access operator [...] is used to access a non-static 2953 /// data member or non-static member function, the reference is ill-formed if 2954 /// the left operand [...] cannot be implicitly converted to a pointer to the 2955 /// naming class of the right operand. 2956 /// 2957 /// C++ [expr.ref]p7: 2958 /// 2959 /// If E2 is a non-static data member or a non-static member function, the 2960 /// program is ill-formed if the class of which E2 is directly a member is an 2961 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2962 /// 2963 /// Note that the latter check does not consider access; the access of the 2964 /// "real" base class is checked as appropriate when checking the access of the 2965 /// member name. 2966 ExprResult 2967 Sema::PerformObjectMemberConversion(Expr *From, 2968 NestedNameSpecifier *Qualifier, 2969 NamedDecl *FoundDecl, 2970 NamedDecl *Member) { 2971 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2972 if (!RD) 2973 return From; 2974 2975 QualType DestRecordType; 2976 QualType DestType; 2977 QualType FromRecordType; 2978 QualType FromType = From->getType(); 2979 bool PointerConversions = false; 2980 if (isa<FieldDecl>(Member)) { 2981 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2982 auto FromPtrType = FromType->getAs<PointerType>(); 2983 DestRecordType = Context.getAddrSpaceQualType( 2984 DestRecordType, FromPtrType 2985 ? FromType->getPointeeType().getAddressSpace() 2986 : FromType.getAddressSpace()); 2987 2988 if (FromPtrType) { 2989 DestType = Context.getPointerType(DestRecordType); 2990 FromRecordType = FromPtrType->getPointeeType(); 2991 PointerConversions = true; 2992 } else { 2993 DestType = DestRecordType; 2994 FromRecordType = FromType; 2995 } 2996 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2997 if (Method->isStatic()) 2998 return From; 2999 3000 DestType = Method->getThisType(); 3001 DestRecordType = DestType->getPointeeType(); 3002 3003 if (FromType->getAs<PointerType>()) { 3004 FromRecordType = FromType->getPointeeType(); 3005 PointerConversions = true; 3006 } else { 3007 FromRecordType = FromType; 3008 DestType = DestRecordType; 3009 } 3010 3011 LangAS FromAS = FromRecordType.getAddressSpace(); 3012 LangAS DestAS = DestRecordType.getAddressSpace(); 3013 if (FromAS != DestAS) { 3014 QualType FromRecordTypeWithoutAS = 3015 Context.removeAddrSpaceQualType(FromRecordType); 3016 QualType FromTypeWithDestAS = 3017 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 3018 if (PointerConversions) 3019 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 3020 From = ImpCastExprToType(From, FromTypeWithDestAS, 3021 CK_AddressSpaceConversion, From->getValueKind()) 3022 .get(); 3023 } 3024 } else { 3025 // No conversion necessary. 3026 return From; 3027 } 3028 3029 if (DestType->isDependentType() || FromType->isDependentType()) 3030 return From; 3031 3032 // If the unqualified types are the same, no conversion is necessary. 3033 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3034 return From; 3035 3036 SourceRange FromRange = From->getSourceRange(); 3037 SourceLocation FromLoc = FromRange.getBegin(); 3038 3039 ExprValueKind VK = From->getValueKind(); 3040 3041 // C++ [class.member.lookup]p8: 3042 // [...] Ambiguities can often be resolved by qualifying a name with its 3043 // class name. 3044 // 3045 // If the member was a qualified name and the qualified referred to a 3046 // specific base subobject type, we'll cast to that intermediate type 3047 // first and then to the object in which the member is declared. That allows 3048 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3049 // 3050 // class Base { public: int x; }; 3051 // class Derived1 : public Base { }; 3052 // class Derived2 : public Base { }; 3053 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3054 // 3055 // void VeryDerived::f() { 3056 // x = 17; // error: ambiguous base subobjects 3057 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3058 // } 3059 if (Qualifier && Qualifier->getAsType()) { 3060 QualType QType = QualType(Qualifier->getAsType(), 0); 3061 assert(QType->isRecordType() && "lookup done with non-record type"); 3062 3063 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); 3064 3065 // In C++98, the qualifier type doesn't actually have to be a base 3066 // type of the object type, in which case we just ignore it. 3067 // Otherwise build the appropriate casts. 3068 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3069 CXXCastPath BasePath; 3070 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3071 FromLoc, FromRange, &BasePath)) 3072 return ExprError(); 3073 3074 if (PointerConversions) 3075 QType = Context.getPointerType(QType); 3076 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3077 VK, &BasePath).get(); 3078 3079 FromType = QType; 3080 FromRecordType = QRecordType; 3081 3082 // If the qualifier type was the same as the destination type, 3083 // we're done. 3084 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3085 return From; 3086 } 3087 } 3088 3089 CXXCastPath BasePath; 3090 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3091 FromLoc, FromRange, &BasePath, 3092 /*IgnoreAccess=*/true)) 3093 return ExprError(); 3094 3095 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3096 VK, &BasePath); 3097 } 3098 3099 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3100 const LookupResult &R, 3101 bool HasTrailingLParen) { 3102 // Only when used directly as the postfix-expression of a call. 3103 if (!HasTrailingLParen) 3104 return false; 3105 3106 // Never if a scope specifier was provided. 3107 if (SS.isSet()) 3108 return false; 3109 3110 // Only in C++ or ObjC++. 3111 if (!getLangOpts().CPlusPlus) 3112 return false; 3113 3114 // Turn off ADL when we find certain kinds of declarations during 3115 // normal lookup: 3116 for (NamedDecl *D : R) { 3117 // C++0x [basic.lookup.argdep]p3: 3118 // -- a declaration of a class member 3119 // Since using decls preserve this property, we check this on the 3120 // original decl. 3121 if (D->isCXXClassMember()) 3122 return false; 3123 3124 // C++0x [basic.lookup.argdep]p3: 3125 // -- a block-scope function declaration that is not a 3126 // using-declaration 3127 // NOTE: we also trigger this for function templates (in fact, we 3128 // don't check the decl type at all, since all other decl types 3129 // turn off ADL anyway). 3130 if (isa<UsingShadowDecl>(D)) 3131 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3132 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3133 return false; 3134 3135 // C++0x [basic.lookup.argdep]p3: 3136 // -- a declaration that is neither a function or a function 3137 // template 3138 // And also for builtin functions. 3139 if (isa<FunctionDecl>(D)) { 3140 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3141 3142 // But also builtin functions. 3143 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3144 return false; 3145 } else if (!isa<FunctionTemplateDecl>(D)) 3146 return false; 3147 } 3148 3149 return true; 3150 } 3151 3152 3153 /// Diagnoses obvious problems with the use of the given declaration 3154 /// as an expression. This is only actually called for lookups that 3155 /// were not overloaded, and it doesn't promise that the declaration 3156 /// will in fact be used. 3157 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3158 if (D->isInvalidDecl()) 3159 return true; 3160 3161 if (isa<TypedefNameDecl>(D)) { 3162 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3163 return true; 3164 } 3165 3166 if (isa<ObjCInterfaceDecl>(D)) { 3167 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3168 return true; 3169 } 3170 3171 if (isa<NamespaceDecl>(D)) { 3172 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3173 return true; 3174 } 3175 3176 return false; 3177 } 3178 3179 // Certain multiversion types should be treated as overloaded even when there is 3180 // only one result. 3181 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3182 assert(R.isSingleResult() && "Expected only a single result"); 3183 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3184 return FD && 3185 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3186 } 3187 3188 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3189 LookupResult &R, bool NeedsADL, 3190 bool AcceptInvalidDecl) { 3191 // If this is a single, fully-resolved result and we don't need ADL, 3192 // just build an ordinary singleton decl ref. 3193 if (!NeedsADL && R.isSingleResult() && 3194 !R.getAsSingle<FunctionTemplateDecl>() && 3195 !ShouldLookupResultBeMultiVersionOverload(R)) 3196 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3197 R.getRepresentativeDecl(), nullptr, 3198 AcceptInvalidDecl); 3199 3200 // We only need to check the declaration if there's exactly one 3201 // result, because in the overloaded case the results can only be 3202 // functions and function templates. 3203 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3204 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3205 return ExprError(); 3206 3207 // Otherwise, just build an unresolved lookup expression. Suppress 3208 // any lookup-related diagnostics; we'll hash these out later, when 3209 // we've picked a target. 3210 R.suppressDiagnostics(); 3211 3212 UnresolvedLookupExpr *ULE 3213 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3214 SS.getWithLocInContext(Context), 3215 R.getLookupNameInfo(), 3216 NeedsADL, R.isOverloadedResult(), 3217 R.begin(), R.end()); 3218 3219 return ULE; 3220 } 3221 3222 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3223 ValueDecl *var); 3224 3225 /// Complete semantic analysis for a reference to the given declaration. 3226 ExprResult Sema::BuildDeclarationNameExpr( 3227 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3228 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3229 bool AcceptInvalidDecl) { 3230 assert(D && "Cannot refer to a NULL declaration"); 3231 assert(!isa<FunctionTemplateDecl>(D) && 3232 "Cannot refer unambiguously to a function template"); 3233 3234 SourceLocation Loc = NameInfo.getLoc(); 3235 if (CheckDeclInExpr(*this, Loc, D)) { 3236 // Recovery from invalid cases (e.g. D is an invalid Decl). 3237 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up 3238 // diagnostics, as invalid decls use int as a fallback type. 3239 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {}); 3240 } 3241 3242 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3243 // Specifically diagnose references to class templates that are missing 3244 // a template argument list. 3245 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3246 return ExprError(); 3247 } 3248 3249 // Make sure that we're referring to a value. 3250 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3251 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3252 Diag(D->getLocation(), diag::note_declared_at); 3253 return ExprError(); 3254 } 3255 3256 // Check whether this declaration can be used. Note that we suppress 3257 // this check when we're going to perform argument-dependent lookup 3258 // on this function name, because this might not be the function 3259 // that overload resolution actually selects. 3260 if (DiagnoseUseOfDecl(D, Loc)) 3261 return ExprError(); 3262 3263 auto *VD = cast<ValueDecl>(D); 3264 3265 // Only create DeclRefExpr's for valid Decl's. 3266 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3267 return ExprError(); 3268 3269 // Handle members of anonymous structs and unions. If we got here, 3270 // and the reference is to a class member indirect field, then this 3271 // must be the subject of a pointer-to-member expression. 3272 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3273 if (!indirectField->isCXXClassMember()) 3274 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3275 indirectField); 3276 3277 QualType type = VD->getType(); 3278 if (type.isNull()) 3279 return ExprError(); 3280 ExprValueKind valueKind = VK_PRValue; 3281 3282 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3283 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3284 // is expanded by some outer '...' in the context of the use. 3285 type = type.getNonPackExpansionType(); 3286 3287 switch (D->getKind()) { 3288 // Ignore all the non-ValueDecl kinds. 3289 #define ABSTRACT_DECL(kind) 3290 #define VALUE(type, base) 3291 #define DECL(type, base) case Decl::type: 3292 #include "clang/AST/DeclNodes.inc" 3293 llvm_unreachable("invalid value decl kind"); 3294 3295 // These shouldn't make it here. 3296 case Decl::ObjCAtDefsField: 3297 llvm_unreachable("forming non-member reference to ivar?"); 3298 3299 // Enum constants are always r-values and never references. 3300 // Unresolved using declarations are dependent. 3301 case Decl::EnumConstant: 3302 case Decl::UnresolvedUsingValue: 3303 case Decl::OMPDeclareReduction: 3304 case Decl::OMPDeclareMapper: 3305 valueKind = VK_PRValue; 3306 break; 3307 3308 // Fields and indirect fields that got here must be for 3309 // pointer-to-member expressions; we just call them l-values for 3310 // internal consistency, because this subexpression doesn't really 3311 // exist in the high-level semantics. 3312 case Decl::Field: 3313 case Decl::IndirectField: 3314 case Decl::ObjCIvar: 3315 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3316 3317 // These can't have reference type in well-formed programs, but 3318 // for internal consistency we do this anyway. 3319 type = type.getNonReferenceType(); 3320 valueKind = VK_LValue; 3321 break; 3322 3323 // Non-type template parameters are either l-values or r-values 3324 // depending on the type. 3325 case Decl::NonTypeTemplateParm: { 3326 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3327 type = reftype->getPointeeType(); 3328 valueKind = VK_LValue; // even if the parameter is an r-value reference 3329 break; 3330 } 3331 3332 // [expr.prim.id.unqual]p2: 3333 // If the entity is a template parameter object for a template 3334 // parameter of type T, the type of the expression is const T. 3335 // [...] The expression is an lvalue if the entity is a [...] template 3336 // parameter object. 3337 if (type->isRecordType()) { 3338 type = type.getUnqualifiedType().withConst(); 3339 valueKind = VK_LValue; 3340 break; 3341 } 3342 3343 // For non-references, we need to strip qualifiers just in case 3344 // the template parameter was declared as 'const int' or whatever. 3345 valueKind = VK_PRValue; 3346 type = type.getUnqualifiedType(); 3347 break; 3348 } 3349 3350 case Decl::Var: 3351 case Decl::VarTemplateSpecialization: 3352 case Decl::VarTemplatePartialSpecialization: 3353 case Decl::Decomposition: 3354 case Decl::OMPCapturedExpr: 3355 // In C, "extern void blah;" is valid and is an r-value. 3356 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3357 type->isVoidType()) { 3358 valueKind = VK_PRValue; 3359 break; 3360 } 3361 LLVM_FALLTHROUGH; 3362 3363 case Decl::ImplicitParam: 3364 case Decl::ParmVar: { 3365 // These are always l-values. 3366 valueKind = VK_LValue; 3367 type = type.getNonReferenceType(); 3368 3369 // FIXME: Does the addition of const really only apply in 3370 // potentially-evaluated contexts? Since the variable isn't actually 3371 // captured in an unevaluated context, it seems that the answer is no. 3372 if (!isUnevaluatedContext()) { 3373 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3374 if (!CapturedType.isNull()) 3375 type = CapturedType; 3376 } 3377 3378 break; 3379 } 3380 3381 case Decl::Binding: { 3382 // These are always lvalues. 3383 valueKind = VK_LValue; 3384 type = type.getNonReferenceType(); 3385 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3386 // decides how that's supposed to work. 3387 auto *BD = cast<BindingDecl>(VD); 3388 if (BD->getDeclContext() != CurContext && !isUnevaluatedContext()) { 3389 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3390 if (DD && DD->hasLocalStorage()) 3391 diagnoseUncapturableValueReference(*this, Loc, BD); 3392 } 3393 break; 3394 } 3395 3396 case Decl::Function: { 3397 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3398 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 3399 type = Context.BuiltinFnTy; 3400 valueKind = VK_PRValue; 3401 break; 3402 } 3403 } 3404 3405 const FunctionType *fty = type->castAs<FunctionType>(); 3406 3407 // If we're referring to a function with an __unknown_anytype 3408 // result type, make the entire expression __unknown_anytype. 3409 if (fty->getReturnType() == Context.UnknownAnyTy) { 3410 type = Context.UnknownAnyTy; 3411 valueKind = VK_PRValue; 3412 break; 3413 } 3414 3415 // Functions are l-values in C++. 3416 if (getLangOpts().CPlusPlus) { 3417 valueKind = VK_LValue; 3418 break; 3419 } 3420 3421 // C99 DR 316 says that, if a function type comes from a 3422 // function definition (without a prototype), that type is only 3423 // used for checking compatibility. Therefore, when referencing 3424 // the function, we pretend that we don't have the full function 3425 // type. 3426 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3427 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3428 fty->getExtInfo()); 3429 3430 // Functions are r-values in C. 3431 valueKind = VK_PRValue; 3432 break; 3433 } 3434 3435 case Decl::CXXDeductionGuide: 3436 llvm_unreachable("building reference to deduction guide"); 3437 3438 case Decl::MSProperty: 3439 case Decl::MSGuid: 3440 case Decl::TemplateParamObject: 3441 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3442 // capture in OpenMP, or duplicated between host and device? 3443 valueKind = VK_LValue; 3444 break; 3445 3446 case Decl::UnnamedGlobalConstant: 3447 valueKind = VK_LValue; 3448 break; 3449 3450 case Decl::CXXMethod: 3451 // If we're referring to a method with an __unknown_anytype 3452 // result type, make the entire expression __unknown_anytype. 3453 // This should only be possible with a type written directly. 3454 if (const FunctionProtoType *proto = 3455 dyn_cast<FunctionProtoType>(VD->getType())) 3456 if (proto->getReturnType() == Context.UnknownAnyTy) { 3457 type = Context.UnknownAnyTy; 3458 valueKind = VK_PRValue; 3459 break; 3460 } 3461 3462 // C++ methods are l-values if static, r-values if non-static. 3463 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3464 valueKind = VK_LValue; 3465 break; 3466 } 3467 LLVM_FALLTHROUGH; 3468 3469 case Decl::CXXConversion: 3470 case Decl::CXXDestructor: 3471 case Decl::CXXConstructor: 3472 valueKind = VK_PRValue; 3473 break; 3474 } 3475 3476 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3477 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3478 TemplateArgs); 3479 } 3480 3481 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3482 SmallString<32> &Target) { 3483 Target.resize(CharByteWidth * (Source.size() + 1)); 3484 char *ResultPtr = &Target[0]; 3485 const llvm::UTF8 *ErrorPtr; 3486 bool success = 3487 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3488 (void)success; 3489 assert(success); 3490 Target.resize(ResultPtr - &Target[0]); 3491 } 3492 3493 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3494 PredefinedExpr::IdentKind IK) { 3495 // Pick the current block, lambda, captured statement or function. 3496 Decl *currentDecl = nullptr; 3497 if (const BlockScopeInfo *BSI = getCurBlock()) 3498 currentDecl = BSI->TheDecl; 3499 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3500 currentDecl = LSI->CallOperator; 3501 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3502 currentDecl = CSI->TheCapturedDecl; 3503 else 3504 currentDecl = getCurFunctionOrMethodDecl(); 3505 3506 if (!currentDecl) { 3507 Diag(Loc, diag::ext_predef_outside_function); 3508 currentDecl = Context.getTranslationUnitDecl(); 3509 } 3510 3511 QualType ResTy; 3512 StringLiteral *SL = nullptr; 3513 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3514 ResTy = Context.DependentTy; 3515 else { 3516 // Pre-defined identifiers are of type char[x], where x is the length of 3517 // the string. 3518 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3519 unsigned Length = Str.length(); 3520 3521 llvm::APInt LengthI(32, Length + 1); 3522 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3523 ResTy = 3524 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3525 SmallString<32> RawChars; 3526 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3527 Str, RawChars); 3528 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3529 ArrayType::Normal, 3530 /*IndexTypeQuals*/ 0); 3531 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3532 /*Pascal*/ false, ResTy, Loc); 3533 } else { 3534 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3535 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3536 ArrayType::Normal, 3537 /*IndexTypeQuals*/ 0); 3538 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3539 /*Pascal*/ false, ResTy, Loc); 3540 } 3541 } 3542 3543 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3544 } 3545 3546 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3547 SourceLocation LParen, 3548 SourceLocation RParen, 3549 TypeSourceInfo *TSI) { 3550 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3551 } 3552 3553 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3554 SourceLocation LParen, 3555 SourceLocation RParen, 3556 ParsedType ParsedTy) { 3557 TypeSourceInfo *TSI = nullptr; 3558 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3559 3560 if (Ty.isNull()) 3561 return ExprError(); 3562 if (!TSI) 3563 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3564 3565 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3566 } 3567 3568 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3569 PredefinedExpr::IdentKind IK; 3570 3571 switch (Kind) { 3572 default: llvm_unreachable("Unknown simple primary expr!"); 3573 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3574 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3575 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3576 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3577 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3578 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3579 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3580 } 3581 3582 return BuildPredefinedExpr(Loc, IK); 3583 } 3584 3585 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3586 SmallString<16> CharBuffer; 3587 bool Invalid = false; 3588 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3589 if (Invalid) 3590 return ExprError(); 3591 3592 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3593 PP, Tok.getKind()); 3594 if (Literal.hadError()) 3595 return ExprError(); 3596 3597 QualType Ty; 3598 if (Literal.isWide()) 3599 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3600 else if (Literal.isUTF8() && getLangOpts().Char8) 3601 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3602 else if (Literal.isUTF16()) 3603 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3604 else if (Literal.isUTF32()) 3605 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3606 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3607 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3608 else 3609 Ty = Context.CharTy; // 'x' -> char in C++ 3610 3611 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3612 if (Literal.isWide()) 3613 Kind = CharacterLiteral::Wide; 3614 else if (Literal.isUTF16()) 3615 Kind = CharacterLiteral::UTF16; 3616 else if (Literal.isUTF32()) 3617 Kind = CharacterLiteral::UTF32; 3618 else if (Literal.isUTF8()) 3619 Kind = CharacterLiteral::UTF8; 3620 3621 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3622 Tok.getLocation()); 3623 3624 if (Literal.getUDSuffix().empty()) 3625 return Lit; 3626 3627 // We're building a user-defined literal. 3628 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3629 SourceLocation UDSuffixLoc = 3630 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3631 3632 // Make sure we're allowed user-defined literals here. 3633 if (!UDLScope) 3634 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3635 3636 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3637 // operator "" X (ch) 3638 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3639 Lit, Tok.getLocation()); 3640 } 3641 3642 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3643 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3644 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3645 Context.IntTy, Loc); 3646 } 3647 3648 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3649 QualType Ty, SourceLocation Loc) { 3650 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3651 3652 using llvm::APFloat; 3653 APFloat Val(Format); 3654 3655 APFloat::opStatus result = Literal.GetFloatValue(Val); 3656 3657 // Overflow is always an error, but underflow is only an error if 3658 // we underflowed to zero (APFloat reports denormals as underflow). 3659 if ((result & APFloat::opOverflow) || 3660 ((result & APFloat::opUnderflow) && Val.isZero())) { 3661 unsigned diagnostic; 3662 SmallString<20> buffer; 3663 if (result & APFloat::opOverflow) { 3664 diagnostic = diag::warn_float_overflow; 3665 APFloat::getLargest(Format).toString(buffer); 3666 } else { 3667 diagnostic = diag::warn_float_underflow; 3668 APFloat::getSmallest(Format).toString(buffer); 3669 } 3670 3671 S.Diag(Loc, diagnostic) 3672 << Ty 3673 << StringRef(buffer.data(), buffer.size()); 3674 } 3675 3676 bool isExact = (result == APFloat::opOK); 3677 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3678 } 3679 3680 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3681 assert(E && "Invalid expression"); 3682 3683 if (E->isValueDependent()) 3684 return false; 3685 3686 QualType QT = E->getType(); 3687 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3688 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3689 return true; 3690 } 3691 3692 llvm::APSInt ValueAPS; 3693 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3694 3695 if (R.isInvalid()) 3696 return true; 3697 3698 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3699 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3700 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3701 << toString(ValueAPS, 10) << ValueIsPositive; 3702 return true; 3703 } 3704 3705 return false; 3706 } 3707 3708 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3709 // Fast path for a single digit (which is quite common). A single digit 3710 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3711 if (Tok.getLength() == 1) { 3712 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3713 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3714 } 3715 3716 SmallString<128> SpellingBuffer; 3717 // NumericLiteralParser wants to overread by one character. Add padding to 3718 // the buffer in case the token is copied to the buffer. If getSpelling() 3719 // returns a StringRef to the memory buffer, it should have a null char at 3720 // the EOF, so it is also safe. 3721 SpellingBuffer.resize(Tok.getLength() + 1); 3722 3723 // Get the spelling of the token, which eliminates trigraphs, etc. 3724 bool Invalid = false; 3725 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3726 if (Invalid) 3727 return ExprError(); 3728 3729 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3730 PP.getSourceManager(), PP.getLangOpts(), 3731 PP.getTargetInfo(), PP.getDiagnostics()); 3732 if (Literal.hadError) 3733 return ExprError(); 3734 3735 if (Literal.hasUDSuffix()) { 3736 // We're building a user-defined literal. 3737 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3738 SourceLocation UDSuffixLoc = 3739 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3740 3741 // Make sure we're allowed user-defined literals here. 3742 if (!UDLScope) 3743 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3744 3745 QualType CookedTy; 3746 if (Literal.isFloatingLiteral()) { 3747 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3748 // long double, the literal is treated as a call of the form 3749 // operator "" X (f L) 3750 CookedTy = Context.LongDoubleTy; 3751 } else { 3752 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3753 // unsigned long long, the literal is treated as a call of the form 3754 // operator "" X (n ULL) 3755 CookedTy = Context.UnsignedLongLongTy; 3756 } 3757 3758 DeclarationName OpName = 3759 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3760 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3761 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3762 3763 SourceLocation TokLoc = Tok.getLocation(); 3764 3765 // Perform literal operator lookup to determine if we're building a raw 3766 // literal or a cooked one. 3767 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3768 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3769 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3770 /*AllowStringTemplatePack*/ false, 3771 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3772 case LOLR_ErrorNoDiagnostic: 3773 // Lookup failure for imaginary constants isn't fatal, there's still the 3774 // GNU extension producing _Complex types. 3775 break; 3776 case LOLR_Error: 3777 return ExprError(); 3778 case LOLR_Cooked: { 3779 Expr *Lit; 3780 if (Literal.isFloatingLiteral()) { 3781 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3782 } else { 3783 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3784 if (Literal.GetIntegerValue(ResultVal)) 3785 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3786 << /* Unsigned */ 1; 3787 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3788 Tok.getLocation()); 3789 } 3790 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3791 } 3792 3793 case LOLR_Raw: { 3794 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3795 // literal is treated as a call of the form 3796 // operator "" X ("n") 3797 unsigned Length = Literal.getUDSuffixOffset(); 3798 QualType StrTy = Context.getConstantArrayType( 3799 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3800 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3801 Expr *Lit = StringLiteral::Create( 3802 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3803 /*Pascal*/false, StrTy, &TokLoc, 1); 3804 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3805 } 3806 3807 case LOLR_Template: { 3808 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3809 // template), L is treated as a call fo the form 3810 // operator "" X <'c1', 'c2', ... 'ck'>() 3811 // where n is the source character sequence c1 c2 ... ck. 3812 TemplateArgumentListInfo ExplicitArgs; 3813 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3814 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3815 llvm::APSInt Value(CharBits, CharIsUnsigned); 3816 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3817 Value = TokSpelling[I]; 3818 TemplateArgument Arg(Context, Value, Context.CharTy); 3819 TemplateArgumentLocInfo ArgInfo; 3820 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3821 } 3822 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3823 &ExplicitArgs); 3824 } 3825 case LOLR_StringTemplatePack: 3826 llvm_unreachable("unexpected literal operator lookup result"); 3827 } 3828 } 3829 3830 Expr *Res; 3831 3832 if (Literal.isFixedPointLiteral()) { 3833 QualType Ty; 3834 3835 if (Literal.isAccum) { 3836 if (Literal.isHalf) { 3837 Ty = Context.ShortAccumTy; 3838 } else if (Literal.isLong) { 3839 Ty = Context.LongAccumTy; 3840 } else { 3841 Ty = Context.AccumTy; 3842 } 3843 } else if (Literal.isFract) { 3844 if (Literal.isHalf) { 3845 Ty = Context.ShortFractTy; 3846 } else if (Literal.isLong) { 3847 Ty = Context.LongFractTy; 3848 } else { 3849 Ty = Context.FractTy; 3850 } 3851 } 3852 3853 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3854 3855 bool isSigned = !Literal.isUnsigned; 3856 unsigned scale = Context.getFixedPointScale(Ty); 3857 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3858 3859 llvm::APInt Val(bit_width, 0, isSigned); 3860 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3861 bool ValIsZero = Val.isZero() && !Overflowed; 3862 3863 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3864 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3865 // Clause 6.4.4 - The value of a constant shall be in the range of 3866 // representable values for its type, with exception for constants of a 3867 // fract type with a value of exactly 1; such a constant shall denote 3868 // the maximal value for the type. 3869 --Val; 3870 else if (Val.ugt(MaxVal) || Overflowed) 3871 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3872 3873 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3874 Tok.getLocation(), scale); 3875 } else if (Literal.isFloatingLiteral()) { 3876 QualType Ty; 3877 if (Literal.isHalf){ 3878 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3879 Ty = Context.HalfTy; 3880 else { 3881 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3882 return ExprError(); 3883 } 3884 } else if (Literal.isFloat) 3885 Ty = Context.FloatTy; 3886 else if (Literal.isLong) 3887 Ty = Context.LongDoubleTy; 3888 else if (Literal.isFloat16) 3889 Ty = Context.Float16Ty; 3890 else if (Literal.isFloat128) 3891 Ty = Context.Float128Ty; 3892 else 3893 Ty = Context.DoubleTy; 3894 3895 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3896 3897 if (Ty == Context.DoubleTy) { 3898 if (getLangOpts().SinglePrecisionConstants) { 3899 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3900 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3901 } 3902 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3903 "cl_khr_fp64", getLangOpts())) { 3904 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3905 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3906 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3907 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3908 } 3909 } 3910 } else if (!Literal.isIntegerLiteral()) { 3911 return ExprError(); 3912 } else { 3913 QualType Ty; 3914 3915 // 'long long' is a C99 or C++11 feature. 3916 if (!getLangOpts().C99 && Literal.isLongLong) { 3917 if (getLangOpts().CPlusPlus) 3918 Diag(Tok.getLocation(), 3919 getLangOpts().CPlusPlus11 ? 3920 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3921 else 3922 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3923 } 3924 3925 // 'z/uz' literals are a C++2b feature. 3926 if (Literal.isSizeT) 3927 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3928 ? getLangOpts().CPlusPlus2b 3929 ? diag::warn_cxx20_compat_size_t_suffix 3930 : diag::ext_cxx2b_size_t_suffix 3931 : diag::err_cxx2b_size_t_suffix); 3932 3933 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++, 3934 // but we do not currently support the suffix in C++ mode because it's not 3935 // entirely clear whether WG21 will prefer this suffix to return a library 3936 // type such as std::bit_int instead of returning a _BitInt. 3937 if (Literal.isBitInt && !getLangOpts().CPlusPlus) 3938 PP.Diag(Tok.getLocation(), getLangOpts().C2x 3939 ? diag::warn_c2x_compat_bitint_suffix 3940 : diag::ext_c2x_bitint_suffix); 3941 3942 // Get the value in the widest-possible width. What is "widest" depends on 3943 // whether the literal is a bit-precise integer or not. For a bit-precise 3944 // integer type, try to scan the source to determine how many bits are 3945 // needed to represent the value. This may seem a bit expensive, but trying 3946 // to get the integer value from an overly-wide APInt is *extremely* 3947 // expensive, so the naive approach of assuming 3948 // llvm::IntegerType::MAX_INT_BITS is a big performance hit. 3949 unsigned BitsNeeded = 3950 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded( 3951 Literal.getLiteralDigits(), Literal.getRadix()) 3952 : Context.getTargetInfo().getIntMaxTWidth(); 3953 llvm::APInt ResultVal(BitsNeeded, 0); 3954 3955 if (Literal.GetIntegerValue(ResultVal)) { 3956 // If this value didn't fit into uintmax_t, error and force to ull. 3957 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3958 << /* Unsigned */ 1; 3959 Ty = Context.UnsignedLongLongTy; 3960 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3961 "long long is not intmax_t?"); 3962 } else { 3963 // If this value fits into a ULL, try to figure out what else it fits into 3964 // according to the rules of C99 6.4.4.1p5. 3965 3966 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3967 // be an unsigned int. 3968 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3969 3970 // Check from smallest to largest, picking the smallest type we can. 3971 unsigned Width = 0; 3972 3973 // Microsoft specific integer suffixes are explicitly sized. 3974 if (Literal.MicrosoftInteger) { 3975 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3976 Width = 8; 3977 Ty = Context.CharTy; 3978 } else { 3979 Width = Literal.MicrosoftInteger; 3980 Ty = Context.getIntTypeForBitwidth(Width, 3981 /*Signed=*/!Literal.isUnsigned); 3982 } 3983 } 3984 3985 // Bit-precise integer literals are automagically-sized based on the 3986 // width required by the literal. 3987 if (Literal.isBitInt) { 3988 // The signed version has one more bit for the sign value. There are no 3989 // zero-width bit-precise integers, even if the literal value is 0. 3990 Width = std::max(ResultVal.getActiveBits(), 1u) + 3991 (Literal.isUnsigned ? 0u : 1u); 3992 3993 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, 3994 // and reset the type to the largest supported width. 3995 unsigned int MaxBitIntWidth = 3996 Context.getTargetInfo().getMaxBitIntWidth(); 3997 if (Width > MaxBitIntWidth) { 3998 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3999 << Literal.isUnsigned; 4000 Width = MaxBitIntWidth; 4001 } 4002 4003 // Reset the result value to the smaller APInt and select the correct 4004 // type to be used. Note, we zext even for signed values because the 4005 // literal itself is always an unsigned value (a preceeding - is a 4006 // unary operator, not part of the literal). 4007 ResultVal = ResultVal.zextOrTrunc(Width); 4008 Ty = Context.getBitIntType(Literal.isUnsigned, Width); 4009 } 4010 4011 // Check C++2b size_t literals. 4012 if (Literal.isSizeT) { 4013 assert(!Literal.MicrosoftInteger && 4014 "size_t literals can't be Microsoft literals"); 4015 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 4016 Context.getTargetInfo().getSizeType()); 4017 4018 // Does it fit in size_t? 4019 if (ResultVal.isIntN(SizeTSize)) { 4020 // Does it fit in ssize_t? 4021 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 4022 Ty = Context.getSignedSizeType(); 4023 else if (AllowUnsigned) 4024 Ty = Context.getSizeType(); 4025 Width = SizeTSize; 4026 } 4027 } 4028 4029 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 4030 !Literal.isSizeT) { 4031 // Are int/unsigned possibilities? 4032 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 4033 4034 // Does it fit in a unsigned int? 4035 if (ResultVal.isIntN(IntSize)) { 4036 // Does it fit in a signed int? 4037 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 4038 Ty = Context.IntTy; 4039 else if (AllowUnsigned) 4040 Ty = Context.UnsignedIntTy; 4041 Width = IntSize; 4042 } 4043 } 4044 4045 // Are long/unsigned long possibilities? 4046 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 4047 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 4048 4049 // Does it fit in a unsigned long? 4050 if (ResultVal.isIntN(LongSize)) { 4051 // Does it fit in a signed long? 4052 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 4053 Ty = Context.LongTy; 4054 else if (AllowUnsigned) 4055 Ty = Context.UnsignedLongTy; 4056 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 4057 // is compatible. 4058 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 4059 const unsigned LongLongSize = 4060 Context.getTargetInfo().getLongLongWidth(); 4061 Diag(Tok.getLocation(), 4062 getLangOpts().CPlusPlus 4063 ? Literal.isLong 4064 ? diag::warn_old_implicitly_unsigned_long_cxx 4065 : /*C++98 UB*/ diag:: 4066 ext_old_implicitly_unsigned_long_cxx 4067 : diag::warn_old_implicitly_unsigned_long) 4068 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4069 : /*will be ill-formed*/ 1); 4070 Ty = Context.UnsignedLongTy; 4071 } 4072 Width = LongSize; 4073 } 4074 } 4075 4076 // Check long long if needed. 4077 if (Ty.isNull() && !Literal.isSizeT) { 4078 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4079 4080 // Does it fit in a unsigned long long? 4081 if (ResultVal.isIntN(LongLongSize)) { 4082 // Does it fit in a signed long long? 4083 // To be compatible with MSVC, hex integer literals ending with the 4084 // LL or i64 suffix are always signed in Microsoft mode. 4085 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4086 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4087 Ty = Context.LongLongTy; 4088 else if (AllowUnsigned) 4089 Ty = Context.UnsignedLongLongTy; 4090 Width = LongLongSize; 4091 } 4092 } 4093 4094 // If we still couldn't decide a type, we either have 'size_t' literal 4095 // that is out of range, or a decimal literal that does not fit in a 4096 // signed long long and has no U suffix. 4097 if (Ty.isNull()) { 4098 if (Literal.isSizeT) 4099 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4100 << Literal.isUnsigned; 4101 else 4102 Diag(Tok.getLocation(), 4103 diag::ext_integer_literal_too_large_for_signed); 4104 Ty = Context.UnsignedLongLongTy; 4105 Width = Context.getTargetInfo().getLongLongWidth(); 4106 } 4107 4108 if (ResultVal.getBitWidth() != Width) 4109 ResultVal = ResultVal.trunc(Width); 4110 } 4111 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4112 } 4113 4114 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4115 if (Literal.isImaginary) { 4116 Res = new (Context) ImaginaryLiteral(Res, 4117 Context.getComplexType(Res->getType())); 4118 4119 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4120 } 4121 return Res; 4122 } 4123 4124 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4125 assert(E && "ActOnParenExpr() missing expr"); 4126 QualType ExprTy = E->getType(); 4127 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4128 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4129 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4130 return new (Context) ParenExpr(L, R, E); 4131 } 4132 4133 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4134 SourceLocation Loc, 4135 SourceRange ArgRange) { 4136 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4137 // scalar or vector data type argument..." 4138 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4139 // type (C99 6.2.5p18) or void. 4140 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4141 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4142 << T << ArgRange; 4143 return true; 4144 } 4145 4146 assert((T->isVoidType() || !T->isIncompleteType()) && 4147 "Scalar types should always be complete"); 4148 return false; 4149 } 4150 4151 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4152 SourceLocation Loc, 4153 SourceRange ArgRange, 4154 UnaryExprOrTypeTrait TraitKind) { 4155 // Invalid types must be hard errors for SFINAE in C++. 4156 if (S.LangOpts.CPlusPlus) 4157 return true; 4158 4159 // C99 6.5.3.4p1: 4160 if (T->isFunctionType() && 4161 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4162 TraitKind == UETT_PreferredAlignOf)) { 4163 // sizeof(function)/alignof(function) is allowed as an extension. 4164 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4165 << getTraitSpelling(TraitKind) << ArgRange; 4166 return false; 4167 } 4168 4169 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4170 // this is an error (OpenCL v1.1 s6.3.k) 4171 if (T->isVoidType()) { 4172 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4173 : diag::ext_sizeof_alignof_void_type; 4174 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4175 return false; 4176 } 4177 4178 return true; 4179 } 4180 4181 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4182 SourceLocation Loc, 4183 SourceRange ArgRange, 4184 UnaryExprOrTypeTrait TraitKind) { 4185 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4186 // runtime doesn't allow it. 4187 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4188 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4189 << T << (TraitKind == UETT_SizeOf) 4190 << ArgRange; 4191 return true; 4192 } 4193 4194 return false; 4195 } 4196 4197 /// Check whether E is a pointer from a decayed array type (the decayed 4198 /// pointer type is equal to T) and emit a warning if it is. 4199 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4200 Expr *E) { 4201 // Don't warn if the operation changed the type. 4202 if (T != E->getType()) 4203 return; 4204 4205 // Now look for array decays. 4206 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4207 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4208 return; 4209 4210 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4211 << ICE->getType() 4212 << ICE->getSubExpr()->getType(); 4213 } 4214 4215 /// Check the constraints on expression operands to unary type expression 4216 /// and type traits. 4217 /// 4218 /// Completes any types necessary and validates the constraints on the operand 4219 /// expression. The logic mostly mirrors the type-based overload, but may modify 4220 /// the expression as it completes the type for that expression through template 4221 /// instantiation, etc. 4222 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4223 UnaryExprOrTypeTrait ExprKind) { 4224 QualType ExprTy = E->getType(); 4225 assert(!ExprTy->isReferenceType()); 4226 4227 bool IsUnevaluatedOperand = 4228 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4229 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4230 if (IsUnevaluatedOperand) { 4231 ExprResult Result = CheckUnevaluatedOperand(E); 4232 if (Result.isInvalid()) 4233 return true; 4234 E = Result.get(); 4235 } 4236 4237 // The operand for sizeof and alignof is in an unevaluated expression context, 4238 // so side effects could result in unintended consequences. 4239 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4240 // used to build SFINAE gadgets. 4241 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4242 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4243 !E->isInstantiationDependent() && 4244 E->HasSideEffects(Context, false)) 4245 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4246 4247 if (ExprKind == UETT_VecStep) 4248 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4249 E->getSourceRange()); 4250 4251 // Explicitly list some types as extensions. 4252 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4253 E->getSourceRange(), ExprKind)) 4254 return false; 4255 4256 // 'alignof' applied to an expression only requires the base element type of 4257 // the expression to be complete. 'sizeof' requires the expression's type to 4258 // be complete (and will attempt to complete it if it's an array of unknown 4259 // bound). 4260 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4261 if (RequireCompleteSizedType( 4262 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4263 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4264 getTraitSpelling(ExprKind), E->getSourceRange())) 4265 return true; 4266 } else { 4267 if (RequireCompleteSizedExprType( 4268 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4269 getTraitSpelling(ExprKind), E->getSourceRange())) 4270 return true; 4271 } 4272 4273 // Completing the expression's type may have changed it. 4274 ExprTy = E->getType(); 4275 assert(!ExprTy->isReferenceType()); 4276 4277 if (ExprTy->isFunctionType()) { 4278 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4279 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4280 return true; 4281 } 4282 4283 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4284 E->getSourceRange(), ExprKind)) 4285 return true; 4286 4287 if (ExprKind == UETT_SizeOf) { 4288 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4289 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4290 QualType OType = PVD->getOriginalType(); 4291 QualType Type = PVD->getType(); 4292 if (Type->isPointerType() && OType->isArrayType()) { 4293 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4294 << Type << OType; 4295 Diag(PVD->getLocation(), diag::note_declared_at); 4296 } 4297 } 4298 } 4299 4300 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4301 // decays into a pointer and returns an unintended result. This is most 4302 // likely a typo for "sizeof(array) op x". 4303 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4304 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4305 BO->getLHS()); 4306 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4307 BO->getRHS()); 4308 } 4309 } 4310 4311 return false; 4312 } 4313 4314 /// Check the constraints on operands to unary expression and type 4315 /// traits. 4316 /// 4317 /// This will complete any types necessary, and validate the various constraints 4318 /// on those operands. 4319 /// 4320 /// The UsualUnaryConversions() function is *not* called by this routine. 4321 /// C99 6.3.2.1p[2-4] all state: 4322 /// Except when it is the operand of the sizeof operator ... 4323 /// 4324 /// C++ [expr.sizeof]p4 4325 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4326 /// standard conversions are not applied to the operand of sizeof. 4327 /// 4328 /// This policy is followed for all of the unary trait expressions. 4329 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4330 SourceLocation OpLoc, 4331 SourceRange ExprRange, 4332 UnaryExprOrTypeTrait ExprKind) { 4333 if (ExprType->isDependentType()) 4334 return false; 4335 4336 // C++ [expr.sizeof]p2: 4337 // When applied to a reference or a reference type, the result 4338 // is the size of the referenced type. 4339 // C++11 [expr.alignof]p3: 4340 // When alignof is applied to a reference type, the result 4341 // shall be the alignment of the referenced type. 4342 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4343 ExprType = Ref->getPointeeType(); 4344 4345 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4346 // When alignof or _Alignof is applied to an array type, the result 4347 // is the alignment of the element type. 4348 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4349 ExprKind == UETT_OpenMPRequiredSimdAlign) 4350 ExprType = Context.getBaseElementType(ExprType); 4351 4352 if (ExprKind == UETT_VecStep) 4353 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4354 4355 // Explicitly list some types as extensions. 4356 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4357 ExprKind)) 4358 return false; 4359 4360 if (RequireCompleteSizedType( 4361 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4362 getTraitSpelling(ExprKind), ExprRange)) 4363 return true; 4364 4365 if (ExprType->isFunctionType()) { 4366 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4367 << getTraitSpelling(ExprKind) << ExprRange; 4368 return true; 4369 } 4370 4371 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4372 ExprKind)) 4373 return true; 4374 4375 return false; 4376 } 4377 4378 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4379 // Cannot know anything else if the expression is dependent. 4380 if (E->isTypeDependent()) 4381 return false; 4382 4383 if (E->getObjectKind() == OK_BitField) { 4384 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4385 << 1 << E->getSourceRange(); 4386 return true; 4387 } 4388 4389 ValueDecl *D = nullptr; 4390 Expr *Inner = E->IgnoreParens(); 4391 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4392 D = DRE->getDecl(); 4393 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4394 D = ME->getMemberDecl(); 4395 } 4396 4397 // If it's a field, require the containing struct to have a 4398 // complete definition so that we can compute the layout. 4399 // 4400 // This can happen in C++11 onwards, either by naming the member 4401 // in a way that is not transformed into a member access expression 4402 // (in an unevaluated operand, for instance), or by naming the member 4403 // in a trailing-return-type. 4404 // 4405 // For the record, since __alignof__ on expressions is a GCC 4406 // extension, GCC seems to permit this but always gives the 4407 // nonsensical answer 0. 4408 // 4409 // We don't really need the layout here --- we could instead just 4410 // directly check for all the appropriate alignment-lowing 4411 // attributes --- but that would require duplicating a lot of 4412 // logic that just isn't worth duplicating for such a marginal 4413 // use-case. 4414 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4415 // Fast path this check, since we at least know the record has a 4416 // definition if we can find a member of it. 4417 if (!FD->getParent()->isCompleteDefinition()) { 4418 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4419 << E->getSourceRange(); 4420 return true; 4421 } 4422 4423 // Otherwise, if it's a field, and the field doesn't have 4424 // reference type, then it must have a complete type (or be a 4425 // flexible array member, which we explicitly want to 4426 // white-list anyway), which makes the following checks trivial. 4427 if (!FD->getType()->isReferenceType()) 4428 return false; 4429 } 4430 4431 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4432 } 4433 4434 bool Sema::CheckVecStepExpr(Expr *E) { 4435 E = E->IgnoreParens(); 4436 4437 // Cannot know anything else if the expression is dependent. 4438 if (E->isTypeDependent()) 4439 return false; 4440 4441 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4442 } 4443 4444 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4445 CapturingScopeInfo *CSI) { 4446 assert(T->isVariablyModifiedType()); 4447 assert(CSI != nullptr); 4448 4449 // We're going to walk down into the type and look for VLA expressions. 4450 do { 4451 const Type *Ty = T.getTypePtr(); 4452 switch (Ty->getTypeClass()) { 4453 #define TYPE(Class, Base) 4454 #define ABSTRACT_TYPE(Class, Base) 4455 #define NON_CANONICAL_TYPE(Class, Base) 4456 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4457 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4458 #include "clang/AST/TypeNodes.inc" 4459 T = QualType(); 4460 break; 4461 // These types are never variably-modified. 4462 case Type::Builtin: 4463 case Type::Complex: 4464 case Type::Vector: 4465 case Type::ExtVector: 4466 case Type::ConstantMatrix: 4467 case Type::Record: 4468 case Type::Enum: 4469 case Type::Elaborated: 4470 case Type::TemplateSpecialization: 4471 case Type::ObjCObject: 4472 case Type::ObjCInterface: 4473 case Type::ObjCObjectPointer: 4474 case Type::ObjCTypeParam: 4475 case Type::Pipe: 4476 case Type::BitInt: 4477 llvm_unreachable("type class is never variably-modified!"); 4478 case Type::Adjusted: 4479 T = cast<AdjustedType>(Ty)->getOriginalType(); 4480 break; 4481 case Type::Decayed: 4482 T = cast<DecayedType>(Ty)->getPointeeType(); 4483 break; 4484 case Type::Pointer: 4485 T = cast<PointerType>(Ty)->getPointeeType(); 4486 break; 4487 case Type::BlockPointer: 4488 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4489 break; 4490 case Type::LValueReference: 4491 case Type::RValueReference: 4492 T = cast<ReferenceType>(Ty)->getPointeeType(); 4493 break; 4494 case Type::MemberPointer: 4495 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4496 break; 4497 case Type::ConstantArray: 4498 case Type::IncompleteArray: 4499 // Losing element qualification here is fine. 4500 T = cast<ArrayType>(Ty)->getElementType(); 4501 break; 4502 case Type::VariableArray: { 4503 // Losing element qualification here is fine. 4504 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4505 4506 // Unknown size indication requires no size computation. 4507 // Otherwise, evaluate and record it. 4508 auto Size = VAT->getSizeExpr(); 4509 if (Size && !CSI->isVLATypeCaptured(VAT) && 4510 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4511 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4512 4513 T = VAT->getElementType(); 4514 break; 4515 } 4516 case Type::FunctionProto: 4517 case Type::FunctionNoProto: 4518 T = cast<FunctionType>(Ty)->getReturnType(); 4519 break; 4520 case Type::Paren: 4521 case Type::TypeOf: 4522 case Type::UnaryTransform: 4523 case Type::Attributed: 4524 case Type::BTFTagAttributed: 4525 case Type::SubstTemplateTypeParm: 4526 case Type::MacroQualified: 4527 // Keep walking after single level desugaring. 4528 T = T.getSingleStepDesugaredType(Context); 4529 break; 4530 case Type::Typedef: 4531 T = cast<TypedefType>(Ty)->desugar(); 4532 break; 4533 case Type::Decltype: 4534 T = cast<DecltypeType>(Ty)->desugar(); 4535 break; 4536 case Type::Using: 4537 T = cast<UsingType>(Ty)->desugar(); 4538 break; 4539 case Type::Auto: 4540 case Type::DeducedTemplateSpecialization: 4541 T = cast<DeducedType>(Ty)->getDeducedType(); 4542 break; 4543 case Type::TypeOfExpr: 4544 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4545 break; 4546 case Type::Atomic: 4547 T = cast<AtomicType>(Ty)->getValueType(); 4548 break; 4549 } 4550 } while (!T.isNull() && T->isVariablyModifiedType()); 4551 } 4552 4553 /// Build a sizeof or alignof expression given a type operand. 4554 ExprResult 4555 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4556 SourceLocation OpLoc, 4557 UnaryExprOrTypeTrait ExprKind, 4558 SourceRange R) { 4559 if (!TInfo) 4560 return ExprError(); 4561 4562 QualType T = TInfo->getType(); 4563 4564 if (!T->isDependentType() && 4565 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4566 return ExprError(); 4567 4568 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4569 if (auto *TT = T->getAs<TypedefType>()) { 4570 for (auto I = FunctionScopes.rbegin(), 4571 E = std::prev(FunctionScopes.rend()); 4572 I != E; ++I) { 4573 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4574 if (CSI == nullptr) 4575 break; 4576 DeclContext *DC = nullptr; 4577 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4578 DC = LSI->CallOperator; 4579 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4580 DC = CRSI->TheCapturedDecl; 4581 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4582 DC = BSI->TheDecl; 4583 if (DC) { 4584 if (DC->containsDecl(TT->getDecl())) 4585 break; 4586 captureVariablyModifiedType(Context, T, CSI); 4587 } 4588 } 4589 } 4590 } 4591 4592 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4593 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && 4594 TInfo->getType()->isVariablyModifiedType()) 4595 TInfo = TransformToPotentiallyEvaluated(TInfo); 4596 4597 return new (Context) UnaryExprOrTypeTraitExpr( 4598 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4599 } 4600 4601 /// Build a sizeof or alignof expression given an expression 4602 /// operand. 4603 ExprResult 4604 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4605 UnaryExprOrTypeTrait ExprKind) { 4606 ExprResult PE = CheckPlaceholderExpr(E); 4607 if (PE.isInvalid()) 4608 return ExprError(); 4609 4610 E = PE.get(); 4611 4612 // Verify that the operand is valid. 4613 bool isInvalid = false; 4614 if (E->isTypeDependent()) { 4615 // Delay type-checking for type-dependent expressions. 4616 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4617 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4618 } else if (ExprKind == UETT_VecStep) { 4619 isInvalid = CheckVecStepExpr(E); 4620 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4621 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4622 isInvalid = true; 4623 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4624 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4625 isInvalid = true; 4626 } else { 4627 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4628 } 4629 4630 if (isInvalid) 4631 return ExprError(); 4632 4633 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4634 PE = TransformToPotentiallyEvaluated(E); 4635 if (PE.isInvalid()) return ExprError(); 4636 E = PE.get(); 4637 } 4638 4639 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4640 return new (Context) UnaryExprOrTypeTraitExpr( 4641 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4642 } 4643 4644 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4645 /// expr and the same for @c alignof and @c __alignof 4646 /// Note that the ArgRange is invalid if isType is false. 4647 ExprResult 4648 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4649 UnaryExprOrTypeTrait ExprKind, bool IsType, 4650 void *TyOrEx, SourceRange ArgRange) { 4651 // If error parsing type, ignore. 4652 if (!TyOrEx) return ExprError(); 4653 4654 if (IsType) { 4655 TypeSourceInfo *TInfo; 4656 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4657 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4658 } 4659 4660 Expr *ArgEx = (Expr *)TyOrEx; 4661 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4662 return Result; 4663 } 4664 4665 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4666 bool IsReal) { 4667 if (V.get()->isTypeDependent()) 4668 return S.Context.DependentTy; 4669 4670 // _Real and _Imag are only l-values for normal l-values. 4671 if (V.get()->getObjectKind() != OK_Ordinary) { 4672 V = S.DefaultLvalueConversion(V.get()); 4673 if (V.isInvalid()) 4674 return QualType(); 4675 } 4676 4677 // These operators return the element type of a complex type. 4678 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4679 return CT->getElementType(); 4680 4681 // Otherwise they pass through real integer and floating point types here. 4682 if (V.get()->getType()->isArithmeticType()) 4683 return V.get()->getType(); 4684 4685 // Test for placeholders. 4686 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4687 if (PR.isInvalid()) return QualType(); 4688 if (PR.get() != V.get()) { 4689 V = PR; 4690 return CheckRealImagOperand(S, V, Loc, IsReal); 4691 } 4692 4693 // Reject anything else. 4694 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4695 << (IsReal ? "__real" : "__imag"); 4696 return QualType(); 4697 } 4698 4699 4700 4701 ExprResult 4702 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4703 tok::TokenKind Kind, Expr *Input) { 4704 UnaryOperatorKind Opc; 4705 switch (Kind) { 4706 default: llvm_unreachable("Unknown unary op!"); 4707 case tok::plusplus: Opc = UO_PostInc; break; 4708 case tok::minusminus: Opc = UO_PostDec; break; 4709 } 4710 4711 // Since this might is a postfix expression, get rid of ParenListExprs. 4712 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4713 if (Result.isInvalid()) return ExprError(); 4714 Input = Result.get(); 4715 4716 return BuildUnaryOp(S, OpLoc, Opc, Input); 4717 } 4718 4719 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4720 /// 4721 /// \return true on error 4722 static bool checkArithmeticOnObjCPointer(Sema &S, 4723 SourceLocation opLoc, 4724 Expr *op) { 4725 assert(op->getType()->isObjCObjectPointerType()); 4726 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4727 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4728 return false; 4729 4730 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4731 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4732 << op->getSourceRange(); 4733 return true; 4734 } 4735 4736 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4737 auto *BaseNoParens = Base->IgnoreParens(); 4738 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4739 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4740 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4741 } 4742 4743 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. 4744 // Typically this is DependentTy, but can sometimes be more precise. 4745 // 4746 // There are cases when we could determine a non-dependent type: 4747 // - LHS and RHS may have non-dependent types despite being type-dependent 4748 // (e.g. unbounded array static members of the current instantiation) 4749 // - one may be a dependent-sized array with known element type 4750 // - one may be a dependent-typed valid index (enum in current instantiation) 4751 // 4752 // We *always* return a dependent type, in such cases it is DependentTy. 4753 // This avoids creating type-dependent expressions with non-dependent types. 4754 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 4755 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, 4756 const ASTContext &Ctx) { 4757 assert(LHS->isTypeDependent() || RHS->isTypeDependent()); 4758 QualType LTy = LHS->getType(), RTy = RHS->getType(); 4759 QualType Result = Ctx.DependentTy; 4760 if (RTy->isIntegralOrUnscopedEnumerationType()) { 4761 if (const PointerType *PT = LTy->getAs<PointerType>()) 4762 Result = PT->getPointeeType(); 4763 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) 4764 Result = AT->getElementType(); 4765 } else if (LTy->isIntegralOrUnscopedEnumerationType()) { 4766 if (const PointerType *PT = RTy->getAs<PointerType>()) 4767 Result = PT->getPointeeType(); 4768 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) 4769 Result = AT->getElementType(); 4770 } 4771 // Ensure we return a dependent type. 4772 return Result->isDependentType() ? Result : Ctx.DependentTy; 4773 } 4774 4775 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args); 4776 4777 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, 4778 SourceLocation lbLoc, 4779 MultiExprArg ArgExprs, 4780 SourceLocation rbLoc) { 4781 4782 if (base && !base->getType().isNull() && 4783 base->hasPlaceholderType(BuiltinType::OMPArraySection)) 4784 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(), 4785 SourceLocation(), /*Length*/ nullptr, 4786 /*Stride=*/nullptr, rbLoc); 4787 4788 // Since this might be a postfix expression, get rid of ParenListExprs. 4789 if (isa<ParenListExpr>(base)) { 4790 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4791 if (result.isInvalid()) 4792 return ExprError(); 4793 base = result.get(); 4794 } 4795 4796 // Check if base and idx form a MatrixSubscriptExpr. 4797 // 4798 // Helper to check for comma expressions, which are not allowed as indices for 4799 // matrix subscript expressions. 4800 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4801 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4802 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4803 << SourceRange(base->getBeginLoc(), rbLoc); 4804 return true; 4805 } 4806 return false; 4807 }; 4808 // The matrix subscript operator ([][])is considered a single operator. 4809 // Separating the index expressions by parenthesis is not allowed. 4810 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) && 4811 !isa<MatrixSubscriptExpr>(base)) { 4812 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4813 << SourceRange(base->getBeginLoc(), rbLoc); 4814 return ExprError(); 4815 } 4816 // If the base is a MatrixSubscriptExpr, try to create a new 4817 // MatrixSubscriptExpr. 4818 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4819 if (matSubscriptE) { 4820 assert(ArgExprs.size() == 1); 4821 if (CheckAndReportCommaError(ArgExprs.front())) 4822 return ExprError(); 4823 4824 assert(matSubscriptE->isIncomplete() && 4825 "base has to be an incomplete matrix subscript"); 4826 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(), 4827 matSubscriptE->getRowIdx(), 4828 ArgExprs.front(), rbLoc); 4829 } 4830 4831 // Handle any non-overload placeholder types in the base and index 4832 // expressions. We can't handle overloads here because the other 4833 // operand might be an overloadable type, in which case the overload 4834 // resolution for the operator overload should get the first crack 4835 // at the overload. 4836 bool IsMSPropertySubscript = false; 4837 if (base->getType()->isNonOverloadPlaceholderType()) { 4838 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4839 if (!IsMSPropertySubscript) { 4840 ExprResult result = CheckPlaceholderExpr(base); 4841 if (result.isInvalid()) 4842 return ExprError(); 4843 base = result.get(); 4844 } 4845 } 4846 4847 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4848 if (base->getType()->isMatrixType()) { 4849 assert(ArgExprs.size() == 1); 4850 if (CheckAndReportCommaError(ArgExprs.front())) 4851 return ExprError(); 4852 4853 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr, 4854 rbLoc); 4855 } 4856 4857 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { 4858 Expr *idx = ArgExprs[0]; 4859 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4860 (isa<CXXOperatorCallExpr>(idx) && 4861 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) { 4862 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4863 << SourceRange(base->getBeginLoc(), rbLoc); 4864 } 4865 } 4866 4867 if (ArgExprs.size() == 1 && 4868 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { 4869 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]); 4870 if (result.isInvalid()) 4871 return ExprError(); 4872 ArgExprs[0] = result.get(); 4873 } else { 4874 if (checkArgsForPlaceholders(*this, ArgExprs)) 4875 return ExprError(); 4876 } 4877 4878 // Build an unanalyzed expression if either operand is type-dependent. 4879 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && 4880 (base->isTypeDependent() || 4881 Expr::hasAnyTypeDependentArguments(ArgExprs))) { 4882 return new (Context) ArraySubscriptExpr( 4883 base, ArgExprs.front(), 4884 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()), 4885 VK_LValue, OK_Ordinary, rbLoc); 4886 } 4887 4888 // MSDN, property (C++) 4889 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4890 // This attribute can also be used in the declaration of an empty array in a 4891 // class or structure definition. For example: 4892 // __declspec(property(get=GetX, put=PutX)) int x[]; 4893 // The above statement indicates that x[] can be used with one or more array 4894 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4895 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4896 if (IsMSPropertySubscript) { 4897 assert(ArgExprs.size() == 1); 4898 // Build MS property subscript expression if base is MS property reference 4899 // or MS property subscript. 4900 return new (Context) 4901 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, 4902 VK_LValue, OK_Ordinary, rbLoc); 4903 } 4904 4905 // Use C++ overloaded-operator rules if either operand has record 4906 // type. The spec says to do this if either type is *overloadable*, 4907 // but enum types can't declare subscript operators or conversion 4908 // operators, so there's nothing interesting for overload resolution 4909 // to do if there aren't any record types involved. 4910 // 4911 // ObjC pointers have their own subscripting logic that is not tied 4912 // to overload resolution and so should not take this path. 4913 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && 4914 ((base->getType()->isRecordType() || 4915 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) { 4916 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs); 4917 } 4918 4919 ExprResult Res = 4920 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc); 4921 4922 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4923 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4924 4925 return Res; 4926 } 4927 4928 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4929 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4930 InitializationKind Kind = 4931 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4932 InitializationSequence InitSeq(*this, Entity, Kind, E); 4933 return InitSeq.Perform(*this, Entity, Kind, E); 4934 } 4935 4936 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4937 Expr *ColumnIdx, 4938 SourceLocation RBLoc) { 4939 ExprResult BaseR = CheckPlaceholderExpr(Base); 4940 if (BaseR.isInvalid()) 4941 return BaseR; 4942 Base = BaseR.get(); 4943 4944 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4945 if (RowR.isInvalid()) 4946 return RowR; 4947 RowIdx = RowR.get(); 4948 4949 if (!ColumnIdx) 4950 return new (Context) MatrixSubscriptExpr( 4951 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4952 4953 // Build an unanalyzed expression if any of the operands is type-dependent. 4954 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4955 ColumnIdx->isTypeDependent()) 4956 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4957 Context.DependentTy, RBLoc); 4958 4959 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4960 if (ColumnR.isInvalid()) 4961 return ColumnR; 4962 ColumnIdx = ColumnR.get(); 4963 4964 // Check that IndexExpr is an integer expression. If it is a constant 4965 // expression, check that it is less than Dim (= the number of elements in the 4966 // corresponding dimension). 4967 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4968 bool IsColumnIdx) -> Expr * { 4969 if (!IndexExpr->getType()->isIntegerType() && 4970 !IndexExpr->isTypeDependent()) { 4971 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4972 << IsColumnIdx; 4973 return nullptr; 4974 } 4975 4976 if (Optional<llvm::APSInt> Idx = 4977 IndexExpr->getIntegerConstantExpr(Context)) { 4978 if ((*Idx < 0 || *Idx >= Dim)) { 4979 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4980 << IsColumnIdx << Dim; 4981 return nullptr; 4982 } 4983 } 4984 4985 ExprResult ConvExpr = 4986 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4987 assert(!ConvExpr.isInvalid() && 4988 "should be able to convert any integer type to size type"); 4989 return ConvExpr.get(); 4990 }; 4991 4992 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4993 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4994 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4995 if (!RowIdx || !ColumnIdx) 4996 return ExprError(); 4997 4998 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4999 MTy->getElementType(), RBLoc); 5000 } 5001 5002 void Sema::CheckAddressOfNoDeref(const Expr *E) { 5003 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5004 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 5005 5006 // For expressions like `&(*s).b`, the base is recorded and what should be 5007 // checked. 5008 const MemberExpr *Member = nullptr; 5009 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 5010 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 5011 5012 LastRecord.PossibleDerefs.erase(StrippedExpr); 5013 } 5014 5015 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 5016 if (isUnevaluatedContext()) 5017 return; 5018 5019 QualType ResultTy = E->getType(); 5020 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5021 5022 // Bail if the element is an array since it is not memory access. 5023 if (isa<ArrayType>(ResultTy)) 5024 return; 5025 5026 if (ResultTy->hasAttr(attr::NoDeref)) { 5027 LastRecord.PossibleDerefs.insert(E); 5028 return; 5029 } 5030 5031 // Check if the base type is a pointer to a member access of a struct 5032 // marked with noderef. 5033 const Expr *Base = E->getBase(); 5034 QualType BaseTy = Base->getType(); 5035 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 5036 // Not a pointer access 5037 return; 5038 5039 const MemberExpr *Member = nullptr; 5040 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 5041 Member->isArrow()) 5042 Base = Member->getBase(); 5043 5044 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 5045 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 5046 LastRecord.PossibleDerefs.insert(E); 5047 } 5048 } 5049 5050 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 5051 Expr *LowerBound, 5052 SourceLocation ColonLocFirst, 5053 SourceLocation ColonLocSecond, 5054 Expr *Length, Expr *Stride, 5055 SourceLocation RBLoc) { 5056 if (Base->hasPlaceholderType() && 5057 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5058 ExprResult Result = CheckPlaceholderExpr(Base); 5059 if (Result.isInvalid()) 5060 return ExprError(); 5061 Base = Result.get(); 5062 } 5063 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 5064 ExprResult Result = CheckPlaceholderExpr(LowerBound); 5065 if (Result.isInvalid()) 5066 return ExprError(); 5067 Result = DefaultLvalueConversion(Result.get()); 5068 if (Result.isInvalid()) 5069 return ExprError(); 5070 LowerBound = Result.get(); 5071 } 5072 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 5073 ExprResult Result = CheckPlaceholderExpr(Length); 5074 if (Result.isInvalid()) 5075 return ExprError(); 5076 Result = DefaultLvalueConversion(Result.get()); 5077 if (Result.isInvalid()) 5078 return ExprError(); 5079 Length = Result.get(); 5080 } 5081 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 5082 ExprResult Result = CheckPlaceholderExpr(Stride); 5083 if (Result.isInvalid()) 5084 return ExprError(); 5085 Result = DefaultLvalueConversion(Result.get()); 5086 if (Result.isInvalid()) 5087 return ExprError(); 5088 Stride = Result.get(); 5089 } 5090 5091 // Build an unanalyzed expression if either operand is type-dependent. 5092 if (Base->isTypeDependent() || 5093 (LowerBound && 5094 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 5095 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 5096 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 5097 return new (Context) OMPArraySectionExpr( 5098 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 5099 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5100 } 5101 5102 // Perform default conversions. 5103 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 5104 QualType ResultTy; 5105 if (OriginalTy->isAnyPointerType()) { 5106 ResultTy = OriginalTy->getPointeeType(); 5107 } else if (OriginalTy->isArrayType()) { 5108 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 5109 } else { 5110 return ExprError( 5111 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 5112 << Base->getSourceRange()); 5113 } 5114 // C99 6.5.2.1p1 5115 if (LowerBound) { 5116 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 5117 LowerBound); 5118 if (Res.isInvalid()) 5119 return ExprError(Diag(LowerBound->getExprLoc(), 5120 diag::err_omp_typecheck_section_not_integer) 5121 << 0 << LowerBound->getSourceRange()); 5122 LowerBound = Res.get(); 5123 5124 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5125 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5126 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5127 << 0 << LowerBound->getSourceRange(); 5128 } 5129 if (Length) { 5130 auto Res = 5131 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5132 if (Res.isInvalid()) 5133 return ExprError(Diag(Length->getExprLoc(), 5134 diag::err_omp_typecheck_section_not_integer) 5135 << 1 << Length->getSourceRange()); 5136 Length = Res.get(); 5137 5138 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5139 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5140 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5141 << 1 << Length->getSourceRange(); 5142 } 5143 if (Stride) { 5144 ExprResult Res = 5145 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5146 if (Res.isInvalid()) 5147 return ExprError(Diag(Stride->getExprLoc(), 5148 diag::err_omp_typecheck_section_not_integer) 5149 << 1 << Stride->getSourceRange()); 5150 Stride = Res.get(); 5151 5152 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5153 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5154 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5155 << 1 << Stride->getSourceRange(); 5156 } 5157 5158 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5159 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5160 // type. Note that functions are not objects, and that (in C99 parlance) 5161 // incomplete types are not object types. 5162 if (ResultTy->isFunctionType()) { 5163 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5164 << ResultTy << Base->getSourceRange(); 5165 return ExprError(); 5166 } 5167 5168 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5169 diag::err_omp_section_incomplete_type, Base)) 5170 return ExprError(); 5171 5172 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5173 Expr::EvalResult Result; 5174 if (LowerBound->EvaluateAsInt(Result, Context)) { 5175 // OpenMP 5.0, [2.1.5 Array Sections] 5176 // The array section must be a subset of the original array. 5177 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5178 if (LowerBoundValue.isNegative()) { 5179 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5180 << LowerBound->getSourceRange(); 5181 return ExprError(); 5182 } 5183 } 5184 } 5185 5186 if (Length) { 5187 Expr::EvalResult Result; 5188 if (Length->EvaluateAsInt(Result, Context)) { 5189 // OpenMP 5.0, [2.1.5 Array Sections] 5190 // The length must evaluate to non-negative integers. 5191 llvm::APSInt LengthValue = Result.Val.getInt(); 5192 if (LengthValue.isNegative()) { 5193 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5194 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5195 << Length->getSourceRange(); 5196 return ExprError(); 5197 } 5198 } 5199 } else if (ColonLocFirst.isValid() && 5200 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5201 !OriginalTy->isVariableArrayType()))) { 5202 // OpenMP 5.0, [2.1.5 Array Sections] 5203 // When the size of the array dimension is not known, the length must be 5204 // specified explicitly. 5205 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5206 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5207 return ExprError(); 5208 } 5209 5210 if (Stride) { 5211 Expr::EvalResult Result; 5212 if (Stride->EvaluateAsInt(Result, Context)) { 5213 // OpenMP 5.0, [2.1.5 Array Sections] 5214 // The stride must evaluate to a positive integer. 5215 llvm::APSInt StrideValue = Result.Val.getInt(); 5216 if (!StrideValue.isStrictlyPositive()) { 5217 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5218 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5219 << Stride->getSourceRange(); 5220 return ExprError(); 5221 } 5222 } 5223 } 5224 5225 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5226 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5227 if (Result.isInvalid()) 5228 return ExprError(); 5229 Base = Result.get(); 5230 } 5231 return new (Context) OMPArraySectionExpr( 5232 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5233 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5234 } 5235 5236 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5237 SourceLocation RParenLoc, 5238 ArrayRef<Expr *> Dims, 5239 ArrayRef<SourceRange> Brackets) { 5240 if (Base->hasPlaceholderType()) { 5241 ExprResult Result = CheckPlaceholderExpr(Base); 5242 if (Result.isInvalid()) 5243 return ExprError(); 5244 Result = DefaultLvalueConversion(Result.get()); 5245 if (Result.isInvalid()) 5246 return ExprError(); 5247 Base = Result.get(); 5248 } 5249 QualType BaseTy = Base->getType(); 5250 // Delay analysis of the types/expressions if instantiation/specialization is 5251 // required. 5252 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5253 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5254 LParenLoc, RParenLoc, Dims, Brackets); 5255 if (!BaseTy->isPointerType() || 5256 (!Base->isTypeDependent() && 5257 BaseTy->getPointeeType()->isIncompleteType())) 5258 return ExprError(Diag(Base->getExprLoc(), 5259 diag::err_omp_non_pointer_type_array_shaping_base) 5260 << Base->getSourceRange()); 5261 5262 SmallVector<Expr *, 4> NewDims; 5263 bool ErrorFound = false; 5264 for (Expr *Dim : Dims) { 5265 if (Dim->hasPlaceholderType()) { 5266 ExprResult Result = CheckPlaceholderExpr(Dim); 5267 if (Result.isInvalid()) { 5268 ErrorFound = true; 5269 continue; 5270 } 5271 Result = DefaultLvalueConversion(Result.get()); 5272 if (Result.isInvalid()) { 5273 ErrorFound = true; 5274 continue; 5275 } 5276 Dim = Result.get(); 5277 } 5278 if (!Dim->isTypeDependent()) { 5279 ExprResult Result = 5280 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5281 if (Result.isInvalid()) { 5282 ErrorFound = true; 5283 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5284 << Dim->getSourceRange(); 5285 continue; 5286 } 5287 Dim = Result.get(); 5288 Expr::EvalResult EvResult; 5289 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5290 // OpenMP 5.0, [2.1.4 Array Shaping] 5291 // Each si is an integral type expression that must evaluate to a 5292 // positive integer. 5293 llvm::APSInt Value = EvResult.Val.getInt(); 5294 if (!Value.isStrictlyPositive()) { 5295 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5296 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5297 << Dim->getSourceRange(); 5298 ErrorFound = true; 5299 continue; 5300 } 5301 } 5302 } 5303 NewDims.push_back(Dim); 5304 } 5305 if (ErrorFound) 5306 return ExprError(); 5307 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5308 LParenLoc, RParenLoc, NewDims, Brackets); 5309 } 5310 5311 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5312 SourceLocation LLoc, SourceLocation RLoc, 5313 ArrayRef<OMPIteratorData> Data) { 5314 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5315 bool IsCorrect = true; 5316 for (const OMPIteratorData &D : Data) { 5317 TypeSourceInfo *TInfo = nullptr; 5318 SourceLocation StartLoc; 5319 QualType DeclTy; 5320 if (!D.Type.getAsOpaquePtr()) { 5321 // OpenMP 5.0, 2.1.6 Iterators 5322 // In an iterator-specifier, if the iterator-type is not specified then 5323 // the type of that iterator is of int type. 5324 DeclTy = Context.IntTy; 5325 StartLoc = D.DeclIdentLoc; 5326 } else { 5327 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5328 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5329 } 5330 5331 bool IsDeclTyDependent = DeclTy->isDependentType() || 5332 DeclTy->containsUnexpandedParameterPack() || 5333 DeclTy->isInstantiationDependentType(); 5334 if (!IsDeclTyDependent) { 5335 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5336 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5337 // The iterator-type must be an integral or pointer type. 5338 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5339 << DeclTy; 5340 IsCorrect = false; 5341 continue; 5342 } 5343 if (DeclTy.isConstant(Context)) { 5344 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5345 // The iterator-type must not be const qualified. 5346 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5347 << DeclTy; 5348 IsCorrect = false; 5349 continue; 5350 } 5351 } 5352 5353 // Iterator declaration. 5354 assert(D.DeclIdent && "Identifier expected."); 5355 // Always try to create iterator declarator to avoid extra error messages 5356 // about unknown declarations use. 5357 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5358 D.DeclIdent, DeclTy, TInfo, SC_None); 5359 VD->setImplicit(); 5360 if (S) { 5361 // Check for conflicting previous declaration. 5362 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5363 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5364 ForVisibleRedeclaration); 5365 Previous.suppressDiagnostics(); 5366 LookupName(Previous, S); 5367 5368 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5369 /*AllowInlineNamespace=*/false); 5370 if (!Previous.empty()) { 5371 NamedDecl *Old = Previous.getRepresentativeDecl(); 5372 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5373 Diag(Old->getLocation(), diag::note_previous_definition); 5374 } else { 5375 PushOnScopeChains(VD, S); 5376 } 5377 } else { 5378 CurContext->addDecl(VD); 5379 } 5380 Expr *Begin = D.Range.Begin; 5381 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5382 ExprResult BeginRes = 5383 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5384 Begin = BeginRes.get(); 5385 } 5386 Expr *End = D.Range.End; 5387 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5388 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5389 End = EndRes.get(); 5390 } 5391 Expr *Step = D.Range.Step; 5392 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5393 if (!Step->getType()->isIntegralType(Context)) { 5394 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5395 << Step << Step->getSourceRange(); 5396 IsCorrect = false; 5397 continue; 5398 } 5399 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5400 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5401 // If the step expression of a range-specification equals zero, the 5402 // behavior is unspecified. 5403 if (Result && Result->isZero()) { 5404 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5405 << Step << Step->getSourceRange(); 5406 IsCorrect = false; 5407 continue; 5408 } 5409 } 5410 if (!Begin || !End || !IsCorrect) { 5411 IsCorrect = false; 5412 continue; 5413 } 5414 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5415 IDElem.IteratorDecl = VD; 5416 IDElem.AssignmentLoc = D.AssignLoc; 5417 IDElem.Range.Begin = Begin; 5418 IDElem.Range.End = End; 5419 IDElem.Range.Step = Step; 5420 IDElem.ColonLoc = D.ColonLoc; 5421 IDElem.SecondColonLoc = D.SecColonLoc; 5422 } 5423 if (!IsCorrect) { 5424 // Invalidate all created iterator declarations if error is found. 5425 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5426 if (Decl *ID = D.IteratorDecl) 5427 ID->setInvalidDecl(); 5428 } 5429 return ExprError(); 5430 } 5431 SmallVector<OMPIteratorHelperData, 4> Helpers; 5432 if (!CurContext->isDependentContext()) { 5433 // Build number of ityeration for each iteration range. 5434 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5435 // ((Begini-Stepi-1-Endi) / -Stepi); 5436 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5437 // (Endi - Begini) 5438 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5439 D.Range.Begin); 5440 if(!Res.isUsable()) { 5441 IsCorrect = false; 5442 continue; 5443 } 5444 ExprResult St, St1; 5445 if (D.Range.Step) { 5446 St = D.Range.Step; 5447 // (Endi - Begini) + Stepi 5448 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5449 if (!Res.isUsable()) { 5450 IsCorrect = false; 5451 continue; 5452 } 5453 // (Endi - Begini) + Stepi - 1 5454 Res = 5455 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5456 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5457 if (!Res.isUsable()) { 5458 IsCorrect = false; 5459 continue; 5460 } 5461 // ((Endi - Begini) + Stepi - 1) / Stepi 5462 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5463 if (!Res.isUsable()) { 5464 IsCorrect = false; 5465 continue; 5466 } 5467 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5468 // (Begini - Endi) 5469 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5470 D.Range.Begin, D.Range.End); 5471 if (!Res1.isUsable()) { 5472 IsCorrect = false; 5473 continue; 5474 } 5475 // (Begini - Endi) - Stepi 5476 Res1 = 5477 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5478 if (!Res1.isUsable()) { 5479 IsCorrect = false; 5480 continue; 5481 } 5482 // (Begini - Endi) - Stepi - 1 5483 Res1 = 5484 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5485 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5486 if (!Res1.isUsable()) { 5487 IsCorrect = false; 5488 continue; 5489 } 5490 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5491 Res1 = 5492 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5493 if (!Res1.isUsable()) { 5494 IsCorrect = false; 5495 continue; 5496 } 5497 // Stepi > 0. 5498 ExprResult CmpRes = 5499 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5500 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5501 if (!CmpRes.isUsable()) { 5502 IsCorrect = false; 5503 continue; 5504 } 5505 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5506 Res.get(), Res1.get()); 5507 if (!Res.isUsable()) { 5508 IsCorrect = false; 5509 continue; 5510 } 5511 } 5512 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5513 if (!Res.isUsable()) { 5514 IsCorrect = false; 5515 continue; 5516 } 5517 5518 // Build counter update. 5519 // Build counter. 5520 auto *CounterVD = 5521 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5522 D.IteratorDecl->getBeginLoc(), nullptr, 5523 Res.get()->getType(), nullptr, SC_None); 5524 CounterVD->setImplicit(); 5525 ExprResult RefRes = 5526 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5527 D.IteratorDecl->getBeginLoc()); 5528 // Build counter update. 5529 // I = Begini + counter * Stepi; 5530 ExprResult UpdateRes; 5531 if (D.Range.Step) { 5532 UpdateRes = CreateBuiltinBinOp( 5533 D.AssignmentLoc, BO_Mul, 5534 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5535 } else { 5536 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5537 } 5538 if (!UpdateRes.isUsable()) { 5539 IsCorrect = false; 5540 continue; 5541 } 5542 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5543 UpdateRes.get()); 5544 if (!UpdateRes.isUsable()) { 5545 IsCorrect = false; 5546 continue; 5547 } 5548 ExprResult VDRes = 5549 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5550 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5551 D.IteratorDecl->getBeginLoc()); 5552 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5553 UpdateRes.get()); 5554 if (!UpdateRes.isUsable()) { 5555 IsCorrect = false; 5556 continue; 5557 } 5558 UpdateRes = 5559 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5560 if (!UpdateRes.isUsable()) { 5561 IsCorrect = false; 5562 continue; 5563 } 5564 ExprResult CounterUpdateRes = 5565 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5566 if (!CounterUpdateRes.isUsable()) { 5567 IsCorrect = false; 5568 continue; 5569 } 5570 CounterUpdateRes = 5571 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5572 if (!CounterUpdateRes.isUsable()) { 5573 IsCorrect = false; 5574 continue; 5575 } 5576 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5577 HD.CounterVD = CounterVD; 5578 HD.Upper = Res.get(); 5579 HD.Update = UpdateRes.get(); 5580 HD.CounterUpdate = CounterUpdateRes.get(); 5581 } 5582 } else { 5583 Helpers.assign(ID.size(), {}); 5584 } 5585 if (!IsCorrect) { 5586 // Invalidate all created iterator declarations if error is found. 5587 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5588 if (Decl *ID = D.IteratorDecl) 5589 ID->setInvalidDecl(); 5590 } 5591 return ExprError(); 5592 } 5593 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5594 LLoc, RLoc, ID, Helpers); 5595 } 5596 5597 ExprResult 5598 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5599 Expr *Idx, SourceLocation RLoc) { 5600 Expr *LHSExp = Base; 5601 Expr *RHSExp = Idx; 5602 5603 ExprValueKind VK = VK_LValue; 5604 ExprObjectKind OK = OK_Ordinary; 5605 5606 // Per C++ core issue 1213, the result is an xvalue if either operand is 5607 // a non-lvalue array, and an lvalue otherwise. 5608 if (getLangOpts().CPlusPlus11) { 5609 for (auto *Op : {LHSExp, RHSExp}) { 5610 Op = Op->IgnoreImplicit(); 5611 if (Op->getType()->isArrayType() && !Op->isLValue()) 5612 VK = VK_XValue; 5613 } 5614 } 5615 5616 // Perform default conversions. 5617 if (!LHSExp->getType()->getAs<VectorType>()) { 5618 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5619 if (Result.isInvalid()) 5620 return ExprError(); 5621 LHSExp = Result.get(); 5622 } 5623 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5624 if (Result.isInvalid()) 5625 return ExprError(); 5626 RHSExp = Result.get(); 5627 5628 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5629 5630 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5631 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5632 // in the subscript position. As a result, we need to derive the array base 5633 // and index from the expression types. 5634 Expr *BaseExpr, *IndexExpr; 5635 QualType ResultType; 5636 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5637 BaseExpr = LHSExp; 5638 IndexExpr = RHSExp; 5639 ResultType = 5640 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); 5641 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5642 BaseExpr = LHSExp; 5643 IndexExpr = RHSExp; 5644 ResultType = PTy->getPointeeType(); 5645 } else if (const ObjCObjectPointerType *PTy = 5646 LHSTy->getAs<ObjCObjectPointerType>()) { 5647 BaseExpr = LHSExp; 5648 IndexExpr = RHSExp; 5649 5650 // Use custom logic if this should be the pseudo-object subscript 5651 // expression. 5652 if (!LangOpts.isSubscriptPointerArithmetic()) 5653 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5654 nullptr); 5655 5656 ResultType = PTy->getPointeeType(); 5657 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5658 // Handle the uncommon case of "123[Ptr]". 5659 BaseExpr = RHSExp; 5660 IndexExpr = LHSExp; 5661 ResultType = PTy->getPointeeType(); 5662 } else if (const ObjCObjectPointerType *PTy = 5663 RHSTy->getAs<ObjCObjectPointerType>()) { 5664 // Handle the uncommon case of "123[Ptr]". 5665 BaseExpr = RHSExp; 5666 IndexExpr = LHSExp; 5667 ResultType = PTy->getPointeeType(); 5668 if (!LangOpts.isSubscriptPointerArithmetic()) { 5669 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5670 << ResultType << BaseExpr->getSourceRange(); 5671 return ExprError(); 5672 } 5673 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5674 BaseExpr = LHSExp; // vectors: V[123] 5675 IndexExpr = RHSExp; 5676 // We apply C++ DR1213 to vector subscripting too. 5677 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5678 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5679 if (Materialized.isInvalid()) 5680 return ExprError(); 5681 LHSExp = Materialized.get(); 5682 } 5683 VK = LHSExp->getValueKind(); 5684 if (VK != VK_PRValue) 5685 OK = OK_VectorComponent; 5686 5687 ResultType = VTy->getElementType(); 5688 QualType BaseType = BaseExpr->getType(); 5689 Qualifiers BaseQuals = BaseType.getQualifiers(); 5690 Qualifiers MemberQuals = ResultType.getQualifiers(); 5691 Qualifiers Combined = BaseQuals + MemberQuals; 5692 if (Combined != MemberQuals) 5693 ResultType = Context.getQualifiedType(ResultType, Combined); 5694 } else if (LHSTy->isBuiltinType() && 5695 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) { 5696 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>(); 5697 if (BTy->isSVEBool()) 5698 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t) 5699 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5700 5701 BaseExpr = LHSExp; 5702 IndexExpr = RHSExp; 5703 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5704 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5705 if (Materialized.isInvalid()) 5706 return ExprError(); 5707 LHSExp = Materialized.get(); 5708 } 5709 VK = LHSExp->getValueKind(); 5710 if (VK != VK_PRValue) 5711 OK = OK_VectorComponent; 5712 5713 ResultType = BTy->getSveEltType(Context); 5714 5715 QualType BaseType = BaseExpr->getType(); 5716 Qualifiers BaseQuals = BaseType.getQualifiers(); 5717 Qualifiers MemberQuals = ResultType.getQualifiers(); 5718 Qualifiers Combined = BaseQuals + MemberQuals; 5719 if (Combined != MemberQuals) 5720 ResultType = Context.getQualifiedType(ResultType, Combined); 5721 } else if (LHSTy->isArrayType()) { 5722 // If we see an array that wasn't promoted by 5723 // DefaultFunctionArrayLvalueConversion, it must be an array that 5724 // wasn't promoted because of the C90 rule that doesn't 5725 // allow promoting non-lvalue arrays. Warn, then 5726 // force the promotion here. 5727 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5728 << LHSExp->getSourceRange(); 5729 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5730 CK_ArrayToPointerDecay).get(); 5731 LHSTy = LHSExp->getType(); 5732 5733 BaseExpr = LHSExp; 5734 IndexExpr = RHSExp; 5735 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5736 } else if (RHSTy->isArrayType()) { 5737 // Same as previous, except for 123[f().a] case 5738 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5739 << RHSExp->getSourceRange(); 5740 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5741 CK_ArrayToPointerDecay).get(); 5742 RHSTy = RHSExp->getType(); 5743 5744 BaseExpr = RHSExp; 5745 IndexExpr = LHSExp; 5746 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5747 } else { 5748 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5749 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5750 } 5751 // C99 6.5.2.1p1 5752 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5753 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5754 << IndexExpr->getSourceRange()); 5755 5756 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5757 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5758 && !IndexExpr->isTypeDependent()) 5759 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5760 5761 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5762 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5763 // type. Note that Functions are not objects, and that (in C99 parlance) 5764 // incomplete types are not object types. 5765 if (ResultType->isFunctionType()) { 5766 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5767 << ResultType << BaseExpr->getSourceRange(); 5768 return ExprError(); 5769 } 5770 5771 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5772 // GNU extension: subscripting on pointer to void 5773 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5774 << BaseExpr->getSourceRange(); 5775 5776 // C forbids expressions of unqualified void type from being l-values. 5777 // See IsCForbiddenLValueType. 5778 if (!ResultType.hasQualifiers()) 5779 VK = VK_PRValue; 5780 } else if (!ResultType->isDependentType() && 5781 RequireCompleteSizedType( 5782 LLoc, ResultType, 5783 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5784 return ExprError(); 5785 5786 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5787 !ResultType.isCForbiddenLValueType()); 5788 5789 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5790 FunctionScopes.size() > 1) { 5791 if (auto *TT = 5792 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5793 for (auto I = FunctionScopes.rbegin(), 5794 E = std::prev(FunctionScopes.rend()); 5795 I != E; ++I) { 5796 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5797 if (CSI == nullptr) 5798 break; 5799 DeclContext *DC = nullptr; 5800 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5801 DC = LSI->CallOperator; 5802 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5803 DC = CRSI->TheCapturedDecl; 5804 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5805 DC = BSI->TheDecl; 5806 if (DC) { 5807 if (DC->containsDecl(TT->getDecl())) 5808 break; 5809 captureVariablyModifiedType( 5810 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5811 } 5812 } 5813 } 5814 } 5815 5816 return new (Context) 5817 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5818 } 5819 5820 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5821 ParmVarDecl *Param) { 5822 if (Param->hasUnparsedDefaultArg()) { 5823 // If we've already cleared out the location for the default argument, 5824 // that means we're parsing it right now. 5825 if (!UnparsedDefaultArgLocs.count(Param)) { 5826 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5827 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5828 Param->setInvalidDecl(); 5829 return true; 5830 } 5831 5832 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5833 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5834 Diag(UnparsedDefaultArgLocs[Param], 5835 diag::note_default_argument_declared_here); 5836 return true; 5837 } 5838 5839 if (Param->hasUninstantiatedDefaultArg() && 5840 InstantiateDefaultArgument(CallLoc, FD, Param)) 5841 return true; 5842 5843 assert(Param->hasInit() && "default argument but no initializer?"); 5844 5845 // If the default expression creates temporaries, we need to 5846 // push them to the current stack of expression temporaries so they'll 5847 // be properly destroyed. 5848 // FIXME: We should really be rebuilding the default argument with new 5849 // bound temporaries; see the comment in PR5810. 5850 // We don't need to do that with block decls, though, because 5851 // blocks in default argument expression can never capture anything. 5852 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5853 // Set the "needs cleanups" bit regardless of whether there are 5854 // any explicit objects. 5855 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5856 5857 // Append all the objects to the cleanup list. Right now, this 5858 // should always be a no-op, because blocks in default argument 5859 // expressions should never be able to capture anything. 5860 assert(!Init->getNumObjects() && 5861 "default argument expression has capturing blocks?"); 5862 } 5863 5864 // We already type-checked the argument, so we know it works. 5865 // Just mark all of the declarations in this potentially-evaluated expression 5866 // as being "referenced". 5867 EnterExpressionEvaluationContext EvalContext( 5868 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5869 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5870 /*SkipLocalVariables=*/true); 5871 return false; 5872 } 5873 5874 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5875 FunctionDecl *FD, ParmVarDecl *Param) { 5876 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5877 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5878 return ExprError(); 5879 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5880 } 5881 5882 Sema::VariadicCallType 5883 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5884 Expr *Fn) { 5885 if (Proto && Proto->isVariadic()) { 5886 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 5887 return VariadicConstructor; 5888 else if (Fn && Fn->getType()->isBlockPointerType()) 5889 return VariadicBlock; 5890 else if (FDecl) { 5891 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5892 if (Method->isInstance()) 5893 return VariadicMethod; 5894 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5895 return VariadicMethod; 5896 return VariadicFunction; 5897 } 5898 return VariadicDoesNotApply; 5899 } 5900 5901 namespace { 5902 class FunctionCallCCC final : public FunctionCallFilterCCC { 5903 public: 5904 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5905 unsigned NumArgs, MemberExpr *ME) 5906 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5907 FunctionName(FuncName) {} 5908 5909 bool ValidateCandidate(const TypoCorrection &candidate) override { 5910 if (!candidate.getCorrectionSpecifier() || 5911 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5912 return false; 5913 } 5914 5915 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5916 } 5917 5918 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5919 return std::make_unique<FunctionCallCCC>(*this); 5920 } 5921 5922 private: 5923 const IdentifierInfo *const FunctionName; 5924 }; 5925 } 5926 5927 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5928 FunctionDecl *FDecl, 5929 ArrayRef<Expr *> Args) { 5930 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5931 DeclarationName FuncName = FDecl->getDeclName(); 5932 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5933 5934 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5935 if (TypoCorrection Corrected = S.CorrectTypo( 5936 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5937 S.getScopeForContext(S.CurContext), nullptr, CCC, 5938 Sema::CTK_ErrorRecovery)) { 5939 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5940 if (Corrected.isOverloaded()) { 5941 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5942 OverloadCandidateSet::iterator Best; 5943 for (NamedDecl *CD : Corrected) { 5944 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5945 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5946 OCS); 5947 } 5948 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5949 case OR_Success: 5950 ND = Best->FoundDecl; 5951 Corrected.setCorrectionDecl(ND); 5952 break; 5953 default: 5954 break; 5955 } 5956 } 5957 ND = ND->getUnderlyingDecl(); 5958 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5959 return Corrected; 5960 } 5961 } 5962 return TypoCorrection(); 5963 } 5964 5965 /// ConvertArgumentsForCall - Converts the arguments specified in 5966 /// Args/NumArgs to the parameter types of the function FDecl with 5967 /// function prototype Proto. Call is the call expression itself, and 5968 /// Fn is the function expression. For a C++ member function, this 5969 /// routine does not attempt to convert the object argument. Returns 5970 /// true if the call is ill-formed. 5971 bool 5972 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5973 FunctionDecl *FDecl, 5974 const FunctionProtoType *Proto, 5975 ArrayRef<Expr *> Args, 5976 SourceLocation RParenLoc, 5977 bool IsExecConfig) { 5978 // Bail out early if calling a builtin with custom typechecking. 5979 if (FDecl) 5980 if (unsigned ID = FDecl->getBuiltinID()) 5981 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5982 return false; 5983 5984 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5985 // assignment, to the types of the corresponding parameter, ... 5986 unsigned NumParams = Proto->getNumParams(); 5987 bool Invalid = false; 5988 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5989 unsigned FnKind = Fn->getType()->isBlockPointerType() 5990 ? 1 /* block */ 5991 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5992 : 0 /* function */); 5993 5994 // If too few arguments are available (and we don't have default 5995 // arguments for the remaining parameters), don't make the call. 5996 if (Args.size() < NumParams) { 5997 if (Args.size() < MinArgs) { 5998 TypoCorrection TC; 5999 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6000 unsigned diag_id = 6001 MinArgs == NumParams && !Proto->isVariadic() 6002 ? diag::err_typecheck_call_too_few_args_suggest 6003 : diag::err_typecheck_call_too_few_args_at_least_suggest; 6004 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 6005 << static_cast<unsigned>(Args.size()) 6006 << TC.getCorrectionRange()); 6007 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 6008 Diag(RParenLoc, 6009 MinArgs == NumParams && !Proto->isVariadic() 6010 ? diag::err_typecheck_call_too_few_args_one 6011 : diag::err_typecheck_call_too_few_args_at_least_one) 6012 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 6013 else 6014 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 6015 ? diag::err_typecheck_call_too_few_args 6016 : diag::err_typecheck_call_too_few_args_at_least) 6017 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 6018 << Fn->getSourceRange(); 6019 6020 // Emit the location of the prototype. 6021 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6022 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6023 6024 return true; 6025 } 6026 // We reserve space for the default arguments when we create 6027 // the call expression, before calling ConvertArgumentsForCall. 6028 assert((Call->getNumArgs() == NumParams) && 6029 "We should have reserved space for the default arguments before!"); 6030 } 6031 6032 // If too many are passed and not variadic, error on the extras and drop 6033 // them. 6034 if (Args.size() > NumParams) { 6035 if (!Proto->isVariadic()) { 6036 TypoCorrection TC; 6037 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6038 unsigned diag_id = 6039 MinArgs == NumParams && !Proto->isVariadic() 6040 ? diag::err_typecheck_call_too_many_args_suggest 6041 : diag::err_typecheck_call_too_many_args_at_most_suggest; 6042 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 6043 << static_cast<unsigned>(Args.size()) 6044 << TC.getCorrectionRange()); 6045 } else if (NumParams == 1 && FDecl && 6046 FDecl->getParamDecl(0)->getDeclName()) 6047 Diag(Args[NumParams]->getBeginLoc(), 6048 MinArgs == NumParams 6049 ? diag::err_typecheck_call_too_many_args_one 6050 : diag::err_typecheck_call_too_many_args_at_most_one) 6051 << FnKind << FDecl->getParamDecl(0) 6052 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 6053 << SourceRange(Args[NumParams]->getBeginLoc(), 6054 Args.back()->getEndLoc()); 6055 else 6056 Diag(Args[NumParams]->getBeginLoc(), 6057 MinArgs == NumParams 6058 ? diag::err_typecheck_call_too_many_args 6059 : diag::err_typecheck_call_too_many_args_at_most) 6060 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 6061 << Fn->getSourceRange() 6062 << SourceRange(Args[NumParams]->getBeginLoc(), 6063 Args.back()->getEndLoc()); 6064 6065 // Emit the location of the prototype. 6066 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6067 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6068 6069 // This deletes the extra arguments. 6070 Call->shrinkNumArgs(NumParams); 6071 return true; 6072 } 6073 } 6074 SmallVector<Expr *, 8> AllArgs; 6075 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 6076 6077 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 6078 AllArgs, CallType); 6079 if (Invalid) 6080 return true; 6081 unsigned TotalNumArgs = AllArgs.size(); 6082 for (unsigned i = 0; i < TotalNumArgs; ++i) 6083 Call->setArg(i, AllArgs[i]); 6084 6085 Call->computeDependence(); 6086 return false; 6087 } 6088 6089 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 6090 const FunctionProtoType *Proto, 6091 unsigned FirstParam, ArrayRef<Expr *> Args, 6092 SmallVectorImpl<Expr *> &AllArgs, 6093 VariadicCallType CallType, bool AllowExplicit, 6094 bool IsListInitialization) { 6095 unsigned NumParams = Proto->getNumParams(); 6096 bool Invalid = false; 6097 size_t ArgIx = 0; 6098 // Continue to check argument types (even if we have too few/many args). 6099 for (unsigned i = FirstParam; i < NumParams; i++) { 6100 QualType ProtoArgType = Proto->getParamType(i); 6101 6102 Expr *Arg; 6103 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 6104 if (ArgIx < Args.size()) { 6105 Arg = Args[ArgIx++]; 6106 6107 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 6108 diag::err_call_incomplete_argument, Arg)) 6109 return true; 6110 6111 // Strip the unbridged-cast placeholder expression off, if applicable. 6112 bool CFAudited = false; 6113 if (Arg->getType() == Context.ARCUnbridgedCastTy && 6114 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6115 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6116 Arg = stripARCUnbridgedCast(Arg); 6117 else if (getLangOpts().ObjCAutoRefCount && 6118 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6119 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6120 CFAudited = true; 6121 6122 if (Proto->getExtParameterInfo(i).isNoEscape() && 6123 ProtoArgType->isBlockPointerType()) 6124 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 6125 BE->getBlockDecl()->setDoesNotEscape(); 6126 6127 InitializedEntity Entity = 6128 Param ? InitializedEntity::InitializeParameter(Context, Param, 6129 ProtoArgType) 6130 : InitializedEntity::InitializeParameter( 6131 Context, ProtoArgType, Proto->isParamConsumed(i)); 6132 6133 // Remember that parameter belongs to a CF audited API. 6134 if (CFAudited) 6135 Entity.setParameterCFAudited(); 6136 6137 ExprResult ArgE = PerformCopyInitialization( 6138 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 6139 if (ArgE.isInvalid()) 6140 return true; 6141 6142 Arg = ArgE.getAs<Expr>(); 6143 } else { 6144 assert(Param && "can't use default arguments without a known callee"); 6145 6146 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 6147 if (ArgExpr.isInvalid()) 6148 return true; 6149 6150 Arg = ArgExpr.getAs<Expr>(); 6151 } 6152 6153 // Check for array bounds violations for each argument to the call. This 6154 // check only triggers warnings when the argument isn't a more complex Expr 6155 // with its own checking, such as a BinaryOperator. 6156 CheckArrayAccess(Arg); 6157 6158 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6159 CheckStaticArrayArgument(CallLoc, Param, Arg); 6160 6161 AllArgs.push_back(Arg); 6162 } 6163 6164 // If this is a variadic call, handle args passed through "...". 6165 if (CallType != VariadicDoesNotApply) { 6166 // Assume that extern "C" functions with variadic arguments that 6167 // return __unknown_anytype aren't *really* variadic. 6168 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6169 FDecl->isExternC()) { 6170 for (Expr *A : Args.slice(ArgIx)) { 6171 QualType paramType; // ignored 6172 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6173 Invalid |= arg.isInvalid(); 6174 AllArgs.push_back(arg.get()); 6175 } 6176 6177 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6178 } else { 6179 for (Expr *A : Args.slice(ArgIx)) { 6180 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6181 Invalid |= Arg.isInvalid(); 6182 AllArgs.push_back(Arg.get()); 6183 } 6184 } 6185 6186 // Check for array bounds violations. 6187 for (Expr *A : Args.slice(ArgIx)) 6188 CheckArrayAccess(A); 6189 } 6190 return Invalid; 6191 } 6192 6193 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6194 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6195 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6196 TL = DTL.getOriginalLoc(); 6197 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6198 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6199 << ATL.getLocalSourceRange(); 6200 } 6201 6202 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6203 /// array parameter, check that it is non-null, and that if it is formed by 6204 /// array-to-pointer decay, the underlying array is sufficiently large. 6205 /// 6206 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6207 /// array type derivation, then for each call to the function, the value of the 6208 /// corresponding actual argument shall provide access to the first element of 6209 /// an array with at least as many elements as specified by the size expression. 6210 void 6211 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6212 ParmVarDecl *Param, 6213 const Expr *ArgExpr) { 6214 // Static array parameters are not supported in C++. 6215 if (!Param || getLangOpts().CPlusPlus) 6216 return; 6217 6218 QualType OrigTy = Param->getOriginalType(); 6219 6220 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6221 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6222 return; 6223 6224 if (ArgExpr->isNullPointerConstant(Context, 6225 Expr::NPC_NeverValueDependent)) { 6226 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6227 DiagnoseCalleeStaticArrayParam(*this, Param); 6228 return; 6229 } 6230 6231 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6232 if (!CAT) 6233 return; 6234 6235 const ConstantArrayType *ArgCAT = 6236 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6237 if (!ArgCAT) 6238 return; 6239 6240 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6241 ArgCAT->getElementType())) { 6242 if (ArgCAT->getSize().ult(CAT->getSize())) { 6243 Diag(CallLoc, diag::warn_static_array_too_small) 6244 << ArgExpr->getSourceRange() 6245 << (unsigned)ArgCAT->getSize().getZExtValue() 6246 << (unsigned)CAT->getSize().getZExtValue() << 0; 6247 DiagnoseCalleeStaticArrayParam(*this, Param); 6248 } 6249 return; 6250 } 6251 6252 Optional<CharUnits> ArgSize = 6253 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6254 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6255 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6256 Diag(CallLoc, diag::warn_static_array_too_small) 6257 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6258 << (unsigned)ParmSize->getQuantity() << 1; 6259 DiagnoseCalleeStaticArrayParam(*this, Param); 6260 } 6261 } 6262 6263 /// Given a function expression of unknown-any type, try to rebuild it 6264 /// to have a function type. 6265 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6266 6267 /// Is the given type a placeholder that we need to lower out 6268 /// immediately during argument processing? 6269 static bool isPlaceholderToRemoveAsArg(QualType type) { 6270 // Placeholders are never sugared. 6271 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6272 if (!placeholder) return false; 6273 6274 switch (placeholder->getKind()) { 6275 // Ignore all the non-placeholder types. 6276 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6277 case BuiltinType::Id: 6278 #include "clang/Basic/OpenCLImageTypes.def" 6279 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6280 case BuiltinType::Id: 6281 #include "clang/Basic/OpenCLExtensionTypes.def" 6282 // In practice we'll never use this, since all SVE types are sugared 6283 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6284 #define SVE_TYPE(Name, Id, SingletonId) \ 6285 case BuiltinType::Id: 6286 #include "clang/Basic/AArch64SVEACLETypes.def" 6287 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6288 case BuiltinType::Id: 6289 #include "clang/Basic/PPCTypes.def" 6290 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6291 #include "clang/Basic/RISCVVTypes.def" 6292 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6293 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6294 #include "clang/AST/BuiltinTypes.def" 6295 return false; 6296 6297 // We cannot lower out overload sets; they might validly be resolved 6298 // by the call machinery. 6299 case BuiltinType::Overload: 6300 return false; 6301 6302 // Unbridged casts in ARC can be handled in some call positions and 6303 // should be left in place. 6304 case BuiltinType::ARCUnbridgedCast: 6305 return false; 6306 6307 // Pseudo-objects should be converted as soon as possible. 6308 case BuiltinType::PseudoObject: 6309 return true; 6310 6311 // The debugger mode could theoretically but currently does not try 6312 // to resolve unknown-typed arguments based on known parameter types. 6313 case BuiltinType::UnknownAny: 6314 return true; 6315 6316 // These are always invalid as call arguments and should be reported. 6317 case BuiltinType::BoundMember: 6318 case BuiltinType::BuiltinFn: 6319 case BuiltinType::IncompleteMatrixIdx: 6320 case BuiltinType::OMPArraySection: 6321 case BuiltinType::OMPArrayShaping: 6322 case BuiltinType::OMPIterator: 6323 return true; 6324 6325 } 6326 llvm_unreachable("bad builtin type kind"); 6327 } 6328 6329 /// Check an argument list for placeholders that we won't try to 6330 /// handle later. 6331 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6332 // Apply this processing to all the arguments at once instead of 6333 // dying at the first failure. 6334 bool hasInvalid = false; 6335 for (size_t i = 0, e = args.size(); i != e; i++) { 6336 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6337 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6338 if (result.isInvalid()) hasInvalid = true; 6339 else args[i] = result.get(); 6340 } 6341 } 6342 return hasInvalid; 6343 } 6344 6345 /// If a builtin function has a pointer argument with no explicit address 6346 /// space, then it should be able to accept a pointer to any address 6347 /// space as input. In order to do this, we need to replace the 6348 /// standard builtin declaration with one that uses the same address space 6349 /// as the call. 6350 /// 6351 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6352 /// it does not contain any pointer arguments without 6353 /// an address space qualifer. Otherwise the rewritten 6354 /// FunctionDecl is returned. 6355 /// TODO: Handle pointer return types. 6356 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6357 FunctionDecl *FDecl, 6358 MultiExprArg ArgExprs) { 6359 6360 QualType DeclType = FDecl->getType(); 6361 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6362 6363 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6364 ArgExprs.size() < FT->getNumParams()) 6365 return nullptr; 6366 6367 bool NeedsNewDecl = false; 6368 unsigned i = 0; 6369 SmallVector<QualType, 8> OverloadParams; 6370 6371 for (QualType ParamType : FT->param_types()) { 6372 6373 // Convert array arguments to pointer to simplify type lookup. 6374 ExprResult ArgRes = 6375 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6376 if (ArgRes.isInvalid()) 6377 return nullptr; 6378 Expr *Arg = ArgRes.get(); 6379 QualType ArgType = Arg->getType(); 6380 if (!ParamType->isPointerType() || 6381 ParamType.hasAddressSpace() || 6382 !ArgType->isPointerType() || 6383 !ArgType->getPointeeType().hasAddressSpace()) { 6384 OverloadParams.push_back(ParamType); 6385 continue; 6386 } 6387 6388 QualType PointeeType = ParamType->getPointeeType(); 6389 if (PointeeType.hasAddressSpace()) 6390 continue; 6391 6392 NeedsNewDecl = true; 6393 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6394 6395 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6396 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6397 } 6398 6399 if (!NeedsNewDecl) 6400 return nullptr; 6401 6402 FunctionProtoType::ExtProtoInfo EPI; 6403 EPI.Variadic = FT->isVariadic(); 6404 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6405 OverloadParams, EPI); 6406 DeclContext *Parent = FDecl->getParent(); 6407 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6408 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6409 FDecl->getIdentifier(), OverloadTy, 6410 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6411 false, 6412 /*hasPrototype=*/true); 6413 SmallVector<ParmVarDecl*, 16> Params; 6414 FT = cast<FunctionProtoType>(OverloadTy); 6415 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6416 QualType ParamType = FT->getParamType(i); 6417 ParmVarDecl *Parm = 6418 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6419 SourceLocation(), nullptr, ParamType, 6420 /*TInfo=*/nullptr, SC_None, nullptr); 6421 Parm->setScopeInfo(0, i); 6422 Params.push_back(Parm); 6423 } 6424 OverloadDecl->setParams(Params); 6425 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6426 return OverloadDecl; 6427 } 6428 6429 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6430 FunctionDecl *Callee, 6431 MultiExprArg ArgExprs) { 6432 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6433 // similar attributes) really don't like it when functions are called with an 6434 // invalid number of args. 6435 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6436 /*PartialOverloading=*/false) && 6437 !Callee->isVariadic()) 6438 return; 6439 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6440 return; 6441 6442 if (const EnableIfAttr *Attr = 6443 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6444 S.Diag(Fn->getBeginLoc(), 6445 isa<CXXMethodDecl>(Callee) 6446 ? diag::err_ovl_no_viable_member_function_in_call 6447 : diag::err_ovl_no_viable_function_in_call) 6448 << Callee << Callee->getSourceRange(); 6449 S.Diag(Callee->getLocation(), 6450 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6451 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6452 return; 6453 } 6454 } 6455 6456 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6457 const UnresolvedMemberExpr *const UME, Sema &S) { 6458 6459 const auto GetFunctionLevelDCIfCXXClass = 6460 [](Sema &S) -> const CXXRecordDecl * { 6461 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6462 if (!DC || !DC->getParent()) 6463 return nullptr; 6464 6465 // If the call to some member function was made from within a member 6466 // function body 'M' return return 'M's parent. 6467 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6468 return MD->getParent()->getCanonicalDecl(); 6469 // else the call was made from within a default member initializer of a 6470 // class, so return the class. 6471 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6472 return RD->getCanonicalDecl(); 6473 return nullptr; 6474 }; 6475 // If our DeclContext is neither a member function nor a class (in the 6476 // case of a lambda in a default member initializer), we can't have an 6477 // enclosing 'this'. 6478 6479 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6480 if (!CurParentClass) 6481 return false; 6482 6483 // The naming class for implicit member functions call is the class in which 6484 // name lookup starts. 6485 const CXXRecordDecl *const NamingClass = 6486 UME->getNamingClass()->getCanonicalDecl(); 6487 assert(NamingClass && "Must have naming class even for implicit access"); 6488 6489 // If the unresolved member functions were found in a 'naming class' that is 6490 // related (either the same or derived from) to the class that contains the 6491 // member function that itself contained the implicit member access. 6492 6493 return CurParentClass == NamingClass || 6494 CurParentClass->isDerivedFrom(NamingClass); 6495 } 6496 6497 static void 6498 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6499 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6500 6501 if (!UME) 6502 return; 6503 6504 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6505 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6506 // already been captured, or if this is an implicit member function call (if 6507 // it isn't, an attempt to capture 'this' should already have been made). 6508 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6509 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6510 return; 6511 6512 // Check if the naming class in which the unresolved members were found is 6513 // related (same as or is a base of) to the enclosing class. 6514 6515 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6516 return; 6517 6518 6519 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6520 // If the enclosing function is not dependent, then this lambda is 6521 // capture ready, so if we can capture this, do so. 6522 if (!EnclosingFunctionCtx->isDependentContext()) { 6523 // If the current lambda and all enclosing lambdas can capture 'this' - 6524 // then go ahead and capture 'this' (since our unresolved overload set 6525 // contains at least one non-static member function). 6526 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6527 S.CheckCXXThisCapture(CallLoc); 6528 } else if (S.CurContext->isDependentContext()) { 6529 // ... since this is an implicit member reference, that might potentially 6530 // involve a 'this' capture, mark 'this' for potential capture in 6531 // enclosing lambdas. 6532 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6533 CurLSI->addPotentialThisCapture(CallLoc); 6534 } 6535 } 6536 6537 // Once a call is fully resolved, warn for unqualified calls to specific 6538 // C++ standard functions, like move and forward. 6539 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) { 6540 // We are only checking unary move and forward so exit early here. 6541 if (Call->getNumArgs() != 1) 6542 return; 6543 6544 Expr *E = Call->getCallee()->IgnoreParenImpCasts(); 6545 if (!E || isa<UnresolvedLookupExpr>(E)) 6546 return; 6547 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E); 6548 if (!DRE || !DRE->getLocation().isValid()) 6549 return; 6550 6551 if (DRE->getQualifier()) 6552 return; 6553 6554 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl()); 6555 if (!D || !D->isInStdNamespace()) 6556 return; 6557 6558 // Only warn for some functions deemed more frequent or problematic. 6559 static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"}; 6560 auto it = llvm::find(SpecialFunctions, D->getName()); 6561 if (it == std::end(SpecialFunctions)) 6562 return; 6563 6564 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function) 6565 << D->getQualifiedNameAsString() 6566 << FixItHint::CreateInsertion(DRE->getLocation(), "std::"); 6567 } 6568 6569 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6570 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6571 Expr *ExecConfig) { 6572 ExprResult Call = 6573 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6574 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6575 if (Call.isInvalid()) 6576 return Call; 6577 6578 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6579 // language modes. 6580 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6581 if (ULE->hasExplicitTemplateArgs() && 6582 ULE->decls_begin() == ULE->decls_end()) { 6583 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6584 ? diag::warn_cxx17_compat_adl_only_template_id 6585 : diag::ext_adl_only_template_id) 6586 << ULE->getName(); 6587 } 6588 } 6589 6590 if (LangOpts.OpenMP) 6591 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6592 ExecConfig); 6593 if (LangOpts.CPlusPlus) { 6594 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6595 if (CE) 6596 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE); 6597 } 6598 return Call; 6599 } 6600 6601 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6602 /// This provides the location of the left/right parens and a list of comma 6603 /// locations. 6604 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6605 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6606 Expr *ExecConfig, bool IsExecConfig, 6607 bool AllowRecovery) { 6608 // Since this might be a postfix expression, get rid of ParenListExprs. 6609 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6610 if (Result.isInvalid()) return ExprError(); 6611 Fn = Result.get(); 6612 6613 if (checkArgsForPlaceholders(*this, ArgExprs)) 6614 return ExprError(); 6615 6616 if (getLangOpts().CPlusPlus) { 6617 // If this is a pseudo-destructor expression, build the call immediately. 6618 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6619 if (!ArgExprs.empty()) { 6620 // Pseudo-destructor calls should not have any arguments. 6621 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6622 << FixItHint::CreateRemoval( 6623 SourceRange(ArgExprs.front()->getBeginLoc(), 6624 ArgExprs.back()->getEndLoc())); 6625 } 6626 6627 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6628 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6629 } 6630 if (Fn->getType() == Context.PseudoObjectTy) { 6631 ExprResult result = CheckPlaceholderExpr(Fn); 6632 if (result.isInvalid()) return ExprError(); 6633 Fn = result.get(); 6634 } 6635 6636 // Determine whether this is a dependent call inside a C++ template, 6637 // in which case we won't do any semantic analysis now. 6638 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6639 if (ExecConfig) { 6640 return CUDAKernelCallExpr::Create(Context, Fn, 6641 cast<CallExpr>(ExecConfig), ArgExprs, 6642 Context.DependentTy, VK_PRValue, 6643 RParenLoc, CurFPFeatureOverrides()); 6644 } else { 6645 6646 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6647 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6648 Fn->getBeginLoc()); 6649 6650 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6651 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6652 } 6653 } 6654 6655 // Determine whether this is a call to an object (C++ [over.call.object]). 6656 if (Fn->getType()->isRecordType()) 6657 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6658 RParenLoc); 6659 6660 if (Fn->getType() == Context.UnknownAnyTy) { 6661 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6662 if (result.isInvalid()) return ExprError(); 6663 Fn = result.get(); 6664 } 6665 6666 if (Fn->getType() == Context.BoundMemberTy) { 6667 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6668 RParenLoc, ExecConfig, IsExecConfig, 6669 AllowRecovery); 6670 } 6671 } 6672 6673 // Check for overloaded calls. This can happen even in C due to extensions. 6674 if (Fn->getType() == Context.OverloadTy) { 6675 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6676 6677 // We aren't supposed to apply this logic if there's an '&' involved. 6678 if (!find.HasFormOfMemberPointer) { 6679 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6680 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6681 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6682 OverloadExpr *ovl = find.Expression; 6683 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6684 return BuildOverloadedCallExpr( 6685 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6686 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6687 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6688 RParenLoc, ExecConfig, IsExecConfig, 6689 AllowRecovery); 6690 } 6691 } 6692 6693 // If we're directly calling a function, get the appropriate declaration. 6694 if (Fn->getType() == Context.UnknownAnyTy) { 6695 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6696 if (result.isInvalid()) return ExprError(); 6697 Fn = result.get(); 6698 } 6699 6700 Expr *NakedFn = Fn->IgnoreParens(); 6701 6702 bool CallingNDeclIndirectly = false; 6703 NamedDecl *NDecl = nullptr; 6704 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6705 if (UnOp->getOpcode() == UO_AddrOf) { 6706 CallingNDeclIndirectly = true; 6707 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6708 } 6709 } 6710 6711 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6712 NDecl = DRE->getDecl(); 6713 6714 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6715 if (FDecl && FDecl->getBuiltinID()) { 6716 // Rewrite the function decl for this builtin by replacing parameters 6717 // with no explicit address space with the address space of the arguments 6718 // in ArgExprs. 6719 if ((FDecl = 6720 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6721 NDecl = FDecl; 6722 Fn = DeclRefExpr::Create( 6723 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6724 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6725 nullptr, DRE->isNonOdrUse()); 6726 } 6727 } 6728 } else if (isa<MemberExpr>(NakedFn)) 6729 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6730 6731 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6732 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6733 FD, /*Complain=*/true, Fn->getBeginLoc())) 6734 return ExprError(); 6735 6736 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6737 6738 // If this expression is a call to a builtin function in HIP device 6739 // compilation, allow a pointer-type argument to default address space to be 6740 // passed as a pointer-type parameter to a non-default address space. 6741 // If Arg is declared in the default address space and Param is declared 6742 // in a non-default address space, perform an implicit address space cast to 6743 // the parameter type. 6744 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6745 FD->getBuiltinID()) { 6746 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6747 ParmVarDecl *Param = FD->getParamDecl(Idx); 6748 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6749 !ArgExprs[Idx]->getType()->isPointerType()) 6750 continue; 6751 6752 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6753 auto ArgTy = ArgExprs[Idx]->getType(); 6754 auto ArgPtTy = ArgTy->getPointeeType(); 6755 auto ArgAS = ArgPtTy.getAddressSpace(); 6756 6757 // Add address space cast if target address spaces are different 6758 bool NeedImplicitASC = 6759 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6760 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6761 // or from specific AS which has target AS matching that of Param. 6762 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6763 if (!NeedImplicitASC) 6764 continue; 6765 6766 // First, ensure that the Arg is an RValue. 6767 if (ArgExprs[Idx]->isGLValue()) { 6768 ArgExprs[Idx] = ImplicitCastExpr::Create( 6769 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6770 nullptr, VK_PRValue, FPOptionsOverride()); 6771 } 6772 6773 // Construct a new arg type with address space of Param 6774 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6775 ArgPtQuals.setAddressSpace(ParamAS); 6776 auto NewArgPtTy = 6777 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6778 auto NewArgTy = 6779 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6780 ArgTy.getQualifiers()); 6781 6782 // Finally perform an implicit address space cast 6783 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6784 CK_AddressSpaceConversion) 6785 .get(); 6786 } 6787 } 6788 } 6789 6790 if (Context.isDependenceAllowed() && 6791 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6792 assert(!getLangOpts().CPlusPlus); 6793 assert((Fn->containsErrors() || 6794 llvm::any_of(ArgExprs, 6795 [](clang::Expr *E) { return E->containsErrors(); })) && 6796 "should only occur in error-recovery path."); 6797 QualType ReturnType = 6798 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6799 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6800 : Context.DependentTy; 6801 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6802 Expr::getValueKindForType(ReturnType), RParenLoc, 6803 CurFPFeatureOverrides()); 6804 } 6805 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6806 ExecConfig, IsExecConfig); 6807 } 6808 6809 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6810 // with the specified CallArgs 6811 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6812 MultiExprArg CallArgs) { 6813 StringRef Name = Context.BuiltinInfo.getName(Id); 6814 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6815 Sema::LookupOrdinaryName); 6816 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6817 6818 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6819 assert(BuiltInDecl && "failed to find builtin declaration"); 6820 6821 ExprResult DeclRef = 6822 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6823 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6824 6825 ExprResult Call = 6826 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6827 6828 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6829 return Call.get(); 6830 } 6831 6832 /// Parse a __builtin_astype expression. 6833 /// 6834 /// __builtin_astype( value, dst type ) 6835 /// 6836 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6837 SourceLocation BuiltinLoc, 6838 SourceLocation RParenLoc) { 6839 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6840 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6841 } 6842 6843 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6844 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6845 SourceLocation BuiltinLoc, 6846 SourceLocation RParenLoc) { 6847 ExprValueKind VK = VK_PRValue; 6848 ExprObjectKind OK = OK_Ordinary; 6849 QualType SrcTy = E->getType(); 6850 if (!SrcTy->isDependentType() && 6851 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6852 return ExprError( 6853 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6854 << DestTy << SrcTy << E->getSourceRange()); 6855 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6856 } 6857 6858 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6859 /// provided arguments. 6860 /// 6861 /// __builtin_convertvector( value, dst type ) 6862 /// 6863 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6864 SourceLocation BuiltinLoc, 6865 SourceLocation RParenLoc) { 6866 TypeSourceInfo *TInfo; 6867 GetTypeFromParser(ParsedDestTy, &TInfo); 6868 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6869 } 6870 6871 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6872 /// i.e. an expression not of \p OverloadTy. The expression should 6873 /// unary-convert to an expression of function-pointer or 6874 /// block-pointer type. 6875 /// 6876 /// \param NDecl the declaration being called, if available 6877 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6878 SourceLocation LParenLoc, 6879 ArrayRef<Expr *> Args, 6880 SourceLocation RParenLoc, Expr *Config, 6881 bool IsExecConfig, ADLCallKind UsesADL) { 6882 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6883 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6884 6885 // Functions with 'interrupt' attribute cannot be called directly. 6886 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6887 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6888 return ExprError(); 6889 } 6890 6891 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6892 // so there's some risk when calling out to non-interrupt handler functions 6893 // that the callee might not preserve them. This is easy to diagnose here, 6894 // but can be very challenging to debug. 6895 // Likewise, X86 interrupt handlers may only call routines with attribute 6896 // no_caller_saved_registers since there is no efficient way to 6897 // save and restore the non-GPR state. 6898 if (auto *Caller = getCurFunctionDecl()) { 6899 if (Caller->hasAttr<ARMInterruptAttr>()) { 6900 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6901 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6902 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6903 if (FDecl) 6904 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6905 } 6906 } 6907 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6908 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6909 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6910 if (FDecl) 6911 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6912 } 6913 } 6914 6915 // Promote the function operand. 6916 // We special-case function promotion here because we only allow promoting 6917 // builtin functions to function pointers in the callee of a call. 6918 ExprResult Result; 6919 QualType ResultTy; 6920 if (BuiltinID && 6921 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6922 // Extract the return type from the (builtin) function pointer type. 6923 // FIXME Several builtins still have setType in 6924 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6925 // Builtins.def to ensure they are correct before removing setType calls. 6926 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6927 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6928 ResultTy = FDecl->getCallResultType(); 6929 } else { 6930 Result = CallExprUnaryConversions(Fn); 6931 ResultTy = Context.BoolTy; 6932 } 6933 if (Result.isInvalid()) 6934 return ExprError(); 6935 Fn = Result.get(); 6936 6937 // Check for a valid function type, but only if it is not a builtin which 6938 // requires custom type checking. These will be handled by 6939 // CheckBuiltinFunctionCall below just after creation of the call expression. 6940 const FunctionType *FuncT = nullptr; 6941 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6942 retry: 6943 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6944 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6945 // have type pointer to function". 6946 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6947 if (!FuncT) 6948 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6949 << Fn->getType() << Fn->getSourceRange()); 6950 } else if (const BlockPointerType *BPT = 6951 Fn->getType()->getAs<BlockPointerType>()) { 6952 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6953 } else { 6954 // Handle calls to expressions of unknown-any type. 6955 if (Fn->getType() == Context.UnknownAnyTy) { 6956 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6957 if (rewrite.isInvalid()) 6958 return ExprError(); 6959 Fn = rewrite.get(); 6960 goto retry; 6961 } 6962 6963 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6964 << Fn->getType() << Fn->getSourceRange()); 6965 } 6966 } 6967 6968 // Get the number of parameters in the function prototype, if any. 6969 // We will allocate space for max(Args.size(), NumParams) arguments 6970 // in the call expression. 6971 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6972 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6973 6974 CallExpr *TheCall; 6975 if (Config) { 6976 assert(UsesADL == ADLCallKind::NotADL && 6977 "CUDAKernelCallExpr should not use ADL"); 6978 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6979 Args, ResultTy, VK_PRValue, RParenLoc, 6980 CurFPFeatureOverrides(), NumParams); 6981 } else { 6982 TheCall = 6983 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6984 CurFPFeatureOverrides(), NumParams, UsesADL); 6985 } 6986 6987 if (!Context.isDependenceAllowed()) { 6988 // Forget about the nulled arguments since typo correction 6989 // do not handle them well. 6990 TheCall->shrinkNumArgs(Args.size()); 6991 // C cannot always handle TypoExpr nodes in builtin calls and direct 6992 // function calls as their argument checking don't necessarily handle 6993 // dependent types properly, so make sure any TypoExprs have been 6994 // dealt with. 6995 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6996 if (!Result.isUsable()) return ExprError(); 6997 CallExpr *TheOldCall = TheCall; 6998 TheCall = dyn_cast<CallExpr>(Result.get()); 6999 bool CorrectedTypos = TheCall != TheOldCall; 7000 if (!TheCall) return Result; 7001 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 7002 7003 // A new call expression node was created if some typos were corrected. 7004 // However it may not have been constructed with enough storage. In this 7005 // case, rebuild the node with enough storage. The waste of space is 7006 // immaterial since this only happens when some typos were corrected. 7007 if (CorrectedTypos && Args.size() < NumParams) { 7008 if (Config) 7009 TheCall = CUDAKernelCallExpr::Create( 7010 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 7011 RParenLoc, CurFPFeatureOverrides(), NumParams); 7012 else 7013 TheCall = 7014 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 7015 CurFPFeatureOverrides(), NumParams, UsesADL); 7016 } 7017 // We can now handle the nulled arguments for the default arguments. 7018 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 7019 } 7020 7021 // Bail out early if calling a builtin with custom type checking. 7022 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 7023 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7024 7025 if (getLangOpts().CUDA) { 7026 if (Config) { 7027 // CUDA: Kernel calls must be to global functions 7028 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 7029 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 7030 << FDecl << Fn->getSourceRange()); 7031 7032 // CUDA: Kernel function must have 'void' return type 7033 if (!FuncT->getReturnType()->isVoidType() && 7034 !FuncT->getReturnType()->getAs<AutoType>() && 7035 !FuncT->getReturnType()->isInstantiationDependentType()) 7036 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 7037 << Fn->getType() << Fn->getSourceRange()); 7038 } else { 7039 // CUDA: Calls to global functions must be configured 7040 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 7041 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 7042 << FDecl << Fn->getSourceRange()); 7043 } 7044 } 7045 7046 // Check for a valid return type 7047 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 7048 FDecl)) 7049 return ExprError(); 7050 7051 // We know the result type of the call, set it. 7052 TheCall->setType(FuncT->getCallResultType(Context)); 7053 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 7054 7055 if (Proto) { 7056 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 7057 IsExecConfig)) 7058 return ExprError(); 7059 } else { 7060 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 7061 7062 if (FDecl) { 7063 // Check if we have too few/too many template arguments, based 7064 // on our knowledge of the function definition. 7065 const FunctionDecl *Def = nullptr; 7066 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 7067 Proto = Def->getType()->getAs<FunctionProtoType>(); 7068 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 7069 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 7070 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 7071 } 7072 7073 // If the function we're calling isn't a function prototype, but we have 7074 // a function prototype from a prior declaratiom, use that prototype. 7075 if (!FDecl->hasPrototype()) 7076 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 7077 } 7078 7079 // If we still haven't found a prototype to use but there are arguments to 7080 // the call, diagnose this as calling a function without a prototype. 7081 // However, if we found a function declaration, check to see if 7082 // -Wdeprecated-non-prototype was disabled where the function was declared. 7083 // If so, we will silence the diagnostic here on the assumption that this 7084 // interface is intentional and the user knows what they're doing. We will 7085 // also silence the diagnostic if there is a function declaration but it 7086 // was implicitly defined (the user already gets diagnostics about the 7087 // creation of the implicit function declaration, so the additional warning 7088 // is not helpful). 7089 if (!Proto && !Args.empty() && 7090 (!FDecl || (!FDecl->isImplicit() && 7091 !Diags.isIgnored(diag::warn_strict_uses_without_prototype, 7092 FDecl->getLocation())))) 7093 Diag(LParenLoc, diag::warn_strict_uses_without_prototype) 7094 << (FDecl != nullptr) << FDecl; 7095 7096 // Promote the arguments (C99 6.5.2.2p6). 7097 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7098 Expr *Arg = Args[i]; 7099 7100 if (Proto && i < Proto->getNumParams()) { 7101 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7102 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 7103 ExprResult ArgE = 7104 PerformCopyInitialization(Entity, SourceLocation(), Arg); 7105 if (ArgE.isInvalid()) 7106 return true; 7107 7108 Arg = ArgE.getAs<Expr>(); 7109 7110 } else { 7111 ExprResult ArgE = DefaultArgumentPromotion(Arg); 7112 7113 if (ArgE.isInvalid()) 7114 return true; 7115 7116 Arg = ArgE.getAs<Expr>(); 7117 } 7118 7119 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 7120 diag::err_call_incomplete_argument, Arg)) 7121 return ExprError(); 7122 7123 TheCall->setArg(i, Arg); 7124 } 7125 TheCall->computeDependence(); 7126 } 7127 7128 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 7129 if (!Method->isStatic()) 7130 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 7131 << Fn->getSourceRange()); 7132 7133 // Check for sentinels 7134 if (NDecl) 7135 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 7136 7137 // Warn for unions passing across security boundary (CMSE). 7138 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 7139 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7140 if (const auto *RT = 7141 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 7142 if (RT->getDecl()->isOrContainsUnion()) 7143 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 7144 << 0 << i; 7145 } 7146 } 7147 } 7148 7149 // Do special checking on direct calls to functions. 7150 if (FDecl) { 7151 if (CheckFunctionCall(FDecl, TheCall, Proto)) 7152 return ExprError(); 7153 7154 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 7155 7156 if (BuiltinID) 7157 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7158 } else if (NDecl) { 7159 if (CheckPointerCall(NDecl, TheCall, Proto)) 7160 return ExprError(); 7161 } else { 7162 if (CheckOtherCall(TheCall, Proto)) 7163 return ExprError(); 7164 } 7165 7166 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 7167 } 7168 7169 ExprResult 7170 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 7171 SourceLocation RParenLoc, Expr *InitExpr) { 7172 assert(Ty && "ActOnCompoundLiteral(): missing type"); 7173 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 7174 7175 TypeSourceInfo *TInfo; 7176 QualType literalType = GetTypeFromParser(Ty, &TInfo); 7177 if (!TInfo) 7178 TInfo = Context.getTrivialTypeSourceInfo(literalType); 7179 7180 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 7181 } 7182 7183 ExprResult 7184 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 7185 SourceLocation RParenLoc, Expr *LiteralExpr) { 7186 QualType literalType = TInfo->getType(); 7187 7188 if (literalType->isArrayType()) { 7189 if (RequireCompleteSizedType( 7190 LParenLoc, Context.getBaseElementType(literalType), 7191 diag::err_array_incomplete_or_sizeless_type, 7192 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7193 return ExprError(); 7194 if (literalType->isVariableArrayType()) { 7195 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 7196 diag::err_variable_object_no_init)) { 7197 return ExprError(); 7198 } 7199 } 7200 } else if (!literalType->isDependentType() && 7201 RequireCompleteType(LParenLoc, literalType, 7202 diag::err_typecheck_decl_incomplete_type, 7203 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7204 return ExprError(); 7205 7206 InitializedEntity Entity 7207 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 7208 InitializationKind Kind 7209 = InitializationKind::CreateCStyleCast(LParenLoc, 7210 SourceRange(LParenLoc, RParenLoc), 7211 /*InitList=*/true); 7212 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 7213 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 7214 &literalType); 7215 if (Result.isInvalid()) 7216 return ExprError(); 7217 LiteralExpr = Result.get(); 7218 7219 bool isFileScope = !CurContext->isFunctionOrMethod(); 7220 7221 // In C, compound literals are l-values for some reason. 7222 // For GCC compatibility, in C++, file-scope array compound literals with 7223 // constant initializers are also l-values, and compound literals are 7224 // otherwise prvalues. 7225 // 7226 // (GCC also treats C++ list-initialized file-scope array prvalues with 7227 // constant initializers as l-values, but that's non-conforming, so we don't 7228 // follow it there.) 7229 // 7230 // FIXME: It would be better to handle the lvalue cases as materializing and 7231 // lifetime-extending a temporary object, but our materialized temporaries 7232 // representation only supports lifetime extension from a variable, not "out 7233 // of thin air". 7234 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7235 // is bound to the result of applying array-to-pointer decay to the compound 7236 // literal. 7237 // FIXME: GCC supports compound literals of reference type, which should 7238 // obviously have a value kind derived from the kind of reference involved. 7239 ExprValueKind VK = 7240 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7241 ? VK_PRValue 7242 : VK_LValue; 7243 7244 if (isFileScope) 7245 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7246 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7247 Expr *Init = ILE->getInit(i); 7248 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7249 } 7250 7251 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7252 VK, LiteralExpr, isFileScope); 7253 if (isFileScope) { 7254 if (!LiteralExpr->isTypeDependent() && 7255 !LiteralExpr->isValueDependent() && 7256 !literalType->isDependentType()) // C99 6.5.2.5p3 7257 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7258 return ExprError(); 7259 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7260 literalType.getAddressSpace() != LangAS::Default) { 7261 // Embedded-C extensions to C99 6.5.2.5: 7262 // "If the compound literal occurs inside the body of a function, the 7263 // type name shall not be qualified by an address-space qualifier." 7264 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7265 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7266 return ExprError(); 7267 } 7268 7269 if (!isFileScope && !getLangOpts().CPlusPlus) { 7270 // Compound literals that have automatic storage duration are destroyed at 7271 // the end of the scope in C; in C++, they're just temporaries. 7272 7273 // Emit diagnostics if it is or contains a C union type that is non-trivial 7274 // to destruct. 7275 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7276 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7277 NTCUC_CompoundLiteral, NTCUK_Destruct); 7278 7279 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7280 if (literalType.isDestructedType()) { 7281 Cleanup.setExprNeedsCleanups(true); 7282 ExprCleanupObjects.push_back(E); 7283 getCurFunction()->setHasBranchProtectedScope(); 7284 } 7285 } 7286 7287 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7288 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7289 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7290 E->getInitializer()->getExprLoc()); 7291 7292 return MaybeBindToTemporary(E); 7293 } 7294 7295 ExprResult 7296 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7297 SourceLocation RBraceLoc) { 7298 // Only produce each kind of designated initialization diagnostic once. 7299 SourceLocation FirstDesignator; 7300 bool DiagnosedArrayDesignator = false; 7301 bool DiagnosedNestedDesignator = false; 7302 bool DiagnosedMixedDesignator = false; 7303 7304 // Check that any designated initializers are syntactically valid in the 7305 // current language mode. 7306 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7307 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7308 if (FirstDesignator.isInvalid()) 7309 FirstDesignator = DIE->getBeginLoc(); 7310 7311 if (!getLangOpts().CPlusPlus) 7312 break; 7313 7314 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7315 DiagnosedNestedDesignator = true; 7316 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7317 << DIE->getDesignatorsSourceRange(); 7318 } 7319 7320 for (auto &Desig : DIE->designators()) { 7321 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7322 DiagnosedArrayDesignator = true; 7323 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7324 << Desig.getSourceRange(); 7325 } 7326 } 7327 7328 if (!DiagnosedMixedDesignator && 7329 !isa<DesignatedInitExpr>(InitArgList[0])) { 7330 DiagnosedMixedDesignator = true; 7331 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7332 << DIE->getSourceRange(); 7333 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7334 << InitArgList[0]->getSourceRange(); 7335 } 7336 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7337 isa<DesignatedInitExpr>(InitArgList[0])) { 7338 DiagnosedMixedDesignator = true; 7339 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7340 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7341 << DIE->getSourceRange(); 7342 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7343 << InitArgList[I]->getSourceRange(); 7344 } 7345 } 7346 7347 if (FirstDesignator.isValid()) { 7348 // Only diagnose designated initiaization as a C++20 extension if we didn't 7349 // already diagnose use of (non-C++20) C99 designator syntax. 7350 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7351 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7352 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7353 ? diag::warn_cxx17_compat_designated_init 7354 : diag::ext_cxx_designated_init); 7355 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7356 Diag(FirstDesignator, diag::ext_designated_init); 7357 } 7358 } 7359 7360 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7361 } 7362 7363 ExprResult 7364 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7365 SourceLocation RBraceLoc) { 7366 // Semantic analysis for initializers is done by ActOnDeclarator() and 7367 // CheckInitializer() - it requires knowledge of the object being initialized. 7368 7369 // Immediately handle non-overload placeholders. Overloads can be 7370 // resolved contextually, but everything else here can't. 7371 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7372 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7373 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7374 7375 // Ignore failures; dropping the entire initializer list because 7376 // of one failure would be terrible for indexing/etc. 7377 if (result.isInvalid()) continue; 7378 7379 InitArgList[I] = result.get(); 7380 } 7381 } 7382 7383 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7384 RBraceLoc); 7385 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7386 return E; 7387 } 7388 7389 /// Do an explicit extend of the given block pointer if we're in ARC. 7390 void Sema::maybeExtendBlockObject(ExprResult &E) { 7391 assert(E.get()->getType()->isBlockPointerType()); 7392 assert(E.get()->isPRValue()); 7393 7394 // Only do this in an r-value context. 7395 if (!getLangOpts().ObjCAutoRefCount) return; 7396 7397 E = ImplicitCastExpr::Create( 7398 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7399 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7400 Cleanup.setExprNeedsCleanups(true); 7401 } 7402 7403 /// Prepare a conversion of the given expression to an ObjC object 7404 /// pointer type. 7405 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7406 QualType type = E.get()->getType(); 7407 if (type->isObjCObjectPointerType()) { 7408 return CK_BitCast; 7409 } else if (type->isBlockPointerType()) { 7410 maybeExtendBlockObject(E); 7411 return CK_BlockPointerToObjCPointerCast; 7412 } else { 7413 assert(type->isPointerType()); 7414 return CK_CPointerToObjCPointerCast; 7415 } 7416 } 7417 7418 /// Prepares for a scalar cast, performing all the necessary stages 7419 /// except the final cast and returning the kind required. 7420 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7421 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7422 // Also, callers should have filtered out the invalid cases with 7423 // pointers. Everything else should be possible. 7424 7425 QualType SrcTy = Src.get()->getType(); 7426 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7427 return CK_NoOp; 7428 7429 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7430 case Type::STK_MemberPointer: 7431 llvm_unreachable("member pointer type in C"); 7432 7433 case Type::STK_CPointer: 7434 case Type::STK_BlockPointer: 7435 case Type::STK_ObjCObjectPointer: 7436 switch (DestTy->getScalarTypeKind()) { 7437 case Type::STK_CPointer: { 7438 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7439 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7440 if (SrcAS != DestAS) 7441 return CK_AddressSpaceConversion; 7442 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7443 return CK_NoOp; 7444 return CK_BitCast; 7445 } 7446 case Type::STK_BlockPointer: 7447 return (SrcKind == Type::STK_BlockPointer 7448 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7449 case Type::STK_ObjCObjectPointer: 7450 if (SrcKind == Type::STK_ObjCObjectPointer) 7451 return CK_BitCast; 7452 if (SrcKind == Type::STK_CPointer) 7453 return CK_CPointerToObjCPointerCast; 7454 maybeExtendBlockObject(Src); 7455 return CK_BlockPointerToObjCPointerCast; 7456 case Type::STK_Bool: 7457 return CK_PointerToBoolean; 7458 case Type::STK_Integral: 7459 return CK_PointerToIntegral; 7460 case Type::STK_Floating: 7461 case Type::STK_FloatingComplex: 7462 case Type::STK_IntegralComplex: 7463 case Type::STK_MemberPointer: 7464 case Type::STK_FixedPoint: 7465 llvm_unreachable("illegal cast from pointer"); 7466 } 7467 llvm_unreachable("Should have returned before this"); 7468 7469 case Type::STK_FixedPoint: 7470 switch (DestTy->getScalarTypeKind()) { 7471 case Type::STK_FixedPoint: 7472 return CK_FixedPointCast; 7473 case Type::STK_Bool: 7474 return CK_FixedPointToBoolean; 7475 case Type::STK_Integral: 7476 return CK_FixedPointToIntegral; 7477 case Type::STK_Floating: 7478 return CK_FixedPointToFloating; 7479 case Type::STK_IntegralComplex: 7480 case Type::STK_FloatingComplex: 7481 Diag(Src.get()->getExprLoc(), 7482 diag::err_unimplemented_conversion_with_fixed_point_type) 7483 << DestTy; 7484 return CK_IntegralCast; 7485 case Type::STK_CPointer: 7486 case Type::STK_ObjCObjectPointer: 7487 case Type::STK_BlockPointer: 7488 case Type::STK_MemberPointer: 7489 llvm_unreachable("illegal cast to pointer type"); 7490 } 7491 llvm_unreachable("Should have returned before this"); 7492 7493 case Type::STK_Bool: // casting from bool is like casting from an integer 7494 case Type::STK_Integral: 7495 switch (DestTy->getScalarTypeKind()) { 7496 case Type::STK_CPointer: 7497 case Type::STK_ObjCObjectPointer: 7498 case Type::STK_BlockPointer: 7499 if (Src.get()->isNullPointerConstant(Context, 7500 Expr::NPC_ValueDependentIsNull)) 7501 return CK_NullToPointer; 7502 return CK_IntegralToPointer; 7503 case Type::STK_Bool: 7504 return CK_IntegralToBoolean; 7505 case Type::STK_Integral: 7506 return CK_IntegralCast; 7507 case Type::STK_Floating: 7508 return CK_IntegralToFloating; 7509 case Type::STK_IntegralComplex: 7510 Src = ImpCastExprToType(Src.get(), 7511 DestTy->castAs<ComplexType>()->getElementType(), 7512 CK_IntegralCast); 7513 return CK_IntegralRealToComplex; 7514 case Type::STK_FloatingComplex: 7515 Src = ImpCastExprToType(Src.get(), 7516 DestTy->castAs<ComplexType>()->getElementType(), 7517 CK_IntegralToFloating); 7518 return CK_FloatingRealToComplex; 7519 case Type::STK_MemberPointer: 7520 llvm_unreachable("member pointer type in C"); 7521 case Type::STK_FixedPoint: 7522 return CK_IntegralToFixedPoint; 7523 } 7524 llvm_unreachable("Should have returned before this"); 7525 7526 case Type::STK_Floating: 7527 switch (DestTy->getScalarTypeKind()) { 7528 case Type::STK_Floating: 7529 return CK_FloatingCast; 7530 case Type::STK_Bool: 7531 return CK_FloatingToBoolean; 7532 case Type::STK_Integral: 7533 return CK_FloatingToIntegral; 7534 case Type::STK_FloatingComplex: 7535 Src = ImpCastExprToType(Src.get(), 7536 DestTy->castAs<ComplexType>()->getElementType(), 7537 CK_FloatingCast); 7538 return CK_FloatingRealToComplex; 7539 case Type::STK_IntegralComplex: 7540 Src = ImpCastExprToType(Src.get(), 7541 DestTy->castAs<ComplexType>()->getElementType(), 7542 CK_FloatingToIntegral); 7543 return CK_IntegralRealToComplex; 7544 case Type::STK_CPointer: 7545 case Type::STK_ObjCObjectPointer: 7546 case Type::STK_BlockPointer: 7547 llvm_unreachable("valid float->pointer cast?"); 7548 case Type::STK_MemberPointer: 7549 llvm_unreachable("member pointer type in C"); 7550 case Type::STK_FixedPoint: 7551 return CK_FloatingToFixedPoint; 7552 } 7553 llvm_unreachable("Should have returned before this"); 7554 7555 case Type::STK_FloatingComplex: 7556 switch (DestTy->getScalarTypeKind()) { 7557 case Type::STK_FloatingComplex: 7558 return CK_FloatingComplexCast; 7559 case Type::STK_IntegralComplex: 7560 return CK_FloatingComplexToIntegralComplex; 7561 case Type::STK_Floating: { 7562 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7563 if (Context.hasSameType(ET, DestTy)) 7564 return CK_FloatingComplexToReal; 7565 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7566 return CK_FloatingCast; 7567 } 7568 case Type::STK_Bool: 7569 return CK_FloatingComplexToBoolean; 7570 case Type::STK_Integral: 7571 Src = ImpCastExprToType(Src.get(), 7572 SrcTy->castAs<ComplexType>()->getElementType(), 7573 CK_FloatingComplexToReal); 7574 return CK_FloatingToIntegral; 7575 case Type::STK_CPointer: 7576 case Type::STK_ObjCObjectPointer: 7577 case Type::STK_BlockPointer: 7578 llvm_unreachable("valid complex float->pointer cast?"); 7579 case Type::STK_MemberPointer: 7580 llvm_unreachable("member pointer type in C"); 7581 case Type::STK_FixedPoint: 7582 Diag(Src.get()->getExprLoc(), 7583 diag::err_unimplemented_conversion_with_fixed_point_type) 7584 << SrcTy; 7585 return CK_IntegralCast; 7586 } 7587 llvm_unreachable("Should have returned before this"); 7588 7589 case Type::STK_IntegralComplex: 7590 switch (DestTy->getScalarTypeKind()) { 7591 case Type::STK_FloatingComplex: 7592 return CK_IntegralComplexToFloatingComplex; 7593 case Type::STK_IntegralComplex: 7594 return CK_IntegralComplexCast; 7595 case Type::STK_Integral: { 7596 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7597 if (Context.hasSameType(ET, DestTy)) 7598 return CK_IntegralComplexToReal; 7599 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7600 return CK_IntegralCast; 7601 } 7602 case Type::STK_Bool: 7603 return CK_IntegralComplexToBoolean; 7604 case Type::STK_Floating: 7605 Src = ImpCastExprToType(Src.get(), 7606 SrcTy->castAs<ComplexType>()->getElementType(), 7607 CK_IntegralComplexToReal); 7608 return CK_IntegralToFloating; 7609 case Type::STK_CPointer: 7610 case Type::STK_ObjCObjectPointer: 7611 case Type::STK_BlockPointer: 7612 llvm_unreachable("valid complex int->pointer cast?"); 7613 case Type::STK_MemberPointer: 7614 llvm_unreachable("member pointer type in C"); 7615 case Type::STK_FixedPoint: 7616 Diag(Src.get()->getExprLoc(), 7617 diag::err_unimplemented_conversion_with_fixed_point_type) 7618 << SrcTy; 7619 return CK_IntegralCast; 7620 } 7621 llvm_unreachable("Should have returned before this"); 7622 } 7623 7624 llvm_unreachable("Unhandled scalar cast"); 7625 } 7626 7627 static bool breakDownVectorType(QualType type, uint64_t &len, 7628 QualType &eltType) { 7629 // Vectors are simple. 7630 if (const VectorType *vecType = type->getAs<VectorType>()) { 7631 len = vecType->getNumElements(); 7632 eltType = vecType->getElementType(); 7633 assert(eltType->isScalarType()); 7634 return true; 7635 } 7636 7637 // We allow lax conversion to and from non-vector types, but only if 7638 // they're real types (i.e. non-complex, non-pointer scalar types). 7639 if (!type->isRealType()) return false; 7640 7641 len = 1; 7642 eltType = type; 7643 return true; 7644 } 7645 7646 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7647 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7648 /// allowed? 7649 /// 7650 /// This will also return false if the two given types do not make sense from 7651 /// the perspective of SVE bitcasts. 7652 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7653 assert(srcTy->isVectorType() || destTy->isVectorType()); 7654 7655 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7656 if (!FirstType->isSizelessBuiltinType()) 7657 return false; 7658 7659 const auto *VecTy = SecondType->getAs<VectorType>(); 7660 return VecTy && 7661 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7662 }; 7663 7664 return ValidScalableConversion(srcTy, destTy) || 7665 ValidScalableConversion(destTy, srcTy); 7666 } 7667 7668 /// Are the two types matrix types and do they have the same dimensions i.e. 7669 /// do they have the same number of rows and the same number of columns? 7670 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7671 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7672 return false; 7673 7674 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7675 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7676 7677 return matSrcType->getNumRows() == matDestType->getNumRows() && 7678 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7679 } 7680 7681 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7682 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7683 7684 uint64_t SrcLen, DestLen; 7685 QualType SrcEltTy, DestEltTy; 7686 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7687 return false; 7688 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7689 return false; 7690 7691 // ASTContext::getTypeSize will return the size rounded up to a 7692 // power of 2, so instead of using that, we need to use the raw 7693 // element size multiplied by the element count. 7694 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7695 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7696 7697 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7698 } 7699 7700 /// Are the two types lax-compatible vector types? That is, given 7701 /// that one of them is a vector, do they have equal storage sizes, 7702 /// where the storage size is the number of elements times the element 7703 /// size? 7704 /// 7705 /// This will also return false if either of the types is neither a 7706 /// vector nor a real type. 7707 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7708 assert(destTy->isVectorType() || srcTy->isVectorType()); 7709 7710 // Disallow lax conversions between scalars and ExtVectors (these 7711 // conversions are allowed for other vector types because common headers 7712 // depend on them). Most scalar OP ExtVector cases are handled by the 7713 // splat path anyway, which does what we want (convert, not bitcast). 7714 // What this rules out for ExtVectors is crazy things like char4*float. 7715 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7716 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7717 7718 return areVectorTypesSameSize(srcTy, destTy); 7719 } 7720 7721 /// Is this a legal conversion between two types, one of which is 7722 /// known to be a vector type? 7723 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7724 assert(destTy->isVectorType() || srcTy->isVectorType()); 7725 7726 switch (Context.getLangOpts().getLaxVectorConversions()) { 7727 case LangOptions::LaxVectorConversionKind::None: 7728 return false; 7729 7730 case LangOptions::LaxVectorConversionKind::Integer: 7731 if (!srcTy->isIntegralOrEnumerationType()) { 7732 auto *Vec = srcTy->getAs<VectorType>(); 7733 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7734 return false; 7735 } 7736 if (!destTy->isIntegralOrEnumerationType()) { 7737 auto *Vec = destTy->getAs<VectorType>(); 7738 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7739 return false; 7740 } 7741 // OK, integer (vector) -> integer (vector) bitcast. 7742 break; 7743 7744 case LangOptions::LaxVectorConversionKind::All: 7745 break; 7746 } 7747 7748 return areLaxCompatibleVectorTypes(srcTy, destTy); 7749 } 7750 7751 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7752 CastKind &Kind) { 7753 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7754 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7755 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7756 << DestTy << SrcTy << R; 7757 } 7758 } else if (SrcTy->isMatrixType()) { 7759 return Diag(R.getBegin(), 7760 diag::err_invalid_conversion_between_matrix_and_type) 7761 << SrcTy << DestTy << R; 7762 } else if (DestTy->isMatrixType()) { 7763 return Diag(R.getBegin(), 7764 diag::err_invalid_conversion_between_matrix_and_type) 7765 << DestTy << SrcTy << R; 7766 } 7767 7768 Kind = CK_MatrixCast; 7769 return false; 7770 } 7771 7772 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7773 CastKind &Kind) { 7774 assert(VectorTy->isVectorType() && "Not a vector type!"); 7775 7776 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7777 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7778 return Diag(R.getBegin(), 7779 Ty->isVectorType() ? 7780 diag::err_invalid_conversion_between_vectors : 7781 diag::err_invalid_conversion_between_vector_and_integer) 7782 << VectorTy << Ty << R; 7783 } else 7784 return Diag(R.getBegin(), 7785 diag::err_invalid_conversion_between_vector_and_scalar) 7786 << VectorTy << Ty << R; 7787 7788 Kind = CK_BitCast; 7789 return false; 7790 } 7791 7792 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7793 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7794 7795 if (DestElemTy == SplattedExpr->getType()) 7796 return SplattedExpr; 7797 7798 assert(DestElemTy->isFloatingType() || 7799 DestElemTy->isIntegralOrEnumerationType()); 7800 7801 CastKind CK; 7802 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7803 // OpenCL requires that we convert `true` boolean expressions to -1, but 7804 // only when splatting vectors. 7805 if (DestElemTy->isFloatingType()) { 7806 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7807 // in two steps: boolean to signed integral, then to floating. 7808 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7809 CK_BooleanToSignedIntegral); 7810 SplattedExpr = CastExprRes.get(); 7811 CK = CK_IntegralToFloating; 7812 } else { 7813 CK = CK_BooleanToSignedIntegral; 7814 } 7815 } else { 7816 ExprResult CastExprRes = SplattedExpr; 7817 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7818 if (CastExprRes.isInvalid()) 7819 return ExprError(); 7820 SplattedExpr = CastExprRes.get(); 7821 } 7822 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7823 } 7824 7825 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7826 Expr *CastExpr, CastKind &Kind) { 7827 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7828 7829 QualType SrcTy = CastExpr->getType(); 7830 7831 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7832 // an ExtVectorType. 7833 // In OpenCL, casts between vectors of different types are not allowed. 7834 // (See OpenCL 6.2). 7835 if (SrcTy->isVectorType()) { 7836 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7837 (getLangOpts().OpenCL && 7838 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7839 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7840 << DestTy << SrcTy << R; 7841 return ExprError(); 7842 } 7843 Kind = CK_BitCast; 7844 return CastExpr; 7845 } 7846 7847 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7848 // conversion will take place first from scalar to elt type, and then 7849 // splat from elt type to vector. 7850 if (SrcTy->isPointerType()) 7851 return Diag(R.getBegin(), 7852 diag::err_invalid_conversion_between_vector_and_scalar) 7853 << DestTy << SrcTy << R; 7854 7855 Kind = CK_VectorSplat; 7856 return prepareVectorSplat(DestTy, CastExpr); 7857 } 7858 7859 ExprResult 7860 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7861 Declarator &D, ParsedType &Ty, 7862 SourceLocation RParenLoc, Expr *CastExpr) { 7863 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7864 "ActOnCastExpr(): missing type or expr"); 7865 7866 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7867 if (D.isInvalidType()) 7868 return ExprError(); 7869 7870 if (getLangOpts().CPlusPlus) { 7871 // Check that there are no default arguments (C++ only). 7872 CheckExtraCXXDefaultArguments(D); 7873 } else { 7874 // Make sure any TypoExprs have been dealt with. 7875 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7876 if (!Res.isUsable()) 7877 return ExprError(); 7878 CastExpr = Res.get(); 7879 } 7880 7881 checkUnusedDeclAttributes(D); 7882 7883 QualType castType = castTInfo->getType(); 7884 Ty = CreateParsedType(castType, castTInfo); 7885 7886 bool isVectorLiteral = false; 7887 7888 // Check for an altivec or OpenCL literal, 7889 // i.e. all the elements are integer constants. 7890 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7891 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7892 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7893 && castType->isVectorType() && (PE || PLE)) { 7894 if (PLE && PLE->getNumExprs() == 0) { 7895 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7896 return ExprError(); 7897 } 7898 if (PE || PLE->getNumExprs() == 1) { 7899 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7900 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7901 isVectorLiteral = true; 7902 } 7903 else 7904 isVectorLiteral = true; 7905 } 7906 7907 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7908 // then handle it as such. 7909 if (isVectorLiteral) 7910 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7911 7912 // If the Expr being casted is a ParenListExpr, handle it specially. 7913 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7914 // sequence of BinOp comma operators. 7915 if (isa<ParenListExpr>(CastExpr)) { 7916 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7917 if (Result.isInvalid()) return ExprError(); 7918 CastExpr = Result.get(); 7919 } 7920 7921 if (getLangOpts().CPlusPlus && !castType->isVoidType()) 7922 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7923 7924 CheckTollFreeBridgeCast(castType, CastExpr); 7925 7926 CheckObjCBridgeRelatedCast(castType, CastExpr); 7927 7928 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7929 7930 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7931 } 7932 7933 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7934 SourceLocation RParenLoc, Expr *E, 7935 TypeSourceInfo *TInfo) { 7936 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7937 "Expected paren or paren list expression"); 7938 7939 Expr **exprs; 7940 unsigned numExprs; 7941 Expr *subExpr; 7942 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7943 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7944 LiteralLParenLoc = PE->getLParenLoc(); 7945 LiteralRParenLoc = PE->getRParenLoc(); 7946 exprs = PE->getExprs(); 7947 numExprs = PE->getNumExprs(); 7948 } else { // isa<ParenExpr> by assertion at function entrance 7949 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7950 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7951 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7952 exprs = &subExpr; 7953 numExprs = 1; 7954 } 7955 7956 QualType Ty = TInfo->getType(); 7957 assert(Ty->isVectorType() && "Expected vector type"); 7958 7959 SmallVector<Expr *, 8> initExprs; 7960 const VectorType *VTy = Ty->castAs<VectorType>(); 7961 unsigned numElems = VTy->getNumElements(); 7962 7963 // '(...)' form of vector initialization in AltiVec: the number of 7964 // initializers must be one or must match the size of the vector. 7965 // If a single value is specified in the initializer then it will be 7966 // replicated to all the components of the vector 7967 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7968 VTy->getElementType())) 7969 return ExprError(); 7970 if (ShouldSplatAltivecScalarInCast(VTy)) { 7971 // The number of initializers must be one or must match the size of the 7972 // vector. If a single value is specified in the initializer then it will 7973 // be replicated to all the components of the vector 7974 if (numExprs == 1) { 7975 QualType ElemTy = VTy->getElementType(); 7976 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7977 if (Literal.isInvalid()) 7978 return ExprError(); 7979 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7980 PrepareScalarCast(Literal, ElemTy)); 7981 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7982 } 7983 else if (numExprs < numElems) { 7984 Diag(E->getExprLoc(), 7985 diag::err_incorrect_number_of_vector_initializers); 7986 return ExprError(); 7987 } 7988 else 7989 initExprs.append(exprs, exprs + numExprs); 7990 } 7991 else { 7992 // For OpenCL, when the number of initializers is a single value, 7993 // it will be replicated to all components of the vector. 7994 if (getLangOpts().OpenCL && 7995 VTy->getVectorKind() == VectorType::GenericVector && 7996 numExprs == 1) { 7997 QualType ElemTy = VTy->getElementType(); 7998 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7999 if (Literal.isInvalid()) 8000 return ExprError(); 8001 Literal = ImpCastExprToType(Literal.get(), ElemTy, 8002 PrepareScalarCast(Literal, ElemTy)); 8003 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 8004 } 8005 8006 initExprs.append(exprs, exprs + numExprs); 8007 } 8008 // FIXME: This means that pretty-printing the final AST will produce curly 8009 // braces instead of the original commas. 8010 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 8011 initExprs, LiteralRParenLoc); 8012 initE->setType(Ty); 8013 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 8014 } 8015 8016 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 8017 /// the ParenListExpr into a sequence of comma binary operators. 8018 ExprResult 8019 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 8020 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 8021 if (!E) 8022 return OrigExpr; 8023 8024 ExprResult Result(E->getExpr(0)); 8025 8026 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 8027 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 8028 E->getExpr(i)); 8029 8030 if (Result.isInvalid()) return ExprError(); 8031 8032 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 8033 } 8034 8035 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 8036 SourceLocation R, 8037 MultiExprArg Val) { 8038 return ParenListExpr::Create(Context, L, Val, R); 8039 } 8040 8041 /// Emit a specialized diagnostic when one expression is a null pointer 8042 /// constant and the other is not a pointer. Returns true if a diagnostic is 8043 /// emitted. 8044 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 8045 SourceLocation QuestionLoc) { 8046 Expr *NullExpr = LHSExpr; 8047 Expr *NonPointerExpr = RHSExpr; 8048 Expr::NullPointerConstantKind NullKind = 8049 NullExpr->isNullPointerConstant(Context, 8050 Expr::NPC_ValueDependentIsNotNull); 8051 8052 if (NullKind == Expr::NPCK_NotNull) { 8053 NullExpr = RHSExpr; 8054 NonPointerExpr = LHSExpr; 8055 NullKind = 8056 NullExpr->isNullPointerConstant(Context, 8057 Expr::NPC_ValueDependentIsNotNull); 8058 } 8059 8060 if (NullKind == Expr::NPCK_NotNull) 8061 return false; 8062 8063 if (NullKind == Expr::NPCK_ZeroExpression) 8064 return false; 8065 8066 if (NullKind == Expr::NPCK_ZeroLiteral) { 8067 // In this case, check to make sure that we got here from a "NULL" 8068 // string in the source code. 8069 NullExpr = NullExpr->IgnoreParenImpCasts(); 8070 SourceLocation loc = NullExpr->getExprLoc(); 8071 if (!findMacroSpelling(loc, "NULL")) 8072 return false; 8073 } 8074 8075 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 8076 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 8077 << NonPointerExpr->getType() << DiagType 8078 << NonPointerExpr->getSourceRange(); 8079 return true; 8080 } 8081 8082 /// Return false if the condition expression is valid, true otherwise. 8083 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 8084 QualType CondTy = Cond->getType(); 8085 8086 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 8087 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 8088 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8089 << CondTy << Cond->getSourceRange(); 8090 return true; 8091 } 8092 8093 // C99 6.5.15p2 8094 if (CondTy->isScalarType()) return false; 8095 8096 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 8097 << CondTy << Cond->getSourceRange(); 8098 return true; 8099 } 8100 8101 /// Handle when one or both operands are void type. 8102 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 8103 ExprResult &RHS) { 8104 Expr *LHSExpr = LHS.get(); 8105 Expr *RHSExpr = RHS.get(); 8106 8107 if (!LHSExpr->getType()->isVoidType()) 8108 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8109 << RHSExpr->getSourceRange(); 8110 if (!RHSExpr->getType()->isVoidType()) 8111 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8112 << LHSExpr->getSourceRange(); 8113 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 8114 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 8115 return S.Context.VoidTy; 8116 } 8117 8118 /// Return false if the NullExpr can be promoted to PointerTy, 8119 /// true otherwise. 8120 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 8121 QualType PointerTy) { 8122 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 8123 !NullExpr.get()->isNullPointerConstant(S.Context, 8124 Expr::NPC_ValueDependentIsNull)) 8125 return true; 8126 8127 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 8128 return false; 8129 } 8130 8131 /// Checks compatibility between two pointers and return the resulting 8132 /// type. 8133 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 8134 ExprResult &RHS, 8135 SourceLocation Loc) { 8136 QualType LHSTy = LHS.get()->getType(); 8137 QualType RHSTy = RHS.get()->getType(); 8138 8139 if (S.Context.hasSameType(LHSTy, RHSTy)) { 8140 // Two identical pointers types are always compatible. 8141 return LHSTy; 8142 } 8143 8144 QualType lhptee, rhptee; 8145 8146 // Get the pointee types. 8147 bool IsBlockPointer = false; 8148 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 8149 lhptee = LHSBTy->getPointeeType(); 8150 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 8151 IsBlockPointer = true; 8152 } else { 8153 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8154 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8155 } 8156 8157 // C99 6.5.15p6: If both operands are pointers to compatible types or to 8158 // differently qualified versions of compatible types, the result type is 8159 // a pointer to an appropriately qualified version of the composite 8160 // type. 8161 8162 // Only CVR-qualifiers exist in the standard, and the differently-qualified 8163 // clause doesn't make sense for our extensions. E.g. address space 2 should 8164 // be incompatible with address space 3: they may live on different devices or 8165 // anything. 8166 Qualifiers lhQual = lhptee.getQualifiers(); 8167 Qualifiers rhQual = rhptee.getQualifiers(); 8168 8169 LangAS ResultAddrSpace = LangAS::Default; 8170 LangAS LAddrSpace = lhQual.getAddressSpace(); 8171 LangAS RAddrSpace = rhQual.getAddressSpace(); 8172 8173 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 8174 // spaces is disallowed. 8175 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 8176 ResultAddrSpace = LAddrSpace; 8177 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 8178 ResultAddrSpace = RAddrSpace; 8179 else { 8180 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8181 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 8182 << RHS.get()->getSourceRange(); 8183 return QualType(); 8184 } 8185 8186 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 8187 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 8188 lhQual.removeCVRQualifiers(); 8189 rhQual.removeCVRQualifiers(); 8190 8191 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 8192 // (C99 6.7.3) for address spaces. We assume that the check should behave in 8193 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 8194 // qual types are compatible iff 8195 // * corresponded types are compatible 8196 // * CVR qualifiers are equal 8197 // * address spaces are equal 8198 // Thus for conditional operator we merge CVR and address space unqualified 8199 // pointees and if there is a composite type we return a pointer to it with 8200 // merged qualifiers. 8201 LHSCastKind = 8202 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8203 RHSCastKind = 8204 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8205 lhQual.removeAddressSpace(); 8206 rhQual.removeAddressSpace(); 8207 8208 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 8209 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 8210 8211 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 8212 8213 if (CompositeTy.isNull()) { 8214 // In this situation, we assume void* type. No especially good 8215 // reason, but this is what gcc does, and we do have to pick 8216 // to get a consistent AST. 8217 QualType incompatTy; 8218 incompatTy = S.Context.getPointerType( 8219 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 8220 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 8221 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 8222 8223 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 8224 // for casts between types with incompatible address space qualifiers. 8225 // For the following code the compiler produces casts between global and 8226 // local address spaces of the corresponded innermost pointees: 8227 // local int *global *a; 8228 // global int *global *b; 8229 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8230 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8231 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8232 << RHS.get()->getSourceRange(); 8233 8234 return incompatTy; 8235 } 8236 8237 // The pointer types are compatible. 8238 // In case of OpenCL ResultTy should have the address space qualifier 8239 // which is a superset of address spaces of both the 2nd and the 3rd 8240 // operands of the conditional operator. 8241 QualType ResultTy = [&, ResultAddrSpace]() { 8242 if (S.getLangOpts().OpenCL) { 8243 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8244 CompositeQuals.setAddressSpace(ResultAddrSpace); 8245 return S.Context 8246 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8247 .withCVRQualifiers(MergedCVRQual); 8248 } 8249 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8250 }(); 8251 if (IsBlockPointer) 8252 ResultTy = S.Context.getBlockPointerType(ResultTy); 8253 else 8254 ResultTy = S.Context.getPointerType(ResultTy); 8255 8256 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8257 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8258 return ResultTy; 8259 } 8260 8261 /// Return the resulting type when the operands are both block pointers. 8262 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8263 ExprResult &LHS, 8264 ExprResult &RHS, 8265 SourceLocation Loc) { 8266 QualType LHSTy = LHS.get()->getType(); 8267 QualType RHSTy = RHS.get()->getType(); 8268 8269 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8270 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8271 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8272 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8273 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8274 return destType; 8275 } 8276 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8277 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8278 << RHS.get()->getSourceRange(); 8279 return QualType(); 8280 } 8281 8282 // We have 2 block pointer types. 8283 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8284 } 8285 8286 /// Return the resulting type when the operands are both pointers. 8287 static QualType 8288 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8289 ExprResult &RHS, 8290 SourceLocation Loc) { 8291 // get the pointer types 8292 QualType LHSTy = LHS.get()->getType(); 8293 QualType RHSTy = RHS.get()->getType(); 8294 8295 // get the "pointed to" types 8296 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8297 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8298 8299 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8300 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8301 // Figure out necessary qualifiers (C99 6.5.15p6) 8302 QualType destPointee 8303 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8304 QualType destType = S.Context.getPointerType(destPointee); 8305 // Add qualifiers if necessary. 8306 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8307 // Promote to void*. 8308 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8309 return destType; 8310 } 8311 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8312 QualType destPointee 8313 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8314 QualType destType = S.Context.getPointerType(destPointee); 8315 // Add qualifiers if necessary. 8316 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8317 // Promote to void*. 8318 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8319 return destType; 8320 } 8321 8322 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8323 } 8324 8325 /// Return false if the first expression is not an integer and the second 8326 /// expression is not a pointer, true otherwise. 8327 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8328 Expr* PointerExpr, SourceLocation Loc, 8329 bool IsIntFirstExpr) { 8330 if (!PointerExpr->getType()->isPointerType() || 8331 !Int.get()->getType()->isIntegerType()) 8332 return false; 8333 8334 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8335 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8336 8337 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8338 << Expr1->getType() << Expr2->getType() 8339 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8340 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8341 CK_IntegralToPointer); 8342 return true; 8343 } 8344 8345 /// Simple conversion between integer and floating point types. 8346 /// 8347 /// Used when handling the OpenCL conditional operator where the 8348 /// condition is a vector while the other operands are scalar. 8349 /// 8350 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8351 /// types are either integer or floating type. Between the two 8352 /// operands, the type with the higher rank is defined as the "result 8353 /// type". The other operand needs to be promoted to the same type. No 8354 /// other type promotion is allowed. We cannot use 8355 /// UsualArithmeticConversions() for this purpose, since it always 8356 /// promotes promotable types. 8357 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8358 ExprResult &RHS, 8359 SourceLocation QuestionLoc) { 8360 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8361 if (LHS.isInvalid()) 8362 return QualType(); 8363 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8364 if (RHS.isInvalid()) 8365 return QualType(); 8366 8367 // For conversion purposes, we ignore any qualifiers. 8368 // For example, "const float" and "float" are equivalent. 8369 QualType LHSType = 8370 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8371 QualType RHSType = 8372 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8373 8374 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8375 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8376 << LHSType << LHS.get()->getSourceRange(); 8377 return QualType(); 8378 } 8379 8380 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8381 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8382 << RHSType << RHS.get()->getSourceRange(); 8383 return QualType(); 8384 } 8385 8386 // If both types are identical, no conversion is needed. 8387 if (LHSType == RHSType) 8388 return LHSType; 8389 8390 // Now handle "real" floating types (i.e. float, double, long double). 8391 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8392 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8393 /*IsCompAssign = */ false); 8394 8395 // Finally, we have two differing integer types. 8396 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8397 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8398 } 8399 8400 /// Convert scalar operands to a vector that matches the 8401 /// condition in length. 8402 /// 8403 /// Used when handling the OpenCL conditional operator where the 8404 /// condition is a vector while the other operands are scalar. 8405 /// 8406 /// We first compute the "result type" for the scalar operands 8407 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8408 /// into a vector of that type where the length matches the condition 8409 /// vector type. s6.11.6 requires that the element types of the result 8410 /// and the condition must have the same number of bits. 8411 static QualType 8412 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8413 QualType CondTy, SourceLocation QuestionLoc) { 8414 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8415 if (ResTy.isNull()) return QualType(); 8416 8417 const VectorType *CV = CondTy->getAs<VectorType>(); 8418 assert(CV); 8419 8420 // Determine the vector result type 8421 unsigned NumElements = CV->getNumElements(); 8422 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8423 8424 // Ensure that all types have the same number of bits 8425 if (S.Context.getTypeSize(CV->getElementType()) 8426 != S.Context.getTypeSize(ResTy)) { 8427 // Since VectorTy is created internally, it does not pretty print 8428 // with an OpenCL name. Instead, we just print a description. 8429 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8430 SmallString<64> Str; 8431 llvm::raw_svector_ostream OS(Str); 8432 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8433 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8434 << CondTy << OS.str(); 8435 return QualType(); 8436 } 8437 8438 // Convert operands to the vector result type 8439 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8440 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8441 8442 return VectorTy; 8443 } 8444 8445 /// Return false if this is a valid OpenCL condition vector 8446 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8447 SourceLocation QuestionLoc) { 8448 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8449 // integral type. 8450 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8451 assert(CondTy); 8452 QualType EleTy = CondTy->getElementType(); 8453 if (EleTy->isIntegerType()) return false; 8454 8455 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8456 << Cond->getType() << Cond->getSourceRange(); 8457 return true; 8458 } 8459 8460 /// Return false if the vector condition type and the vector 8461 /// result type are compatible. 8462 /// 8463 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8464 /// number of elements, and their element types have the same number 8465 /// of bits. 8466 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8467 SourceLocation QuestionLoc) { 8468 const VectorType *CV = CondTy->getAs<VectorType>(); 8469 const VectorType *RV = VecResTy->getAs<VectorType>(); 8470 assert(CV && RV); 8471 8472 if (CV->getNumElements() != RV->getNumElements()) { 8473 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8474 << CondTy << VecResTy; 8475 return true; 8476 } 8477 8478 QualType CVE = CV->getElementType(); 8479 QualType RVE = RV->getElementType(); 8480 8481 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8482 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8483 << CondTy << VecResTy; 8484 return true; 8485 } 8486 8487 return false; 8488 } 8489 8490 /// Return the resulting type for the conditional operator in 8491 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8492 /// s6.3.i) when the condition is a vector type. 8493 static QualType 8494 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8495 ExprResult &LHS, ExprResult &RHS, 8496 SourceLocation QuestionLoc) { 8497 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8498 if (Cond.isInvalid()) 8499 return QualType(); 8500 QualType CondTy = Cond.get()->getType(); 8501 8502 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8503 return QualType(); 8504 8505 // If either operand is a vector then find the vector type of the 8506 // result as specified in OpenCL v1.1 s6.3.i. 8507 if (LHS.get()->getType()->isVectorType() || 8508 RHS.get()->getType()->isVectorType()) { 8509 bool IsBoolVecLang = 8510 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; 8511 QualType VecResTy = 8512 S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8513 /*isCompAssign*/ false, 8514 /*AllowBothBool*/ true, 8515 /*AllowBoolConversions*/ false, 8516 /*AllowBooleanOperation*/ IsBoolVecLang, 8517 /*ReportInvalid*/ true); 8518 if (VecResTy.isNull()) 8519 return QualType(); 8520 // The result type must match the condition type as specified in 8521 // OpenCL v1.1 s6.11.6. 8522 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8523 return QualType(); 8524 return VecResTy; 8525 } 8526 8527 // Both operands are scalar. 8528 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8529 } 8530 8531 /// Return true if the Expr is block type 8532 static bool checkBlockType(Sema &S, const Expr *E) { 8533 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8534 QualType Ty = CE->getCallee()->getType(); 8535 if (Ty->isBlockPointerType()) { 8536 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8537 return true; 8538 } 8539 } 8540 return false; 8541 } 8542 8543 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8544 /// In that case, LHS = cond. 8545 /// C99 6.5.15 8546 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8547 ExprResult &RHS, ExprValueKind &VK, 8548 ExprObjectKind &OK, 8549 SourceLocation QuestionLoc) { 8550 8551 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8552 if (!LHSResult.isUsable()) return QualType(); 8553 LHS = LHSResult; 8554 8555 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8556 if (!RHSResult.isUsable()) return QualType(); 8557 RHS = RHSResult; 8558 8559 // C++ is sufficiently different to merit its own checker. 8560 if (getLangOpts().CPlusPlus) 8561 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8562 8563 VK = VK_PRValue; 8564 OK = OK_Ordinary; 8565 8566 if (Context.isDependenceAllowed() && 8567 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8568 RHS.get()->isTypeDependent())) { 8569 assert(!getLangOpts().CPlusPlus); 8570 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8571 RHS.get()->containsErrors()) && 8572 "should only occur in error-recovery path."); 8573 return Context.DependentTy; 8574 } 8575 8576 // The OpenCL operator with a vector condition is sufficiently 8577 // different to merit its own checker. 8578 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8579 Cond.get()->getType()->isExtVectorType()) 8580 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8581 8582 // First, check the condition. 8583 Cond = UsualUnaryConversions(Cond.get()); 8584 if (Cond.isInvalid()) 8585 return QualType(); 8586 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8587 return QualType(); 8588 8589 // Now check the two expressions. 8590 if (LHS.get()->getType()->isVectorType() || 8591 RHS.get()->getType()->isVectorType()) 8592 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, 8593 /*AllowBothBool*/ true, 8594 /*AllowBoolConversions*/ false, 8595 /*AllowBooleanOperation*/ false, 8596 /*ReportInvalid*/ true); 8597 8598 QualType ResTy = 8599 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8600 if (LHS.isInvalid() || RHS.isInvalid()) 8601 return QualType(); 8602 8603 QualType LHSTy = LHS.get()->getType(); 8604 QualType RHSTy = RHS.get()->getType(); 8605 8606 // Diagnose attempts to convert between __ibm128, __float128 and long double 8607 // where such conversions currently can't be handled. 8608 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8609 Diag(QuestionLoc, 8610 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8611 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8612 return QualType(); 8613 } 8614 8615 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8616 // selection operator (?:). 8617 if (getLangOpts().OpenCL && 8618 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8619 return QualType(); 8620 } 8621 8622 // If both operands have arithmetic type, do the usual arithmetic conversions 8623 // to find a common type: C99 6.5.15p3,5. 8624 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8625 // Disallow invalid arithmetic conversions, such as those between bit- 8626 // precise integers types of different sizes, or between a bit-precise 8627 // integer and another type. 8628 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { 8629 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8630 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8631 << RHS.get()->getSourceRange(); 8632 return QualType(); 8633 } 8634 8635 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8636 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8637 8638 return ResTy; 8639 } 8640 8641 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8642 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8643 return LHSTy; 8644 } 8645 8646 // If both operands are the same structure or union type, the result is that 8647 // type. 8648 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8649 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8650 if (LHSRT->getDecl() == RHSRT->getDecl()) 8651 // "If both the operands have structure or union type, the result has 8652 // that type." This implies that CV qualifiers are dropped. 8653 return LHSTy.getUnqualifiedType(); 8654 // FIXME: Type of conditional expression must be complete in C mode. 8655 } 8656 8657 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8658 // The following || allows only one side to be void (a GCC-ism). 8659 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8660 return checkConditionalVoidType(*this, LHS, RHS); 8661 } 8662 8663 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8664 // the type of the other operand." 8665 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8666 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8667 8668 // All objective-c pointer type analysis is done here. 8669 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8670 QuestionLoc); 8671 if (LHS.isInvalid() || RHS.isInvalid()) 8672 return QualType(); 8673 if (!compositeType.isNull()) 8674 return compositeType; 8675 8676 8677 // Handle block pointer types. 8678 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8679 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8680 QuestionLoc); 8681 8682 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8683 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8684 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8685 QuestionLoc); 8686 8687 // GCC compatibility: soften pointer/integer mismatch. Note that 8688 // null pointers have been filtered out by this point. 8689 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8690 /*IsIntFirstExpr=*/true)) 8691 return RHSTy; 8692 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8693 /*IsIntFirstExpr=*/false)) 8694 return LHSTy; 8695 8696 // Allow ?: operations in which both operands have the same 8697 // built-in sizeless type. 8698 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8699 return LHSTy; 8700 8701 // Emit a better diagnostic if one of the expressions is a null pointer 8702 // constant and the other is not a pointer type. In this case, the user most 8703 // likely forgot to take the address of the other expression. 8704 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8705 return QualType(); 8706 8707 // Otherwise, the operands are not compatible. 8708 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8709 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8710 << RHS.get()->getSourceRange(); 8711 return QualType(); 8712 } 8713 8714 /// FindCompositeObjCPointerType - Helper method to find composite type of 8715 /// two objective-c pointer types of the two input expressions. 8716 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8717 SourceLocation QuestionLoc) { 8718 QualType LHSTy = LHS.get()->getType(); 8719 QualType RHSTy = RHS.get()->getType(); 8720 8721 // Handle things like Class and struct objc_class*. Here we case the result 8722 // to the pseudo-builtin, because that will be implicitly cast back to the 8723 // redefinition type if an attempt is made to access its fields. 8724 if (LHSTy->isObjCClassType() && 8725 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8726 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8727 return LHSTy; 8728 } 8729 if (RHSTy->isObjCClassType() && 8730 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8731 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8732 return RHSTy; 8733 } 8734 // And the same for struct objc_object* / id 8735 if (LHSTy->isObjCIdType() && 8736 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8737 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8738 return LHSTy; 8739 } 8740 if (RHSTy->isObjCIdType() && 8741 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8742 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8743 return RHSTy; 8744 } 8745 // And the same for struct objc_selector* / SEL 8746 if (Context.isObjCSelType(LHSTy) && 8747 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8748 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8749 return LHSTy; 8750 } 8751 if (Context.isObjCSelType(RHSTy) && 8752 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8753 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8754 return RHSTy; 8755 } 8756 // Check constraints for Objective-C object pointers types. 8757 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8758 8759 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8760 // Two identical object pointer types are always compatible. 8761 return LHSTy; 8762 } 8763 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8764 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8765 QualType compositeType = LHSTy; 8766 8767 // If both operands are interfaces and either operand can be 8768 // assigned to the other, use that type as the composite 8769 // type. This allows 8770 // xxx ? (A*) a : (B*) b 8771 // where B is a subclass of A. 8772 // 8773 // Additionally, as for assignment, if either type is 'id' 8774 // allow silent coercion. Finally, if the types are 8775 // incompatible then make sure to use 'id' as the composite 8776 // type so the result is acceptable for sending messages to. 8777 8778 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8779 // It could return the composite type. 8780 if (!(compositeType = 8781 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8782 // Nothing more to do. 8783 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8784 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8785 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8786 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8787 } else if ((LHSOPT->isObjCQualifiedIdType() || 8788 RHSOPT->isObjCQualifiedIdType()) && 8789 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8790 true)) { 8791 // Need to handle "id<xx>" explicitly. 8792 // GCC allows qualified id and any Objective-C type to devolve to 8793 // id. Currently localizing to here until clear this should be 8794 // part of ObjCQualifiedIdTypesAreCompatible. 8795 compositeType = Context.getObjCIdType(); 8796 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8797 compositeType = Context.getObjCIdType(); 8798 } else { 8799 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8800 << LHSTy << RHSTy 8801 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8802 QualType incompatTy = Context.getObjCIdType(); 8803 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8804 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8805 return incompatTy; 8806 } 8807 // The object pointer types are compatible. 8808 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8809 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8810 return compositeType; 8811 } 8812 // Check Objective-C object pointer types and 'void *' 8813 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8814 if (getLangOpts().ObjCAutoRefCount) { 8815 // ARC forbids the implicit conversion of object pointers to 'void *', 8816 // so these types are not compatible. 8817 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8818 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8819 LHS = RHS = true; 8820 return QualType(); 8821 } 8822 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8823 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8824 QualType destPointee 8825 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8826 QualType destType = Context.getPointerType(destPointee); 8827 // Add qualifiers if necessary. 8828 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8829 // Promote to void*. 8830 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8831 return destType; 8832 } 8833 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8834 if (getLangOpts().ObjCAutoRefCount) { 8835 // ARC forbids the implicit conversion of object pointers to 'void *', 8836 // so these types are not compatible. 8837 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8838 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8839 LHS = RHS = true; 8840 return QualType(); 8841 } 8842 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8843 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8844 QualType destPointee 8845 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8846 QualType destType = Context.getPointerType(destPointee); 8847 // Add qualifiers if necessary. 8848 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8849 // Promote to void*. 8850 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8851 return destType; 8852 } 8853 return QualType(); 8854 } 8855 8856 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8857 /// ParenRange in parentheses. 8858 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8859 const PartialDiagnostic &Note, 8860 SourceRange ParenRange) { 8861 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8862 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8863 EndLoc.isValid()) { 8864 Self.Diag(Loc, Note) 8865 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8866 << FixItHint::CreateInsertion(EndLoc, ")"); 8867 } else { 8868 // We can't display the parentheses, so just show the bare note. 8869 Self.Diag(Loc, Note) << ParenRange; 8870 } 8871 } 8872 8873 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8874 return BinaryOperator::isAdditiveOp(Opc) || 8875 BinaryOperator::isMultiplicativeOp(Opc) || 8876 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8877 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8878 // not any of the logical operators. Bitwise-xor is commonly used as a 8879 // logical-xor because there is no logical-xor operator. The logical 8880 // operators, including uses of xor, have a high false positive rate for 8881 // precedence warnings. 8882 } 8883 8884 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8885 /// expression, either using a built-in or overloaded operator, 8886 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8887 /// expression. 8888 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8889 Expr **RHSExprs) { 8890 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8891 E = E->IgnoreImpCasts(); 8892 E = E->IgnoreConversionOperatorSingleStep(); 8893 E = E->IgnoreImpCasts(); 8894 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8895 E = MTE->getSubExpr(); 8896 E = E->IgnoreImpCasts(); 8897 } 8898 8899 // Built-in binary operator. 8900 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8901 if (IsArithmeticOp(OP->getOpcode())) { 8902 *Opcode = OP->getOpcode(); 8903 *RHSExprs = OP->getRHS(); 8904 return true; 8905 } 8906 } 8907 8908 // Overloaded operator. 8909 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8910 if (Call->getNumArgs() != 2) 8911 return false; 8912 8913 // Make sure this is really a binary operator that is safe to pass into 8914 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8915 OverloadedOperatorKind OO = Call->getOperator(); 8916 if (OO < OO_Plus || OO > OO_Arrow || 8917 OO == OO_PlusPlus || OO == OO_MinusMinus) 8918 return false; 8919 8920 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8921 if (IsArithmeticOp(OpKind)) { 8922 *Opcode = OpKind; 8923 *RHSExprs = Call->getArg(1); 8924 return true; 8925 } 8926 } 8927 8928 return false; 8929 } 8930 8931 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8932 /// or is a logical expression such as (x==y) which has int type, but is 8933 /// commonly interpreted as boolean. 8934 static bool ExprLooksBoolean(Expr *E) { 8935 E = E->IgnoreParenImpCasts(); 8936 8937 if (E->getType()->isBooleanType()) 8938 return true; 8939 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8940 return OP->isComparisonOp() || OP->isLogicalOp(); 8941 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8942 return OP->getOpcode() == UO_LNot; 8943 if (E->getType()->isPointerType()) 8944 return true; 8945 // FIXME: What about overloaded operator calls returning "unspecified boolean 8946 // type"s (commonly pointer-to-members)? 8947 8948 return false; 8949 } 8950 8951 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8952 /// and binary operator are mixed in a way that suggests the programmer assumed 8953 /// the conditional operator has higher precedence, for example: 8954 /// "int x = a + someBinaryCondition ? 1 : 2". 8955 static void DiagnoseConditionalPrecedence(Sema &Self, 8956 SourceLocation OpLoc, 8957 Expr *Condition, 8958 Expr *LHSExpr, 8959 Expr *RHSExpr) { 8960 BinaryOperatorKind CondOpcode; 8961 Expr *CondRHS; 8962 8963 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8964 return; 8965 if (!ExprLooksBoolean(CondRHS)) 8966 return; 8967 8968 // The condition is an arithmetic binary expression, with a right- 8969 // hand side that looks boolean, so warn. 8970 8971 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8972 ? diag::warn_precedence_bitwise_conditional 8973 : diag::warn_precedence_conditional; 8974 8975 Self.Diag(OpLoc, DiagID) 8976 << Condition->getSourceRange() 8977 << BinaryOperator::getOpcodeStr(CondOpcode); 8978 8979 SuggestParentheses( 8980 Self, OpLoc, 8981 Self.PDiag(diag::note_precedence_silence) 8982 << BinaryOperator::getOpcodeStr(CondOpcode), 8983 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8984 8985 SuggestParentheses(Self, OpLoc, 8986 Self.PDiag(diag::note_precedence_conditional_first), 8987 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8988 } 8989 8990 /// Compute the nullability of a conditional expression. 8991 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8992 QualType LHSTy, QualType RHSTy, 8993 ASTContext &Ctx) { 8994 if (!ResTy->isAnyPointerType()) 8995 return ResTy; 8996 8997 auto GetNullability = [&Ctx](QualType Ty) { 8998 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8999 if (Kind) { 9000 // For our purposes, treat _Nullable_result as _Nullable. 9001 if (*Kind == NullabilityKind::NullableResult) 9002 return NullabilityKind::Nullable; 9003 return *Kind; 9004 } 9005 return NullabilityKind::Unspecified; 9006 }; 9007 9008 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 9009 NullabilityKind MergedKind; 9010 9011 // Compute nullability of a binary conditional expression. 9012 if (IsBin) { 9013 if (LHSKind == NullabilityKind::NonNull) 9014 MergedKind = NullabilityKind::NonNull; 9015 else 9016 MergedKind = RHSKind; 9017 // Compute nullability of a normal conditional expression. 9018 } else { 9019 if (LHSKind == NullabilityKind::Nullable || 9020 RHSKind == NullabilityKind::Nullable) 9021 MergedKind = NullabilityKind::Nullable; 9022 else if (LHSKind == NullabilityKind::NonNull) 9023 MergedKind = RHSKind; 9024 else if (RHSKind == NullabilityKind::NonNull) 9025 MergedKind = LHSKind; 9026 else 9027 MergedKind = NullabilityKind::Unspecified; 9028 } 9029 9030 // Return if ResTy already has the correct nullability. 9031 if (GetNullability(ResTy) == MergedKind) 9032 return ResTy; 9033 9034 // Strip all nullability from ResTy. 9035 while (ResTy->getNullability(Ctx)) 9036 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 9037 9038 // Create a new AttributedType with the new nullability kind. 9039 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 9040 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 9041 } 9042 9043 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 9044 /// in the case of a the GNU conditional expr extension. 9045 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 9046 SourceLocation ColonLoc, 9047 Expr *CondExpr, Expr *LHSExpr, 9048 Expr *RHSExpr) { 9049 if (!Context.isDependenceAllowed()) { 9050 // C cannot handle TypoExpr nodes in the condition because it 9051 // doesn't handle dependent types properly, so make sure any TypoExprs have 9052 // been dealt with before checking the operands. 9053 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 9054 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 9055 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 9056 9057 if (!CondResult.isUsable()) 9058 return ExprError(); 9059 9060 if (LHSExpr) { 9061 if (!LHSResult.isUsable()) 9062 return ExprError(); 9063 } 9064 9065 if (!RHSResult.isUsable()) 9066 return ExprError(); 9067 9068 CondExpr = CondResult.get(); 9069 LHSExpr = LHSResult.get(); 9070 RHSExpr = RHSResult.get(); 9071 } 9072 9073 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 9074 // was the condition. 9075 OpaqueValueExpr *opaqueValue = nullptr; 9076 Expr *commonExpr = nullptr; 9077 if (!LHSExpr) { 9078 commonExpr = CondExpr; 9079 // Lower out placeholder types first. This is important so that we don't 9080 // try to capture a placeholder. This happens in few cases in C++; such 9081 // as Objective-C++'s dictionary subscripting syntax. 9082 if (commonExpr->hasPlaceholderType()) { 9083 ExprResult result = CheckPlaceholderExpr(commonExpr); 9084 if (!result.isUsable()) return ExprError(); 9085 commonExpr = result.get(); 9086 } 9087 // We usually want to apply unary conversions *before* saving, except 9088 // in the special case of a C++ l-value conditional. 9089 if (!(getLangOpts().CPlusPlus 9090 && !commonExpr->isTypeDependent() 9091 && commonExpr->getValueKind() == RHSExpr->getValueKind() 9092 && commonExpr->isGLValue() 9093 && commonExpr->isOrdinaryOrBitFieldObject() 9094 && RHSExpr->isOrdinaryOrBitFieldObject() 9095 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 9096 ExprResult commonRes = UsualUnaryConversions(commonExpr); 9097 if (commonRes.isInvalid()) 9098 return ExprError(); 9099 commonExpr = commonRes.get(); 9100 } 9101 9102 // If the common expression is a class or array prvalue, materialize it 9103 // so that we can safely refer to it multiple times. 9104 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 9105 commonExpr->getType()->isArrayType())) { 9106 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 9107 if (MatExpr.isInvalid()) 9108 return ExprError(); 9109 commonExpr = MatExpr.get(); 9110 } 9111 9112 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 9113 commonExpr->getType(), 9114 commonExpr->getValueKind(), 9115 commonExpr->getObjectKind(), 9116 commonExpr); 9117 LHSExpr = CondExpr = opaqueValue; 9118 } 9119 9120 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 9121 ExprValueKind VK = VK_PRValue; 9122 ExprObjectKind OK = OK_Ordinary; 9123 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 9124 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 9125 VK, OK, QuestionLoc); 9126 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 9127 RHS.isInvalid()) 9128 return ExprError(); 9129 9130 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 9131 RHS.get()); 9132 9133 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 9134 9135 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 9136 Context); 9137 9138 if (!commonExpr) 9139 return new (Context) 9140 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 9141 RHS.get(), result, VK, OK); 9142 9143 return new (Context) BinaryConditionalOperator( 9144 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 9145 ColonLoc, result, VK, OK); 9146 } 9147 9148 // Check if we have a conversion between incompatible cmse function pointer 9149 // types, that is, a conversion between a function pointer with the 9150 // cmse_nonsecure_call attribute and one without. 9151 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 9152 QualType ToType) { 9153 if (const auto *ToFn = 9154 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 9155 if (const auto *FromFn = 9156 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 9157 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 9158 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 9159 9160 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 9161 } 9162 } 9163 return false; 9164 } 9165 9166 // checkPointerTypesForAssignment - This is a very tricky routine (despite 9167 // being closely modeled after the C99 spec:-). The odd characteristic of this 9168 // routine is it effectively iqnores the qualifiers on the top level pointee. 9169 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 9170 // FIXME: add a couple examples in this comment. 9171 static Sema::AssignConvertType 9172 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 9173 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9174 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9175 9176 // get the "pointed to" type (ignoring qualifiers at the top level) 9177 const Type *lhptee, *rhptee; 9178 Qualifiers lhq, rhq; 9179 std::tie(lhptee, lhq) = 9180 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 9181 std::tie(rhptee, rhq) = 9182 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 9183 9184 Sema::AssignConvertType ConvTy = Sema::Compatible; 9185 9186 // C99 6.5.16.1p1: This following citation is common to constraints 9187 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 9188 // qualifiers of the type *pointed to* by the right; 9189 9190 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 9191 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 9192 lhq.compatiblyIncludesObjCLifetime(rhq)) { 9193 // Ignore lifetime for further calculation. 9194 lhq.removeObjCLifetime(); 9195 rhq.removeObjCLifetime(); 9196 } 9197 9198 if (!lhq.compatiblyIncludes(rhq)) { 9199 // Treat address-space mismatches as fatal. 9200 if (!lhq.isAddressSpaceSupersetOf(rhq)) 9201 return Sema::IncompatiblePointerDiscardsQualifiers; 9202 9203 // It's okay to add or remove GC or lifetime qualifiers when converting to 9204 // and from void*. 9205 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 9206 .compatiblyIncludes( 9207 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 9208 && (lhptee->isVoidType() || rhptee->isVoidType())) 9209 ; // keep old 9210 9211 // Treat lifetime mismatches as fatal. 9212 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 9213 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 9214 9215 // For GCC/MS compatibility, other qualifier mismatches are treated 9216 // as still compatible in C. 9217 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9218 } 9219 9220 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 9221 // incomplete type and the other is a pointer to a qualified or unqualified 9222 // version of void... 9223 if (lhptee->isVoidType()) { 9224 if (rhptee->isIncompleteOrObjectType()) 9225 return ConvTy; 9226 9227 // As an extension, we allow cast to/from void* to function pointer. 9228 assert(rhptee->isFunctionType()); 9229 return Sema::FunctionVoidPointer; 9230 } 9231 9232 if (rhptee->isVoidType()) { 9233 if (lhptee->isIncompleteOrObjectType()) 9234 return ConvTy; 9235 9236 // As an extension, we allow cast to/from void* to function pointer. 9237 assert(lhptee->isFunctionType()); 9238 return Sema::FunctionVoidPointer; 9239 } 9240 9241 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9242 // unqualified versions of compatible types, ... 9243 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9244 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9245 // Check if the pointee types are compatible ignoring the sign. 9246 // We explicitly check for char so that we catch "char" vs 9247 // "unsigned char" on systems where "char" is unsigned. 9248 if (lhptee->isCharType()) 9249 ltrans = S.Context.UnsignedCharTy; 9250 else if (lhptee->hasSignedIntegerRepresentation()) 9251 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9252 9253 if (rhptee->isCharType()) 9254 rtrans = S.Context.UnsignedCharTy; 9255 else if (rhptee->hasSignedIntegerRepresentation()) 9256 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9257 9258 if (ltrans == rtrans) { 9259 // Types are compatible ignoring the sign. Qualifier incompatibility 9260 // takes priority over sign incompatibility because the sign 9261 // warning can be disabled. 9262 if (ConvTy != Sema::Compatible) 9263 return ConvTy; 9264 9265 return Sema::IncompatiblePointerSign; 9266 } 9267 9268 // If we are a multi-level pointer, it's possible that our issue is simply 9269 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9270 // the eventual target type is the same and the pointers have the same 9271 // level of indirection, this must be the issue. 9272 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9273 do { 9274 std::tie(lhptee, lhq) = 9275 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9276 std::tie(rhptee, rhq) = 9277 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9278 9279 // Inconsistent address spaces at this point is invalid, even if the 9280 // address spaces would be compatible. 9281 // FIXME: This doesn't catch address space mismatches for pointers of 9282 // different nesting levels, like: 9283 // __local int *** a; 9284 // int ** b = a; 9285 // It's not clear how to actually determine when such pointers are 9286 // invalidly incompatible. 9287 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9288 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9289 9290 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9291 9292 if (lhptee == rhptee) 9293 return Sema::IncompatibleNestedPointerQualifiers; 9294 } 9295 9296 // General pointer incompatibility takes priority over qualifiers. 9297 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9298 return Sema::IncompatibleFunctionPointer; 9299 return Sema::IncompatiblePointer; 9300 } 9301 if (!S.getLangOpts().CPlusPlus && 9302 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9303 return Sema::IncompatibleFunctionPointer; 9304 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9305 return Sema::IncompatibleFunctionPointer; 9306 return ConvTy; 9307 } 9308 9309 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9310 /// block pointer types are compatible or whether a block and normal pointer 9311 /// are compatible. It is more restrict than comparing two function pointer 9312 // types. 9313 static Sema::AssignConvertType 9314 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9315 QualType RHSType) { 9316 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9317 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9318 9319 QualType lhptee, rhptee; 9320 9321 // get the "pointed to" type (ignoring qualifiers at the top level) 9322 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9323 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9324 9325 // In C++, the types have to match exactly. 9326 if (S.getLangOpts().CPlusPlus) 9327 return Sema::IncompatibleBlockPointer; 9328 9329 Sema::AssignConvertType ConvTy = Sema::Compatible; 9330 9331 // For blocks we enforce that qualifiers are identical. 9332 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9333 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9334 if (S.getLangOpts().OpenCL) { 9335 LQuals.removeAddressSpace(); 9336 RQuals.removeAddressSpace(); 9337 } 9338 if (LQuals != RQuals) 9339 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9340 9341 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9342 // assignment. 9343 // The current behavior is similar to C++ lambdas. A block might be 9344 // assigned to a variable iff its return type and parameters are compatible 9345 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9346 // an assignment. Presumably it should behave in way that a function pointer 9347 // assignment does in C, so for each parameter and return type: 9348 // * CVR and address space of LHS should be a superset of CVR and address 9349 // space of RHS. 9350 // * unqualified types should be compatible. 9351 if (S.getLangOpts().OpenCL) { 9352 if (!S.Context.typesAreBlockPointerCompatible( 9353 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9354 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9355 return Sema::IncompatibleBlockPointer; 9356 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9357 return Sema::IncompatibleBlockPointer; 9358 9359 return ConvTy; 9360 } 9361 9362 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9363 /// for assignment compatibility. 9364 static Sema::AssignConvertType 9365 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9366 QualType RHSType) { 9367 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9368 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9369 9370 if (LHSType->isObjCBuiltinType()) { 9371 // Class is not compatible with ObjC object pointers. 9372 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9373 !RHSType->isObjCQualifiedClassType()) 9374 return Sema::IncompatiblePointer; 9375 return Sema::Compatible; 9376 } 9377 if (RHSType->isObjCBuiltinType()) { 9378 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9379 !LHSType->isObjCQualifiedClassType()) 9380 return Sema::IncompatiblePointer; 9381 return Sema::Compatible; 9382 } 9383 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9384 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9385 9386 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9387 // make an exception for id<P> 9388 !LHSType->isObjCQualifiedIdType()) 9389 return Sema::CompatiblePointerDiscardsQualifiers; 9390 9391 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9392 return Sema::Compatible; 9393 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9394 return Sema::IncompatibleObjCQualifiedId; 9395 return Sema::IncompatiblePointer; 9396 } 9397 9398 Sema::AssignConvertType 9399 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9400 QualType LHSType, QualType RHSType) { 9401 // Fake up an opaque expression. We don't actually care about what 9402 // cast operations are required, so if CheckAssignmentConstraints 9403 // adds casts to this they'll be wasted, but fortunately that doesn't 9404 // usually happen on valid code. 9405 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9406 ExprResult RHSPtr = &RHSExpr; 9407 CastKind K; 9408 9409 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9410 } 9411 9412 /// This helper function returns true if QT is a vector type that has element 9413 /// type ElementType. 9414 static bool isVector(QualType QT, QualType ElementType) { 9415 if (const VectorType *VT = QT->getAs<VectorType>()) 9416 return VT->getElementType().getCanonicalType() == ElementType; 9417 return false; 9418 } 9419 9420 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9421 /// has code to accommodate several GCC extensions when type checking 9422 /// pointers. Here are some objectionable examples that GCC considers warnings: 9423 /// 9424 /// int a, *pint; 9425 /// short *pshort; 9426 /// struct foo *pfoo; 9427 /// 9428 /// pint = pshort; // warning: assignment from incompatible pointer type 9429 /// a = pint; // warning: assignment makes integer from pointer without a cast 9430 /// pint = a; // warning: assignment makes pointer from integer without a cast 9431 /// pint = pfoo; // warning: assignment from incompatible pointer type 9432 /// 9433 /// As a result, the code for dealing with pointers is more complex than the 9434 /// C99 spec dictates. 9435 /// 9436 /// Sets 'Kind' for any result kind except Incompatible. 9437 Sema::AssignConvertType 9438 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9439 CastKind &Kind, bool ConvertRHS) { 9440 QualType RHSType = RHS.get()->getType(); 9441 QualType OrigLHSType = LHSType; 9442 9443 // Get canonical types. We're not formatting these types, just comparing 9444 // them. 9445 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9446 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9447 9448 // Common case: no conversion required. 9449 if (LHSType == RHSType) { 9450 Kind = CK_NoOp; 9451 return Compatible; 9452 } 9453 9454 // If the LHS has an __auto_type, there are no additional type constraints 9455 // to be worried about. 9456 if (const auto *AT = dyn_cast<AutoType>(LHSType)) { 9457 if (AT->isGNUAutoType()) { 9458 Kind = CK_NoOp; 9459 return Compatible; 9460 } 9461 } 9462 9463 // If we have an atomic type, try a non-atomic assignment, then just add an 9464 // atomic qualification step. 9465 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9466 Sema::AssignConvertType result = 9467 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9468 if (result != Compatible) 9469 return result; 9470 if (Kind != CK_NoOp && ConvertRHS) 9471 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9472 Kind = CK_NonAtomicToAtomic; 9473 return Compatible; 9474 } 9475 9476 // If the left-hand side is a reference type, then we are in a 9477 // (rare!) case where we've allowed the use of references in C, 9478 // e.g., as a parameter type in a built-in function. In this case, 9479 // just make sure that the type referenced is compatible with the 9480 // right-hand side type. The caller is responsible for adjusting 9481 // LHSType so that the resulting expression does not have reference 9482 // type. 9483 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9484 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9485 Kind = CK_LValueBitCast; 9486 return Compatible; 9487 } 9488 return Incompatible; 9489 } 9490 9491 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9492 // to the same ExtVector type. 9493 if (LHSType->isExtVectorType()) { 9494 if (RHSType->isExtVectorType()) 9495 return Incompatible; 9496 if (RHSType->isArithmeticType()) { 9497 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9498 if (ConvertRHS) 9499 RHS = prepareVectorSplat(LHSType, RHS.get()); 9500 Kind = CK_VectorSplat; 9501 return Compatible; 9502 } 9503 } 9504 9505 // Conversions to or from vector type. 9506 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9507 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9508 // Allow assignments of an AltiVec vector type to an equivalent GCC 9509 // vector type and vice versa 9510 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9511 Kind = CK_BitCast; 9512 return Compatible; 9513 } 9514 9515 // If we are allowing lax vector conversions, and LHS and RHS are both 9516 // vectors, the total size only needs to be the same. This is a bitcast; 9517 // no bits are changed but the result type is different. 9518 if (isLaxVectorConversion(RHSType, LHSType)) { 9519 Kind = CK_BitCast; 9520 return IncompatibleVectors; 9521 } 9522 } 9523 9524 // When the RHS comes from another lax conversion (e.g. binops between 9525 // scalars and vectors) the result is canonicalized as a vector. When the 9526 // LHS is also a vector, the lax is allowed by the condition above. Handle 9527 // the case where LHS is a scalar. 9528 if (LHSType->isScalarType()) { 9529 const VectorType *VecType = RHSType->getAs<VectorType>(); 9530 if (VecType && VecType->getNumElements() == 1 && 9531 isLaxVectorConversion(RHSType, LHSType)) { 9532 ExprResult *VecExpr = &RHS; 9533 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9534 Kind = CK_BitCast; 9535 return Compatible; 9536 } 9537 } 9538 9539 // Allow assignments between fixed-length and sizeless SVE vectors. 9540 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9541 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9542 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9543 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9544 Kind = CK_BitCast; 9545 return Compatible; 9546 } 9547 9548 return Incompatible; 9549 } 9550 9551 // Diagnose attempts to convert between __ibm128, __float128 and long double 9552 // where such conversions currently can't be handled. 9553 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9554 return Incompatible; 9555 9556 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9557 // discards the imaginary part. 9558 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9559 !LHSType->getAs<ComplexType>()) 9560 return Incompatible; 9561 9562 // Arithmetic conversions. 9563 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9564 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9565 if (ConvertRHS) 9566 Kind = PrepareScalarCast(RHS, LHSType); 9567 return Compatible; 9568 } 9569 9570 // Conversions to normal pointers. 9571 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9572 // U* -> T* 9573 if (isa<PointerType>(RHSType)) { 9574 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9575 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9576 if (AddrSpaceL != AddrSpaceR) 9577 Kind = CK_AddressSpaceConversion; 9578 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9579 Kind = CK_NoOp; 9580 else 9581 Kind = CK_BitCast; 9582 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9583 } 9584 9585 // int -> T* 9586 if (RHSType->isIntegerType()) { 9587 Kind = CK_IntegralToPointer; // FIXME: null? 9588 return IntToPointer; 9589 } 9590 9591 // C pointers are not compatible with ObjC object pointers, 9592 // with two exceptions: 9593 if (isa<ObjCObjectPointerType>(RHSType)) { 9594 // - conversions to void* 9595 if (LHSPointer->getPointeeType()->isVoidType()) { 9596 Kind = CK_BitCast; 9597 return Compatible; 9598 } 9599 9600 // - conversions from 'Class' to the redefinition type 9601 if (RHSType->isObjCClassType() && 9602 Context.hasSameType(LHSType, 9603 Context.getObjCClassRedefinitionType())) { 9604 Kind = CK_BitCast; 9605 return Compatible; 9606 } 9607 9608 Kind = CK_BitCast; 9609 return IncompatiblePointer; 9610 } 9611 9612 // U^ -> void* 9613 if (RHSType->getAs<BlockPointerType>()) { 9614 if (LHSPointer->getPointeeType()->isVoidType()) { 9615 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9616 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9617 ->getPointeeType() 9618 .getAddressSpace(); 9619 Kind = 9620 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9621 return Compatible; 9622 } 9623 } 9624 9625 return Incompatible; 9626 } 9627 9628 // Conversions to block pointers. 9629 if (isa<BlockPointerType>(LHSType)) { 9630 // U^ -> T^ 9631 if (RHSType->isBlockPointerType()) { 9632 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9633 ->getPointeeType() 9634 .getAddressSpace(); 9635 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9636 ->getPointeeType() 9637 .getAddressSpace(); 9638 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9639 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9640 } 9641 9642 // int or null -> T^ 9643 if (RHSType->isIntegerType()) { 9644 Kind = CK_IntegralToPointer; // FIXME: null 9645 return IntToBlockPointer; 9646 } 9647 9648 // id -> T^ 9649 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9650 Kind = CK_AnyPointerToBlockPointerCast; 9651 return Compatible; 9652 } 9653 9654 // void* -> T^ 9655 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9656 if (RHSPT->getPointeeType()->isVoidType()) { 9657 Kind = CK_AnyPointerToBlockPointerCast; 9658 return Compatible; 9659 } 9660 9661 return Incompatible; 9662 } 9663 9664 // Conversions to Objective-C pointers. 9665 if (isa<ObjCObjectPointerType>(LHSType)) { 9666 // A* -> B* 9667 if (RHSType->isObjCObjectPointerType()) { 9668 Kind = CK_BitCast; 9669 Sema::AssignConvertType result = 9670 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9671 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9672 result == Compatible && 9673 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9674 result = IncompatibleObjCWeakRef; 9675 return result; 9676 } 9677 9678 // int or null -> A* 9679 if (RHSType->isIntegerType()) { 9680 Kind = CK_IntegralToPointer; // FIXME: null 9681 return IntToPointer; 9682 } 9683 9684 // In general, C pointers are not compatible with ObjC object pointers, 9685 // with two exceptions: 9686 if (isa<PointerType>(RHSType)) { 9687 Kind = CK_CPointerToObjCPointerCast; 9688 9689 // - conversions from 'void*' 9690 if (RHSType->isVoidPointerType()) { 9691 return Compatible; 9692 } 9693 9694 // - conversions to 'Class' from its redefinition type 9695 if (LHSType->isObjCClassType() && 9696 Context.hasSameType(RHSType, 9697 Context.getObjCClassRedefinitionType())) { 9698 return Compatible; 9699 } 9700 9701 return IncompatiblePointer; 9702 } 9703 9704 // Only under strict condition T^ is compatible with an Objective-C pointer. 9705 if (RHSType->isBlockPointerType() && 9706 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9707 if (ConvertRHS) 9708 maybeExtendBlockObject(RHS); 9709 Kind = CK_BlockPointerToObjCPointerCast; 9710 return Compatible; 9711 } 9712 9713 return Incompatible; 9714 } 9715 9716 // Conversions from pointers that are not covered by the above. 9717 if (isa<PointerType>(RHSType)) { 9718 // T* -> _Bool 9719 if (LHSType == Context.BoolTy) { 9720 Kind = CK_PointerToBoolean; 9721 return Compatible; 9722 } 9723 9724 // T* -> int 9725 if (LHSType->isIntegerType()) { 9726 Kind = CK_PointerToIntegral; 9727 return PointerToInt; 9728 } 9729 9730 return Incompatible; 9731 } 9732 9733 // Conversions from Objective-C pointers that are not covered by the above. 9734 if (isa<ObjCObjectPointerType>(RHSType)) { 9735 // T* -> _Bool 9736 if (LHSType == Context.BoolTy) { 9737 Kind = CK_PointerToBoolean; 9738 return Compatible; 9739 } 9740 9741 // T* -> int 9742 if (LHSType->isIntegerType()) { 9743 Kind = CK_PointerToIntegral; 9744 return PointerToInt; 9745 } 9746 9747 return Incompatible; 9748 } 9749 9750 // struct A -> struct B 9751 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9752 if (Context.typesAreCompatible(LHSType, RHSType)) { 9753 Kind = CK_NoOp; 9754 return Compatible; 9755 } 9756 } 9757 9758 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9759 Kind = CK_IntToOCLSampler; 9760 return Compatible; 9761 } 9762 9763 return Incompatible; 9764 } 9765 9766 /// Constructs a transparent union from an expression that is 9767 /// used to initialize the transparent union. 9768 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9769 ExprResult &EResult, QualType UnionType, 9770 FieldDecl *Field) { 9771 // Build an initializer list that designates the appropriate member 9772 // of the transparent union. 9773 Expr *E = EResult.get(); 9774 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9775 E, SourceLocation()); 9776 Initializer->setType(UnionType); 9777 Initializer->setInitializedFieldInUnion(Field); 9778 9779 // Build a compound literal constructing a value of the transparent 9780 // union type from this initializer list. 9781 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9782 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9783 VK_PRValue, Initializer, false); 9784 } 9785 9786 Sema::AssignConvertType 9787 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9788 ExprResult &RHS) { 9789 QualType RHSType = RHS.get()->getType(); 9790 9791 // If the ArgType is a Union type, we want to handle a potential 9792 // transparent_union GCC extension. 9793 const RecordType *UT = ArgType->getAsUnionType(); 9794 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9795 return Incompatible; 9796 9797 // The field to initialize within the transparent union. 9798 RecordDecl *UD = UT->getDecl(); 9799 FieldDecl *InitField = nullptr; 9800 // It's compatible if the expression matches any of the fields. 9801 for (auto *it : UD->fields()) { 9802 if (it->getType()->isPointerType()) { 9803 // If the transparent union contains a pointer type, we allow: 9804 // 1) void pointer 9805 // 2) null pointer constant 9806 if (RHSType->isPointerType()) 9807 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9808 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9809 InitField = it; 9810 break; 9811 } 9812 9813 if (RHS.get()->isNullPointerConstant(Context, 9814 Expr::NPC_ValueDependentIsNull)) { 9815 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9816 CK_NullToPointer); 9817 InitField = it; 9818 break; 9819 } 9820 } 9821 9822 CastKind Kind; 9823 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9824 == Compatible) { 9825 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9826 InitField = it; 9827 break; 9828 } 9829 } 9830 9831 if (!InitField) 9832 return Incompatible; 9833 9834 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9835 return Compatible; 9836 } 9837 9838 Sema::AssignConvertType 9839 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9840 bool Diagnose, 9841 bool DiagnoseCFAudited, 9842 bool ConvertRHS) { 9843 // We need to be able to tell the caller whether we diagnosed a problem, if 9844 // they ask us to issue diagnostics. 9845 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9846 9847 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9848 // we can't avoid *all* modifications at the moment, so we need some somewhere 9849 // to put the updated value. 9850 ExprResult LocalRHS = CallerRHS; 9851 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9852 9853 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9854 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9855 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9856 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9857 Diag(RHS.get()->getExprLoc(), 9858 diag::warn_noderef_to_dereferenceable_pointer) 9859 << RHS.get()->getSourceRange(); 9860 } 9861 } 9862 } 9863 9864 if (getLangOpts().CPlusPlus) { 9865 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9866 // C++ 5.17p3: If the left operand is not of class type, the 9867 // expression is implicitly converted (C++ 4) to the 9868 // cv-unqualified type of the left operand. 9869 QualType RHSType = RHS.get()->getType(); 9870 if (Diagnose) { 9871 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9872 AA_Assigning); 9873 } else { 9874 ImplicitConversionSequence ICS = 9875 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9876 /*SuppressUserConversions=*/false, 9877 AllowedExplicit::None, 9878 /*InOverloadResolution=*/false, 9879 /*CStyle=*/false, 9880 /*AllowObjCWritebackConversion=*/false); 9881 if (ICS.isFailure()) 9882 return Incompatible; 9883 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9884 ICS, AA_Assigning); 9885 } 9886 if (RHS.isInvalid()) 9887 return Incompatible; 9888 Sema::AssignConvertType result = Compatible; 9889 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9890 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9891 result = IncompatibleObjCWeakRef; 9892 return result; 9893 } 9894 9895 // FIXME: Currently, we fall through and treat C++ classes like C 9896 // structures. 9897 // FIXME: We also fall through for atomics; not sure what should 9898 // happen there, though. 9899 } else if (RHS.get()->getType() == Context.OverloadTy) { 9900 // As a set of extensions to C, we support overloading on functions. These 9901 // functions need to be resolved here. 9902 DeclAccessPair DAP; 9903 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9904 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9905 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9906 else 9907 return Incompatible; 9908 } 9909 9910 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9911 // a null pointer constant. 9912 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9913 LHSType->isBlockPointerType()) && 9914 RHS.get()->isNullPointerConstant(Context, 9915 Expr::NPC_ValueDependentIsNull)) { 9916 if (Diagnose || ConvertRHS) { 9917 CastKind Kind; 9918 CXXCastPath Path; 9919 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9920 /*IgnoreBaseAccess=*/false, Diagnose); 9921 if (ConvertRHS) 9922 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9923 } 9924 return Compatible; 9925 } 9926 9927 // OpenCL queue_t type assignment. 9928 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9929 Context, Expr::NPC_ValueDependentIsNull)) { 9930 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9931 return Compatible; 9932 } 9933 9934 // This check seems unnatural, however it is necessary to ensure the proper 9935 // conversion of functions/arrays. If the conversion were done for all 9936 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9937 // expressions that suppress this implicit conversion (&, sizeof). 9938 // 9939 // Suppress this for references: C++ 8.5.3p5. 9940 if (!LHSType->isReferenceType()) { 9941 // FIXME: We potentially allocate here even if ConvertRHS is false. 9942 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9943 if (RHS.isInvalid()) 9944 return Incompatible; 9945 } 9946 CastKind Kind; 9947 Sema::AssignConvertType result = 9948 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9949 9950 // C99 6.5.16.1p2: The value of the right operand is converted to the 9951 // type of the assignment expression. 9952 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9953 // so that we can use references in built-in functions even in C. 9954 // The getNonReferenceType() call makes sure that the resulting expression 9955 // does not have reference type. 9956 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9957 QualType Ty = LHSType.getNonLValueExprType(Context); 9958 Expr *E = RHS.get(); 9959 9960 // Check for various Objective-C errors. If we are not reporting 9961 // diagnostics and just checking for errors, e.g., during overload 9962 // resolution, return Incompatible to indicate the failure. 9963 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9964 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9965 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9966 if (!Diagnose) 9967 return Incompatible; 9968 } 9969 if (getLangOpts().ObjC && 9970 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9971 E->getType(), E, Diagnose) || 9972 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9973 if (!Diagnose) 9974 return Incompatible; 9975 // Replace the expression with a corrected version and continue so we 9976 // can find further errors. 9977 RHS = E; 9978 return Compatible; 9979 } 9980 9981 if (ConvertRHS) 9982 RHS = ImpCastExprToType(E, Ty, Kind); 9983 } 9984 9985 return result; 9986 } 9987 9988 namespace { 9989 /// The original operand to an operator, prior to the application of the usual 9990 /// arithmetic conversions and converting the arguments of a builtin operator 9991 /// candidate. 9992 struct OriginalOperand { 9993 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9994 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9995 Op = MTE->getSubExpr(); 9996 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9997 Op = BTE->getSubExpr(); 9998 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9999 Orig = ICE->getSubExprAsWritten(); 10000 Conversion = ICE->getConversionFunction(); 10001 } 10002 } 10003 10004 QualType getType() const { return Orig->getType(); } 10005 10006 Expr *Orig; 10007 NamedDecl *Conversion; 10008 }; 10009 } 10010 10011 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 10012 ExprResult &RHS) { 10013 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 10014 10015 Diag(Loc, diag::err_typecheck_invalid_operands) 10016 << OrigLHS.getType() << OrigRHS.getType() 10017 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10018 10019 // If a user-defined conversion was applied to either of the operands prior 10020 // to applying the built-in operator rules, tell the user about it. 10021 if (OrigLHS.Conversion) { 10022 Diag(OrigLHS.Conversion->getLocation(), 10023 diag::note_typecheck_invalid_operands_converted) 10024 << 0 << LHS.get()->getType(); 10025 } 10026 if (OrigRHS.Conversion) { 10027 Diag(OrigRHS.Conversion->getLocation(), 10028 diag::note_typecheck_invalid_operands_converted) 10029 << 1 << RHS.get()->getType(); 10030 } 10031 10032 return QualType(); 10033 } 10034 10035 // Diagnose cases where a scalar was implicitly converted to a vector and 10036 // diagnose the underlying types. Otherwise, diagnose the error 10037 // as invalid vector logical operands for non-C++ cases. 10038 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 10039 ExprResult &RHS) { 10040 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 10041 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 10042 10043 bool LHSNatVec = LHSType->isVectorType(); 10044 bool RHSNatVec = RHSType->isVectorType(); 10045 10046 if (!(LHSNatVec && RHSNatVec)) { 10047 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 10048 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 10049 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10050 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 10051 << Vector->getSourceRange(); 10052 return QualType(); 10053 } 10054 10055 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10056 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 10057 << RHS.get()->getSourceRange(); 10058 10059 return QualType(); 10060 } 10061 10062 /// Try to convert a value of non-vector type to a vector type by converting 10063 /// the type to the element type of the vector and then performing a splat. 10064 /// If the language is OpenCL, we only use conversions that promote scalar 10065 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 10066 /// for float->int. 10067 /// 10068 /// OpenCL V2.0 6.2.6.p2: 10069 /// An error shall occur if any scalar operand type has greater rank 10070 /// than the type of the vector element. 10071 /// 10072 /// \param scalar - if non-null, actually perform the conversions 10073 /// \return true if the operation fails (but without diagnosing the failure) 10074 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 10075 QualType scalarTy, 10076 QualType vectorEltTy, 10077 QualType vectorTy, 10078 unsigned &DiagID) { 10079 // The conversion to apply to the scalar before splatting it, 10080 // if necessary. 10081 CastKind scalarCast = CK_NoOp; 10082 10083 if (vectorEltTy->isIntegralType(S.Context)) { 10084 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 10085 (scalarTy->isIntegerType() && 10086 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 10087 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10088 return true; 10089 } 10090 if (!scalarTy->isIntegralType(S.Context)) 10091 return true; 10092 scalarCast = CK_IntegralCast; 10093 } else if (vectorEltTy->isRealFloatingType()) { 10094 if (scalarTy->isRealFloatingType()) { 10095 if (S.getLangOpts().OpenCL && 10096 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 10097 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10098 return true; 10099 } 10100 scalarCast = CK_FloatingCast; 10101 } 10102 else if (scalarTy->isIntegralType(S.Context)) 10103 scalarCast = CK_IntegralToFloating; 10104 else 10105 return true; 10106 } else { 10107 return true; 10108 } 10109 10110 // Adjust scalar if desired. 10111 if (scalar) { 10112 if (scalarCast != CK_NoOp) 10113 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 10114 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 10115 } 10116 return false; 10117 } 10118 10119 /// Convert vector E to a vector with the same number of elements but different 10120 /// element type. 10121 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 10122 const auto *VecTy = E->getType()->getAs<VectorType>(); 10123 assert(VecTy && "Expression E must be a vector"); 10124 QualType NewVecTy = 10125 VecTy->isExtVectorType() 10126 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements()) 10127 : S.Context.getVectorType(ElementType, VecTy->getNumElements(), 10128 VecTy->getVectorKind()); 10129 10130 // Look through the implicit cast. Return the subexpression if its type is 10131 // NewVecTy. 10132 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10133 if (ICE->getSubExpr()->getType() == NewVecTy) 10134 return ICE->getSubExpr(); 10135 10136 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 10137 return S.ImpCastExprToType(E, NewVecTy, Cast); 10138 } 10139 10140 /// Test if a (constant) integer Int can be casted to another integer type 10141 /// IntTy without losing precision. 10142 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 10143 QualType OtherIntTy) { 10144 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10145 10146 // Reject cases where the value of the Int is unknown as that would 10147 // possibly cause truncation, but accept cases where the scalar can be 10148 // demoted without loss of precision. 10149 Expr::EvalResult EVResult; 10150 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10151 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 10152 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 10153 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 10154 10155 if (CstInt) { 10156 // If the scalar is constant and is of a higher order and has more active 10157 // bits that the vector element type, reject it. 10158 llvm::APSInt Result = EVResult.Val.getInt(); 10159 unsigned NumBits = IntSigned 10160 ? (Result.isNegative() ? Result.getMinSignedBits() 10161 : Result.getActiveBits()) 10162 : Result.getActiveBits(); 10163 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 10164 return true; 10165 10166 // If the signedness of the scalar type and the vector element type 10167 // differs and the number of bits is greater than that of the vector 10168 // element reject it. 10169 return (IntSigned != OtherIntSigned && 10170 NumBits > S.Context.getIntWidth(OtherIntTy)); 10171 } 10172 10173 // Reject cases where the value of the scalar is not constant and it's 10174 // order is greater than that of the vector element type. 10175 return (Order < 0); 10176 } 10177 10178 /// Test if a (constant) integer Int can be casted to floating point type 10179 /// FloatTy without losing precision. 10180 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 10181 QualType FloatTy) { 10182 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10183 10184 // Determine if the integer constant can be expressed as a floating point 10185 // number of the appropriate type. 10186 Expr::EvalResult EVResult; 10187 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10188 10189 uint64_t Bits = 0; 10190 if (CstInt) { 10191 // Reject constants that would be truncated if they were converted to 10192 // the floating point type. Test by simple to/from conversion. 10193 // FIXME: Ideally the conversion to an APFloat and from an APFloat 10194 // could be avoided if there was a convertFromAPInt method 10195 // which could signal back if implicit truncation occurred. 10196 llvm::APSInt Result = EVResult.Val.getInt(); 10197 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 10198 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 10199 llvm::APFloat::rmTowardZero); 10200 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 10201 !IntTy->hasSignedIntegerRepresentation()); 10202 bool Ignored = false; 10203 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 10204 &Ignored); 10205 if (Result != ConvertBack) 10206 return true; 10207 } else { 10208 // Reject types that cannot be fully encoded into the mantissa of 10209 // the float. 10210 Bits = S.Context.getTypeSize(IntTy); 10211 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 10212 S.Context.getFloatTypeSemantics(FloatTy)); 10213 if (Bits > FloatPrec) 10214 return true; 10215 } 10216 10217 return false; 10218 } 10219 10220 /// Attempt to convert and splat Scalar into a vector whose types matches 10221 /// Vector following GCC conversion rules. The rule is that implicit 10222 /// conversion can occur when Scalar can be casted to match Vector's element 10223 /// type without causing truncation of Scalar. 10224 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 10225 ExprResult *Vector) { 10226 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 10227 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 10228 const auto *VT = VectorTy->castAs<VectorType>(); 10229 10230 assert(!isa<ExtVectorType>(VT) && 10231 "ExtVectorTypes should not be handled here!"); 10232 10233 QualType VectorEltTy = VT->getElementType(); 10234 10235 // Reject cases where the vector element type or the scalar element type are 10236 // not integral or floating point types. 10237 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 10238 return true; 10239 10240 // The conversion to apply to the scalar before splatting it, 10241 // if necessary. 10242 CastKind ScalarCast = CK_NoOp; 10243 10244 // Accept cases where the vector elements are integers and the scalar is 10245 // an integer. 10246 // FIXME: Notionally if the scalar was a floating point value with a precise 10247 // integral representation, we could cast it to an appropriate integer 10248 // type and then perform the rest of the checks here. GCC will perform 10249 // this conversion in some cases as determined by the input language. 10250 // We should accept it on a language independent basis. 10251 if (VectorEltTy->isIntegralType(S.Context) && 10252 ScalarTy->isIntegralType(S.Context) && 10253 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10254 10255 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10256 return true; 10257 10258 ScalarCast = CK_IntegralCast; 10259 } else if (VectorEltTy->isIntegralType(S.Context) && 10260 ScalarTy->isRealFloatingType()) { 10261 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10262 ScalarCast = CK_FloatingToIntegral; 10263 else 10264 return true; 10265 } else if (VectorEltTy->isRealFloatingType()) { 10266 if (ScalarTy->isRealFloatingType()) { 10267 10268 // Reject cases where the scalar type is not a constant and has a higher 10269 // Order than the vector element type. 10270 llvm::APFloat Result(0.0); 10271 10272 // Determine whether this is a constant scalar. In the event that the 10273 // value is dependent (and thus cannot be evaluated by the constant 10274 // evaluator), skip the evaluation. This will then diagnose once the 10275 // expression is instantiated. 10276 bool CstScalar = Scalar->get()->isValueDependent() || 10277 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10278 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10279 if (!CstScalar && Order < 0) 10280 return true; 10281 10282 // If the scalar cannot be safely casted to the vector element type, 10283 // reject it. 10284 if (CstScalar) { 10285 bool Truncated = false; 10286 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10287 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10288 if (Truncated) 10289 return true; 10290 } 10291 10292 ScalarCast = CK_FloatingCast; 10293 } else if (ScalarTy->isIntegralType(S.Context)) { 10294 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10295 return true; 10296 10297 ScalarCast = CK_IntegralToFloating; 10298 } else 10299 return true; 10300 } else if (ScalarTy->isEnumeralType()) 10301 return true; 10302 10303 // Adjust scalar if desired. 10304 if (Scalar) { 10305 if (ScalarCast != CK_NoOp) 10306 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10307 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10308 } 10309 return false; 10310 } 10311 10312 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10313 SourceLocation Loc, bool IsCompAssign, 10314 bool AllowBothBool, 10315 bool AllowBoolConversions, 10316 bool AllowBoolOperation, 10317 bool ReportInvalid) { 10318 if (!IsCompAssign) { 10319 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10320 if (LHS.isInvalid()) 10321 return QualType(); 10322 } 10323 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10324 if (RHS.isInvalid()) 10325 return QualType(); 10326 10327 // For conversion purposes, we ignore any qualifiers. 10328 // For example, "const float" and "float" are equivalent. 10329 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10330 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10331 10332 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10333 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10334 assert(LHSVecType || RHSVecType); 10335 10336 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10337 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10338 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10339 10340 // AltiVec-style "vector bool op vector bool" combinations are allowed 10341 // for some operators but not others. 10342 if (!AllowBothBool && 10343 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10344 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10345 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10346 10347 // This operation may not be performed on boolean vectors. 10348 if (!AllowBoolOperation && 10349 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) 10350 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10351 10352 // If the vector types are identical, return. 10353 if (Context.hasSameType(LHSType, RHSType)) 10354 return LHSType; 10355 10356 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10357 if (LHSVecType && RHSVecType && 10358 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10359 if (isa<ExtVectorType>(LHSVecType)) { 10360 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10361 return LHSType; 10362 } 10363 10364 if (!IsCompAssign) 10365 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10366 return RHSType; 10367 } 10368 10369 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10370 // can be mixed, with the result being the non-bool type. The non-bool 10371 // operand must have integer element type. 10372 if (AllowBoolConversions && LHSVecType && RHSVecType && 10373 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10374 (Context.getTypeSize(LHSVecType->getElementType()) == 10375 Context.getTypeSize(RHSVecType->getElementType()))) { 10376 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10377 LHSVecType->getElementType()->isIntegerType() && 10378 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10379 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10380 return LHSType; 10381 } 10382 if (!IsCompAssign && 10383 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10384 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10385 RHSVecType->getElementType()->isIntegerType()) { 10386 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10387 return RHSType; 10388 } 10389 } 10390 10391 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10392 // since the ambiguity can affect the ABI. 10393 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10394 const VectorType *VecType = SecondType->getAs<VectorType>(); 10395 return FirstType->isSizelessBuiltinType() && VecType && 10396 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10397 VecType->getVectorKind() == 10398 VectorType::SveFixedLengthPredicateVector); 10399 }; 10400 10401 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10402 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10403 return QualType(); 10404 } 10405 10406 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10407 // since the ambiguity can affect the ABI. 10408 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10409 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10410 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10411 10412 if (FirstVecType && SecondVecType) 10413 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10414 (SecondVecType->getVectorKind() == 10415 VectorType::SveFixedLengthDataVector || 10416 SecondVecType->getVectorKind() == 10417 VectorType::SveFixedLengthPredicateVector); 10418 10419 return FirstType->isSizelessBuiltinType() && SecondVecType && 10420 SecondVecType->getVectorKind() == VectorType::GenericVector; 10421 }; 10422 10423 if (IsSveGnuConversion(LHSType, RHSType) || 10424 IsSveGnuConversion(RHSType, LHSType)) { 10425 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10426 return QualType(); 10427 } 10428 10429 // If there's a vector type and a scalar, try to convert the scalar to 10430 // the vector element type and splat. 10431 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10432 if (!RHSVecType) { 10433 if (isa<ExtVectorType>(LHSVecType)) { 10434 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10435 LHSVecType->getElementType(), LHSType, 10436 DiagID)) 10437 return LHSType; 10438 } else { 10439 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10440 return LHSType; 10441 } 10442 } 10443 if (!LHSVecType) { 10444 if (isa<ExtVectorType>(RHSVecType)) { 10445 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10446 LHSType, RHSVecType->getElementType(), 10447 RHSType, DiagID)) 10448 return RHSType; 10449 } else { 10450 if (LHS.get()->isLValue() || 10451 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10452 return RHSType; 10453 } 10454 } 10455 10456 // FIXME: The code below also handles conversion between vectors and 10457 // non-scalars, we should break this down into fine grained specific checks 10458 // and emit proper diagnostics. 10459 QualType VecType = LHSVecType ? LHSType : RHSType; 10460 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10461 QualType OtherType = LHSVecType ? RHSType : LHSType; 10462 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10463 if (isLaxVectorConversion(OtherType, VecType)) { 10464 // If we're allowing lax vector conversions, only the total (data) size 10465 // needs to be the same. For non compound assignment, if one of the types is 10466 // scalar, the result is always the vector type. 10467 if (!IsCompAssign) { 10468 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10469 return VecType; 10470 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10471 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10472 // type. Note that this is already done by non-compound assignments in 10473 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10474 // <1 x T> -> T. The result is also a vector type. 10475 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10476 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10477 ExprResult *RHSExpr = &RHS; 10478 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10479 return VecType; 10480 } 10481 } 10482 10483 // Okay, the expression is invalid. 10484 10485 // If there's a non-vector, non-real operand, diagnose that. 10486 if ((!RHSVecType && !RHSType->isRealType()) || 10487 (!LHSVecType && !LHSType->isRealType())) { 10488 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10489 << LHSType << RHSType 10490 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10491 return QualType(); 10492 } 10493 10494 // OpenCL V1.1 6.2.6.p1: 10495 // If the operands are of more than one vector type, then an error shall 10496 // occur. Implicit conversions between vector types are not permitted, per 10497 // section 6.2.1. 10498 if (getLangOpts().OpenCL && 10499 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10500 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10501 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10502 << RHSType; 10503 return QualType(); 10504 } 10505 10506 10507 // If there is a vector type that is not a ExtVector and a scalar, we reach 10508 // this point if scalar could not be converted to the vector's element type 10509 // without truncation. 10510 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10511 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10512 QualType Scalar = LHSVecType ? RHSType : LHSType; 10513 QualType Vector = LHSVecType ? LHSType : RHSType; 10514 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10515 Diag(Loc, 10516 diag::err_typecheck_vector_not_convertable_implict_truncation) 10517 << ScalarOrVector << Scalar << Vector; 10518 10519 return QualType(); 10520 } 10521 10522 // Otherwise, use the generic diagnostic. 10523 Diag(Loc, DiagID) 10524 << LHSType << RHSType 10525 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10526 return QualType(); 10527 } 10528 10529 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, 10530 SourceLocation Loc, 10531 bool IsCompAssign, 10532 ArithConvKind OperationKind) { 10533 if (!IsCompAssign) { 10534 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10535 if (LHS.isInvalid()) 10536 return QualType(); 10537 } 10538 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10539 if (RHS.isInvalid()) 10540 return QualType(); 10541 10542 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10543 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10544 10545 unsigned DiagID = diag::err_typecheck_invalid_operands; 10546 if ((OperationKind == ACK_Arithmetic) && 10547 (LHSType->castAs<BuiltinType>()->isSVEBool() || 10548 RHSType->castAs<BuiltinType>()->isSVEBool())) { 10549 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10550 << RHS.get()->getSourceRange(); 10551 return QualType(); 10552 } 10553 10554 if (Context.hasSameType(LHSType, RHSType)) 10555 return LHSType; 10556 10557 auto tryScalableVectorConvert = [this](ExprResult *Src, QualType SrcType, 10558 QualType DestType) { 10559 const QualType DestBaseType = DestType->getSveEltType(Context); 10560 if (DestBaseType->getUnqualifiedDesugaredType() == 10561 SrcType->getUnqualifiedDesugaredType()) { 10562 unsigned DiagID = diag::err_typecheck_invalid_operands; 10563 if (!tryVectorConvertAndSplat(*this, Src, SrcType, DestBaseType, DestType, 10564 DiagID)) 10565 return DestType; 10566 } 10567 return QualType(); 10568 }; 10569 10570 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) { 10571 auto DestType = tryScalableVectorConvert(&RHS, RHSType, LHSType); 10572 if (DestType == QualType()) 10573 return InvalidOperands(Loc, LHS, RHS); 10574 return DestType; 10575 } 10576 10577 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) { 10578 auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS), 10579 LHSType, RHSType); 10580 if (DestType == QualType()) 10581 return InvalidOperands(Loc, LHS, RHS); 10582 return DestType; 10583 } 10584 10585 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10586 << RHS.get()->getSourceRange(); 10587 return QualType(); 10588 } 10589 10590 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10591 // expression. These are mainly cases where the null pointer is used as an 10592 // integer instead of a pointer. 10593 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10594 SourceLocation Loc, bool IsCompare) { 10595 // The canonical way to check for a GNU null is with isNullPointerConstant, 10596 // but we use a bit of a hack here for speed; this is a relatively 10597 // hot path, and isNullPointerConstant is slow. 10598 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10599 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10600 10601 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10602 10603 // Avoid analyzing cases where the result will either be invalid (and 10604 // diagnosed as such) or entirely valid and not something to warn about. 10605 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10606 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10607 return; 10608 10609 // Comparison operations would not make sense with a null pointer no matter 10610 // what the other expression is. 10611 if (!IsCompare) { 10612 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10613 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10614 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10615 return; 10616 } 10617 10618 // The rest of the operations only make sense with a null pointer 10619 // if the other expression is a pointer. 10620 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10621 NonNullType->canDecayToPointerType()) 10622 return; 10623 10624 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10625 << LHSNull /* LHS is NULL */ << NonNullType 10626 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10627 } 10628 10629 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10630 SourceLocation Loc) { 10631 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10632 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10633 if (!LUE || !RUE) 10634 return; 10635 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10636 RUE->getKind() != UETT_SizeOf) 10637 return; 10638 10639 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10640 QualType LHSTy = LHSArg->getType(); 10641 QualType RHSTy; 10642 10643 if (RUE->isArgumentType()) 10644 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10645 else 10646 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10647 10648 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10649 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10650 return; 10651 10652 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10653 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10654 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10655 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10656 << LHSArgDecl; 10657 } 10658 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10659 QualType ArrayElemTy = ArrayTy->getElementType(); 10660 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10661 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10662 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10663 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10664 return; 10665 S.Diag(Loc, diag::warn_division_sizeof_array) 10666 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10667 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10668 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10669 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10670 << LHSArgDecl; 10671 } 10672 10673 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10674 } 10675 } 10676 10677 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10678 ExprResult &RHS, 10679 SourceLocation Loc, bool IsDiv) { 10680 // Check for division/remainder by zero. 10681 Expr::EvalResult RHSValue; 10682 if (!RHS.get()->isValueDependent() && 10683 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10684 RHSValue.Val.getInt() == 0) 10685 S.DiagRuntimeBehavior(Loc, RHS.get(), 10686 S.PDiag(diag::warn_remainder_division_by_zero) 10687 << IsDiv << RHS.get()->getSourceRange()); 10688 } 10689 10690 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10691 SourceLocation Loc, 10692 bool IsCompAssign, bool IsDiv) { 10693 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10694 10695 QualType LHSTy = LHS.get()->getType(); 10696 QualType RHSTy = RHS.get()->getType(); 10697 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10698 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10699 /*AllowBothBool*/ getLangOpts().AltiVec, 10700 /*AllowBoolConversions*/ false, 10701 /*AllowBooleanOperation*/ false, 10702 /*ReportInvalid*/ true); 10703 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType()) 10704 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 10705 ACK_Arithmetic); 10706 if (!IsDiv && 10707 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10708 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10709 // For division, only matrix-by-scalar is supported. Other combinations with 10710 // matrix types are invalid. 10711 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10712 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10713 10714 QualType compType = UsualArithmeticConversions( 10715 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10716 if (LHS.isInvalid() || RHS.isInvalid()) 10717 return QualType(); 10718 10719 10720 if (compType.isNull() || !compType->isArithmeticType()) 10721 return InvalidOperands(Loc, LHS, RHS); 10722 if (IsDiv) { 10723 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10724 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10725 } 10726 return compType; 10727 } 10728 10729 QualType Sema::CheckRemainderOperands( 10730 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10731 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10732 10733 if (LHS.get()->getType()->isVectorType() || 10734 RHS.get()->getType()->isVectorType()) { 10735 if (LHS.get()->getType()->hasIntegerRepresentation() && 10736 RHS.get()->getType()->hasIntegerRepresentation()) 10737 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10738 /*AllowBothBool*/ getLangOpts().AltiVec, 10739 /*AllowBoolConversions*/ false, 10740 /*AllowBooleanOperation*/ false, 10741 /*ReportInvalid*/ true); 10742 return InvalidOperands(Loc, LHS, RHS); 10743 } 10744 10745 if (LHS.get()->getType()->isVLSTBuiltinType() || 10746 RHS.get()->getType()->isVLSTBuiltinType()) { 10747 if (LHS.get()->getType()->hasIntegerRepresentation() && 10748 RHS.get()->getType()->hasIntegerRepresentation()) 10749 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 10750 ACK_Arithmetic); 10751 10752 return InvalidOperands(Loc, LHS, RHS); 10753 } 10754 10755 QualType compType = UsualArithmeticConversions( 10756 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10757 if (LHS.isInvalid() || RHS.isInvalid()) 10758 return QualType(); 10759 10760 if (compType.isNull() || !compType->isIntegerType()) 10761 return InvalidOperands(Loc, LHS, RHS); 10762 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10763 return compType; 10764 } 10765 10766 /// Diagnose invalid arithmetic on two void pointers. 10767 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10768 Expr *LHSExpr, Expr *RHSExpr) { 10769 S.Diag(Loc, S.getLangOpts().CPlusPlus 10770 ? diag::err_typecheck_pointer_arith_void_type 10771 : diag::ext_gnu_void_ptr) 10772 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10773 << RHSExpr->getSourceRange(); 10774 } 10775 10776 /// Diagnose invalid arithmetic on a void pointer. 10777 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10778 Expr *Pointer) { 10779 S.Diag(Loc, S.getLangOpts().CPlusPlus 10780 ? diag::err_typecheck_pointer_arith_void_type 10781 : diag::ext_gnu_void_ptr) 10782 << 0 /* one pointer */ << Pointer->getSourceRange(); 10783 } 10784 10785 /// Diagnose invalid arithmetic on a null pointer. 10786 /// 10787 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10788 /// idiom, which we recognize as a GNU extension. 10789 /// 10790 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10791 Expr *Pointer, bool IsGNUIdiom) { 10792 if (IsGNUIdiom) 10793 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10794 << Pointer->getSourceRange(); 10795 else 10796 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10797 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10798 } 10799 10800 /// Diagnose invalid subraction on a null pointer. 10801 /// 10802 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10803 Expr *Pointer, bool BothNull) { 10804 // Null - null is valid in C++ [expr.add]p7 10805 if (BothNull && S.getLangOpts().CPlusPlus) 10806 return; 10807 10808 // Is this s a macro from a system header? 10809 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10810 return; 10811 10812 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10813 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10814 } 10815 10816 /// Diagnose invalid arithmetic on two function pointers. 10817 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10818 Expr *LHS, Expr *RHS) { 10819 assert(LHS->getType()->isAnyPointerType()); 10820 assert(RHS->getType()->isAnyPointerType()); 10821 S.Diag(Loc, S.getLangOpts().CPlusPlus 10822 ? diag::err_typecheck_pointer_arith_function_type 10823 : diag::ext_gnu_ptr_func_arith) 10824 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10825 // We only show the second type if it differs from the first. 10826 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10827 RHS->getType()) 10828 << RHS->getType()->getPointeeType() 10829 << LHS->getSourceRange() << RHS->getSourceRange(); 10830 } 10831 10832 /// Diagnose invalid arithmetic on a function pointer. 10833 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10834 Expr *Pointer) { 10835 assert(Pointer->getType()->isAnyPointerType()); 10836 S.Diag(Loc, S.getLangOpts().CPlusPlus 10837 ? diag::err_typecheck_pointer_arith_function_type 10838 : diag::ext_gnu_ptr_func_arith) 10839 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10840 << 0 /* one pointer, so only one type */ 10841 << Pointer->getSourceRange(); 10842 } 10843 10844 /// Emit error if Operand is incomplete pointer type 10845 /// 10846 /// \returns True if pointer has incomplete type 10847 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10848 Expr *Operand) { 10849 QualType ResType = Operand->getType(); 10850 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10851 ResType = ResAtomicType->getValueType(); 10852 10853 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10854 QualType PointeeTy = ResType->getPointeeType(); 10855 return S.RequireCompleteSizedType( 10856 Loc, PointeeTy, 10857 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10858 Operand->getSourceRange()); 10859 } 10860 10861 /// Check the validity of an arithmetic pointer operand. 10862 /// 10863 /// If the operand has pointer type, this code will check for pointer types 10864 /// which are invalid in arithmetic operations. These will be diagnosed 10865 /// appropriately, including whether or not the use is supported as an 10866 /// extension. 10867 /// 10868 /// \returns True when the operand is valid to use (even if as an extension). 10869 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10870 Expr *Operand) { 10871 QualType ResType = Operand->getType(); 10872 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10873 ResType = ResAtomicType->getValueType(); 10874 10875 if (!ResType->isAnyPointerType()) return true; 10876 10877 QualType PointeeTy = ResType->getPointeeType(); 10878 if (PointeeTy->isVoidType()) { 10879 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10880 return !S.getLangOpts().CPlusPlus; 10881 } 10882 if (PointeeTy->isFunctionType()) { 10883 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10884 return !S.getLangOpts().CPlusPlus; 10885 } 10886 10887 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10888 10889 return true; 10890 } 10891 10892 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10893 /// operands. 10894 /// 10895 /// This routine will diagnose any invalid arithmetic on pointer operands much 10896 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10897 /// for emitting a single diagnostic even for operations where both LHS and RHS 10898 /// are (potentially problematic) pointers. 10899 /// 10900 /// \returns True when the operand is valid to use (even if as an extension). 10901 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10902 Expr *LHSExpr, Expr *RHSExpr) { 10903 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10904 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10905 if (!isLHSPointer && !isRHSPointer) return true; 10906 10907 QualType LHSPointeeTy, RHSPointeeTy; 10908 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10909 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10910 10911 // if both are pointers check if operation is valid wrt address spaces 10912 if (isLHSPointer && isRHSPointer) { 10913 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10914 S.Diag(Loc, 10915 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10916 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10917 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10918 return false; 10919 } 10920 } 10921 10922 // Check for arithmetic on pointers to incomplete types. 10923 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10924 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10925 if (isLHSVoidPtr || isRHSVoidPtr) { 10926 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10927 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10928 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10929 10930 return !S.getLangOpts().CPlusPlus; 10931 } 10932 10933 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10934 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10935 if (isLHSFuncPtr || isRHSFuncPtr) { 10936 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10937 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10938 RHSExpr); 10939 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10940 10941 return !S.getLangOpts().CPlusPlus; 10942 } 10943 10944 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10945 return false; 10946 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10947 return false; 10948 10949 return true; 10950 } 10951 10952 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10953 /// literal. 10954 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10955 Expr *LHSExpr, Expr *RHSExpr) { 10956 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10957 Expr* IndexExpr = RHSExpr; 10958 if (!StrExpr) { 10959 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10960 IndexExpr = LHSExpr; 10961 } 10962 10963 bool IsStringPlusInt = StrExpr && 10964 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10965 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10966 return; 10967 10968 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10969 Self.Diag(OpLoc, diag::warn_string_plus_int) 10970 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10971 10972 // Only print a fixit for "str" + int, not for int + "str". 10973 if (IndexExpr == RHSExpr) { 10974 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10975 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10976 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10977 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10978 << FixItHint::CreateInsertion(EndLoc, "]"); 10979 } else 10980 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10981 } 10982 10983 /// Emit a warning when adding a char literal to a string. 10984 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10985 Expr *LHSExpr, Expr *RHSExpr) { 10986 const Expr *StringRefExpr = LHSExpr; 10987 const CharacterLiteral *CharExpr = 10988 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10989 10990 if (!CharExpr) { 10991 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10992 StringRefExpr = RHSExpr; 10993 } 10994 10995 if (!CharExpr || !StringRefExpr) 10996 return; 10997 10998 const QualType StringType = StringRefExpr->getType(); 10999 11000 // Return if not a PointerType. 11001 if (!StringType->isAnyPointerType()) 11002 return; 11003 11004 // Return if not a CharacterType. 11005 if (!StringType->getPointeeType()->isAnyCharacterType()) 11006 return; 11007 11008 ASTContext &Ctx = Self.getASTContext(); 11009 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 11010 11011 const QualType CharType = CharExpr->getType(); 11012 if (!CharType->isAnyCharacterType() && 11013 CharType->isIntegerType() && 11014 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 11015 Self.Diag(OpLoc, diag::warn_string_plus_char) 11016 << DiagRange << Ctx.CharTy; 11017 } else { 11018 Self.Diag(OpLoc, diag::warn_string_plus_char) 11019 << DiagRange << CharExpr->getType(); 11020 } 11021 11022 // Only print a fixit for str + char, not for char + str. 11023 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 11024 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 11025 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 11026 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 11027 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 11028 << FixItHint::CreateInsertion(EndLoc, "]"); 11029 } else { 11030 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 11031 } 11032 } 11033 11034 /// Emit error when two pointers are incompatible. 11035 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 11036 Expr *LHSExpr, Expr *RHSExpr) { 11037 assert(LHSExpr->getType()->isAnyPointerType()); 11038 assert(RHSExpr->getType()->isAnyPointerType()); 11039 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 11040 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 11041 << RHSExpr->getSourceRange(); 11042 } 11043 11044 // C99 6.5.6 11045 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 11046 SourceLocation Loc, BinaryOperatorKind Opc, 11047 QualType* CompLHSTy) { 11048 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11049 11050 if (LHS.get()->getType()->isVectorType() || 11051 RHS.get()->getType()->isVectorType()) { 11052 QualType compType = 11053 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11054 /*AllowBothBool*/ getLangOpts().AltiVec, 11055 /*AllowBoolConversions*/ getLangOpts().ZVector, 11056 /*AllowBooleanOperation*/ false, 11057 /*ReportInvalid*/ true); 11058 if (CompLHSTy) *CompLHSTy = compType; 11059 return compType; 11060 } 11061 11062 if (LHS.get()->getType()->isVLSTBuiltinType() || 11063 RHS.get()->getType()->isVLSTBuiltinType()) { 11064 QualType compType = 11065 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11066 if (CompLHSTy) 11067 *CompLHSTy = compType; 11068 return compType; 11069 } 11070 11071 if (LHS.get()->getType()->isConstantMatrixType() || 11072 RHS.get()->getType()->isConstantMatrixType()) { 11073 QualType compType = 11074 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11075 if (CompLHSTy) 11076 *CompLHSTy = compType; 11077 return compType; 11078 } 11079 11080 QualType compType = UsualArithmeticConversions( 11081 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11082 if (LHS.isInvalid() || RHS.isInvalid()) 11083 return QualType(); 11084 11085 // Diagnose "string literal" '+' int and string '+' "char literal". 11086 if (Opc == BO_Add) { 11087 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 11088 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 11089 } 11090 11091 // handle the common case first (both operands are arithmetic). 11092 if (!compType.isNull() && compType->isArithmeticType()) { 11093 if (CompLHSTy) *CompLHSTy = compType; 11094 return compType; 11095 } 11096 11097 // Type-checking. Ultimately the pointer's going to be in PExp; 11098 // note that we bias towards the LHS being the pointer. 11099 Expr *PExp = LHS.get(), *IExp = RHS.get(); 11100 11101 bool isObjCPointer; 11102 if (PExp->getType()->isPointerType()) { 11103 isObjCPointer = false; 11104 } else if (PExp->getType()->isObjCObjectPointerType()) { 11105 isObjCPointer = true; 11106 } else { 11107 std::swap(PExp, IExp); 11108 if (PExp->getType()->isPointerType()) { 11109 isObjCPointer = false; 11110 } else if (PExp->getType()->isObjCObjectPointerType()) { 11111 isObjCPointer = true; 11112 } else { 11113 return InvalidOperands(Loc, LHS, RHS); 11114 } 11115 } 11116 assert(PExp->getType()->isAnyPointerType()); 11117 11118 if (!IExp->getType()->isIntegerType()) 11119 return InvalidOperands(Loc, LHS, RHS); 11120 11121 // Adding to a null pointer results in undefined behavior. 11122 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 11123 Context, Expr::NPC_ValueDependentIsNotNull)) { 11124 // In C++ adding zero to a null pointer is defined. 11125 Expr::EvalResult KnownVal; 11126 if (!getLangOpts().CPlusPlus || 11127 (!IExp->isValueDependent() && 11128 (!IExp->EvaluateAsInt(KnownVal, Context) || 11129 KnownVal.Val.getInt() != 0))) { 11130 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 11131 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 11132 Context, BO_Add, PExp, IExp); 11133 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 11134 } 11135 } 11136 11137 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 11138 return QualType(); 11139 11140 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 11141 return QualType(); 11142 11143 // Check array bounds for pointer arithemtic 11144 CheckArrayAccess(PExp, IExp); 11145 11146 if (CompLHSTy) { 11147 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 11148 if (LHSTy.isNull()) { 11149 LHSTy = LHS.get()->getType(); 11150 if (LHSTy->isPromotableIntegerType()) 11151 LHSTy = Context.getPromotedIntegerType(LHSTy); 11152 } 11153 *CompLHSTy = LHSTy; 11154 } 11155 11156 return PExp->getType(); 11157 } 11158 11159 // C99 6.5.6 11160 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 11161 SourceLocation Loc, 11162 QualType* CompLHSTy) { 11163 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11164 11165 if (LHS.get()->getType()->isVectorType() || 11166 RHS.get()->getType()->isVectorType()) { 11167 QualType compType = 11168 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11169 /*AllowBothBool*/ getLangOpts().AltiVec, 11170 /*AllowBoolConversions*/ getLangOpts().ZVector, 11171 /*AllowBooleanOperation*/ false, 11172 /*ReportInvalid*/ true); 11173 if (CompLHSTy) *CompLHSTy = compType; 11174 return compType; 11175 } 11176 11177 if (LHS.get()->getType()->isVLSTBuiltinType() || 11178 RHS.get()->getType()->isVLSTBuiltinType()) { 11179 QualType compType = 11180 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11181 if (CompLHSTy) 11182 *CompLHSTy = compType; 11183 return compType; 11184 } 11185 11186 if (LHS.get()->getType()->isConstantMatrixType() || 11187 RHS.get()->getType()->isConstantMatrixType()) { 11188 QualType compType = 11189 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11190 if (CompLHSTy) 11191 *CompLHSTy = compType; 11192 return compType; 11193 } 11194 11195 QualType compType = UsualArithmeticConversions( 11196 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11197 if (LHS.isInvalid() || RHS.isInvalid()) 11198 return QualType(); 11199 11200 // Enforce type constraints: C99 6.5.6p3. 11201 11202 // Handle the common case first (both operands are arithmetic). 11203 if (!compType.isNull() && compType->isArithmeticType()) { 11204 if (CompLHSTy) *CompLHSTy = compType; 11205 return compType; 11206 } 11207 11208 // Either ptr - int or ptr - ptr. 11209 if (LHS.get()->getType()->isAnyPointerType()) { 11210 QualType lpointee = LHS.get()->getType()->getPointeeType(); 11211 11212 // Diagnose bad cases where we step over interface counts. 11213 if (LHS.get()->getType()->isObjCObjectPointerType() && 11214 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 11215 return QualType(); 11216 11217 // The result type of a pointer-int computation is the pointer type. 11218 if (RHS.get()->getType()->isIntegerType()) { 11219 // Subtracting from a null pointer should produce a warning. 11220 // The last argument to the diagnose call says this doesn't match the 11221 // GNU int-to-pointer idiom. 11222 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 11223 Expr::NPC_ValueDependentIsNotNull)) { 11224 // In C++ adding zero to a null pointer is defined. 11225 Expr::EvalResult KnownVal; 11226 if (!getLangOpts().CPlusPlus || 11227 (!RHS.get()->isValueDependent() && 11228 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 11229 KnownVal.Val.getInt() != 0))) { 11230 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 11231 } 11232 } 11233 11234 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 11235 return QualType(); 11236 11237 // Check array bounds for pointer arithemtic 11238 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 11239 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 11240 11241 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11242 return LHS.get()->getType(); 11243 } 11244 11245 // Handle pointer-pointer subtractions. 11246 if (const PointerType *RHSPTy 11247 = RHS.get()->getType()->getAs<PointerType>()) { 11248 QualType rpointee = RHSPTy->getPointeeType(); 11249 11250 if (getLangOpts().CPlusPlus) { 11251 // Pointee types must be the same: C++ [expr.add] 11252 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 11253 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11254 } 11255 } else { 11256 // Pointee types must be compatible C99 6.5.6p3 11257 if (!Context.typesAreCompatible( 11258 Context.getCanonicalType(lpointee).getUnqualifiedType(), 11259 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 11260 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11261 return QualType(); 11262 } 11263 } 11264 11265 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 11266 LHS.get(), RHS.get())) 11267 return QualType(); 11268 11269 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11270 Context, Expr::NPC_ValueDependentIsNotNull); 11271 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11272 Context, Expr::NPC_ValueDependentIsNotNull); 11273 11274 // Subtracting nullptr or from nullptr is suspect 11275 if (LHSIsNullPtr) 11276 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 11277 if (RHSIsNullPtr) 11278 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 11279 11280 // The pointee type may have zero size. As an extension, a structure or 11281 // union may have zero size or an array may have zero length. In this 11282 // case subtraction does not make sense. 11283 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 11284 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 11285 if (ElementSize.isZero()) { 11286 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 11287 << rpointee.getUnqualifiedType() 11288 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11289 } 11290 } 11291 11292 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11293 return Context.getPointerDiffType(); 11294 } 11295 } 11296 11297 return InvalidOperands(Loc, LHS, RHS); 11298 } 11299 11300 static bool isScopedEnumerationType(QualType T) { 11301 if (const EnumType *ET = T->getAs<EnumType>()) 11302 return ET->getDecl()->isScoped(); 11303 return false; 11304 } 11305 11306 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 11307 SourceLocation Loc, BinaryOperatorKind Opc, 11308 QualType LHSType) { 11309 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 11310 // so skip remaining warnings as we don't want to modify values within Sema. 11311 if (S.getLangOpts().OpenCL) 11312 return; 11313 11314 // Check right/shifter operand 11315 Expr::EvalResult RHSResult; 11316 if (RHS.get()->isValueDependent() || 11317 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 11318 return; 11319 llvm::APSInt Right = RHSResult.Val.getInt(); 11320 11321 if (Right.isNegative()) { 11322 S.DiagRuntimeBehavior(Loc, RHS.get(), 11323 S.PDiag(diag::warn_shift_negative) 11324 << RHS.get()->getSourceRange()); 11325 return; 11326 } 11327 11328 QualType LHSExprType = LHS.get()->getType(); 11329 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 11330 if (LHSExprType->isBitIntType()) 11331 LeftSize = S.Context.getIntWidth(LHSExprType); 11332 else if (LHSExprType->isFixedPointType()) { 11333 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 11334 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 11335 } 11336 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 11337 if (Right.uge(LeftBits)) { 11338 S.DiagRuntimeBehavior(Loc, RHS.get(), 11339 S.PDiag(diag::warn_shift_gt_typewidth) 11340 << RHS.get()->getSourceRange()); 11341 return; 11342 } 11343 11344 // FIXME: We probably need to handle fixed point types specially here. 11345 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 11346 return; 11347 11348 // When left shifting an ICE which is signed, we can check for overflow which 11349 // according to C++ standards prior to C++2a has undefined behavior 11350 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 11351 // more than the maximum value representable in the result type, so never 11352 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11353 // expression is still probably a bug.) 11354 Expr::EvalResult LHSResult; 11355 if (LHS.get()->isValueDependent() || 11356 LHSType->hasUnsignedIntegerRepresentation() || 11357 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11358 return; 11359 llvm::APSInt Left = LHSResult.Val.getInt(); 11360 11361 // If LHS does not have a signed type and non-negative value 11362 // then, the behavior is undefined before C++2a. Warn about it. 11363 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11364 !S.getLangOpts().CPlusPlus20) { 11365 S.DiagRuntimeBehavior(Loc, LHS.get(), 11366 S.PDiag(diag::warn_shift_lhs_negative) 11367 << LHS.get()->getSourceRange()); 11368 return; 11369 } 11370 11371 llvm::APInt ResultBits = 11372 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11373 if (LeftBits.uge(ResultBits)) 11374 return; 11375 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11376 Result = Result.shl(Right); 11377 11378 // Print the bit representation of the signed integer as an unsigned 11379 // hexadecimal number. 11380 SmallString<40> HexResult; 11381 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11382 11383 // If we are only missing a sign bit, this is less likely to result in actual 11384 // bugs -- if the result is cast back to an unsigned type, it will have the 11385 // expected value. Thus we place this behind a different warning that can be 11386 // turned off separately if needed. 11387 if (LeftBits == ResultBits - 1) { 11388 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11389 << HexResult << LHSType 11390 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11391 return; 11392 } 11393 11394 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11395 << HexResult.str() << Result.getMinSignedBits() << LHSType 11396 << Left.getBitWidth() << LHS.get()->getSourceRange() 11397 << RHS.get()->getSourceRange(); 11398 } 11399 11400 /// Return the resulting type when a vector is shifted 11401 /// by a scalar or vector shift amount. 11402 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11403 SourceLocation Loc, bool IsCompAssign) { 11404 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11405 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11406 !LHS.get()->getType()->isVectorType()) { 11407 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11408 << RHS.get()->getType() << LHS.get()->getType() 11409 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11410 return QualType(); 11411 } 11412 11413 if (!IsCompAssign) { 11414 LHS = S.UsualUnaryConversions(LHS.get()); 11415 if (LHS.isInvalid()) return QualType(); 11416 } 11417 11418 RHS = S.UsualUnaryConversions(RHS.get()); 11419 if (RHS.isInvalid()) return QualType(); 11420 11421 QualType LHSType = LHS.get()->getType(); 11422 // Note that LHS might be a scalar because the routine calls not only in 11423 // OpenCL case. 11424 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11425 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11426 11427 // Note that RHS might not be a vector. 11428 QualType RHSType = RHS.get()->getType(); 11429 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11430 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11431 11432 // Do not allow shifts for boolean vectors. 11433 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || 11434 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { 11435 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11436 << LHS.get()->getType() << RHS.get()->getType() 11437 << LHS.get()->getSourceRange(); 11438 return QualType(); 11439 } 11440 11441 // The operands need to be integers. 11442 if (!LHSEleType->isIntegerType()) { 11443 S.Diag(Loc, diag::err_typecheck_expect_int) 11444 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11445 return QualType(); 11446 } 11447 11448 if (!RHSEleType->isIntegerType()) { 11449 S.Diag(Loc, diag::err_typecheck_expect_int) 11450 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11451 return QualType(); 11452 } 11453 11454 if (!LHSVecTy) { 11455 assert(RHSVecTy); 11456 if (IsCompAssign) 11457 return RHSType; 11458 if (LHSEleType != RHSEleType) { 11459 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11460 LHSEleType = RHSEleType; 11461 } 11462 QualType VecTy = 11463 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11464 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11465 LHSType = VecTy; 11466 } else if (RHSVecTy) { 11467 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11468 // are applied component-wise. So if RHS is a vector, then ensure 11469 // that the number of elements is the same as LHS... 11470 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11471 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11472 << LHS.get()->getType() << RHS.get()->getType() 11473 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11474 return QualType(); 11475 } 11476 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11477 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11478 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11479 if (LHSBT != RHSBT && 11480 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11481 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11482 << LHS.get()->getType() << RHS.get()->getType() 11483 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11484 } 11485 } 11486 } else { 11487 // ...else expand RHS to match the number of elements in LHS. 11488 QualType VecTy = 11489 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11490 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11491 } 11492 11493 return LHSType; 11494 } 11495 11496 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, 11497 ExprResult &RHS, SourceLocation Loc, 11498 bool IsCompAssign) { 11499 if (!IsCompAssign) { 11500 LHS = S.UsualUnaryConversions(LHS.get()); 11501 if (LHS.isInvalid()) 11502 return QualType(); 11503 } 11504 11505 RHS = S.UsualUnaryConversions(RHS.get()); 11506 if (RHS.isInvalid()) 11507 return QualType(); 11508 11509 QualType LHSType = LHS.get()->getType(); 11510 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 11511 QualType LHSEleType = LHSType->isVLSTBuiltinType() 11512 ? LHSBuiltinTy->getSveEltType(S.getASTContext()) 11513 : LHSType; 11514 11515 // Note that RHS might not be a vector 11516 QualType RHSType = RHS.get()->getType(); 11517 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); 11518 QualType RHSEleType = RHSType->isVLSTBuiltinType() 11519 ? RHSBuiltinTy->getSveEltType(S.getASTContext()) 11520 : RHSType; 11521 11522 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || 11523 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) { 11524 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11525 << LHSType << RHSType << LHS.get()->getSourceRange(); 11526 return QualType(); 11527 } 11528 11529 if (!LHSEleType->isIntegerType()) { 11530 S.Diag(Loc, diag::err_typecheck_expect_int) 11531 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11532 return QualType(); 11533 } 11534 11535 if (!RHSEleType->isIntegerType()) { 11536 S.Diag(Loc, diag::err_typecheck_expect_int) 11537 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11538 return QualType(); 11539 } 11540 11541 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() && 11542 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != 11543 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) { 11544 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11545 << LHSType << RHSType << LHS.get()->getSourceRange() 11546 << RHS.get()->getSourceRange(); 11547 return QualType(); 11548 } 11549 11550 if (!LHSType->isVLSTBuiltinType()) { 11551 assert(RHSType->isVLSTBuiltinType()); 11552 if (IsCompAssign) 11553 return RHSType; 11554 if (LHSEleType != RHSEleType) { 11555 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast); 11556 LHSEleType = RHSEleType; 11557 } 11558 const llvm::ElementCount VecSize = 11559 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC; 11560 QualType VecTy = 11561 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue()); 11562 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat); 11563 LHSType = VecTy; 11564 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) { 11565 if (S.Context.getTypeSize(RHSBuiltinTy) != 11566 S.Context.getTypeSize(LHSBuiltinTy)) { 11567 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11568 << LHSType << RHSType << LHS.get()->getSourceRange() 11569 << RHS.get()->getSourceRange(); 11570 return QualType(); 11571 } 11572 } else { 11573 const llvm::ElementCount VecSize = 11574 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC; 11575 if (LHSEleType != RHSEleType) { 11576 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast); 11577 RHSEleType = LHSEleType; 11578 } 11579 QualType VecTy = 11580 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue()); 11581 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11582 } 11583 11584 return LHSType; 11585 } 11586 11587 // C99 6.5.7 11588 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11589 SourceLocation Loc, BinaryOperatorKind Opc, 11590 bool IsCompAssign) { 11591 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11592 11593 // Vector shifts promote their scalar inputs to vector type. 11594 if (LHS.get()->getType()->isVectorType() || 11595 RHS.get()->getType()->isVectorType()) { 11596 if (LangOpts.ZVector) { 11597 // The shift operators for the z vector extensions work basically 11598 // like general shifts, except that neither the LHS nor the RHS is 11599 // allowed to be a "vector bool". 11600 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11601 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11602 return InvalidOperands(Loc, LHS, RHS); 11603 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11604 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11605 return InvalidOperands(Loc, LHS, RHS); 11606 } 11607 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11608 } 11609 11610 if (LHS.get()->getType()->isVLSTBuiltinType() || 11611 RHS.get()->getType()->isVLSTBuiltinType()) 11612 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11613 11614 // Shifts don't perform usual arithmetic conversions, they just do integer 11615 // promotions on each operand. C99 6.5.7p3 11616 11617 // For the LHS, do usual unary conversions, but then reset them away 11618 // if this is a compound assignment. 11619 ExprResult OldLHS = LHS; 11620 LHS = UsualUnaryConversions(LHS.get()); 11621 if (LHS.isInvalid()) 11622 return QualType(); 11623 QualType LHSType = LHS.get()->getType(); 11624 if (IsCompAssign) LHS = OldLHS; 11625 11626 // The RHS is simpler. 11627 RHS = UsualUnaryConversions(RHS.get()); 11628 if (RHS.isInvalid()) 11629 return QualType(); 11630 QualType RHSType = RHS.get()->getType(); 11631 11632 // C99 6.5.7p2: Each of the operands shall have integer type. 11633 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11634 if ((!LHSType->isFixedPointOrIntegerType() && 11635 !LHSType->hasIntegerRepresentation()) || 11636 !RHSType->hasIntegerRepresentation()) 11637 return InvalidOperands(Loc, LHS, RHS); 11638 11639 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11640 // hasIntegerRepresentation() above instead of this. 11641 if (isScopedEnumerationType(LHSType) || 11642 isScopedEnumerationType(RHSType)) { 11643 return InvalidOperands(Loc, LHS, RHS); 11644 } 11645 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11646 11647 // "The type of the result is that of the promoted left operand." 11648 return LHSType; 11649 } 11650 11651 /// Diagnose bad pointer comparisons. 11652 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11653 ExprResult &LHS, ExprResult &RHS, 11654 bool IsError) { 11655 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11656 : diag::ext_typecheck_comparison_of_distinct_pointers) 11657 << LHS.get()->getType() << RHS.get()->getType() 11658 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11659 } 11660 11661 /// Returns false if the pointers are converted to a composite type, 11662 /// true otherwise. 11663 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11664 ExprResult &LHS, ExprResult &RHS) { 11665 // C++ [expr.rel]p2: 11666 // [...] Pointer conversions (4.10) and qualification 11667 // conversions (4.4) are performed on pointer operands (or on 11668 // a pointer operand and a null pointer constant) to bring 11669 // them to their composite pointer type. [...] 11670 // 11671 // C++ [expr.eq]p1 uses the same notion for (in)equality 11672 // comparisons of pointers. 11673 11674 QualType LHSType = LHS.get()->getType(); 11675 QualType RHSType = RHS.get()->getType(); 11676 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11677 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11678 11679 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11680 if (T.isNull()) { 11681 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11682 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11683 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11684 else 11685 S.InvalidOperands(Loc, LHS, RHS); 11686 return true; 11687 } 11688 11689 return false; 11690 } 11691 11692 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11693 ExprResult &LHS, 11694 ExprResult &RHS, 11695 bool IsError) { 11696 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11697 : diag::ext_typecheck_comparison_of_fptr_to_void) 11698 << LHS.get()->getType() << RHS.get()->getType() 11699 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11700 } 11701 11702 static bool isObjCObjectLiteral(ExprResult &E) { 11703 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11704 case Stmt::ObjCArrayLiteralClass: 11705 case Stmt::ObjCDictionaryLiteralClass: 11706 case Stmt::ObjCStringLiteralClass: 11707 case Stmt::ObjCBoxedExprClass: 11708 return true; 11709 default: 11710 // Note that ObjCBoolLiteral is NOT an object literal! 11711 return false; 11712 } 11713 } 11714 11715 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11716 const ObjCObjectPointerType *Type = 11717 LHS->getType()->getAs<ObjCObjectPointerType>(); 11718 11719 // If this is not actually an Objective-C object, bail out. 11720 if (!Type) 11721 return false; 11722 11723 // Get the LHS object's interface type. 11724 QualType InterfaceType = Type->getPointeeType(); 11725 11726 // If the RHS isn't an Objective-C object, bail out. 11727 if (!RHS->getType()->isObjCObjectPointerType()) 11728 return false; 11729 11730 // Try to find the -isEqual: method. 11731 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11732 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11733 InterfaceType, 11734 /*IsInstance=*/true); 11735 if (!Method) { 11736 if (Type->isObjCIdType()) { 11737 // For 'id', just check the global pool. 11738 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11739 /*receiverId=*/true); 11740 } else { 11741 // Check protocols. 11742 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11743 /*IsInstance=*/true); 11744 } 11745 } 11746 11747 if (!Method) 11748 return false; 11749 11750 QualType T = Method->parameters()[0]->getType(); 11751 if (!T->isObjCObjectPointerType()) 11752 return false; 11753 11754 QualType R = Method->getReturnType(); 11755 if (!R->isScalarType()) 11756 return false; 11757 11758 return true; 11759 } 11760 11761 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11762 FromE = FromE->IgnoreParenImpCasts(); 11763 switch (FromE->getStmtClass()) { 11764 default: 11765 break; 11766 case Stmt::ObjCStringLiteralClass: 11767 // "string literal" 11768 return LK_String; 11769 case Stmt::ObjCArrayLiteralClass: 11770 // "array literal" 11771 return LK_Array; 11772 case Stmt::ObjCDictionaryLiteralClass: 11773 // "dictionary literal" 11774 return LK_Dictionary; 11775 case Stmt::BlockExprClass: 11776 return LK_Block; 11777 case Stmt::ObjCBoxedExprClass: { 11778 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11779 switch (Inner->getStmtClass()) { 11780 case Stmt::IntegerLiteralClass: 11781 case Stmt::FloatingLiteralClass: 11782 case Stmt::CharacterLiteralClass: 11783 case Stmt::ObjCBoolLiteralExprClass: 11784 case Stmt::CXXBoolLiteralExprClass: 11785 // "numeric literal" 11786 return LK_Numeric; 11787 case Stmt::ImplicitCastExprClass: { 11788 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11789 // Boolean literals can be represented by implicit casts. 11790 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11791 return LK_Numeric; 11792 break; 11793 } 11794 default: 11795 break; 11796 } 11797 return LK_Boxed; 11798 } 11799 } 11800 return LK_None; 11801 } 11802 11803 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11804 ExprResult &LHS, ExprResult &RHS, 11805 BinaryOperator::Opcode Opc){ 11806 Expr *Literal; 11807 Expr *Other; 11808 if (isObjCObjectLiteral(LHS)) { 11809 Literal = LHS.get(); 11810 Other = RHS.get(); 11811 } else { 11812 Literal = RHS.get(); 11813 Other = LHS.get(); 11814 } 11815 11816 // Don't warn on comparisons against nil. 11817 Other = Other->IgnoreParenCasts(); 11818 if (Other->isNullPointerConstant(S.getASTContext(), 11819 Expr::NPC_ValueDependentIsNotNull)) 11820 return; 11821 11822 // This should be kept in sync with warn_objc_literal_comparison. 11823 // LK_String should always be after the other literals, since it has its own 11824 // warning flag. 11825 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11826 assert(LiteralKind != Sema::LK_Block); 11827 if (LiteralKind == Sema::LK_None) { 11828 llvm_unreachable("Unknown Objective-C object literal kind"); 11829 } 11830 11831 if (LiteralKind == Sema::LK_String) 11832 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11833 << Literal->getSourceRange(); 11834 else 11835 S.Diag(Loc, diag::warn_objc_literal_comparison) 11836 << LiteralKind << Literal->getSourceRange(); 11837 11838 if (BinaryOperator::isEqualityOp(Opc) && 11839 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11840 SourceLocation Start = LHS.get()->getBeginLoc(); 11841 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11842 CharSourceRange OpRange = 11843 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11844 11845 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11846 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11847 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11848 << FixItHint::CreateInsertion(End, "]"); 11849 } 11850 } 11851 11852 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11853 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11854 ExprResult &RHS, SourceLocation Loc, 11855 BinaryOperatorKind Opc) { 11856 // Check that left hand side is !something. 11857 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11858 if (!UO || UO->getOpcode() != UO_LNot) return; 11859 11860 // Only check if the right hand side is non-bool arithmetic type. 11861 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11862 11863 // Make sure that the something in !something is not bool. 11864 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11865 if (SubExpr->isKnownToHaveBooleanValue()) return; 11866 11867 // Emit warning. 11868 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11869 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11870 << Loc << IsBitwiseOp; 11871 11872 // First note suggest !(x < y) 11873 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11874 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11875 FirstClose = S.getLocForEndOfToken(FirstClose); 11876 if (FirstClose.isInvalid()) 11877 FirstOpen = SourceLocation(); 11878 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11879 << IsBitwiseOp 11880 << FixItHint::CreateInsertion(FirstOpen, "(") 11881 << FixItHint::CreateInsertion(FirstClose, ")"); 11882 11883 // Second note suggests (!x) < y 11884 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11885 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11886 SecondClose = S.getLocForEndOfToken(SecondClose); 11887 if (SecondClose.isInvalid()) 11888 SecondOpen = SourceLocation(); 11889 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11890 << FixItHint::CreateInsertion(SecondOpen, "(") 11891 << FixItHint::CreateInsertion(SecondClose, ")"); 11892 } 11893 11894 // Returns true if E refers to a non-weak array. 11895 static bool checkForArray(const Expr *E) { 11896 const ValueDecl *D = nullptr; 11897 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11898 D = DR->getDecl(); 11899 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11900 if (Mem->isImplicitAccess()) 11901 D = Mem->getMemberDecl(); 11902 } 11903 if (!D) 11904 return false; 11905 return D->getType()->isArrayType() && !D->isWeak(); 11906 } 11907 11908 /// Diagnose some forms of syntactically-obvious tautological comparison. 11909 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11910 Expr *LHS, Expr *RHS, 11911 BinaryOperatorKind Opc) { 11912 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11913 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11914 11915 QualType LHSType = LHS->getType(); 11916 QualType RHSType = RHS->getType(); 11917 if (LHSType->hasFloatingRepresentation() || 11918 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11919 S.inTemplateInstantiation()) 11920 return; 11921 11922 // Comparisons between two array types are ill-formed for operator<=>, so 11923 // we shouldn't emit any additional warnings about it. 11924 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11925 return; 11926 11927 // For non-floating point types, check for self-comparisons of the form 11928 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11929 // often indicate logic errors in the program. 11930 // 11931 // NOTE: Don't warn about comparison expressions resulting from macro 11932 // expansion. Also don't warn about comparisons which are only self 11933 // comparisons within a template instantiation. The warnings should catch 11934 // obvious cases in the definition of the template anyways. The idea is to 11935 // warn when the typed comparison operator will always evaluate to the same 11936 // result. 11937 11938 // Used for indexing into %select in warn_comparison_always 11939 enum { 11940 AlwaysConstant, 11941 AlwaysTrue, 11942 AlwaysFalse, 11943 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11944 }; 11945 11946 // C++2a [depr.array.comp]: 11947 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11948 // operands of array type are deprecated. 11949 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11950 RHSStripped->getType()->isArrayType()) { 11951 S.Diag(Loc, diag::warn_depr_array_comparison) 11952 << LHS->getSourceRange() << RHS->getSourceRange() 11953 << LHSStripped->getType() << RHSStripped->getType(); 11954 // Carry on to produce the tautological comparison warning, if this 11955 // expression is potentially-evaluated, we can resolve the array to a 11956 // non-weak declaration, and so on. 11957 } 11958 11959 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11960 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11961 unsigned Result; 11962 switch (Opc) { 11963 case BO_EQ: 11964 case BO_LE: 11965 case BO_GE: 11966 Result = AlwaysTrue; 11967 break; 11968 case BO_NE: 11969 case BO_LT: 11970 case BO_GT: 11971 Result = AlwaysFalse; 11972 break; 11973 case BO_Cmp: 11974 Result = AlwaysEqual; 11975 break; 11976 default: 11977 Result = AlwaysConstant; 11978 break; 11979 } 11980 S.DiagRuntimeBehavior(Loc, nullptr, 11981 S.PDiag(diag::warn_comparison_always) 11982 << 0 /*self-comparison*/ 11983 << Result); 11984 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11985 // What is it always going to evaluate to? 11986 unsigned Result; 11987 switch (Opc) { 11988 case BO_EQ: // e.g. array1 == array2 11989 Result = AlwaysFalse; 11990 break; 11991 case BO_NE: // e.g. array1 != array2 11992 Result = AlwaysTrue; 11993 break; 11994 default: // e.g. array1 <= array2 11995 // The best we can say is 'a constant' 11996 Result = AlwaysConstant; 11997 break; 11998 } 11999 S.DiagRuntimeBehavior(Loc, nullptr, 12000 S.PDiag(diag::warn_comparison_always) 12001 << 1 /*array comparison*/ 12002 << Result); 12003 } 12004 } 12005 12006 if (isa<CastExpr>(LHSStripped)) 12007 LHSStripped = LHSStripped->IgnoreParenCasts(); 12008 if (isa<CastExpr>(RHSStripped)) 12009 RHSStripped = RHSStripped->IgnoreParenCasts(); 12010 12011 // Warn about comparisons against a string constant (unless the other 12012 // operand is null); the user probably wants string comparison function. 12013 Expr *LiteralString = nullptr; 12014 Expr *LiteralStringStripped = nullptr; 12015 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 12016 !RHSStripped->isNullPointerConstant(S.Context, 12017 Expr::NPC_ValueDependentIsNull)) { 12018 LiteralString = LHS; 12019 LiteralStringStripped = LHSStripped; 12020 } else if ((isa<StringLiteral>(RHSStripped) || 12021 isa<ObjCEncodeExpr>(RHSStripped)) && 12022 !LHSStripped->isNullPointerConstant(S.Context, 12023 Expr::NPC_ValueDependentIsNull)) { 12024 LiteralString = RHS; 12025 LiteralStringStripped = RHSStripped; 12026 } 12027 12028 if (LiteralString) { 12029 S.DiagRuntimeBehavior(Loc, nullptr, 12030 S.PDiag(diag::warn_stringcompare) 12031 << isa<ObjCEncodeExpr>(LiteralStringStripped) 12032 << LiteralString->getSourceRange()); 12033 } 12034 } 12035 12036 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 12037 switch (CK) { 12038 default: { 12039 #ifndef NDEBUG 12040 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 12041 << "\n"; 12042 #endif 12043 llvm_unreachable("unhandled cast kind"); 12044 } 12045 case CK_UserDefinedConversion: 12046 return ICK_Identity; 12047 case CK_LValueToRValue: 12048 return ICK_Lvalue_To_Rvalue; 12049 case CK_ArrayToPointerDecay: 12050 return ICK_Array_To_Pointer; 12051 case CK_FunctionToPointerDecay: 12052 return ICK_Function_To_Pointer; 12053 case CK_IntegralCast: 12054 return ICK_Integral_Conversion; 12055 case CK_FloatingCast: 12056 return ICK_Floating_Conversion; 12057 case CK_IntegralToFloating: 12058 case CK_FloatingToIntegral: 12059 return ICK_Floating_Integral; 12060 case CK_IntegralComplexCast: 12061 case CK_FloatingComplexCast: 12062 case CK_FloatingComplexToIntegralComplex: 12063 case CK_IntegralComplexToFloatingComplex: 12064 return ICK_Complex_Conversion; 12065 case CK_FloatingComplexToReal: 12066 case CK_FloatingRealToComplex: 12067 case CK_IntegralComplexToReal: 12068 case CK_IntegralRealToComplex: 12069 return ICK_Complex_Real; 12070 } 12071 } 12072 12073 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 12074 QualType FromType, 12075 SourceLocation Loc) { 12076 // Check for a narrowing implicit conversion. 12077 StandardConversionSequence SCS; 12078 SCS.setAsIdentityConversion(); 12079 SCS.setToType(0, FromType); 12080 SCS.setToType(1, ToType); 12081 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 12082 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 12083 12084 APValue PreNarrowingValue; 12085 QualType PreNarrowingType; 12086 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 12087 PreNarrowingType, 12088 /*IgnoreFloatToIntegralConversion*/ true)) { 12089 case NK_Dependent_Narrowing: 12090 // Implicit conversion to a narrower type, but the expression is 12091 // value-dependent so we can't tell whether it's actually narrowing. 12092 case NK_Not_Narrowing: 12093 return false; 12094 12095 case NK_Constant_Narrowing: 12096 // Implicit conversion to a narrower type, and the value is not a constant 12097 // expression. 12098 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12099 << /*Constant*/ 1 12100 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 12101 return true; 12102 12103 case NK_Variable_Narrowing: 12104 // Implicit conversion to a narrower type, and the value is not a constant 12105 // expression. 12106 case NK_Type_Narrowing: 12107 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12108 << /*Constant*/ 0 << FromType << ToType; 12109 // TODO: It's not a constant expression, but what if the user intended it 12110 // to be? Can we produce notes to help them figure out why it isn't? 12111 return true; 12112 } 12113 llvm_unreachable("unhandled case in switch"); 12114 } 12115 12116 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 12117 ExprResult &LHS, 12118 ExprResult &RHS, 12119 SourceLocation Loc) { 12120 QualType LHSType = LHS.get()->getType(); 12121 QualType RHSType = RHS.get()->getType(); 12122 // Dig out the original argument type and expression before implicit casts 12123 // were applied. These are the types/expressions we need to check the 12124 // [expr.spaceship] requirements against. 12125 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 12126 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 12127 QualType LHSStrippedType = LHSStripped.get()->getType(); 12128 QualType RHSStrippedType = RHSStripped.get()->getType(); 12129 12130 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 12131 // other is not, the program is ill-formed. 12132 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 12133 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12134 return QualType(); 12135 } 12136 12137 // FIXME: Consider combining this with checkEnumArithmeticConversions. 12138 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 12139 RHSStrippedType->isEnumeralType(); 12140 if (NumEnumArgs == 1) { 12141 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 12142 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 12143 if (OtherTy->hasFloatingRepresentation()) { 12144 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12145 return QualType(); 12146 } 12147 } 12148 if (NumEnumArgs == 2) { 12149 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 12150 // type E, the operator yields the result of converting the operands 12151 // to the underlying type of E and applying <=> to the converted operands. 12152 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 12153 S.InvalidOperands(Loc, LHS, RHS); 12154 return QualType(); 12155 } 12156 QualType IntType = 12157 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 12158 assert(IntType->isArithmeticType()); 12159 12160 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 12161 // promote the boolean type, and all other promotable integer types, to 12162 // avoid this. 12163 if (IntType->isPromotableIntegerType()) 12164 IntType = S.Context.getPromotedIntegerType(IntType); 12165 12166 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 12167 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 12168 LHSType = RHSType = IntType; 12169 } 12170 12171 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 12172 // usual arithmetic conversions are applied to the operands. 12173 QualType Type = 12174 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12175 if (LHS.isInvalid() || RHS.isInvalid()) 12176 return QualType(); 12177 if (Type.isNull()) 12178 return S.InvalidOperands(Loc, LHS, RHS); 12179 12180 Optional<ComparisonCategoryType> CCT = 12181 getComparisonCategoryForBuiltinCmp(Type); 12182 if (!CCT) 12183 return S.InvalidOperands(Loc, LHS, RHS); 12184 12185 bool HasNarrowing = checkThreeWayNarrowingConversion( 12186 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 12187 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 12188 RHS.get()->getBeginLoc()); 12189 if (HasNarrowing) 12190 return QualType(); 12191 12192 assert(!Type.isNull() && "composite type for <=> has not been set"); 12193 12194 return S.CheckComparisonCategoryType( 12195 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 12196 } 12197 12198 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 12199 ExprResult &RHS, 12200 SourceLocation Loc, 12201 BinaryOperatorKind Opc) { 12202 if (Opc == BO_Cmp) 12203 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 12204 12205 // C99 6.5.8p3 / C99 6.5.9p4 12206 QualType Type = 12207 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12208 if (LHS.isInvalid() || RHS.isInvalid()) 12209 return QualType(); 12210 if (Type.isNull()) 12211 return S.InvalidOperands(Loc, LHS, RHS); 12212 assert(Type->isArithmeticType() || Type->isEnumeralType()); 12213 12214 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 12215 return S.InvalidOperands(Loc, LHS, RHS); 12216 12217 // Check for comparisons of floating point operands using != and ==. 12218 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 12219 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12220 12221 // The result of comparisons is 'bool' in C++, 'int' in C. 12222 return S.Context.getLogicalOperationType(); 12223 } 12224 12225 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 12226 if (!NullE.get()->getType()->isAnyPointerType()) 12227 return; 12228 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 12229 if (!E.get()->getType()->isAnyPointerType() && 12230 E.get()->isNullPointerConstant(Context, 12231 Expr::NPC_ValueDependentIsNotNull) == 12232 Expr::NPCK_ZeroExpression) { 12233 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 12234 if (CL->getValue() == 0) 12235 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12236 << NullValue 12237 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12238 NullValue ? "NULL" : "(void *)0"); 12239 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 12240 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 12241 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 12242 if (T == Context.CharTy) 12243 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12244 << NullValue 12245 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12246 NullValue ? "NULL" : "(void *)0"); 12247 } 12248 } 12249 } 12250 12251 // C99 6.5.8, C++ [expr.rel] 12252 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 12253 SourceLocation Loc, 12254 BinaryOperatorKind Opc) { 12255 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 12256 bool IsThreeWay = Opc == BO_Cmp; 12257 bool IsOrdered = IsRelational || IsThreeWay; 12258 auto IsAnyPointerType = [](ExprResult E) { 12259 QualType Ty = E.get()->getType(); 12260 return Ty->isPointerType() || Ty->isMemberPointerType(); 12261 }; 12262 12263 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 12264 // type, array-to-pointer, ..., conversions are performed on both operands to 12265 // bring them to their composite type. 12266 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 12267 // any type-related checks. 12268 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 12269 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12270 if (LHS.isInvalid()) 12271 return QualType(); 12272 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12273 if (RHS.isInvalid()) 12274 return QualType(); 12275 } else { 12276 LHS = DefaultLvalueConversion(LHS.get()); 12277 if (LHS.isInvalid()) 12278 return QualType(); 12279 RHS = DefaultLvalueConversion(RHS.get()); 12280 if (RHS.isInvalid()) 12281 return QualType(); 12282 } 12283 12284 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 12285 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 12286 CheckPtrComparisonWithNullChar(LHS, RHS); 12287 CheckPtrComparisonWithNullChar(RHS, LHS); 12288 } 12289 12290 // Handle vector comparisons separately. 12291 if (LHS.get()->getType()->isVectorType() || 12292 RHS.get()->getType()->isVectorType()) 12293 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 12294 12295 if (LHS.get()->getType()->isVLSTBuiltinType() || 12296 RHS.get()->getType()->isVLSTBuiltinType()) 12297 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc); 12298 12299 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12300 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12301 12302 QualType LHSType = LHS.get()->getType(); 12303 QualType RHSType = RHS.get()->getType(); 12304 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 12305 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 12306 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 12307 12308 const Expr::NullPointerConstantKind LHSNullKind = 12309 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12310 const Expr::NullPointerConstantKind RHSNullKind = 12311 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12312 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 12313 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 12314 12315 auto computeResultTy = [&]() { 12316 if (Opc != BO_Cmp) 12317 return Context.getLogicalOperationType(); 12318 assert(getLangOpts().CPlusPlus); 12319 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 12320 12321 QualType CompositeTy = LHS.get()->getType(); 12322 assert(!CompositeTy->isReferenceType()); 12323 12324 Optional<ComparisonCategoryType> CCT = 12325 getComparisonCategoryForBuiltinCmp(CompositeTy); 12326 if (!CCT) 12327 return InvalidOperands(Loc, LHS, RHS); 12328 12329 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 12330 // P0946R0: Comparisons between a null pointer constant and an object 12331 // pointer result in std::strong_equality, which is ill-formed under 12332 // P1959R0. 12333 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 12334 << (LHSIsNull ? LHS.get()->getSourceRange() 12335 : RHS.get()->getSourceRange()); 12336 return QualType(); 12337 } 12338 12339 return CheckComparisonCategoryType( 12340 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 12341 }; 12342 12343 if (!IsOrdered && LHSIsNull != RHSIsNull) { 12344 bool IsEquality = Opc == BO_EQ; 12345 if (RHSIsNull) 12346 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 12347 RHS.get()->getSourceRange()); 12348 else 12349 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 12350 LHS.get()->getSourceRange()); 12351 } 12352 12353 if (IsOrdered && LHSType->isFunctionPointerType() && 12354 RHSType->isFunctionPointerType()) { 12355 // Valid unless a relational comparison of function pointers 12356 bool IsError = Opc == BO_Cmp; 12357 auto DiagID = 12358 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 12359 : getLangOpts().CPlusPlus 12360 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 12361 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 12362 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 12363 << RHS.get()->getSourceRange(); 12364 if (IsError) 12365 return QualType(); 12366 } 12367 12368 if ((LHSType->isIntegerType() && !LHSIsNull) || 12369 (RHSType->isIntegerType() && !RHSIsNull)) { 12370 // Skip normal pointer conversion checks in this case; we have better 12371 // diagnostics for this below. 12372 } else if (getLangOpts().CPlusPlus) { 12373 // Equality comparison of a function pointer to a void pointer is invalid, 12374 // but we allow it as an extension. 12375 // FIXME: If we really want to allow this, should it be part of composite 12376 // pointer type computation so it works in conditionals too? 12377 if (!IsOrdered && 12378 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 12379 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 12380 // This is a gcc extension compatibility comparison. 12381 // In a SFINAE context, we treat this as a hard error to maintain 12382 // conformance with the C++ standard. 12383 diagnoseFunctionPointerToVoidComparison( 12384 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 12385 12386 if (isSFINAEContext()) 12387 return QualType(); 12388 12389 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12390 return computeResultTy(); 12391 } 12392 12393 // C++ [expr.eq]p2: 12394 // If at least one operand is a pointer [...] bring them to their 12395 // composite pointer type. 12396 // C++ [expr.spaceship]p6 12397 // If at least one of the operands is of pointer type, [...] bring them 12398 // to their composite pointer type. 12399 // C++ [expr.rel]p2: 12400 // If both operands are pointers, [...] bring them to their composite 12401 // pointer type. 12402 // For <=>, the only valid non-pointer types are arrays and functions, and 12403 // we already decayed those, so this is really the same as the relational 12404 // comparison rule. 12405 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 12406 (IsOrdered ? 2 : 1) && 12407 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 12408 RHSType->isObjCObjectPointerType()))) { 12409 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12410 return QualType(); 12411 return computeResultTy(); 12412 } 12413 } else if (LHSType->isPointerType() && 12414 RHSType->isPointerType()) { // C99 6.5.8p2 12415 // All of the following pointer-related warnings are GCC extensions, except 12416 // when handling null pointer constants. 12417 QualType LCanPointeeTy = 12418 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12419 QualType RCanPointeeTy = 12420 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12421 12422 // C99 6.5.9p2 and C99 6.5.8p2 12423 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 12424 RCanPointeeTy.getUnqualifiedType())) { 12425 if (IsRelational) { 12426 // Pointers both need to point to complete or incomplete types 12427 if ((LCanPointeeTy->isIncompleteType() != 12428 RCanPointeeTy->isIncompleteType()) && 12429 !getLangOpts().C11) { 12430 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 12431 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 12432 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 12433 << RCanPointeeTy->isIncompleteType(); 12434 } 12435 } 12436 } else if (!IsRelational && 12437 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 12438 // Valid unless comparison between non-null pointer and function pointer 12439 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 12440 && !LHSIsNull && !RHSIsNull) 12441 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 12442 /*isError*/false); 12443 } else { 12444 // Invalid 12445 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 12446 } 12447 if (LCanPointeeTy != RCanPointeeTy) { 12448 // Treat NULL constant as a special case in OpenCL. 12449 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 12450 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 12451 Diag(Loc, 12452 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 12453 << LHSType << RHSType << 0 /* comparison */ 12454 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12455 } 12456 } 12457 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 12458 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12459 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12460 : CK_BitCast; 12461 if (LHSIsNull && !RHSIsNull) 12462 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12463 else 12464 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12465 } 12466 return computeResultTy(); 12467 } 12468 12469 if (getLangOpts().CPlusPlus) { 12470 // C++ [expr.eq]p4: 12471 // Two operands of type std::nullptr_t or one operand of type 12472 // std::nullptr_t and the other a null pointer constant compare equal. 12473 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12474 if (LHSType->isNullPtrType()) { 12475 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12476 return computeResultTy(); 12477 } 12478 if (RHSType->isNullPtrType()) { 12479 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12480 return computeResultTy(); 12481 } 12482 } 12483 12484 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12485 // These aren't covered by the composite pointer type rules. 12486 if (!IsOrdered && RHSType->isNullPtrType() && 12487 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12488 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12489 return computeResultTy(); 12490 } 12491 if (!IsOrdered && LHSType->isNullPtrType() && 12492 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12493 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12494 return computeResultTy(); 12495 } 12496 12497 if (IsRelational && 12498 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12499 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12500 // HACK: Relational comparison of nullptr_t against a pointer type is 12501 // invalid per DR583, but we allow it within std::less<> and friends, 12502 // since otherwise common uses of it break. 12503 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12504 // friends to have std::nullptr_t overload candidates. 12505 DeclContext *DC = CurContext; 12506 if (isa<FunctionDecl>(DC)) 12507 DC = DC->getParent(); 12508 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12509 if (CTSD->isInStdNamespace() && 12510 llvm::StringSwitch<bool>(CTSD->getName()) 12511 .Cases("less", "less_equal", "greater", "greater_equal", true) 12512 .Default(false)) { 12513 if (RHSType->isNullPtrType()) 12514 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12515 else 12516 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12517 return computeResultTy(); 12518 } 12519 } 12520 } 12521 12522 // C++ [expr.eq]p2: 12523 // If at least one operand is a pointer to member, [...] bring them to 12524 // their composite pointer type. 12525 if (!IsOrdered && 12526 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12527 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12528 return QualType(); 12529 else 12530 return computeResultTy(); 12531 } 12532 } 12533 12534 // Handle block pointer types. 12535 if (!IsOrdered && LHSType->isBlockPointerType() && 12536 RHSType->isBlockPointerType()) { 12537 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12538 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12539 12540 if (!LHSIsNull && !RHSIsNull && 12541 !Context.typesAreCompatible(lpointee, rpointee)) { 12542 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12543 << LHSType << RHSType << LHS.get()->getSourceRange() 12544 << RHS.get()->getSourceRange(); 12545 } 12546 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12547 return computeResultTy(); 12548 } 12549 12550 // Allow block pointers to be compared with null pointer constants. 12551 if (!IsOrdered 12552 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12553 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12554 if (!LHSIsNull && !RHSIsNull) { 12555 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12556 ->getPointeeType()->isVoidType()) 12557 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12558 ->getPointeeType()->isVoidType()))) 12559 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12560 << LHSType << RHSType << LHS.get()->getSourceRange() 12561 << RHS.get()->getSourceRange(); 12562 } 12563 if (LHSIsNull && !RHSIsNull) 12564 LHS = ImpCastExprToType(LHS.get(), RHSType, 12565 RHSType->isPointerType() ? CK_BitCast 12566 : CK_AnyPointerToBlockPointerCast); 12567 else 12568 RHS = ImpCastExprToType(RHS.get(), LHSType, 12569 LHSType->isPointerType() ? CK_BitCast 12570 : CK_AnyPointerToBlockPointerCast); 12571 return computeResultTy(); 12572 } 12573 12574 if (LHSType->isObjCObjectPointerType() || 12575 RHSType->isObjCObjectPointerType()) { 12576 const PointerType *LPT = LHSType->getAs<PointerType>(); 12577 const PointerType *RPT = RHSType->getAs<PointerType>(); 12578 if (LPT || RPT) { 12579 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12580 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12581 12582 if (!LPtrToVoid && !RPtrToVoid && 12583 !Context.typesAreCompatible(LHSType, RHSType)) { 12584 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12585 /*isError*/false); 12586 } 12587 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12588 // the RHS, but we have test coverage for this behavior. 12589 // FIXME: Consider using convertPointersToCompositeType in C++. 12590 if (LHSIsNull && !RHSIsNull) { 12591 Expr *E = LHS.get(); 12592 if (getLangOpts().ObjCAutoRefCount) 12593 CheckObjCConversion(SourceRange(), RHSType, E, 12594 CCK_ImplicitConversion); 12595 LHS = ImpCastExprToType(E, RHSType, 12596 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12597 } 12598 else { 12599 Expr *E = RHS.get(); 12600 if (getLangOpts().ObjCAutoRefCount) 12601 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12602 /*Diagnose=*/true, 12603 /*DiagnoseCFAudited=*/false, Opc); 12604 RHS = ImpCastExprToType(E, LHSType, 12605 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12606 } 12607 return computeResultTy(); 12608 } 12609 if (LHSType->isObjCObjectPointerType() && 12610 RHSType->isObjCObjectPointerType()) { 12611 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12612 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12613 /*isError*/false); 12614 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12615 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12616 12617 if (LHSIsNull && !RHSIsNull) 12618 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12619 else 12620 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12621 return computeResultTy(); 12622 } 12623 12624 if (!IsOrdered && LHSType->isBlockPointerType() && 12625 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12626 LHS = ImpCastExprToType(LHS.get(), RHSType, 12627 CK_BlockPointerToObjCPointerCast); 12628 return computeResultTy(); 12629 } else if (!IsOrdered && 12630 LHSType->isBlockCompatibleObjCPointerType(Context) && 12631 RHSType->isBlockPointerType()) { 12632 RHS = ImpCastExprToType(RHS.get(), LHSType, 12633 CK_BlockPointerToObjCPointerCast); 12634 return computeResultTy(); 12635 } 12636 } 12637 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12638 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12639 unsigned DiagID = 0; 12640 bool isError = false; 12641 if (LangOpts.DebuggerSupport) { 12642 // Under a debugger, allow the comparison of pointers to integers, 12643 // since users tend to want to compare addresses. 12644 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12645 (RHSIsNull && RHSType->isIntegerType())) { 12646 if (IsOrdered) { 12647 isError = getLangOpts().CPlusPlus; 12648 DiagID = 12649 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12650 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12651 } 12652 } else if (getLangOpts().CPlusPlus) { 12653 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12654 isError = true; 12655 } else if (IsOrdered) 12656 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12657 else 12658 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12659 12660 if (DiagID) { 12661 Diag(Loc, DiagID) 12662 << LHSType << RHSType << LHS.get()->getSourceRange() 12663 << RHS.get()->getSourceRange(); 12664 if (isError) 12665 return QualType(); 12666 } 12667 12668 if (LHSType->isIntegerType()) 12669 LHS = ImpCastExprToType(LHS.get(), RHSType, 12670 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12671 else 12672 RHS = ImpCastExprToType(RHS.get(), LHSType, 12673 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12674 return computeResultTy(); 12675 } 12676 12677 // Handle block pointers. 12678 if (!IsOrdered && RHSIsNull 12679 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12680 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12681 return computeResultTy(); 12682 } 12683 if (!IsOrdered && LHSIsNull 12684 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12685 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12686 return computeResultTy(); 12687 } 12688 12689 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12690 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12691 return computeResultTy(); 12692 } 12693 12694 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12695 return computeResultTy(); 12696 } 12697 12698 if (LHSIsNull && RHSType->isQueueT()) { 12699 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12700 return computeResultTy(); 12701 } 12702 12703 if (LHSType->isQueueT() && RHSIsNull) { 12704 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12705 return computeResultTy(); 12706 } 12707 } 12708 12709 return InvalidOperands(Loc, LHS, RHS); 12710 } 12711 12712 // Return a signed ext_vector_type that is of identical size and number of 12713 // elements. For floating point vectors, return an integer type of identical 12714 // size and number of elements. In the non ext_vector_type case, search from 12715 // the largest type to the smallest type to avoid cases where long long == long, 12716 // where long gets picked over long long. 12717 QualType Sema::GetSignedVectorType(QualType V) { 12718 const VectorType *VTy = V->castAs<VectorType>(); 12719 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12720 12721 if (isa<ExtVectorType>(VTy)) { 12722 if (VTy->isExtVectorBoolType()) 12723 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements()); 12724 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12725 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12726 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12727 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12728 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12729 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12730 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12731 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); 12732 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12733 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12734 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12735 "Unhandled vector element size in vector compare"); 12736 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12737 } 12738 12739 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12740 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), 12741 VectorType::GenericVector); 12742 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12743 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12744 VectorType::GenericVector); 12745 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12746 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12747 VectorType::GenericVector); 12748 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12749 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12750 VectorType::GenericVector); 12751 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12752 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12753 VectorType::GenericVector); 12754 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12755 "Unhandled vector element size in vector compare"); 12756 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12757 VectorType::GenericVector); 12758 } 12759 12760 QualType Sema::GetSignedSizelessVectorType(QualType V) { 12761 const BuiltinType *VTy = V->castAs<BuiltinType>(); 12762 assert(VTy->isSizelessBuiltinType() && "expected sizeless type"); 12763 12764 const QualType ETy = V->getSveEltType(Context); 12765 const auto TypeSize = Context.getTypeSize(ETy); 12766 12767 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true); 12768 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC; 12769 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue()); 12770 } 12771 12772 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12773 /// operates on extended vector types. Instead of producing an IntTy result, 12774 /// like a scalar comparison, a vector comparison produces a vector of integer 12775 /// types. 12776 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12777 SourceLocation Loc, 12778 BinaryOperatorKind Opc) { 12779 if (Opc == BO_Cmp) { 12780 Diag(Loc, diag::err_three_way_vector_comparison); 12781 return QualType(); 12782 } 12783 12784 // Check to make sure we're operating on vectors of the same type and width, 12785 // Allowing one side to be a scalar of element type. 12786 QualType vType = 12787 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false, 12788 /*AllowBothBool*/ true, 12789 /*AllowBoolConversions*/ getLangOpts().ZVector, 12790 /*AllowBooleanOperation*/ true, 12791 /*ReportInvalid*/ true); 12792 if (vType.isNull()) 12793 return vType; 12794 12795 QualType LHSType = LHS.get()->getType(); 12796 12797 // Determine the return type of a vector compare. By default clang will return 12798 // a scalar for all vector compares except vector bool and vector pixel. 12799 // With the gcc compiler we will always return a vector type and with the xl 12800 // compiler we will always return a scalar type. This switch allows choosing 12801 // which behavior is prefered. 12802 if (getLangOpts().AltiVec) { 12803 switch (getLangOpts().getAltivecSrcCompat()) { 12804 case LangOptions::AltivecSrcCompatKind::Mixed: 12805 // If AltiVec, the comparison results in a numeric type, i.e. 12806 // bool for C++, int for C 12807 if (vType->castAs<VectorType>()->getVectorKind() == 12808 VectorType::AltiVecVector) 12809 return Context.getLogicalOperationType(); 12810 else 12811 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12812 break; 12813 case LangOptions::AltivecSrcCompatKind::GCC: 12814 // For GCC we always return the vector type. 12815 break; 12816 case LangOptions::AltivecSrcCompatKind::XL: 12817 return Context.getLogicalOperationType(); 12818 break; 12819 } 12820 } 12821 12822 // For non-floating point types, check for self-comparisons of the form 12823 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12824 // often indicate logic errors in the program. 12825 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12826 12827 // Check for comparisons of floating point operands using != and ==. 12828 if (BinaryOperator::isEqualityOp(Opc) && 12829 LHSType->hasFloatingRepresentation()) { 12830 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12831 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12832 } 12833 12834 // Return a signed type for the vector. 12835 return GetSignedVectorType(vType); 12836 } 12837 12838 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS, 12839 ExprResult &RHS, 12840 SourceLocation Loc, 12841 BinaryOperatorKind Opc) { 12842 if (Opc == BO_Cmp) { 12843 Diag(Loc, diag::err_three_way_vector_comparison); 12844 return QualType(); 12845 } 12846 12847 // Check to make sure we're operating on vectors of the same type and width, 12848 // Allowing one side to be a scalar of element type. 12849 QualType vType = CheckSizelessVectorOperands( 12850 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison); 12851 12852 if (vType.isNull()) 12853 return vType; 12854 12855 QualType LHSType = LHS.get()->getType(); 12856 12857 // For non-floating point types, check for self-comparisons of the form 12858 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12859 // often indicate logic errors in the program. 12860 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12861 12862 // Check for comparisons of floating point operands using != and ==. 12863 if (BinaryOperator::isEqualityOp(Opc) && 12864 LHSType->hasFloatingRepresentation()) { 12865 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12866 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12867 } 12868 12869 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 12870 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>(); 12871 12872 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() && 12873 RHSBuiltinTy->isSVEBool()) 12874 return LHSType; 12875 12876 // Return a signed type for the vector. 12877 return GetSignedSizelessVectorType(vType); 12878 } 12879 12880 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12881 const ExprResult &XorRHS, 12882 const SourceLocation Loc) { 12883 // Do not diagnose macros. 12884 if (Loc.isMacroID()) 12885 return; 12886 12887 // Do not diagnose if both LHS and RHS are macros. 12888 if (XorLHS.get()->getExprLoc().isMacroID() && 12889 XorRHS.get()->getExprLoc().isMacroID()) 12890 return; 12891 12892 bool Negative = false; 12893 bool ExplicitPlus = false; 12894 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12895 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12896 12897 if (!LHSInt) 12898 return; 12899 if (!RHSInt) { 12900 // Check negative literals. 12901 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12902 UnaryOperatorKind Opc = UO->getOpcode(); 12903 if (Opc != UO_Minus && Opc != UO_Plus) 12904 return; 12905 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12906 if (!RHSInt) 12907 return; 12908 Negative = (Opc == UO_Minus); 12909 ExplicitPlus = !Negative; 12910 } else { 12911 return; 12912 } 12913 } 12914 12915 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12916 llvm::APInt RightSideValue = RHSInt->getValue(); 12917 if (LeftSideValue != 2 && LeftSideValue != 10) 12918 return; 12919 12920 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12921 return; 12922 12923 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12924 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12925 llvm::StringRef ExprStr = 12926 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12927 12928 CharSourceRange XorRange = 12929 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12930 llvm::StringRef XorStr = 12931 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12932 // Do not diagnose if xor keyword/macro is used. 12933 if (XorStr == "xor") 12934 return; 12935 12936 std::string LHSStr = std::string(Lexer::getSourceText( 12937 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12938 S.getSourceManager(), S.getLangOpts())); 12939 std::string RHSStr = std::string(Lexer::getSourceText( 12940 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12941 S.getSourceManager(), S.getLangOpts())); 12942 12943 if (Negative) { 12944 RightSideValue = -RightSideValue; 12945 RHSStr = "-" + RHSStr; 12946 } else if (ExplicitPlus) { 12947 RHSStr = "+" + RHSStr; 12948 } 12949 12950 StringRef LHSStrRef = LHSStr; 12951 StringRef RHSStrRef = RHSStr; 12952 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12953 // literals. 12954 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12955 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12956 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12957 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12958 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12959 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12960 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12961 return; 12962 12963 bool SuggestXor = 12964 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12965 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12966 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12967 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12968 std::string SuggestedExpr = "1 << " + RHSStr; 12969 bool Overflow = false; 12970 llvm::APInt One = (LeftSideValue - 1); 12971 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12972 if (Overflow) { 12973 if (RightSideIntValue < 64) 12974 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12975 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12976 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12977 else if (RightSideIntValue == 64) 12978 S.Diag(Loc, diag::warn_xor_used_as_pow) 12979 << ExprStr << toString(XorValue, 10, true); 12980 else 12981 return; 12982 } else { 12983 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12984 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12985 << toString(PowValue, 10, true) 12986 << FixItHint::CreateReplacement( 12987 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12988 } 12989 12990 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12991 << ("0x2 ^ " + RHSStr) << SuggestXor; 12992 } else if (LeftSideValue == 10) { 12993 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12994 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12995 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12996 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12997 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12998 << ("0xA ^ " + RHSStr) << SuggestXor; 12999 } 13000 } 13001 13002 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13003 SourceLocation Loc) { 13004 // Ensure that either both operands are of the same vector type, or 13005 // one operand is of a vector type and the other is of its element type. 13006 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 13007 /*AllowBothBool*/ true, 13008 /*AllowBoolConversions*/ false, 13009 /*AllowBooleanOperation*/ false, 13010 /*ReportInvalid*/ false); 13011 if (vType.isNull()) 13012 return InvalidOperands(Loc, LHS, RHS); 13013 if (getLangOpts().OpenCL && 13014 getLangOpts().getOpenCLCompatibleVersion() < 120 && 13015 vType->hasFloatingRepresentation()) 13016 return InvalidOperands(Loc, LHS, RHS); 13017 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 13018 // usage of the logical operators && and || with vectors in C. This 13019 // check could be notionally dropped. 13020 if (!getLangOpts().CPlusPlus && 13021 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 13022 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 13023 13024 return GetSignedVectorType(LHS.get()->getType()); 13025 } 13026 13027 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 13028 SourceLocation Loc, 13029 bool IsCompAssign) { 13030 if (!IsCompAssign) { 13031 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13032 if (LHS.isInvalid()) 13033 return QualType(); 13034 } 13035 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13036 if (RHS.isInvalid()) 13037 return QualType(); 13038 13039 // For conversion purposes, we ignore any qualifiers. 13040 // For example, "const float" and "float" are equivalent. 13041 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 13042 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 13043 13044 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 13045 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 13046 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13047 13048 if (Context.hasSameType(LHSType, RHSType)) 13049 return LHSType; 13050 13051 // Type conversion may change LHS/RHS. Keep copies to the original results, in 13052 // case we have to return InvalidOperands. 13053 ExprResult OriginalLHS = LHS; 13054 ExprResult OriginalRHS = RHS; 13055 if (LHSMatType && !RHSMatType) { 13056 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 13057 if (!RHS.isInvalid()) 13058 return LHSType; 13059 13060 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13061 } 13062 13063 if (!LHSMatType && RHSMatType) { 13064 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 13065 if (!LHS.isInvalid()) 13066 return RHSType; 13067 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13068 } 13069 13070 return InvalidOperands(Loc, LHS, RHS); 13071 } 13072 13073 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 13074 SourceLocation Loc, 13075 bool IsCompAssign) { 13076 if (!IsCompAssign) { 13077 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13078 if (LHS.isInvalid()) 13079 return QualType(); 13080 } 13081 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13082 if (RHS.isInvalid()) 13083 return QualType(); 13084 13085 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 13086 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 13087 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13088 13089 if (LHSMatType && RHSMatType) { 13090 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 13091 return InvalidOperands(Loc, LHS, RHS); 13092 13093 if (!Context.hasSameType(LHSMatType->getElementType(), 13094 RHSMatType->getElementType())) 13095 return InvalidOperands(Loc, LHS, RHS); 13096 13097 return Context.getConstantMatrixType(LHSMatType->getElementType(), 13098 LHSMatType->getNumRows(), 13099 RHSMatType->getNumColumns()); 13100 } 13101 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 13102 } 13103 13104 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { 13105 switch (Opc) { 13106 default: 13107 return false; 13108 case BO_And: 13109 case BO_AndAssign: 13110 case BO_Or: 13111 case BO_OrAssign: 13112 case BO_Xor: 13113 case BO_XorAssign: 13114 return true; 13115 } 13116 } 13117 13118 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 13119 SourceLocation Loc, 13120 BinaryOperatorKind Opc) { 13121 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 13122 13123 bool IsCompAssign = 13124 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 13125 13126 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); 13127 13128 if (LHS.get()->getType()->isVectorType() || 13129 RHS.get()->getType()->isVectorType()) { 13130 if (LHS.get()->getType()->hasIntegerRepresentation() && 13131 RHS.get()->getType()->hasIntegerRepresentation()) 13132 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 13133 /*AllowBothBool*/ true, 13134 /*AllowBoolConversions*/ getLangOpts().ZVector, 13135 /*AllowBooleanOperation*/ LegalBoolVecOperator, 13136 /*ReportInvalid*/ true); 13137 return InvalidOperands(Loc, LHS, RHS); 13138 } 13139 13140 if (LHS.get()->getType()->isVLSTBuiltinType() || 13141 RHS.get()->getType()->isVLSTBuiltinType()) { 13142 if (LHS.get()->getType()->hasIntegerRepresentation() && 13143 RHS.get()->getType()->hasIntegerRepresentation()) 13144 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13145 ACK_BitwiseOp); 13146 return InvalidOperands(Loc, LHS, RHS); 13147 } 13148 13149 if (LHS.get()->getType()->isVLSTBuiltinType() || 13150 RHS.get()->getType()->isVLSTBuiltinType()) { 13151 if (LHS.get()->getType()->hasIntegerRepresentation() && 13152 RHS.get()->getType()->hasIntegerRepresentation()) 13153 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13154 ACK_BitwiseOp); 13155 return InvalidOperands(Loc, LHS, RHS); 13156 } 13157 13158 if (Opc == BO_And) 13159 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 13160 13161 if (LHS.get()->getType()->hasFloatingRepresentation() || 13162 RHS.get()->getType()->hasFloatingRepresentation()) 13163 return InvalidOperands(Loc, LHS, RHS); 13164 13165 ExprResult LHSResult = LHS, RHSResult = RHS; 13166 QualType compType = UsualArithmeticConversions( 13167 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 13168 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 13169 return QualType(); 13170 LHS = LHSResult.get(); 13171 RHS = RHSResult.get(); 13172 13173 if (Opc == BO_Xor) 13174 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 13175 13176 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 13177 return compType; 13178 return InvalidOperands(Loc, LHS, RHS); 13179 } 13180 13181 // C99 6.5.[13,14] 13182 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13183 SourceLocation Loc, 13184 BinaryOperatorKind Opc) { 13185 // Check vector operands differently. 13186 if (LHS.get()->getType()->isVectorType() || 13187 RHS.get()->getType()->isVectorType()) 13188 return CheckVectorLogicalOperands(LHS, RHS, Loc); 13189 13190 bool EnumConstantInBoolContext = false; 13191 for (const ExprResult &HS : {LHS, RHS}) { 13192 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 13193 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 13194 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 13195 EnumConstantInBoolContext = true; 13196 } 13197 } 13198 13199 if (EnumConstantInBoolContext) 13200 Diag(Loc, diag::warn_enum_constant_in_bool_context); 13201 13202 // Diagnose cases where the user write a logical and/or but probably meant a 13203 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 13204 // is a constant. 13205 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 13206 !LHS.get()->getType()->isBooleanType() && 13207 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 13208 // Don't warn in macros or template instantiations. 13209 !Loc.isMacroID() && !inTemplateInstantiation()) { 13210 // If the RHS can be constant folded, and if it constant folds to something 13211 // that isn't 0 or 1 (which indicate a potential logical operation that 13212 // happened to fold to true/false) then warn. 13213 // Parens on the RHS are ignored. 13214 Expr::EvalResult EVResult; 13215 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 13216 llvm::APSInt Result = EVResult.Val.getInt(); 13217 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 13218 !RHS.get()->getExprLoc().isMacroID()) || 13219 (Result != 0 && Result != 1)) { 13220 Diag(Loc, diag::warn_logical_instead_of_bitwise) 13221 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||"); 13222 // Suggest replacing the logical operator with the bitwise version 13223 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 13224 << (Opc == BO_LAnd ? "&" : "|") 13225 << FixItHint::CreateReplacement( 13226 SourceRange(Loc, getLocForEndOfToken(Loc)), 13227 Opc == BO_LAnd ? "&" : "|"); 13228 if (Opc == BO_LAnd) 13229 // Suggest replacing "Foo() && kNonZero" with "Foo()" 13230 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 13231 << FixItHint::CreateRemoval( 13232 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 13233 RHS.get()->getEndLoc())); 13234 } 13235 } 13236 } 13237 13238 if (!Context.getLangOpts().CPlusPlus) { 13239 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 13240 // not operate on the built-in scalar and vector float types. 13241 if (Context.getLangOpts().OpenCL && 13242 Context.getLangOpts().OpenCLVersion < 120) { 13243 if (LHS.get()->getType()->isFloatingType() || 13244 RHS.get()->getType()->isFloatingType()) 13245 return InvalidOperands(Loc, LHS, RHS); 13246 } 13247 13248 LHS = UsualUnaryConversions(LHS.get()); 13249 if (LHS.isInvalid()) 13250 return QualType(); 13251 13252 RHS = UsualUnaryConversions(RHS.get()); 13253 if (RHS.isInvalid()) 13254 return QualType(); 13255 13256 if (!LHS.get()->getType()->isScalarType() || 13257 !RHS.get()->getType()->isScalarType()) 13258 return InvalidOperands(Loc, LHS, RHS); 13259 13260 return Context.IntTy; 13261 } 13262 13263 // The following is safe because we only use this method for 13264 // non-overloadable operands. 13265 13266 // C++ [expr.log.and]p1 13267 // C++ [expr.log.or]p1 13268 // The operands are both contextually converted to type bool. 13269 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 13270 if (LHSRes.isInvalid()) 13271 return InvalidOperands(Loc, LHS, RHS); 13272 LHS = LHSRes; 13273 13274 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 13275 if (RHSRes.isInvalid()) 13276 return InvalidOperands(Loc, LHS, RHS); 13277 RHS = RHSRes; 13278 13279 // C++ [expr.log.and]p2 13280 // C++ [expr.log.or]p2 13281 // The result is a bool. 13282 return Context.BoolTy; 13283 } 13284 13285 static bool IsReadonlyMessage(Expr *E, Sema &S) { 13286 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13287 if (!ME) return false; 13288 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 13289 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 13290 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 13291 if (!Base) return false; 13292 return Base->getMethodDecl() != nullptr; 13293 } 13294 13295 /// Is the given expression (which must be 'const') a reference to a 13296 /// variable which was originally non-const, but which has become 13297 /// 'const' due to being captured within a block? 13298 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 13299 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 13300 assert(E->isLValue() && E->getType().isConstQualified()); 13301 E = E->IgnoreParens(); 13302 13303 // Must be a reference to a declaration from an enclosing scope. 13304 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 13305 if (!DRE) return NCCK_None; 13306 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 13307 13308 // The declaration must be a variable which is not declared 'const'. 13309 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 13310 if (!var) return NCCK_None; 13311 if (var->getType().isConstQualified()) return NCCK_None; 13312 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 13313 13314 // Decide whether the first capture was for a block or a lambda. 13315 DeclContext *DC = S.CurContext, *Prev = nullptr; 13316 // Decide whether the first capture was for a block or a lambda. 13317 while (DC) { 13318 // For init-capture, it is possible that the variable belongs to the 13319 // template pattern of the current context. 13320 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 13321 if (var->isInitCapture() && 13322 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 13323 break; 13324 if (DC == var->getDeclContext()) 13325 break; 13326 Prev = DC; 13327 DC = DC->getParent(); 13328 } 13329 // Unless we have an init-capture, we've gone one step too far. 13330 if (!var->isInitCapture()) 13331 DC = Prev; 13332 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 13333 } 13334 13335 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 13336 Ty = Ty.getNonReferenceType(); 13337 if (IsDereference && Ty->isPointerType()) 13338 Ty = Ty->getPointeeType(); 13339 return !Ty.isConstQualified(); 13340 } 13341 13342 // Update err_typecheck_assign_const and note_typecheck_assign_const 13343 // when this enum is changed. 13344 enum { 13345 ConstFunction, 13346 ConstVariable, 13347 ConstMember, 13348 ConstMethod, 13349 NestedConstMember, 13350 ConstUnknown, // Keep as last element 13351 }; 13352 13353 /// Emit the "read-only variable not assignable" error and print notes to give 13354 /// more information about why the variable is not assignable, such as pointing 13355 /// to the declaration of a const variable, showing that a method is const, or 13356 /// that the function is returning a const reference. 13357 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 13358 SourceLocation Loc) { 13359 SourceRange ExprRange = E->getSourceRange(); 13360 13361 // Only emit one error on the first const found. All other consts will emit 13362 // a note to the error. 13363 bool DiagnosticEmitted = false; 13364 13365 // Track if the current expression is the result of a dereference, and if the 13366 // next checked expression is the result of a dereference. 13367 bool IsDereference = false; 13368 bool NextIsDereference = false; 13369 13370 // Loop to process MemberExpr chains. 13371 while (true) { 13372 IsDereference = NextIsDereference; 13373 13374 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 13375 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13376 NextIsDereference = ME->isArrow(); 13377 const ValueDecl *VD = ME->getMemberDecl(); 13378 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 13379 // Mutable fields can be modified even if the class is const. 13380 if (Field->isMutable()) { 13381 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 13382 break; 13383 } 13384 13385 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 13386 if (!DiagnosticEmitted) { 13387 S.Diag(Loc, diag::err_typecheck_assign_const) 13388 << ExprRange << ConstMember << false /*static*/ << Field 13389 << Field->getType(); 13390 DiagnosticEmitted = true; 13391 } 13392 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13393 << ConstMember << false /*static*/ << Field << Field->getType() 13394 << Field->getSourceRange(); 13395 } 13396 E = ME->getBase(); 13397 continue; 13398 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 13399 if (VDecl->getType().isConstQualified()) { 13400 if (!DiagnosticEmitted) { 13401 S.Diag(Loc, diag::err_typecheck_assign_const) 13402 << ExprRange << ConstMember << true /*static*/ << VDecl 13403 << VDecl->getType(); 13404 DiagnosticEmitted = true; 13405 } 13406 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13407 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 13408 << VDecl->getSourceRange(); 13409 } 13410 // Static fields do not inherit constness from parents. 13411 break; 13412 } 13413 break; // End MemberExpr 13414 } else if (const ArraySubscriptExpr *ASE = 13415 dyn_cast<ArraySubscriptExpr>(E)) { 13416 E = ASE->getBase()->IgnoreParenImpCasts(); 13417 continue; 13418 } else if (const ExtVectorElementExpr *EVE = 13419 dyn_cast<ExtVectorElementExpr>(E)) { 13420 E = EVE->getBase()->IgnoreParenImpCasts(); 13421 continue; 13422 } 13423 break; 13424 } 13425 13426 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 13427 // Function calls 13428 const FunctionDecl *FD = CE->getDirectCallee(); 13429 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 13430 if (!DiagnosticEmitted) { 13431 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13432 << ConstFunction << FD; 13433 DiagnosticEmitted = true; 13434 } 13435 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 13436 diag::note_typecheck_assign_const) 13437 << ConstFunction << FD << FD->getReturnType() 13438 << FD->getReturnTypeSourceRange(); 13439 } 13440 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13441 // Point to variable declaration. 13442 if (const ValueDecl *VD = DRE->getDecl()) { 13443 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 13444 if (!DiagnosticEmitted) { 13445 S.Diag(Loc, diag::err_typecheck_assign_const) 13446 << ExprRange << ConstVariable << VD << VD->getType(); 13447 DiagnosticEmitted = true; 13448 } 13449 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13450 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 13451 } 13452 } 13453 } else if (isa<CXXThisExpr>(E)) { 13454 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 13455 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 13456 if (MD->isConst()) { 13457 if (!DiagnosticEmitted) { 13458 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13459 << ConstMethod << MD; 13460 DiagnosticEmitted = true; 13461 } 13462 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 13463 << ConstMethod << MD << MD->getSourceRange(); 13464 } 13465 } 13466 } 13467 } 13468 13469 if (DiagnosticEmitted) 13470 return; 13471 13472 // Can't determine a more specific message, so display the generic error. 13473 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 13474 } 13475 13476 enum OriginalExprKind { 13477 OEK_Variable, 13478 OEK_Member, 13479 OEK_LValue 13480 }; 13481 13482 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 13483 const RecordType *Ty, 13484 SourceLocation Loc, SourceRange Range, 13485 OriginalExprKind OEK, 13486 bool &DiagnosticEmitted) { 13487 std::vector<const RecordType *> RecordTypeList; 13488 RecordTypeList.push_back(Ty); 13489 unsigned NextToCheckIndex = 0; 13490 // We walk the record hierarchy breadth-first to ensure that we print 13491 // diagnostics in field nesting order. 13492 while (RecordTypeList.size() > NextToCheckIndex) { 13493 bool IsNested = NextToCheckIndex > 0; 13494 for (const FieldDecl *Field : 13495 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 13496 // First, check every field for constness. 13497 QualType FieldTy = Field->getType(); 13498 if (FieldTy.isConstQualified()) { 13499 if (!DiagnosticEmitted) { 13500 S.Diag(Loc, diag::err_typecheck_assign_const) 13501 << Range << NestedConstMember << OEK << VD 13502 << IsNested << Field; 13503 DiagnosticEmitted = true; 13504 } 13505 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 13506 << NestedConstMember << IsNested << Field 13507 << FieldTy << Field->getSourceRange(); 13508 } 13509 13510 // Then we append it to the list to check next in order. 13511 FieldTy = FieldTy.getCanonicalType(); 13512 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 13513 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 13514 RecordTypeList.push_back(FieldRecTy); 13515 } 13516 } 13517 ++NextToCheckIndex; 13518 } 13519 } 13520 13521 /// Emit an error for the case where a record we are trying to assign to has a 13522 /// const-qualified field somewhere in its hierarchy. 13523 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 13524 SourceLocation Loc) { 13525 QualType Ty = E->getType(); 13526 assert(Ty->isRecordType() && "lvalue was not record?"); 13527 SourceRange Range = E->getSourceRange(); 13528 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 13529 bool DiagEmitted = false; 13530 13531 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 13532 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 13533 Range, OEK_Member, DiagEmitted); 13534 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13535 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 13536 Range, OEK_Variable, DiagEmitted); 13537 else 13538 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 13539 Range, OEK_LValue, DiagEmitted); 13540 if (!DiagEmitted) 13541 DiagnoseConstAssignment(S, E, Loc); 13542 } 13543 13544 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 13545 /// emit an error and return true. If so, return false. 13546 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 13547 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 13548 13549 S.CheckShadowingDeclModification(E, Loc); 13550 13551 SourceLocation OrigLoc = Loc; 13552 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 13553 &Loc); 13554 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 13555 IsLV = Expr::MLV_InvalidMessageExpression; 13556 if (IsLV == Expr::MLV_Valid) 13557 return false; 13558 13559 unsigned DiagID = 0; 13560 bool NeedType = false; 13561 switch (IsLV) { // C99 6.5.16p2 13562 case Expr::MLV_ConstQualified: 13563 // Use a specialized diagnostic when we're assigning to an object 13564 // from an enclosing function or block. 13565 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13566 if (NCCK == NCCK_Block) 13567 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13568 else 13569 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13570 break; 13571 } 13572 13573 // In ARC, use some specialized diagnostics for occasions where we 13574 // infer 'const'. These are always pseudo-strong variables. 13575 if (S.getLangOpts().ObjCAutoRefCount) { 13576 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13577 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13578 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13579 13580 // Use the normal diagnostic if it's pseudo-__strong but the 13581 // user actually wrote 'const'. 13582 if (var->isARCPseudoStrong() && 13583 (!var->getTypeSourceInfo() || 13584 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13585 // There are three pseudo-strong cases: 13586 // - self 13587 ObjCMethodDecl *method = S.getCurMethodDecl(); 13588 if (method && var == method->getSelfDecl()) { 13589 DiagID = method->isClassMethod() 13590 ? diag::err_typecheck_arc_assign_self_class_method 13591 : diag::err_typecheck_arc_assign_self; 13592 13593 // - Objective-C externally_retained attribute. 13594 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13595 isa<ParmVarDecl>(var)) { 13596 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13597 13598 // - fast enumeration variables 13599 } else { 13600 DiagID = diag::err_typecheck_arr_assign_enumeration; 13601 } 13602 13603 SourceRange Assign; 13604 if (Loc != OrigLoc) 13605 Assign = SourceRange(OrigLoc, OrigLoc); 13606 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13607 // We need to preserve the AST regardless, so migration tool 13608 // can do its job. 13609 return false; 13610 } 13611 } 13612 } 13613 13614 // If none of the special cases above are triggered, then this is a 13615 // simple const assignment. 13616 if (DiagID == 0) { 13617 DiagnoseConstAssignment(S, E, Loc); 13618 return true; 13619 } 13620 13621 break; 13622 case Expr::MLV_ConstAddrSpace: 13623 DiagnoseConstAssignment(S, E, Loc); 13624 return true; 13625 case Expr::MLV_ConstQualifiedField: 13626 DiagnoseRecursiveConstFields(S, E, Loc); 13627 return true; 13628 case Expr::MLV_ArrayType: 13629 case Expr::MLV_ArrayTemporary: 13630 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13631 NeedType = true; 13632 break; 13633 case Expr::MLV_NotObjectType: 13634 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13635 NeedType = true; 13636 break; 13637 case Expr::MLV_LValueCast: 13638 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13639 break; 13640 case Expr::MLV_Valid: 13641 llvm_unreachable("did not take early return for MLV_Valid"); 13642 case Expr::MLV_InvalidExpression: 13643 case Expr::MLV_MemberFunction: 13644 case Expr::MLV_ClassTemporary: 13645 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13646 break; 13647 case Expr::MLV_IncompleteType: 13648 case Expr::MLV_IncompleteVoidType: 13649 return S.RequireCompleteType(Loc, E->getType(), 13650 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13651 case Expr::MLV_DuplicateVectorComponents: 13652 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13653 break; 13654 case Expr::MLV_NoSetterProperty: 13655 llvm_unreachable("readonly properties should be processed differently"); 13656 case Expr::MLV_InvalidMessageExpression: 13657 DiagID = diag::err_readonly_message_assignment; 13658 break; 13659 case Expr::MLV_SubObjCPropertySetting: 13660 DiagID = diag::err_no_subobject_property_setting; 13661 break; 13662 } 13663 13664 SourceRange Assign; 13665 if (Loc != OrigLoc) 13666 Assign = SourceRange(OrigLoc, OrigLoc); 13667 if (NeedType) 13668 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13669 else 13670 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13671 return true; 13672 } 13673 13674 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13675 SourceLocation Loc, 13676 Sema &Sema) { 13677 if (Sema.inTemplateInstantiation()) 13678 return; 13679 if (Sema.isUnevaluatedContext()) 13680 return; 13681 if (Loc.isInvalid() || Loc.isMacroID()) 13682 return; 13683 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13684 return; 13685 13686 // C / C++ fields 13687 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13688 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13689 if (ML && MR) { 13690 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13691 return; 13692 const ValueDecl *LHSDecl = 13693 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13694 const ValueDecl *RHSDecl = 13695 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13696 if (LHSDecl != RHSDecl) 13697 return; 13698 if (LHSDecl->getType().isVolatileQualified()) 13699 return; 13700 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13701 if (RefTy->getPointeeType().isVolatileQualified()) 13702 return; 13703 13704 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13705 } 13706 13707 // Objective-C instance variables 13708 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13709 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13710 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13711 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13712 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13713 if (RL && RR && RL->getDecl() == RR->getDecl()) 13714 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13715 } 13716 } 13717 13718 // C99 6.5.16.1 13719 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13720 SourceLocation Loc, 13721 QualType CompoundType) { 13722 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13723 13724 // Verify that LHS is a modifiable lvalue, and emit error if not. 13725 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13726 return QualType(); 13727 13728 QualType LHSType = LHSExpr->getType(); 13729 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13730 CompoundType; 13731 // OpenCL v1.2 s6.1.1.1 p2: 13732 // The half data type can only be used to declare a pointer to a buffer that 13733 // contains half values 13734 if (getLangOpts().OpenCL && 13735 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13736 LHSType->isHalfType()) { 13737 Diag(Loc, diag::err_opencl_half_load_store) << 1 13738 << LHSType.getUnqualifiedType(); 13739 return QualType(); 13740 } 13741 13742 AssignConvertType ConvTy; 13743 if (CompoundType.isNull()) { 13744 Expr *RHSCheck = RHS.get(); 13745 13746 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13747 13748 QualType LHSTy(LHSType); 13749 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13750 if (RHS.isInvalid()) 13751 return QualType(); 13752 // Special case of NSObject attributes on c-style pointer types. 13753 if (ConvTy == IncompatiblePointer && 13754 ((Context.isObjCNSObjectType(LHSType) && 13755 RHSType->isObjCObjectPointerType()) || 13756 (Context.isObjCNSObjectType(RHSType) && 13757 LHSType->isObjCObjectPointerType()))) 13758 ConvTy = Compatible; 13759 13760 if (ConvTy == Compatible && 13761 LHSType->isObjCObjectType()) 13762 Diag(Loc, diag::err_objc_object_assignment) 13763 << LHSType; 13764 13765 // If the RHS is a unary plus or minus, check to see if they = and + are 13766 // right next to each other. If so, the user may have typo'd "x =+ 4" 13767 // instead of "x += 4". 13768 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13769 RHSCheck = ICE->getSubExpr(); 13770 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13771 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13772 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13773 // Only if the two operators are exactly adjacent. 13774 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13775 // And there is a space or other character before the subexpr of the 13776 // unary +/-. We don't want to warn on "x=-1". 13777 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13778 UO->getSubExpr()->getBeginLoc().isFileID()) { 13779 Diag(Loc, diag::warn_not_compound_assign) 13780 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13781 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13782 } 13783 } 13784 13785 if (ConvTy == Compatible) { 13786 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13787 // Warn about retain cycles where a block captures the LHS, but 13788 // not if the LHS is a simple variable into which the block is 13789 // being stored...unless that variable can be captured by reference! 13790 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13791 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13792 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13793 checkRetainCycles(LHSExpr, RHS.get()); 13794 } 13795 13796 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13797 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13798 // It is safe to assign a weak reference into a strong variable. 13799 // Although this code can still have problems: 13800 // id x = self.weakProp; 13801 // id y = self.weakProp; 13802 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13803 // paths through the function. This should be revisited if 13804 // -Wrepeated-use-of-weak is made flow-sensitive. 13805 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13806 // variable, which will be valid for the current autorelease scope. 13807 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13808 RHS.get()->getBeginLoc())) 13809 getCurFunction()->markSafeWeakUse(RHS.get()); 13810 13811 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13812 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13813 } 13814 } 13815 } else { 13816 // Compound assignment "x += y" 13817 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13818 } 13819 13820 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13821 RHS.get(), AA_Assigning)) 13822 return QualType(); 13823 13824 CheckForNullPointerDereference(*this, LHSExpr); 13825 13826 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13827 if (CompoundType.isNull()) { 13828 // C++2a [expr.ass]p5: 13829 // A simple-assignment whose left operand is of a volatile-qualified 13830 // type is deprecated unless the assignment is either a discarded-value 13831 // expression or an unevaluated operand 13832 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13833 } else { 13834 // C++2a [expr.ass]p6: 13835 // [Compound-assignment] expressions are deprecated if E1 has 13836 // volatile-qualified type 13837 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13838 } 13839 } 13840 13841 // C11 6.5.16p3: The type of an assignment expression is the type of the 13842 // left operand would have after lvalue conversion. 13843 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has 13844 // qualified type, the value has the unqualified version of the type of the 13845 // lvalue; additionally, if the lvalue has atomic type, the value has the 13846 // non-atomic version of the type of the lvalue. 13847 // C++ 5.17p1: the type of the assignment expression is that of its left 13848 // operand. 13849 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); 13850 } 13851 13852 // Only ignore explicit casts to void. 13853 static bool IgnoreCommaOperand(const Expr *E) { 13854 E = E->IgnoreParens(); 13855 13856 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13857 if (CE->getCastKind() == CK_ToVoid) { 13858 return true; 13859 } 13860 13861 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13862 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13863 CE->getSubExpr()->getType()->isDependentType()) { 13864 return true; 13865 } 13866 } 13867 13868 return false; 13869 } 13870 13871 // Look for instances where it is likely the comma operator is confused with 13872 // another operator. There is an explicit list of acceptable expressions for 13873 // the left hand side of the comma operator, otherwise emit a warning. 13874 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13875 // No warnings in macros 13876 if (Loc.isMacroID()) 13877 return; 13878 13879 // Don't warn in template instantiations. 13880 if (inTemplateInstantiation()) 13881 return; 13882 13883 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13884 // instead, skip more than needed, then call back into here with the 13885 // CommaVisitor in SemaStmt.cpp. 13886 // The listed locations are the initialization and increment portions 13887 // of a for loop. The additional checks are on the condition of 13888 // if statements, do/while loops, and for loops. 13889 // Differences in scope flags for C89 mode requires the extra logic. 13890 const unsigned ForIncrementFlags = 13891 getLangOpts().C99 || getLangOpts().CPlusPlus 13892 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13893 : Scope::ContinueScope | Scope::BreakScope; 13894 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13895 const unsigned ScopeFlags = getCurScope()->getFlags(); 13896 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13897 (ScopeFlags & ForInitFlags) == ForInitFlags) 13898 return; 13899 13900 // If there are multiple comma operators used together, get the RHS of the 13901 // of the comma operator as the LHS. 13902 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13903 if (BO->getOpcode() != BO_Comma) 13904 break; 13905 LHS = BO->getRHS(); 13906 } 13907 13908 // Only allow some expressions on LHS to not warn. 13909 if (IgnoreCommaOperand(LHS)) 13910 return; 13911 13912 Diag(Loc, diag::warn_comma_operator); 13913 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13914 << LHS->getSourceRange() 13915 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13916 LangOpts.CPlusPlus ? "static_cast<void>(" 13917 : "(void)(") 13918 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13919 ")"); 13920 } 13921 13922 // C99 6.5.17 13923 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13924 SourceLocation Loc) { 13925 LHS = S.CheckPlaceholderExpr(LHS.get()); 13926 RHS = S.CheckPlaceholderExpr(RHS.get()); 13927 if (LHS.isInvalid() || RHS.isInvalid()) 13928 return QualType(); 13929 13930 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13931 // operands, but not unary promotions. 13932 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13933 13934 // So we treat the LHS as a ignored value, and in C++ we allow the 13935 // containing site to determine what should be done with the RHS. 13936 LHS = S.IgnoredValueConversions(LHS.get()); 13937 if (LHS.isInvalid()) 13938 return QualType(); 13939 13940 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13941 13942 if (!S.getLangOpts().CPlusPlus) { 13943 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13944 if (RHS.isInvalid()) 13945 return QualType(); 13946 if (!RHS.get()->getType()->isVoidType()) 13947 S.RequireCompleteType(Loc, RHS.get()->getType(), 13948 diag::err_incomplete_type); 13949 } 13950 13951 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13952 S.DiagnoseCommaOperator(LHS.get(), Loc); 13953 13954 return RHS.get()->getType(); 13955 } 13956 13957 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13958 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13959 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13960 ExprValueKind &VK, 13961 ExprObjectKind &OK, 13962 SourceLocation OpLoc, 13963 bool IsInc, bool IsPrefix) { 13964 if (Op->isTypeDependent()) 13965 return S.Context.DependentTy; 13966 13967 QualType ResType = Op->getType(); 13968 // Atomic types can be used for increment / decrement where the non-atomic 13969 // versions can, so ignore the _Atomic() specifier for the purpose of 13970 // checking. 13971 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13972 ResType = ResAtomicType->getValueType(); 13973 13974 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13975 13976 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13977 // Decrement of bool is not allowed. 13978 if (!IsInc) { 13979 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13980 return QualType(); 13981 } 13982 // Increment of bool sets it to true, but is deprecated. 13983 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13984 : diag::warn_increment_bool) 13985 << Op->getSourceRange(); 13986 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13987 // Error on enum increments and decrements in C++ mode 13988 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13989 return QualType(); 13990 } else if (ResType->isRealType()) { 13991 // OK! 13992 } else if (ResType->isPointerType()) { 13993 // C99 6.5.2.4p2, 6.5.6p2 13994 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13995 return QualType(); 13996 } else if (ResType->isObjCObjectPointerType()) { 13997 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13998 // Otherwise, we just need a complete type. 13999 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 14000 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 14001 return QualType(); 14002 } else if (ResType->isAnyComplexType()) { 14003 // C99 does not support ++/-- on complex types, we allow as an extension. 14004 S.Diag(OpLoc, diag::ext_integer_increment_complex) 14005 << ResType << Op->getSourceRange(); 14006 } else if (ResType->isPlaceholderType()) { 14007 ExprResult PR = S.CheckPlaceholderExpr(Op); 14008 if (PR.isInvalid()) return QualType(); 14009 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 14010 IsInc, IsPrefix); 14011 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 14012 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 14013 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 14014 (ResType->castAs<VectorType>()->getVectorKind() != 14015 VectorType::AltiVecBool)) { 14016 // The z vector extensions allow ++ and -- for non-bool vectors. 14017 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 14018 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 14019 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 14020 } else { 14021 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 14022 << ResType << int(IsInc) << Op->getSourceRange(); 14023 return QualType(); 14024 } 14025 // At this point, we know we have a real, complex or pointer type. 14026 // Now make sure the operand is a modifiable lvalue. 14027 if (CheckForModifiableLvalue(Op, OpLoc, S)) 14028 return QualType(); 14029 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 14030 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 14031 // An operand with volatile-qualified type is deprecated 14032 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 14033 << IsInc << ResType; 14034 } 14035 // In C++, a prefix increment is the same type as the operand. Otherwise 14036 // (in C or with postfix), the increment is the unqualified type of the 14037 // operand. 14038 if (IsPrefix && S.getLangOpts().CPlusPlus) { 14039 VK = VK_LValue; 14040 OK = Op->getObjectKind(); 14041 return ResType; 14042 } else { 14043 VK = VK_PRValue; 14044 return ResType.getUnqualifiedType(); 14045 } 14046 } 14047 14048 14049 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 14050 /// This routine allows us to typecheck complex/recursive expressions 14051 /// where the declaration is needed for type checking. We only need to 14052 /// handle cases when the expression references a function designator 14053 /// or is an lvalue. Here are some examples: 14054 /// - &(x) => x 14055 /// - &*****f => f for f a function designator. 14056 /// - &s.xx => s 14057 /// - &s.zz[1].yy -> s, if zz is an array 14058 /// - *(x + 1) -> x, if x is an array 14059 /// - &"123"[2] -> 0 14060 /// - & __real__ x -> x 14061 /// 14062 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 14063 /// members. 14064 static ValueDecl *getPrimaryDecl(Expr *E) { 14065 switch (E->getStmtClass()) { 14066 case Stmt::DeclRefExprClass: 14067 return cast<DeclRefExpr>(E)->getDecl(); 14068 case Stmt::MemberExprClass: 14069 // If this is an arrow operator, the address is an offset from 14070 // the base's value, so the object the base refers to is 14071 // irrelevant. 14072 if (cast<MemberExpr>(E)->isArrow()) 14073 return nullptr; 14074 // Otherwise, the expression refers to a part of the base 14075 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 14076 case Stmt::ArraySubscriptExprClass: { 14077 // FIXME: This code shouldn't be necessary! We should catch the implicit 14078 // promotion of register arrays earlier. 14079 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 14080 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 14081 if (ICE->getSubExpr()->getType()->isArrayType()) 14082 return getPrimaryDecl(ICE->getSubExpr()); 14083 } 14084 return nullptr; 14085 } 14086 case Stmt::UnaryOperatorClass: { 14087 UnaryOperator *UO = cast<UnaryOperator>(E); 14088 14089 switch(UO->getOpcode()) { 14090 case UO_Real: 14091 case UO_Imag: 14092 case UO_Extension: 14093 return getPrimaryDecl(UO->getSubExpr()); 14094 default: 14095 return nullptr; 14096 } 14097 } 14098 case Stmt::ParenExprClass: 14099 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 14100 case Stmt::ImplicitCastExprClass: 14101 // If the result of an implicit cast is an l-value, we care about 14102 // the sub-expression; otherwise, the result here doesn't matter. 14103 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 14104 case Stmt::CXXUuidofExprClass: 14105 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 14106 default: 14107 return nullptr; 14108 } 14109 } 14110 14111 namespace { 14112 enum { 14113 AO_Bit_Field = 0, 14114 AO_Vector_Element = 1, 14115 AO_Property_Expansion = 2, 14116 AO_Register_Variable = 3, 14117 AO_Matrix_Element = 4, 14118 AO_No_Error = 5 14119 }; 14120 } 14121 /// Diagnose invalid operand for address of operations. 14122 /// 14123 /// \param Type The type of operand which cannot have its address taken. 14124 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 14125 Expr *E, unsigned Type) { 14126 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 14127 } 14128 14129 /// CheckAddressOfOperand - The operand of & must be either a function 14130 /// designator or an lvalue designating an object. If it is an lvalue, the 14131 /// object cannot be declared with storage class register or be a bit field. 14132 /// Note: The usual conversions are *not* applied to the operand of the & 14133 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 14134 /// In C++, the operand might be an overloaded function name, in which case 14135 /// we allow the '&' but retain the overloaded-function type. 14136 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 14137 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 14138 if (PTy->getKind() == BuiltinType::Overload) { 14139 Expr *E = OrigOp.get()->IgnoreParens(); 14140 if (!isa<OverloadExpr>(E)) { 14141 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 14142 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 14143 << OrigOp.get()->getSourceRange(); 14144 return QualType(); 14145 } 14146 14147 OverloadExpr *Ovl = cast<OverloadExpr>(E); 14148 if (isa<UnresolvedMemberExpr>(Ovl)) 14149 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 14150 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14151 << OrigOp.get()->getSourceRange(); 14152 return QualType(); 14153 } 14154 14155 return Context.OverloadTy; 14156 } 14157 14158 if (PTy->getKind() == BuiltinType::UnknownAny) 14159 return Context.UnknownAnyTy; 14160 14161 if (PTy->getKind() == BuiltinType::BoundMember) { 14162 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14163 << OrigOp.get()->getSourceRange(); 14164 return QualType(); 14165 } 14166 14167 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 14168 if (OrigOp.isInvalid()) return QualType(); 14169 } 14170 14171 if (OrigOp.get()->isTypeDependent()) 14172 return Context.DependentTy; 14173 14174 assert(!OrigOp.get()->hasPlaceholderType()); 14175 14176 // Make sure to ignore parentheses in subsequent checks 14177 Expr *op = OrigOp.get()->IgnoreParens(); 14178 14179 // In OpenCL captures for blocks called as lambda functions 14180 // are located in the private address space. Blocks used in 14181 // enqueue_kernel can be located in a different address space 14182 // depending on a vendor implementation. Thus preventing 14183 // taking an address of the capture to avoid invalid AS casts. 14184 if (LangOpts.OpenCL) { 14185 auto* VarRef = dyn_cast<DeclRefExpr>(op); 14186 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 14187 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 14188 return QualType(); 14189 } 14190 } 14191 14192 if (getLangOpts().C99) { 14193 // Implement C99-only parts of addressof rules. 14194 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 14195 if (uOp->getOpcode() == UO_Deref) 14196 // Per C99 6.5.3.2, the address of a deref always returns a valid result 14197 // (assuming the deref expression is valid). 14198 return uOp->getSubExpr()->getType(); 14199 } 14200 // Technically, there should be a check for array subscript 14201 // expressions here, but the result of one is always an lvalue anyway. 14202 } 14203 ValueDecl *dcl = getPrimaryDecl(op); 14204 14205 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 14206 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 14207 op->getBeginLoc())) 14208 return QualType(); 14209 14210 Expr::LValueClassification lval = op->ClassifyLValue(Context); 14211 unsigned AddressOfError = AO_No_Error; 14212 14213 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 14214 bool sfinae = (bool)isSFINAEContext(); 14215 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 14216 : diag::ext_typecheck_addrof_temporary) 14217 << op->getType() << op->getSourceRange(); 14218 if (sfinae) 14219 return QualType(); 14220 // Materialize the temporary as an lvalue so that we can take its address. 14221 OrigOp = op = 14222 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 14223 } else if (isa<ObjCSelectorExpr>(op)) { 14224 return Context.getPointerType(op->getType()); 14225 } else if (lval == Expr::LV_MemberFunction) { 14226 // If it's an instance method, make a member pointer. 14227 // The expression must have exactly the form &A::foo. 14228 14229 // If the underlying expression isn't a decl ref, give up. 14230 if (!isa<DeclRefExpr>(op)) { 14231 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14232 << OrigOp.get()->getSourceRange(); 14233 return QualType(); 14234 } 14235 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 14236 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 14237 14238 // The id-expression was parenthesized. 14239 if (OrigOp.get() != DRE) { 14240 Diag(OpLoc, diag::err_parens_pointer_member_function) 14241 << OrigOp.get()->getSourceRange(); 14242 14243 // The method was named without a qualifier. 14244 } else if (!DRE->getQualifier()) { 14245 if (MD->getParent()->getName().empty()) 14246 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14247 << op->getSourceRange(); 14248 else { 14249 SmallString<32> Str; 14250 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 14251 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14252 << op->getSourceRange() 14253 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 14254 } 14255 } 14256 14257 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 14258 if (isa<CXXDestructorDecl>(MD)) 14259 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 14260 14261 QualType MPTy = Context.getMemberPointerType( 14262 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 14263 // Under the MS ABI, lock down the inheritance model now. 14264 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14265 (void)isCompleteType(OpLoc, MPTy); 14266 return MPTy; 14267 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 14268 // C99 6.5.3.2p1 14269 // The operand must be either an l-value or a function designator 14270 if (!op->getType()->isFunctionType()) { 14271 // Use a special diagnostic for loads from property references. 14272 if (isa<PseudoObjectExpr>(op)) { 14273 AddressOfError = AO_Property_Expansion; 14274 } else { 14275 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 14276 << op->getType() << op->getSourceRange(); 14277 return QualType(); 14278 } 14279 } 14280 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 14281 // The operand cannot be a bit-field 14282 AddressOfError = AO_Bit_Field; 14283 } else if (op->getObjectKind() == OK_VectorComponent) { 14284 // The operand cannot be an element of a vector 14285 AddressOfError = AO_Vector_Element; 14286 } else if (op->getObjectKind() == OK_MatrixComponent) { 14287 // The operand cannot be an element of a matrix. 14288 AddressOfError = AO_Matrix_Element; 14289 } else if (dcl) { // C99 6.5.3.2p1 14290 // We have an lvalue with a decl. Make sure the decl is not declared 14291 // with the register storage-class specifier. 14292 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 14293 // in C++ it is not error to take address of a register 14294 // variable (c++03 7.1.1P3) 14295 if (vd->getStorageClass() == SC_Register && 14296 !getLangOpts().CPlusPlus) { 14297 AddressOfError = AO_Register_Variable; 14298 } 14299 } else if (isa<MSPropertyDecl>(dcl)) { 14300 AddressOfError = AO_Property_Expansion; 14301 } else if (isa<FunctionTemplateDecl>(dcl)) { 14302 return Context.OverloadTy; 14303 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 14304 // Okay: we can take the address of a field. 14305 // Could be a pointer to member, though, if there is an explicit 14306 // scope qualifier for the class. 14307 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 14308 DeclContext *Ctx = dcl->getDeclContext(); 14309 if (Ctx && Ctx->isRecord()) { 14310 if (dcl->getType()->isReferenceType()) { 14311 Diag(OpLoc, 14312 diag::err_cannot_form_pointer_to_member_of_reference_type) 14313 << dcl->getDeclName() << dcl->getType(); 14314 return QualType(); 14315 } 14316 14317 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 14318 Ctx = Ctx->getParent(); 14319 14320 QualType MPTy = Context.getMemberPointerType( 14321 op->getType(), 14322 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 14323 // Under the MS ABI, lock down the inheritance model now. 14324 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14325 (void)isCompleteType(OpLoc, MPTy); 14326 return MPTy; 14327 } 14328 } 14329 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, 14330 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl)) 14331 llvm_unreachable("Unknown/unexpected decl type"); 14332 } 14333 14334 if (AddressOfError != AO_No_Error) { 14335 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 14336 return QualType(); 14337 } 14338 14339 if (lval == Expr::LV_IncompleteVoidType) { 14340 // Taking the address of a void variable is technically illegal, but we 14341 // allow it in cases which are otherwise valid. 14342 // Example: "extern void x; void* y = &x;". 14343 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 14344 } 14345 14346 // If the operand has type "type", the result has type "pointer to type". 14347 if (op->getType()->isObjCObjectType()) 14348 return Context.getObjCObjectPointerType(op->getType()); 14349 14350 CheckAddressOfPackedMember(op); 14351 14352 return Context.getPointerType(op->getType()); 14353 } 14354 14355 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 14356 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 14357 if (!DRE) 14358 return; 14359 const Decl *D = DRE->getDecl(); 14360 if (!D) 14361 return; 14362 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 14363 if (!Param) 14364 return; 14365 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 14366 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 14367 return; 14368 if (FunctionScopeInfo *FD = S.getCurFunction()) 14369 if (!FD->ModifiedNonNullParams.count(Param)) 14370 FD->ModifiedNonNullParams.insert(Param); 14371 } 14372 14373 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 14374 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 14375 SourceLocation OpLoc) { 14376 if (Op->isTypeDependent()) 14377 return S.Context.DependentTy; 14378 14379 ExprResult ConvResult = S.UsualUnaryConversions(Op); 14380 if (ConvResult.isInvalid()) 14381 return QualType(); 14382 Op = ConvResult.get(); 14383 QualType OpTy = Op->getType(); 14384 QualType Result; 14385 14386 if (isa<CXXReinterpretCastExpr>(Op)) { 14387 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 14388 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 14389 Op->getSourceRange()); 14390 } 14391 14392 if (const PointerType *PT = OpTy->getAs<PointerType>()) 14393 { 14394 Result = PT->getPointeeType(); 14395 } 14396 else if (const ObjCObjectPointerType *OPT = 14397 OpTy->getAs<ObjCObjectPointerType>()) 14398 Result = OPT->getPointeeType(); 14399 else { 14400 ExprResult PR = S.CheckPlaceholderExpr(Op); 14401 if (PR.isInvalid()) return QualType(); 14402 if (PR.get() != Op) 14403 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 14404 } 14405 14406 if (Result.isNull()) { 14407 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 14408 << OpTy << Op->getSourceRange(); 14409 return QualType(); 14410 } 14411 14412 // Note that per both C89 and C99, indirection is always legal, even if Result 14413 // is an incomplete type or void. It would be possible to warn about 14414 // dereferencing a void pointer, but it's completely well-defined, and such a 14415 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 14416 // for pointers to 'void' but is fine for any other pointer type: 14417 // 14418 // C++ [expr.unary.op]p1: 14419 // [...] the expression to which [the unary * operator] is applied shall 14420 // be a pointer to an object type, or a pointer to a function type 14421 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 14422 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 14423 << OpTy << Op->getSourceRange(); 14424 14425 // Dereferences are usually l-values... 14426 VK = VK_LValue; 14427 14428 // ...except that certain expressions are never l-values in C. 14429 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 14430 VK = VK_PRValue; 14431 14432 return Result; 14433 } 14434 14435 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 14436 BinaryOperatorKind Opc; 14437 switch (Kind) { 14438 default: llvm_unreachable("Unknown binop!"); 14439 case tok::periodstar: Opc = BO_PtrMemD; break; 14440 case tok::arrowstar: Opc = BO_PtrMemI; break; 14441 case tok::star: Opc = BO_Mul; break; 14442 case tok::slash: Opc = BO_Div; break; 14443 case tok::percent: Opc = BO_Rem; break; 14444 case tok::plus: Opc = BO_Add; break; 14445 case tok::minus: Opc = BO_Sub; break; 14446 case tok::lessless: Opc = BO_Shl; break; 14447 case tok::greatergreater: Opc = BO_Shr; break; 14448 case tok::lessequal: Opc = BO_LE; break; 14449 case tok::less: Opc = BO_LT; break; 14450 case tok::greaterequal: Opc = BO_GE; break; 14451 case tok::greater: Opc = BO_GT; break; 14452 case tok::exclaimequal: Opc = BO_NE; break; 14453 case tok::equalequal: Opc = BO_EQ; break; 14454 case tok::spaceship: Opc = BO_Cmp; break; 14455 case tok::amp: Opc = BO_And; break; 14456 case tok::caret: Opc = BO_Xor; break; 14457 case tok::pipe: Opc = BO_Or; break; 14458 case tok::ampamp: Opc = BO_LAnd; break; 14459 case tok::pipepipe: Opc = BO_LOr; break; 14460 case tok::equal: Opc = BO_Assign; break; 14461 case tok::starequal: Opc = BO_MulAssign; break; 14462 case tok::slashequal: Opc = BO_DivAssign; break; 14463 case tok::percentequal: Opc = BO_RemAssign; break; 14464 case tok::plusequal: Opc = BO_AddAssign; break; 14465 case tok::minusequal: Opc = BO_SubAssign; break; 14466 case tok::lesslessequal: Opc = BO_ShlAssign; break; 14467 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 14468 case tok::ampequal: Opc = BO_AndAssign; break; 14469 case tok::caretequal: Opc = BO_XorAssign; break; 14470 case tok::pipeequal: Opc = BO_OrAssign; break; 14471 case tok::comma: Opc = BO_Comma; break; 14472 } 14473 return Opc; 14474 } 14475 14476 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 14477 tok::TokenKind Kind) { 14478 UnaryOperatorKind Opc; 14479 switch (Kind) { 14480 default: llvm_unreachable("Unknown unary op!"); 14481 case tok::plusplus: Opc = UO_PreInc; break; 14482 case tok::minusminus: Opc = UO_PreDec; break; 14483 case tok::amp: Opc = UO_AddrOf; break; 14484 case tok::star: Opc = UO_Deref; break; 14485 case tok::plus: Opc = UO_Plus; break; 14486 case tok::minus: Opc = UO_Minus; break; 14487 case tok::tilde: Opc = UO_Not; break; 14488 case tok::exclaim: Opc = UO_LNot; break; 14489 case tok::kw___real: Opc = UO_Real; break; 14490 case tok::kw___imag: Opc = UO_Imag; break; 14491 case tok::kw___extension__: Opc = UO_Extension; break; 14492 } 14493 return Opc; 14494 } 14495 14496 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 14497 /// This warning suppressed in the event of macro expansions. 14498 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 14499 SourceLocation OpLoc, bool IsBuiltin) { 14500 if (S.inTemplateInstantiation()) 14501 return; 14502 if (S.isUnevaluatedContext()) 14503 return; 14504 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 14505 return; 14506 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14507 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14508 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14509 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14510 if (!LHSDeclRef || !RHSDeclRef || 14511 LHSDeclRef->getLocation().isMacroID() || 14512 RHSDeclRef->getLocation().isMacroID()) 14513 return; 14514 const ValueDecl *LHSDecl = 14515 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 14516 const ValueDecl *RHSDecl = 14517 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 14518 if (LHSDecl != RHSDecl) 14519 return; 14520 if (LHSDecl->getType().isVolatileQualified()) 14521 return; 14522 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 14523 if (RefTy->getPointeeType().isVolatileQualified()) 14524 return; 14525 14526 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 14527 : diag::warn_self_assignment_overloaded) 14528 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 14529 << RHSExpr->getSourceRange(); 14530 } 14531 14532 /// Check if a bitwise-& is performed on an Objective-C pointer. This 14533 /// is usually indicative of introspection within the Objective-C pointer. 14534 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 14535 SourceLocation OpLoc) { 14536 if (!S.getLangOpts().ObjC) 14537 return; 14538 14539 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 14540 const Expr *LHS = L.get(); 14541 const Expr *RHS = R.get(); 14542 14543 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14544 ObjCPointerExpr = LHS; 14545 OtherExpr = RHS; 14546 } 14547 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14548 ObjCPointerExpr = RHS; 14549 OtherExpr = LHS; 14550 } 14551 14552 // This warning is deliberately made very specific to reduce false 14553 // positives with logic that uses '&' for hashing. This logic mainly 14554 // looks for code trying to introspect into tagged pointers, which 14555 // code should generally never do. 14556 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 14557 unsigned Diag = diag::warn_objc_pointer_masking; 14558 // Determine if we are introspecting the result of performSelectorXXX. 14559 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 14560 // Special case messages to -performSelector and friends, which 14561 // can return non-pointer values boxed in a pointer value. 14562 // Some clients may wish to silence warnings in this subcase. 14563 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14564 Selector S = ME->getSelector(); 14565 StringRef SelArg0 = S.getNameForSlot(0); 14566 if (SelArg0.startswith("performSelector")) 14567 Diag = diag::warn_objc_pointer_masking_performSelector; 14568 } 14569 14570 S.Diag(OpLoc, Diag) 14571 << ObjCPointerExpr->getSourceRange(); 14572 } 14573 } 14574 14575 static NamedDecl *getDeclFromExpr(Expr *E) { 14576 if (!E) 14577 return nullptr; 14578 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14579 return DRE->getDecl(); 14580 if (auto *ME = dyn_cast<MemberExpr>(E)) 14581 return ME->getMemberDecl(); 14582 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14583 return IRE->getDecl(); 14584 return nullptr; 14585 } 14586 14587 // This helper function promotes a binary operator's operands (which are of a 14588 // half vector type) to a vector of floats and then truncates the result to 14589 // a vector of either half or short. 14590 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14591 BinaryOperatorKind Opc, QualType ResultTy, 14592 ExprValueKind VK, ExprObjectKind OK, 14593 bool IsCompAssign, SourceLocation OpLoc, 14594 FPOptionsOverride FPFeatures) { 14595 auto &Context = S.getASTContext(); 14596 assert((isVector(ResultTy, Context.HalfTy) || 14597 isVector(ResultTy, Context.ShortTy)) && 14598 "Result must be a vector of half or short"); 14599 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14600 isVector(RHS.get()->getType(), Context.HalfTy) && 14601 "both operands expected to be a half vector"); 14602 14603 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14604 QualType BinOpResTy = RHS.get()->getType(); 14605 14606 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14607 // change BinOpResTy to a vector of ints. 14608 if (isVector(ResultTy, Context.ShortTy)) 14609 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14610 14611 if (IsCompAssign) 14612 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14613 ResultTy, VK, OK, OpLoc, FPFeatures, 14614 BinOpResTy, BinOpResTy); 14615 14616 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14617 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14618 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14619 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14620 } 14621 14622 static std::pair<ExprResult, ExprResult> 14623 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14624 Expr *RHSExpr) { 14625 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14626 if (!S.Context.isDependenceAllowed()) { 14627 // C cannot handle TypoExpr nodes on either side of a binop because it 14628 // doesn't handle dependent types properly, so make sure any TypoExprs have 14629 // been dealt with before checking the operands. 14630 LHS = S.CorrectDelayedTyposInExpr(LHS); 14631 RHS = S.CorrectDelayedTyposInExpr( 14632 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14633 [Opc, LHS](Expr *E) { 14634 if (Opc != BO_Assign) 14635 return ExprResult(E); 14636 // Avoid correcting the RHS to the same Expr as the LHS. 14637 Decl *D = getDeclFromExpr(E); 14638 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14639 }); 14640 } 14641 return std::make_pair(LHS, RHS); 14642 } 14643 14644 /// Returns true if conversion between vectors of halfs and vectors of floats 14645 /// is needed. 14646 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14647 Expr *E0, Expr *E1 = nullptr) { 14648 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14649 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14650 return false; 14651 14652 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14653 QualType Ty = E->IgnoreImplicit()->getType(); 14654 14655 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14656 // to vectors of floats. Although the element type of the vectors is __fp16, 14657 // the vectors shouldn't be treated as storage-only types. See the 14658 // discussion here: https://reviews.llvm.org/rG825235c140e7 14659 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14660 if (VT->getVectorKind() == VectorType::NeonVector) 14661 return false; 14662 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14663 } 14664 return false; 14665 }; 14666 14667 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14668 } 14669 14670 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14671 /// operator @p Opc at location @c TokLoc. This routine only supports 14672 /// built-in operations; ActOnBinOp handles overloaded operators. 14673 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14674 BinaryOperatorKind Opc, 14675 Expr *LHSExpr, Expr *RHSExpr) { 14676 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14677 // The syntax only allows initializer lists on the RHS of assignment, 14678 // so we don't need to worry about accepting invalid code for 14679 // non-assignment operators. 14680 // C++11 5.17p9: 14681 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14682 // of x = {} is x = T(). 14683 InitializationKind Kind = InitializationKind::CreateDirectList( 14684 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14685 InitializedEntity Entity = 14686 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14687 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14688 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14689 if (Init.isInvalid()) 14690 return Init; 14691 RHSExpr = Init.get(); 14692 } 14693 14694 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14695 QualType ResultTy; // Result type of the binary operator. 14696 // The following two variables are used for compound assignment operators 14697 QualType CompLHSTy; // Type of LHS after promotions for computation 14698 QualType CompResultTy; // Type of computation result 14699 ExprValueKind VK = VK_PRValue; 14700 ExprObjectKind OK = OK_Ordinary; 14701 bool ConvertHalfVec = false; 14702 14703 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14704 if (!LHS.isUsable() || !RHS.isUsable()) 14705 return ExprError(); 14706 14707 if (getLangOpts().OpenCL) { 14708 QualType LHSTy = LHSExpr->getType(); 14709 QualType RHSTy = RHSExpr->getType(); 14710 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14711 // the ATOMIC_VAR_INIT macro. 14712 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14713 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14714 if (BO_Assign == Opc) 14715 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14716 else 14717 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14718 return ExprError(); 14719 } 14720 14721 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14722 // only with a builtin functions and therefore should be disallowed here. 14723 if (LHSTy->isImageType() || RHSTy->isImageType() || 14724 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14725 LHSTy->isPipeType() || RHSTy->isPipeType() || 14726 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14727 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14728 return ExprError(); 14729 } 14730 } 14731 14732 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14733 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14734 14735 switch (Opc) { 14736 case BO_Assign: 14737 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14738 if (getLangOpts().CPlusPlus && 14739 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14740 VK = LHS.get()->getValueKind(); 14741 OK = LHS.get()->getObjectKind(); 14742 } 14743 if (!ResultTy.isNull()) { 14744 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14745 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14746 14747 // Avoid copying a block to the heap if the block is assigned to a local 14748 // auto variable that is declared in the same scope as the block. This 14749 // optimization is unsafe if the local variable is declared in an outer 14750 // scope. For example: 14751 // 14752 // BlockTy b; 14753 // { 14754 // b = ^{...}; 14755 // } 14756 // // It is unsafe to invoke the block here if it wasn't copied to the 14757 // // heap. 14758 // b(); 14759 14760 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14761 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14762 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14763 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14764 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14765 14766 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14767 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14768 NTCUC_Assignment, NTCUK_Copy); 14769 } 14770 RecordModifiableNonNullParam(*this, LHS.get()); 14771 break; 14772 case BO_PtrMemD: 14773 case BO_PtrMemI: 14774 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14775 Opc == BO_PtrMemI); 14776 break; 14777 case BO_Mul: 14778 case BO_Div: 14779 ConvertHalfVec = true; 14780 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14781 Opc == BO_Div); 14782 break; 14783 case BO_Rem: 14784 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14785 break; 14786 case BO_Add: 14787 ConvertHalfVec = true; 14788 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14789 break; 14790 case BO_Sub: 14791 ConvertHalfVec = true; 14792 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14793 break; 14794 case BO_Shl: 14795 case BO_Shr: 14796 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14797 break; 14798 case BO_LE: 14799 case BO_LT: 14800 case BO_GE: 14801 case BO_GT: 14802 ConvertHalfVec = true; 14803 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14804 break; 14805 case BO_EQ: 14806 case BO_NE: 14807 ConvertHalfVec = true; 14808 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14809 break; 14810 case BO_Cmp: 14811 ConvertHalfVec = true; 14812 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14813 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14814 break; 14815 case BO_And: 14816 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14817 LLVM_FALLTHROUGH; 14818 case BO_Xor: 14819 case BO_Or: 14820 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14821 break; 14822 case BO_LAnd: 14823 case BO_LOr: 14824 ConvertHalfVec = true; 14825 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14826 break; 14827 case BO_MulAssign: 14828 case BO_DivAssign: 14829 ConvertHalfVec = true; 14830 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14831 Opc == BO_DivAssign); 14832 CompLHSTy = CompResultTy; 14833 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14834 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14835 break; 14836 case BO_RemAssign: 14837 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14838 CompLHSTy = CompResultTy; 14839 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14840 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14841 break; 14842 case BO_AddAssign: 14843 ConvertHalfVec = true; 14844 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14845 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14846 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14847 break; 14848 case BO_SubAssign: 14849 ConvertHalfVec = true; 14850 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14851 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14852 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14853 break; 14854 case BO_ShlAssign: 14855 case BO_ShrAssign: 14856 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14857 CompLHSTy = CompResultTy; 14858 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14859 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14860 break; 14861 case BO_AndAssign: 14862 case BO_OrAssign: // fallthrough 14863 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14864 LLVM_FALLTHROUGH; 14865 case BO_XorAssign: 14866 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14867 CompLHSTy = CompResultTy; 14868 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14869 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14870 break; 14871 case BO_Comma: 14872 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14873 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14874 VK = RHS.get()->getValueKind(); 14875 OK = RHS.get()->getObjectKind(); 14876 } 14877 break; 14878 } 14879 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14880 return ExprError(); 14881 14882 // Some of the binary operations require promoting operands of half vector to 14883 // float vectors and truncating the result back to half vector. For now, we do 14884 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14885 // arm64). 14886 assert( 14887 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14888 isVector(LHS.get()->getType(), Context.HalfTy)) && 14889 "both sides are half vectors or neither sides are"); 14890 ConvertHalfVec = 14891 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14892 14893 // Check for array bounds violations for both sides of the BinaryOperator 14894 CheckArrayAccess(LHS.get()); 14895 CheckArrayAccess(RHS.get()); 14896 14897 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14898 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14899 &Context.Idents.get("object_setClass"), 14900 SourceLocation(), LookupOrdinaryName); 14901 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14902 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14903 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14904 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14905 "object_setClass(") 14906 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14907 ",") 14908 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14909 } 14910 else 14911 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14912 } 14913 else if (const ObjCIvarRefExpr *OIRE = 14914 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14915 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14916 14917 // Opc is not a compound assignment if CompResultTy is null. 14918 if (CompResultTy.isNull()) { 14919 if (ConvertHalfVec) 14920 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14921 OpLoc, CurFPFeatureOverrides()); 14922 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14923 VK, OK, OpLoc, CurFPFeatureOverrides()); 14924 } 14925 14926 // Handle compound assignments. 14927 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14928 OK_ObjCProperty) { 14929 VK = VK_LValue; 14930 OK = LHS.get()->getObjectKind(); 14931 } 14932 14933 // The LHS is not converted to the result type for fixed-point compound 14934 // assignment as the common type is computed on demand. Reset the CompLHSTy 14935 // to the LHS type we would have gotten after unary conversions. 14936 if (CompResultTy->isFixedPointType()) 14937 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14938 14939 if (ConvertHalfVec) 14940 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14941 OpLoc, CurFPFeatureOverrides()); 14942 14943 return CompoundAssignOperator::Create( 14944 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14945 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14946 } 14947 14948 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14949 /// operators are mixed in a way that suggests that the programmer forgot that 14950 /// comparison operators have higher precedence. The most typical example of 14951 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14952 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14953 SourceLocation OpLoc, Expr *LHSExpr, 14954 Expr *RHSExpr) { 14955 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14956 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14957 14958 // Check that one of the sides is a comparison operator and the other isn't. 14959 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14960 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14961 if (isLeftComp == isRightComp) 14962 return; 14963 14964 // Bitwise operations are sometimes used as eager logical ops. 14965 // Don't diagnose this. 14966 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14967 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14968 if (isLeftBitwise || isRightBitwise) 14969 return; 14970 14971 SourceRange DiagRange = isLeftComp 14972 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14973 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14974 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14975 SourceRange ParensRange = 14976 isLeftComp 14977 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14978 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14979 14980 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14981 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14982 SuggestParentheses(Self, OpLoc, 14983 Self.PDiag(diag::note_precedence_silence) << OpStr, 14984 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14985 SuggestParentheses(Self, OpLoc, 14986 Self.PDiag(diag::note_precedence_bitwise_first) 14987 << BinaryOperator::getOpcodeStr(Opc), 14988 ParensRange); 14989 } 14990 14991 /// It accepts a '&&' expr that is inside a '||' one. 14992 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14993 /// in parentheses. 14994 static void 14995 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14996 BinaryOperator *Bop) { 14997 assert(Bop->getOpcode() == BO_LAnd); 14998 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14999 << Bop->getSourceRange() << OpLoc; 15000 SuggestParentheses(Self, Bop->getOperatorLoc(), 15001 Self.PDiag(diag::note_precedence_silence) 15002 << Bop->getOpcodeStr(), 15003 Bop->getSourceRange()); 15004 } 15005 15006 /// Returns true if the given expression can be evaluated as a constant 15007 /// 'true'. 15008 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 15009 bool Res; 15010 return !E->isValueDependent() && 15011 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 15012 } 15013 15014 /// Returns true if the given expression can be evaluated as a constant 15015 /// 'false'. 15016 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 15017 bool Res; 15018 return !E->isValueDependent() && 15019 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 15020 } 15021 15022 /// Look for '&&' in the left hand of a '||' expr. 15023 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 15024 Expr *LHSExpr, Expr *RHSExpr) { 15025 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 15026 if (Bop->getOpcode() == BO_LAnd) { 15027 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 15028 if (EvaluatesAsFalse(S, RHSExpr)) 15029 return; 15030 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 15031 if (!EvaluatesAsTrue(S, Bop->getLHS())) 15032 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15033 } else if (Bop->getOpcode() == BO_LOr) { 15034 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 15035 // If it's "a || b && 1 || c" we didn't warn earlier for 15036 // "a || b && 1", but warn now. 15037 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 15038 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 15039 } 15040 } 15041 } 15042 } 15043 15044 /// Look for '&&' in the right hand of a '||' expr. 15045 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 15046 Expr *LHSExpr, Expr *RHSExpr) { 15047 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 15048 if (Bop->getOpcode() == BO_LAnd) { 15049 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 15050 if (EvaluatesAsFalse(S, LHSExpr)) 15051 return; 15052 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 15053 if (!EvaluatesAsTrue(S, Bop->getRHS())) 15054 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15055 } 15056 } 15057 } 15058 15059 /// Look for bitwise op in the left or right hand of a bitwise op with 15060 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 15061 /// the '&' expression in parentheses. 15062 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 15063 SourceLocation OpLoc, Expr *SubExpr) { 15064 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15065 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 15066 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 15067 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 15068 << Bop->getSourceRange() << OpLoc; 15069 SuggestParentheses(S, Bop->getOperatorLoc(), 15070 S.PDiag(diag::note_precedence_silence) 15071 << Bop->getOpcodeStr(), 15072 Bop->getSourceRange()); 15073 } 15074 } 15075 } 15076 15077 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 15078 Expr *SubExpr, StringRef Shift) { 15079 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15080 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 15081 StringRef Op = Bop->getOpcodeStr(); 15082 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 15083 << Bop->getSourceRange() << OpLoc << Shift << Op; 15084 SuggestParentheses(S, Bop->getOperatorLoc(), 15085 S.PDiag(diag::note_precedence_silence) << Op, 15086 Bop->getSourceRange()); 15087 } 15088 } 15089 } 15090 15091 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 15092 Expr *LHSExpr, Expr *RHSExpr) { 15093 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 15094 if (!OCE) 15095 return; 15096 15097 FunctionDecl *FD = OCE->getDirectCallee(); 15098 if (!FD || !FD->isOverloadedOperator()) 15099 return; 15100 15101 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 15102 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 15103 return; 15104 15105 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 15106 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 15107 << (Kind == OO_LessLess); 15108 SuggestParentheses(S, OCE->getOperatorLoc(), 15109 S.PDiag(diag::note_precedence_silence) 15110 << (Kind == OO_LessLess ? "<<" : ">>"), 15111 OCE->getSourceRange()); 15112 SuggestParentheses( 15113 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 15114 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 15115 } 15116 15117 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 15118 /// precedence. 15119 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 15120 SourceLocation OpLoc, Expr *LHSExpr, 15121 Expr *RHSExpr){ 15122 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 15123 if (BinaryOperator::isBitwiseOp(Opc)) 15124 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 15125 15126 // Diagnose "arg1 & arg2 | arg3" 15127 if ((Opc == BO_Or || Opc == BO_Xor) && 15128 !OpLoc.isMacroID()/* Don't warn in macros. */) { 15129 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 15130 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 15131 } 15132 15133 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 15134 // We don't warn for 'assert(a || b && "bad")' since this is safe. 15135 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 15136 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 15137 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 15138 } 15139 15140 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 15141 || Opc == BO_Shr) { 15142 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 15143 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 15144 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 15145 } 15146 15147 // Warn on overloaded shift operators and comparisons, such as: 15148 // cout << 5 == 4; 15149 if (BinaryOperator::isComparisonOp(Opc)) 15150 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 15151 } 15152 15153 // Binary Operators. 'Tok' is the token for the operator. 15154 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 15155 tok::TokenKind Kind, 15156 Expr *LHSExpr, Expr *RHSExpr) { 15157 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 15158 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 15159 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 15160 15161 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 15162 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 15163 15164 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 15165 } 15166 15167 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 15168 UnresolvedSetImpl &Functions) { 15169 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 15170 if (OverOp != OO_None && OverOp != OO_Equal) 15171 LookupOverloadedOperatorName(OverOp, S, Functions); 15172 15173 // In C++20 onwards, we may have a second operator to look up. 15174 if (getLangOpts().CPlusPlus20) { 15175 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 15176 LookupOverloadedOperatorName(ExtraOp, S, Functions); 15177 } 15178 } 15179 15180 /// Build an overloaded binary operator expression in the given scope. 15181 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 15182 BinaryOperatorKind Opc, 15183 Expr *LHS, Expr *RHS) { 15184 switch (Opc) { 15185 case BO_Assign: 15186 case BO_DivAssign: 15187 case BO_RemAssign: 15188 case BO_SubAssign: 15189 case BO_AndAssign: 15190 case BO_OrAssign: 15191 case BO_XorAssign: 15192 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 15193 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 15194 break; 15195 default: 15196 break; 15197 } 15198 15199 // Find all of the overloaded operators visible from this point. 15200 UnresolvedSet<16> Functions; 15201 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 15202 15203 // Build the (potentially-overloaded, potentially-dependent) 15204 // binary operation. 15205 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 15206 } 15207 15208 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 15209 BinaryOperatorKind Opc, 15210 Expr *LHSExpr, Expr *RHSExpr) { 15211 ExprResult LHS, RHS; 15212 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 15213 if (!LHS.isUsable() || !RHS.isUsable()) 15214 return ExprError(); 15215 LHSExpr = LHS.get(); 15216 RHSExpr = RHS.get(); 15217 15218 // We want to end up calling one of checkPseudoObjectAssignment 15219 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 15220 // both expressions are overloadable or either is type-dependent), 15221 // or CreateBuiltinBinOp (in any other case). We also want to get 15222 // any placeholder types out of the way. 15223 15224 // Handle pseudo-objects in the LHS. 15225 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 15226 // Assignments with a pseudo-object l-value need special analysis. 15227 if (pty->getKind() == BuiltinType::PseudoObject && 15228 BinaryOperator::isAssignmentOp(Opc)) 15229 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 15230 15231 // Don't resolve overloads if the other type is overloadable. 15232 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 15233 // We can't actually test that if we still have a placeholder, 15234 // though. Fortunately, none of the exceptions we see in that 15235 // code below are valid when the LHS is an overload set. Note 15236 // that an overload set can be dependently-typed, but it never 15237 // instantiates to having an overloadable type. 15238 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15239 if (resolvedRHS.isInvalid()) return ExprError(); 15240 RHSExpr = resolvedRHS.get(); 15241 15242 if (RHSExpr->isTypeDependent() || 15243 RHSExpr->getType()->isOverloadableType()) 15244 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15245 } 15246 15247 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 15248 // template, diagnose the missing 'template' keyword instead of diagnosing 15249 // an invalid use of a bound member function. 15250 // 15251 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 15252 // to C++1z [over.over]/1.4, but we already checked for that case above. 15253 if (Opc == BO_LT && inTemplateInstantiation() && 15254 (pty->getKind() == BuiltinType::BoundMember || 15255 pty->getKind() == BuiltinType::Overload)) { 15256 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 15257 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 15258 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 15259 return isa<FunctionTemplateDecl>(ND); 15260 })) { 15261 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 15262 : OE->getNameLoc(), 15263 diag::err_template_kw_missing) 15264 << OE->getName().getAsString() << ""; 15265 return ExprError(); 15266 } 15267 } 15268 15269 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 15270 if (LHS.isInvalid()) return ExprError(); 15271 LHSExpr = LHS.get(); 15272 } 15273 15274 // Handle pseudo-objects in the RHS. 15275 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 15276 // An overload in the RHS can potentially be resolved by the type 15277 // being assigned to. 15278 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 15279 if (getLangOpts().CPlusPlus && 15280 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 15281 LHSExpr->getType()->isOverloadableType())) 15282 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15283 15284 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15285 } 15286 15287 // Don't resolve overloads if the other type is overloadable. 15288 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 15289 LHSExpr->getType()->isOverloadableType()) 15290 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15291 15292 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15293 if (!resolvedRHS.isUsable()) return ExprError(); 15294 RHSExpr = resolvedRHS.get(); 15295 } 15296 15297 if (getLangOpts().CPlusPlus) { 15298 // If either expression is type-dependent, always build an 15299 // overloaded op. 15300 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 15301 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15302 15303 // Otherwise, build an overloaded op if either expression has an 15304 // overloadable type. 15305 if (LHSExpr->getType()->isOverloadableType() || 15306 RHSExpr->getType()->isOverloadableType()) 15307 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15308 } 15309 15310 if (getLangOpts().RecoveryAST && 15311 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 15312 assert(!getLangOpts().CPlusPlus); 15313 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 15314 "Should only occur in error-recovery path."); 15315 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 15316 // C [6.15.16] p3: 15317 // An assignment expression has the value of the left operand after the 15318 // assignment, but is not an lvalue. 15319 return CompoundAssignOperator::Create( 15320 Context, LHSExpr, RHSExpr, Opc, 15321 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 15322 OpLoc, CurFPFeatureOverrides()); 15323 QualType ResultType; 15324 switch (Opc) { 15325 case BO_Assign: 15326 ResultType = LHSExpr->getType().getUnqualifiedType(); 15327 break; 15328 case BO_LT: 15329 case BO_GT: 15330 case BO_LE: 15331 case BO_GE: 15332 case BO_EQ: 15333 case BO_NE: 15334 case BO_LAnd: 15335 case BO_LOr: 15336 // These operators have a fixed result type regardless of operands. 15337 ResultType = Context.IntTy; 15338 break; 15339 case BO_Comma: 15340 ResultType = RHSExpr->getType(); 15341 break; 15342 default: 15343 ResultType = Context.DependentTy; 15344 break; 15345 } 15346 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 15347 VK_PRValue, OK_Ordinary, OpLoc, 15348 CurFPFeatureOverrides()); 15349 } 15350 15351 // Build a built-in binary operation. 15352 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15353 } 15354 15355 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 15356 if (T.isNull() || T->isDependentType()) 15357 return false; 15358 15359 if (!T->isPromotableIntegerType()) 15360 return true; 15361 15362 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 15363 } 15364 15365 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 15366 UnaryOperatorKind Opc, 15367 Expr *InputExpr) { 15368 ExprResult Input = InputExpr; 15369 ExprValueKind VK = VK_PRValue; 15370 ExprObjectKind OK = OK_Ordinary; 15371 QualType resultType; 15372 bool CanOverflow = false; 15373 15374 bool ConvertHalfVec = false; 15375 if (getLangOpts().OpenCL) { 15376 QualType Ty = InputExpr->getType(); 15377 // The only legal unary operation for atomics is '&'. 15378 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 15379 // OpenCL special types - image, sampler, pipe, and blocks are to be used 15380 // only with a builtin functions and therefore should be disallowed here. 15381 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 15382 || Ty->isBlockPointerType())) { 15383 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15384 << InputExpr->getType() 15385 << Input.get()->getSourceRange()); 15386 } 15387 } 15388 15389 if (getLangOpts().HLSL) { 15390 if (Opc == UO_AddrOf) 15391 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0); 15392 if (Opc == UO_Deref) 15393 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1); 15394 } 15395 15396 switch (Opc) { 15397 case UO_PreInc: 15398 case UO_PreDec: 15399 case UO_PostInc: 15400 case UO_PostDec: 15401 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 15402 OpLoc, 15403 Opc == UO_PreInc || 15404 Opc == UO_PostInc, 15405 Opc == UO_PreInc || 15406 Opc == UO_PreDec); 15407 CanOverflow = isOverflowingIntegerType(Context, resultType); 15408 break; 15409 case UO_AddrOf: 15410 resultType = CheckAddressOfOperand(Input, OpLoc); 15411 CheckAddressOfNoDeref(InputExpr); 15412 RecordModifiableNonNullParam(*this, InputExpr); 15413 break; 15414 case UO_Deref: { 15415 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15416 if (Input.isInvalid()) return ExprError(); 15417 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 15418 break; 15419 } 15420 case UO_Plus: 15421 case UO_Minus: 15422 CanOverflow = Opc == UO_Minus && 15423 isOverflowingIntegerType(Context, Input.get()->getType()); 15424 Input = UsualUnaryConversions(Input.get()); 15425 if (Input.isInvalid()) return ExprError(); 15426 // Unary plus and minus require promoting an operand of half vector to a 15427 // float vector and truncating the result back to a half vector. For now, we 15428 // do this only when HalfArgsAndReturns is set (that is, when the target is 15429 // arm or arm64). 15430 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 15431 15432 // If the operand is a half vector, promote it to a float vector. 15433 if (ConvertHalfVec) 15434 Input = convertVector(Input.get(), Context.FloatTy, *this); 15435 resultType = Input.get()->getType(); 15436 if (resultType->isDependentType()) 15437 break; 15438 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 15439 break; 15440 else if (resultType->isVectorType() && 15441 // The z vector extensions don't allow + or - with bool vectors. 15442 (!Context.getLangOpts().ZVector || 15443 resultType->castAs<VectorType>()->getVectorKind() != 15444 VectorType::AltiVecBool)) 15445 break; 15446 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 15447 Opc == UO_Plus && 15448 resultType->isPointerType()) 15449 break; 15450 15451 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15452 << resultType << Input.get()->getSourceRange()); 15453 15454 case UO_Not: // bitwise complement 15455 Input = UsualUnaryConversions(Input.get()); 15456 if (Input.isInvalid()) 15457 return ExprError(); 15458 resultType = Input.get()->getType(); 15459 if (resultType->isDependentType()) 15460 break; 15461 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 15462 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 15463 // C99 does not support '~' for complex conjugation. 15464 Diag(OpLoc, diag::ext_integer_complement_complex) 15465 << resultType << Input.get()->getSourceRange(); 15466 else if (resultType->hasIntegerRepresentation()) 15467 break; 15468 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 15469 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 15470 // on vector float types. 15471 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15472 if (!T->isIntegerType()) 15473 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15474 << resultType << Input.get()->getSourceRange()); 15475 } else { 15476 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15477 << resultType << Input.get()->getSourceRange()); 15478 } 15479 break; 15480 15481 case UO_LNot: // logical negation 15482 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 15483 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15484 if (Input.isInvalid()) return ExprError(); 15485 resultType = Input.get()->getType(); 15486 15487 // Though we still have to promote half FP to float... 15488 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 15489 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 15490 resultType = Context.FloatTy; 15491 } 15492 15493 if (resultType->isDependentType()) 15494 break; 15495 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 15496 // C99 6.5.3.3p1: ok, fallthrough; 15497 if (Context.getLangOpts().CPlusPlus) { 15498 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 15499 // operand contextually converted to bool. 15500 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 15501 ScalarTypeToBooleanCastKind(resultType)); 15502 } else if (Context.getLangOpts().OpenCL && 15503 Context.getLangOpts().OpenCLVersion < 120) { 15504 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15505 // operate on scalar float types. 15506 if (!resultType->isIntegerType() && !resultType->isPointerType()) 15507 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15508 << resultType << Input.get()->getSourceRange()); 15509 } 15510 } else if (resultType->isExtVectorType()) { 15511 if (Context.getLangOpts().OpenCL && 15512 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 15513 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15514 // operate on vector float types. 15515 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15516 if (!T->isIntegerType()) 15517 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15518 << resultType << Input.get()->getSourceRange()); 15519 } 15520 // Vector logical not returns the signed variant of the operand type. 15521 resultType = GetSignedVectorType(resultType); 15522 break; 15523 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 15524 const VectorType *VTy = resultType->castAs<VectorType>(); 15525 if (VTy->getVectorKind() != VectorType::GenericVector) 15526 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15527 << resultType << Input.get()->getSourceRange()); 15528 15529 // Vector logical not returns the signed variant of the operand type. 15530 resultType = GetSignedVectorType(resultType); 15531 break; 15532 } else { 15533 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15534 << resultType << Input.get()->getSourceRange()); 15535 } 15536 15537 // LNot always has type int. C99 6.5.3.3p5. 15538 // In C++, it's bool. C++ 5.3.1p8 15539 resultType = Context.getLogicalOperationType(); 15540 break; 15541 case UO_Real: 15542 case UO_Imag: 15543 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 15544 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 15545 // complex l-values to ordinary l-values and all other values to r-values. 15546 if (Input.isInvalid()) return ExprError(); 15547 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 15548 if (Input.get()->isGLValue() && 15549 Input.get()->getObjectKind() == OK_Ordinary) 15550 VK = Input.get()->getValueKind(); 15551 } else if (!getLangOpts().CPlusPlus) { 15552 // In C, a volatile scalar is read by __imag. In C++, it is not. 15553 Input = DefaultLvalueConversion(Input.get()); 15554 } 15555 break; 15556 case UO_Extension: 15557 resultType = Input.get()->getType(); 15558 VK = Input.get()->getValueKind(); 15559 OK = Input.get()->getObjectKind(); 15560 break; 15561 case UO_Coawait: 15562 // It's unnecessary to represent the pass-through operator co_await in the 15563 // AST; just return the input expression instead. 15564 assert(!Input.get()->getType()->isDependentType() && 15565 "the co_await expression must be non-dependant before " 15566 "building operator co_await"); 15567 return Input; 15568 } 15569 if (resultType.isNull() || Input.isInvalid()) 15570 return ExprError(); 15571 15572 // Check for array bounds violations in the operand of the UnaryOperator, 15573 // except for the '*' and '&' operators that have to be handled specially 15574 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15575 // that are explicitly defined as valid by the standard). 15576 if (Opc != UO_AddrOf && Opc != UO_Deref) 15577 CheckArrayAccess(Input.get()); 15578 15579 auto *UO = 15580 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15581 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15582 15583 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15584 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15585 !isUnevaluatedContext()) 15586 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15587 15588 // Convert the result back to a half vector. 15589 if (ConvertHalfVec) 15590 return convertVector(UO, Context.HalfTy, *this); 15591 return UO; 15592 } 15593 15594 /// Determine whether the given expression is a qualified member 15595 /// access expression, of a form that could be turned into a pointer to member 15596 /// with the address-of operator. 15597 bool Sema::isQualifiedMemberAccess(Expr *E) { 15598 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15599 if (!DRE->getQualifier()) 15600 return false; 15601 15602 ValueDecl *VD = DRE->getDecl(); 15603 if (!VD->isCXXClassMember()) 15604 return false; 15605 15606 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15607 return true; 15608 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15609 return Method->isInstance(); 15610 15611 return false; 15612 } 15613 15614 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15615 if (!ULE->getQualifier()) 15616 return false; 15617 15618 for (NamedDecl *D : ULE->decls()) { 15619 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15620 if (Method->isInstance()) 15621 return true; 15622 } else { 15623 // Overload set does not contain methods. 15624 break; 15625 } 15626 } 15627 15628 return false; 15629 } 15630 15631 return false; 15632 } 15633 15634 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15635 UnaryOperatorKind Opc, Expr *Input) { 15636 // First things first: handle placeholders so that the 15637 // overloaded-operator check considers the right type. 15638 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15639 // Increment and decrement of pseudo-object references. 15640 if (pty->getKind() == BuiltinType::PseudoObject && 15641 UnaryOperator::isIncrementDecrementOp(Opc)) 15642 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15643 15644 // extension is always a builtin operator. 15645 if (Opc == UO_Extension) 15646 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15647 15648 // & gets special logic for several kinds of placeholder. 15649 // The builtin code knows what to do. 15650 if (Opc == UO_AddrOf && 15651 (pty->getKind() == BuiltinType::Overload || 15652 pty->getKind() == BuiltinType::UnknownAny || 15653 pty->getKind() == BuiltinType::BoundMember)) 15654 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15655 15656 // Anything else needs to be handled now. 15657 ExprResult Result = CheckPlaceholderExpr(Input); 15658 if (Result.isInvalid()) return ExprError(); 15659 Input = Result.get(); 15660 } 15661 15662 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15663 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15664 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15665 // Find all of the overloaded operators visible from this point. 15666 UnresolvedSet<16> Functions; 15667 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15668 if (S && OverOp != OO_None) 15669 LookupOverloadedOperatorName(OverOp, S, Functions); 15670 15671 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15672 } 15673 15674 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15675 } 15676 15677 // Unary Operators. 'Tok' is the token for the operator. 15678 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15679 tok::TokenKind Op, Expr *Input) { 15680 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15681 } 15682 15683 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15684 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15685 LabelDecl *TheDecl) { 15686 TheDecl->markUsed(Context); 15687 // Create the AST node. The address of a label always has type 'void*'. 15688 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15689 Context.getPointerType(Context.VoidTy)); 15690 } 15691 15692 void Sema::ActOnStartStmtExpr() { 15693 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15694 } 15695 15696 void Sema::ActOnStmtExprError() { 15697 // Note that function is also called by TreeTransform when leaving a 15698 // StmtExpr scope without rebuilding anything. 15699 15700 DiscardCleanupsInEvaluationContext(); 15701 PopExpressionEvaluationContext(); 15702 } 15703 15704 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15705 SourceLocation RPLoc) { 15706 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15707 } 15708 15709 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15710 SourceLocation RPLoc, unsigned TemplateDepth) { 15711 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15712 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15713 15714 if (hasAnyUnrecoverableErrorsInThisFunction()) 15715 DiscardCleanupsInEvaluationContext(); 15716 assert(!Cleanup.exprNeedsCleanups() && 15717 "cleanups within StmtExpr not correctly bound!"); 15718 PopExpressionEvaluationContext(); 15719 15720 // FIXME: there are a variety of strange constraints to enforce here, for 15721 // example, it is not possible to goto into a stmt expression apparently. 15722 // More semantic analysis is needed. 15723 15724 // If there are sub-stmts in the compound stmt, take the type of the last one 15725 // as the type of the stmtexpr. 15726 QualType Ty = Context.VoidTy; 15727 bool StmtExprMayBindToTemp = false; 15728 if (!Compound->body_empty()) { 15729 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15730 if (const auto *LastStmt = 15731 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15732 if (const Expr *Value = LastStmt->getExprStmt()) { 15733 StmtExprMayBindToTemp = true; 15734 Ty = Value->getType(); 15735 } 15736 } 15737 } 15738 15739 // FIXME: Check that expression type is complete/non-abstract; statement 15740 // expressions are not lvalues. 15741 Expr *ResStmtExpr = 15742 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15743 if (StmtExprMayBindToTemp) 15744 return MaybeBindToTemporary(ResStmtExpr); 15745 return ResStmtExpr; 15746 } 15747 15748 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15749 if (ER.isInvalid()) 15750 return ExprError(); 15751 15752 // Do function/array conversion on the last expression, but not 15753 // lvalue-to-rvalue. However, initialize an unqualified type. 15754 ER = DefaultFunctionArrayConversion(ER.get()); 15755 if (ER.isInvalid()) 15756 return ExprError(); 15757 Expr *E = ER.get(); 15758 15759 if (E->isTypeDependent()) 15760 return E; 15761 15762 // In ARC, if the final expression ends in a consume, splice 15763 // the consume out and bind it later. In the alternate case 15764 // (when dealing with a retainable type), the result 15765 // initialization will create a produce. In both cases the 15766 // result will be +1, and we'll need to balance that out with 15767 // a bind. 15768 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15769 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15770 return Cast->getSubExpr(); 15771 15772 // FIXME: Provide a better location for the initialization. 15773 return PerformCopyInitialization( 15774 InitializedEntity::InitializeStmtExprResult( 15775 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15776 SourceLocation(), E); 15777 } 15778 15779 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15780 TypeSourceInfo *TInfo, 15781 ArrayRef<OffsetOfComponent> Components, 15782 SourceLocation RParenLoc) { 15783 QualType ArgTy = TInfo->getType(); 15784 bool Dependent = ArgTy->isDependentType(); 15785 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15786 15787 // We must have at least one component that refers to the type, and the first 15788 // one is known to be a field designator. Verify that the ArgTy represents 15789 // a struct/union/class. 15790 if (!Dependent && !ArgTy->isRecordType()) 15791 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15792 << ArgTy << TypeRange); 15793 15794 // Type must be complete per C99 7.17p3 because a declaring a variable 15795 // with an incomplete type would be ill-formed. 15796 if (!Dependent 15797 && RequireCompleteType(BuiltinLoc, ArgTy, 15798 diag::err_offsetof_incomplete_type, TypeRange)) 15799 return ExprError(); 15800 15801 bool DidWarnAboutNonPOD = false; 15802 QualType CurrentType = ArgTy; 15803 SmallVector<OffsetOfNode, 4> Comps; 15804 SmallVector<Expr*, 4> Exprs; 15805 for (const OffsetOfComponent &OC : Components) { 15806 if (OC.isBrackets) { 15807 // Offset of an array sub-field. TODO: Should we allow vector elements? 15808 if (!CurrentType->isDependentType()) { 15809 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15810 if(!AT) 15811 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15812 << CurrentType); 15813 CurrentType = AT->getElementType(); 15814 } else 15815 CurrentType = Context.DependentTy; 15816 15817 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15818 if (IdxRval.isInvalid()) 15819 return ExprError(); 15820 Expr *Idx = IdxRval.get(); 15821 15822 // The expression must be an integral expression. 15823 // FIXME: An integral constant expression? 15824 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15825 !Idx->getType()->isIntegerType()) 15826 return ExprError( 15827 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15828 << Idx->getSourceRange()); 15829 15830 // Record this array index. 15831 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15832 Exprs.push_back(Idx); 15833 continue; 15834 } 15835 15836 // Offset of a field. 15837 if (CurrentType->isDependentType()) { 15838 // We have the offset of a field, but we can't look into the dependent 15839 // type. Just record the identifier of the field. 15840 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15841 CurrentType = Context.DependentTy; 15842 continue; 15843 } 15844 15845 // We need to have a complete type to look into. 15846 if (RequireCompleteType(OC.LocStart, CurrentType, 15847 diag::err_offsetof_incomplete_type)) 15848 return ExprError(); 15849 15850 // Look for the designated field. 15851 const RecordType *RC = CurrentType->getAs<RecordType>(); 15852 if (!RC) 15853 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15854 << CurrentType); 15855 RecordDecl *RD = RC->getDecl(); 15856 15857 // C++ [lib.support.types]p5: 15858 // The macro offsetof accepts a restricted set of type arguments in this 15859 // International Standard. type shall be a POD structure or a POD union 15860 // (clause 9). 15861 // C++11 [support.types]p4: 15862 // If type is not a standard-layout class (Clause 9), the results are 15863 // undefined. 15864 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15865 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15866 unsigned DiagID = 15867 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15868 : diag::ext_offsetof_non_pod_type; 15869 15870 if (!IsSafe && !DidWarnAboutNonPOD && 15871 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15872 PDiag(DiagID) 15873 << SourceRange(Components[0].LocStart, OC.LocEnd) 15874 << CurrentType)) 15875 DidWarnAboutNonPOD = true; 15876 } 15877 15878 // Look for the field. 15879 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15880 LookupQualifiedName(R, RD); 15881 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15882 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15883 if (!MemberDecl) { 15884 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15885 MemberDecl = IndirectMemberDecl->getAnonField(); 15886 } 15887 15888 if (!MemberDecl) 15889 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15890 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15891 OC.LocEnd)); 15892 15893 // C99 7.17p3: 15894 // (If the specified member is a bit-field, the behavior is undefined.) 15895 // 15896 // We diagnose this as an error. 15897 if (MemberDecl->isBitField()) { 15898 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15899 << MemberDecl->getDeclName() 15900 << SourceRange(BuiltinLoc, RParenLoc); 15901 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15902 return ExprError(); 15903 } 15904 15905 RecordDecl *Parent = MemberDecl->getParent(); 15906 if (IndirectMemberDecl) 15907 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15908 15909 // If the member was found in a base class, introduce OffsetOfNodes for 15910 // the base class indirections. 15911 CXXBasePaths Paths; 15912 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15913 Paths)) { 15914 if (Paths.getDetectedVirtual()) { 15915 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15916 << MemberDecl->getDeclName() 15917 << SourceRange(BuiltinLoc, RParenLoc); 15918 return ExprError(); 15919 } 15920 15921 CXXBasePath &Path = Paths.front(); 15922 for (const CXXBasePathElement &B : Path) 15923 Comps.push_back(OffsetOfNode(B.Base)); 15924 } 15925 15926 if (IndirectMemberDecl) { 15927 for (auto *FI : IndirectMemberDecl->chain()) { 15928 assert(isa<FieldDecl>(FI)); 15929 Comps.push_back(OffsetOfNode(OC.LocStart, 15930 cast<FieldDecl>(FI), OC.LocEnd)); 15931 } 15932 } else 15933 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15934 15935 CurrentType = MemberDecl->getType().getNonReferenceType(); 15936 } 15937 15938 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15939 Comps, Exprs, RParenLoc); 15940 } 15941 15942 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15943 SourceLocation BuiltinLoc, 15944 SourceLocation TypeLoc, 15945 ParsedType ParsedArgTy, 15946 ArrayRef<OffsetOfComponent> Components, 15947 SourceLocation RParenLoc) { 15948 15949 TypeSourceInfo *ArgTInfo; 15950 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15951 if (ArgTy.isNull()) 15952 return ExprError(); 15953 15954 if (!ArgTInfo) 15955 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15956 15957 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15958 } 15959 15960 15961 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15962 Expr *CondExpr, 15963 Expr *LHSExpr, Expr *RHSExpr, 15964 SourceLocation RPLoc) { 15965 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15966 15967 ExprValueKind VK = VK_PRValue; 15968 ExprObjectKind OK = OK_Ordinary; 15969 QualType resType; 15970 bool CondIsTrue = false; 15971 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15972 resType = Context.DependentTy; 15973 } else { 15974 // The conditional expression is required to be a constant expression. 15975 llvm::APSInt condEval(32); 15976 ExprResult CondICE = VerifyIntegerConstantExpression( 15977 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15978 if (CondICE.isInvalid()) 15979 return ExprError(); 15980 CondExpr = CondICE.get(); 15981 CondIsTrue = condEval.getZExtValue(); 15982 15983 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15984 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15985 15986 resType = ActiveExpr->getType(); 15987 VK = ActiveExpr->getValueKind(); 15988 OK = ActiveExpr->getObjectKind(); 15989 } 15990 15991 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15992 resType, VK, OK, RPLoc, CondIsTrue); 15993 } 15994 15995 //===----------------------------------------------------------------------===// 15996 // Clang Extensions. 15997 //===----------------------------------------------------------------------===// 15998 15999 /// ActOnBlockStart - This callback is invoked when a block literal is started. 16000 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 16001 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 16002 16003 if (LangOpts.CPlusPlus) { 16004 MangleNumberingContext *MCtx; 16005 Decl *ManglingContextDecl; 16006 std::tie(MCtx, ManglingContextDecl) = 16007 getCurrentMangleNumberContext(Block->getDeclContext()); 16008 if (MCtx) { 16009 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 16010 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 16011 } 16012 } 16013 16014 PushBlockScope(CurScope, Block); 16015 CurContext->addDecl(Block); 16016 if (CurScope) 16017 PushDeclContext(CurScope, Block); 16018 else 16019 CurContext = Block; 16020 16021 getCurBlock()->HasImplicitReturnType = true; 16022 16023 // Enter a new evaluation context to insulate the block from any 16024 // cleanups from the enclosing full-expression. 16025 PushExpressionEvaluationContext( 16026 ExpressionEvaluationContext::PotentiallyEvaluated); 16027 } 16028 16029 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 16030 Scope *CurScope) { 16031 assert(ParamInfo.getIdentifier() == nullptr && 16032 "block-id should have no identifier!"); 16033 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 16034 BlockScopeInfo *CurBlock = getCurBlock(); 16035 16036 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 16037 QualType T = Sig->getType(); 16038 16039 // FIXME: We should allow unexpanded parameter packs here, but that would, 16040 // in turn, make the block expression contain unexpanded parameter packs. 16041 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 16042 // Drop the parameters. 16043 FunctionProtoType::ExtProtoInfo EPI; 16044 EPI.HasTrailingReturn = false; 16045 EPI.TypeQuals.addConst(); 16046 T = Context.getFunctionType(Context.DependentTy, None, EPI); 16047 Sig = Context.getTrivialTypeSourceInfo(T); 16048 } 16049 16050 // GetTypeForDeclarator always produces a function type for a block 16051 // literal signature. Furthermore, it is always a FunctionProtoType 16052 // unless the function was written with a typedef. 16053 assert(T->isFunctionType() && 16054 "GetTypeForDeclarator made a non-function block signature"); 16055 16056 // Look for an explicit signature in that function type. 16057 FunctionProtoTypeLoc ExplicitSignature; 16058 16059 if ((ExplicitSignature = Sig->getTypeLoc() 16060 .getAsAdjusted<FunctionProtoTypeLoc>())) { 16061 16062 // Check whether that explicit signature was synthesized by 16063 // GetTypeForDeclarator. If so, don't save that as part of the 16064 // written signature. 16065 if (ExplicitSignature.getLocalRangeBegin() == 16066 ExplicitSignature.getLocalRangeEnd()) { 16067 // This would be much cheaper if we stored TypeLocs instead of 16068 // TypeSourceInfos. 16069 TypeLoc Result = ExplicitSignature.getReturnLoc(); 16070 unsigned Size = Result.getFullDataSize(); 16071 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 16072 Sig->getTypeLoc().initializeFullCopy(Result, Size); 16073 16074 ExplicitSignature = FunctionProtoTypeLoc(); 16075 } 16076 } 16077 16078 CurBlock->TheDecl->setSignatureAsWritten(Sig); 16079 CurBlock->FunctionType = T; 16080 16081 const auto *Fn = T->castAs<FunctionType>(); 16082 QualType RetTy = Fn->getReturnType(); 16083 bool isVariadic = 16084 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 16085 16086 CurBlock->TheDecl->setIsVariadic(isVariadic); 16087 16088 // Context.DependentTy is used as a placeholder for a missing block 16089 // return type. TODO: what should we do with declarators like: 16090 // ^ * { ... } 16091 // If the answer is "apply template argument deduction".... 16092 if (RetTy != Context.DependentTy) { 16093 CurBlock->ReturnType = RetTy; 16094 CurBlock->TheDecl->setBlockMissingReturnType(false); 16095 CurBlock->HasImplicitReturnType = false; 16096 } 16097 16098 // Push block parameters from the declarator if we had them. 16099 SmallVector<ParmVarDecl*, 8> Params; 16100 if (ExplicitSignature) { 16101 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 16102 ParmVarDecl *Param = ExplicitSignature.getParam(I); 16103 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 16104 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 16105 // Diagnose this as an extension in C17 and earlier. 16106 if (!getLangOpts().C2x) 16107 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 16108 } 16109 Params.push_back(Param); 16110 } 16111 16112 // Fake up parameter variables if we have a typedef, like 16113 // ^ fntype { ... } 16114 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 16115 for (const auto &I : Fn->param_types()) { 16116 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 16117 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 16118 Params.push_back(Param); 16119 } 16120 } 16121 16122 // Set the parameters on the block decl. 16123 if (!Params.empty()) { 16124 CurBlock->TheDecl->setParams(Params); 16125 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 16126 /*CheckParameterNames=*/false); 16127 } 16128 16129 // Finally we can process decl attributes. 16130 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 16131 16132 // Put the parameter variables in scope. 16133 for (auto AI : CurBlock->TheDecl->parameters()) { 16134 AI->setOwningFunction(CurBlock->TheDecl); 16135 16136 // If this has an identifier, add it to the scope stack. 16137 if (AI->getIdentifier()) { 16138 CheckShadow(CurBlock->TheScope, AI); 16139 16140 PushOnScopeChains(AI, CurBlock->TheScope); 16141 } 16142 } 16143 } 16144 16145 /// ActOnBlockError - If there is an error parsing a block, this callback 16146 /// is invoked to pop the information about the block from the action impl. 16147 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 16148 // Leave the expression-evaluation context. 16149 DiscardCleanupsInEvaluationContext(); 16150 PopExpressionEvaluationContext(); 16151 16152 // Pop off CurBlock, handle nested blocks. 16153 PopDeclContext(); 16154 PopFunctionScopeInfo(); 16155 } 16156 16157 /// ActOnBlockStmtExpr - This is called when the body of a block statement 16158 /// literal was successfully completed. ^(int x){...} 16159 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 16160 Stmt *Body, Scope *CurScope) { 16161 // If blocks are disabled, emit an error. 16162 if (!LangOpts.Blocks) 16163 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 16164 16165 // Leave the expression-evaluation context. 16166 if (hasAnyUnrecoverableErrorsInThisFunction()) 16167 DiscardCleanupsInEvaluationContext(); 16168 assert(!Cleanup.exprNeedsCleanups() && 16169 "cleanups within block not correctly bound!"); 16170 PopExpressionEvaluationContext(); 16171 16172 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 16173 BlockDecl *BD = BSI->TheDecl; 16174 16175 if (BSI->HasImplicitReturnType) 16176 deduceClosureReturnType(*BSI); 16177 16178 QualType RetTy = Context.VoidTy; 16179 if (!BSI->ReturnType.isNull()) 16180 RetTy = BSI->ReturnType; 16181 16182 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 16183 QualType BlockTy; 16184 16185 // If the user wrote a function type in some form, try to use that. 16186 if (!BSI->FunctionType.isNull()) { 16187 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 16188 16189 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 16190 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 16191 16192 // Turn protoless block types into nullary block types. 16193 if (isa<FunctionNoProtoType>(FTy)) { 16194 FunctionProtoType::ExtProtoInfo EPI; 16195 EPI.ExtInfo = Ext; 16196 BlockTy = Context.getFunctionType(RetTy, None, EPI); 16197 16198 // Otherwise, if we don't need to change anything about the function type, 16199 // preserve its sugar structure. 16200 } else if (FTy->getReturnType() == RetTy && 16201 (!NoReturn || FTy->getNoReturnAttr())) { 16202 BlockTy = BSI->FunctionType; 16203 16204 // Otherwise, make the minimal modifications to the function type. 16205 } else { 16206 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 16207 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 16208 EPI.TypeQuals = Qualifiers(); 16209 EPI.ExtInfo = Ext; 16210 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 16211 } 16212 16213 // If we don't have a function type, just build one from nothing. 16214 } else { 16215 FunctionProtoType::ExtProtoInfo EPI; 16216 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 16217 BlockTy = Context.getFunctionType(RetTy, None, EPI); 16218 } 16219 16220 DiagnoseUnusedParameters(BD->parameters()); 16221 BlockTy = Context.getBlockPointerType(BlockTy); 16222 16223 // If needed, diagnose invalid gotos and switches in the block. 16224 if (getCurFunction()->NeedsScopeChecking() && 16225 !PP.isCodeCompletionEnabled()) 16226 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 16227 16228 BD->setBody(cast<CompoundStmt>(Body)); 16229 16230 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 16231 DiagnoseUnguardedAvailabilityViolations(BD); 16232 16233 // Try to apply the named return value optimization. We have to check again 16234 // if we can do this, though, because blocks keep return statements around 16235 // to deduce an implicit return type. 16236 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 16237 !BD->isDependentContext()) 16238 computeNRVO(Body, BSI); 16239 16240 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 16241 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 16242 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 16243 NTCUK_Destruct|NTCUK_Copy); 16244 16245 PopDeclContext(); 16246 16247 // Set the captured variables on the block. 16248 SmallVector<BlockDecl::Capture, 4> Captures; 16249 for (Capture &Cap : BSI->Captures) { 16250 if (Cap.isInvalid() || Cap.isThisCapture()) 16251 continue; 16252 16253 VarDecl *Var = Cap.getVariable(); 16254 Expr *CopyExpr = nullptr; 16255 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 16256 if (const RecordType *Record = 16257 Cap.getCaptureType()->getAs<RecordType>()) { 16258 // The capture logic needs the destructor, so make sure we mark it. 16259 // Usually this is unnecessary because most local variables have 16260 // their destructors marked at declaration time, but parameters are 16261 // an exception because it's technically only the call site that 16262 // actually requires the destructor. 16263 if (isa<ParmVarDecl>(Var)) 16264 FinalizeVarWithDestructor(Var, Record); 16265 16266 // Enter a separate potentially-evaluated context while building block 16267 // initializers to isolate their cleanups from those of the block 16268 // itself. 16269 // FIXME: Is this appropriate even when the block itself occurs in an 16270 // unevaluated operand? 16271 EnterExpressionEvaluationContext EvalContext( 16272 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16273 16274 SourceLocation Loc = Cap.getLocation(); 16275 16276 ExprResult Result = BuildDeclarationNameExpr( 16277 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 16278 16279 // According to the blocks spec, the capture of a variable from 16280 // the stack requires a const copy constructor. This is not true 16281 // of the copy/move done to move a __block variable to the heap. 16282 if (!Result.isInvalid() && 16283 !Result.get()->getType().isConstQualified()) { 16284 Result = ImpCastExprToType(Result.get(), 16285 Result.get()->getType().withConst(), 16286 CK_NoOp, VK_LValue); 16287 } 16288 16289 if (!Result.isInvalid()) { 16290 Result = PerformCopyInitialization( 16291 InitializedEntity::InitializeBlock(Var->getLocation(), 16292 Cap.getCaptureType()), 16293 Loc, Result.get()); 16294 } 16295 16296 // Build a full-expression copy expression if initialization 16297 // succeeded and used a non-trivial constructor. Recover from 16298 // errors by pretending that the copy isn't necessary. 16299 if (!Result.isInvalid() && 16300 !cast<CXXConstructExpr>(Result.get())->getConstructor() 16301 ->isTrivial()) { 16302 Result = MaybeCreateExprWithCleanups(Result); 16303 CopyExpr = Result.get(); 16304 } 16305 } 16306 } 16307 16308 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 16309 CopyExpr); 16310 Captures.push_back(NewCap); 16311 } 16312 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 16313 16314 // Pop the block scope now but keep it alive to the end of this function. 16315 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 16316 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 16317 16318 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 16319 16320 // If the block isn't obviously global, i.e. it captures anything at 16321 // all, then we need to do a few things in the surrounding context: 16322 if (Result->getBlockDecl()->hasCaptures()) { 16323 // First, this expression has a new cleanup object. 16324 ExprCleanupObjects.push_back(Result->getBlockDecl()); 16325 Cleanup.setExprNeedsCleanups(true); 16326 16327 // It also gets a branch-protected scope if any of the captured 16328 // variables needs destruction. 16329 for (const auto &CI : Result->getBlockDecl()->captures()) { 16330 const VarDecl *var = CI.getVariable(); 16331 if (var->getType().isDestructedType() != QualType::DK_none) { 16332 setFunctionHasBranchProtectedScope(); 16333 break; 16334 } 16335 } 16336 } 16337 16338 if (getCurFunction()) 16339 getCurFunction()->addBlock(BD); 16340 16341 return Result; 16342 } 16343 16344 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 16345 SourceLocation RPLoc) { 16346 TypeSourceInfo *TInfo; 16347 GetTypeFromParser(Ty, &TInfo); 16348 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 16349 } 16350 16351 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 16352 Expr *E, TypeSourceInfo *TInfo, 16353 SourceLocation RPLoc) { 16354 Expr *OrigExpr = E; 16355 bool IsMS = false; 16356 16357 // CUDA device code does not support varargs. 16358 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 16359 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 16360 CUDAFunctionTarget T = IdentifyCUDATarget(F); 16361 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 16362 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 16363 } 16364 } 16365 16366 // NVPTX does not support va_arg expression. 16367 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 16368 Context.getTargetInfo().getTriple().isNVPTX()) 16369 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 16370 16371 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 16372 // as Microsoft ABI on an actual Microsoft platform, where 16373 // __builtin_ms_va_list and __builtin_va_list are the same.) 16374 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 16375 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 16376 QualType MSVaListType = Context.getBuiltinMSVaListType(); 16377 if (Context.hasSameType(MSVaListType, E->getType())) { 16378 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16379 return ExprError(); 16380 IsMS = true; 16381 } 16382 } 16383 16384 // Get the va_list type 16385 QualType VaListType = Context.getBuiltinVaListType(); 16386 if (!IsMS) { 16387 if (VaListType->isArrayType()) { 16388 // Deal with implicit array decay; for example, on x86-64, 16389 // va_list is an array, but it's supposed to decay to 16390 // a pointer for va_arg. 16391 VaListType = Context.getArrayDecayedType(VaListType); 16392 // Make sure the input expression also decays appropriately. 16393 ExprResult Result = UsualUnaryConversions(E); 16394 if (Result.isInvalid()) 16395 return ExprError(); 16396 E = Result.get(); 16397 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 16398 // If va_list is a record type and we are compiling in C++ mode, 16399 // check the argument using reference binding. 16400 InitializedEntity Entity = InitializedEntity::InitializeParameter( 16401 Context, Context.getLValueReferenceType(VaListType), false); 16402 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 16403 if (Init.isInvalid()) 16404 return ExprError(); 16405 E = Init.getAs<Expr>(); 16406 } else { 16407 // Otherwise, the va_list argument must be an l-value because 16408 // it is modified by va_arg. 16409 if (!E->isTypeDependent() && 16410 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16411 return ExprError(); 16412 } 16413 } 16414 16415 if (!IsMS && !E->isTypeDependent() && 16416 !Context.hasSameType(VaListType, E->getType())) 16417 return ExprError( 16418 Diag(E->getBeginLoc(), 16419 diag::err_first_argument_to_va_arg_not_of_type_va_list) 16420 << OrigExpr->getType() << E->getSourceRange()); 16421 16422 if (!TInfo->getType()->isDependentType()) { 16423 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 16424 diag::err_second_parameter_to_va_arg_incomplete, 16425 TInfo->getTypeLoc())) 16426 return ExprError(); 16427 16428 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 16429 TInfo->getType(), 16430 diag::err_second_parameter_to_va_arg_abstract, 16431 TInfo->getTypeLoc())) 16432 return ExprError(); 16433 16434 if (!TInfo->getType().isPODType(Context)) { 16435 Diag(TInfo->getTypeLoc().getBeginLoc(), 16436 TInfo->getType()->isObjCLifetimeType() 16437 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 16438 : diag::warn_second_parameter_to_va_arg_not_pod) 16439 << TInfo->getType() 16440 << TInfo->getTypeLoc().getSourceRange(); 16441 } 16442 16443 // Check for va_arg where arguments of the given type will be promoted 16444 // (i.e. this va_arg is guaranteed to have undefined behavior). 16445 QualType PromoteType; 16446 if (TInfo->getType()->isPromotableIntegerType()) { 16447 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 16448 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 16449 // and C2x 7.16.1.1p2 says, in part: 16450 // If type is not compatible with the type of the actual next argument 16451 // (as promoted according to the default argument promotions), the 16452 // behavior is undefined, except for the following cases: 16453 // - both types are pointers to qualified or unqualified versions of 16454 // compatible types; 16455 // - one type is a signed integer type, the other type is the 16456 // corresponding unsigned integer type, and the value is 16457 // representable in both types; 16458 // - one type is pointer to qualified or unqualified void and the 16459 // other is a pointer to a qualified or unqualified character type. 16460 // Given that type compatibility is the primary requirement (ignoring 16461 // qualifications), you would think we could call typesAreCompatible() 16462 // directly to test this. However, in C++, that checks for *same type*, 16463 // which causes false positives when passing an enumeration type to 16464 // va_arg. Instead, get the underlying type of the enumeration and pass 16465 // that. 16466 QualType UnderlyingType = TInfo->getType(); 16467 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 16468 UnderlyingType = ET->getDecl()->getIntegerType(); 16469 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16470 /*CompareUnqualified*/ true)) 16471 PromoteType = QualType(); 16472 16473 // If the types are still not compatible, we need to test whether the 16474 // promoted type and the underlying type are the same except for 16475 // signedness. Ask the AST for the correctly corresponding type and see 16476 // if that's compatible. 16477 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && 16478 PromoteType->isUnsignedIntegerType() != 16479 UnderlyingType->isUnsignedIntegerType()) { 16480 UnderlyingType = 16481 UnderlyingType->isUnsignedIntegerType() 16482 ? Context.getCorrespondingSignedType(UnderlyingType) 16483 : Context.getCorrespondingUnsignedType(UnderlyingType); 16484 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16485 /*CompareUnqualified*/ true)) 16486 PromoteType = QualType(); 16487 } 16488 } 16489 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 16490 PromoteType = Context.DoubleTy; 16491 if (!PromoteType.isNull()) 16492 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 16493 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 16494 << TInfo->getType() 16495 << PromoteType 16496 << TInfo->getTypeLoc().getSourceRange()); 16497 } 16498 16499 QualType T = TInfo->getType().getNonLValueExprType(Context); 16500 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 16501 } 16502 16503 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 16504 // The type of __null will be int or long, depending on the size of 16505 // pointers on the target. 16506 QualType Ty; 16507 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 16508 if (pw == Context.getTargetInfo().getIntWidth()) 16509 Ty = Context.IntTy; 16510 else if (pw == Context.getTargetInfo().getLongWidth()) 16511 Ty = Context.LongTy; 16512 else if (pw == Context.getTargetInfo().getLongLongWidth()) 16513 Ty = Context.LongLongTy; 16514 else { 16515 llvm_unreachable("I don't know size of pointer!"); 16516 } 16517 16518 return new (Context) GNUNullExpr(Ty, TokenLoc); 16519 } 16520 16521 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { 16522 CXXRecordDecl *ImplDecl = nullptr; 16523 16524 // Fetch the std::source_location::__impl decl. 16525 if (NamespaceDecl *Std = S.getStdNamespace()) { 16526 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"), 16527 Loc, Sema::LookupOrdinaryName); 16528 if (S.LookupQualifiedName(ResultSL, Std)) { 16529 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { 16530 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"), 16531 Loc, Sema::LookupOrdinaryName); 16532 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && 16533 S.LookupQualifiedName(ResultImpl, SLDecl)) { 16534 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); 16535 } 16536 } 16537 } 16538 } 16539 16540 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { 16541 S.Diag(Loc, diag::err_std_source_location_impl_not_found); 16542 return nullptr; 16543 } 16544 16545 // Verify that __impl is a trivial struct type, with no base classes, and with 16546 // only the four expected fields. 16547 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || 16548 ImplDecl->getNumBases() != 0) { 16549 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 16550 return nullptr; 16551 } 16552 16553 unsigned Count = 0; 16554 for (FieldDecl *F : ImplDecl->fields()) { 16555 StringRef Name = F->getName(); 16556 16557 if (Name == "_M_file_name") { 16558 if (F->getType() != 16559 S.Context.getPointerType(S.Context.CharTy.withConst())) 16560 break; 16561 Count++; 16562 } else if (Name == "_M_function_name") { 16563 if (F->getType() != 16564 S.Context.getPointerType(S.Context.CharTy.withConst())) 16565 break; 16566 Count++; 16567 } else if (Name == "_M_line") { 16568 if (!F->getType()->isIntegerType()) 16569 break; 16570 Count++; 16571 } else if (Name == "_M_column") { 16572 if (!F->getType()->isIntegerType()) 16573 break; 16574 Count++; 16575 } else { 16576 Count = 100; // invalid 16577 break; 16578 } 16579 } 16580 if (Count != 4) { 16581 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 16582 return nullptr; 16583 } 16584 16585 return ImplDecl; 16586 } 16587 16588 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 16589 SourceLocation BuiltinLoc, 16590 SourceLocation RPLoc) { 16591 QualType ResultTy; 16592 switch (Kind) { 16593 case SourceLocExpr::File: 16594 case SourceLocExpr::Function: { 16595 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0); 16596 ResultTy = 16597 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType()); 16598 break; 16599 } 16600 case SourceLocExpr::Line: 16601 case SourceLocExpr::Column: 16602 ResultTy = Context.UnsignedIntTy; 16603 break; 16604 case SourceLocExpr::SourceLocStruct: 16605 if (!StdSourceLocationImplDecl) { 16606 StdSourceLocationImplDecl = 16607 LookupStdSourceLocationImpl(*this, BuiltinLoc); 16608 if (!StdSourceLocationImplDecl) 16609 return ExprError(); 16610 } 16611 ResultTy = Context.getPointerType( 16612 Context.getRecordType(StdSourceLocationImplDecl).withConst()); 16613 break; 16614 } 16615 16616 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext); 16617 } 16618 16619 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 16620 QualType ResultTy, 16621 SourceLocation BuiltinLoc, 16622 SourceLocation RPLoc, 16623 DeclContext *ParentContext) { 16624 return new (Context) 16625 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); 16626 } 16627 16628 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 16629 bool Diagnose) { 16630 if (!getLangOpts().ObjC) 16631 return false; 16632 16633 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 16634 if (!PT) 16635 return false; 16636 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 16637 16638 // Ignore any parens, implicit casts (should only be 16639 // array-to-pointer decays), and not-so-opaque values. The last is 16640 // important for making this trigger for property assignments. 16641 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 16642 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 16643 if (OV->getSourceExpr()) 16644 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 16645 16646 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 16647 if (!PT->isObjCIdType() && 16648 !(ID && ID->getIdentifier()->isStr("NSString"))) 16649 return false; 16650 if (!SL->isAscii()) 16651 return false; 16652 16653 if (Diagnose) { 16654 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 16655 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 16656 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 16657 } 16658 return true; 16659 } 16660 16661 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16662 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16663 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16664 !SrcExpr->isNullPointerConstant( 16665 getASTContext(), Expr::NPC_NeverValueDependent)) { 16666 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16667 return false; 16668 if (Diagnose) { 16669 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16670 << /*number*/1 16671 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16672 Expr *NumLit = 16673 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16674 if (NumLit) 16675 Exp = NumLit; 16676 } 16677 return true; 16678 } 16679 16680 return false; 16681 } 16682 16683 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16684 const Expr *SrcExpr) { 16685 if (!DstType->isFunctionPointerType() || 16686 !SrcExpr->getType()->isFunctionType()) 16687 return false; 16688 16689 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16690 if (!DRE) 16691 return false; 16692 16693 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16694 if (!FD) 16695 return false; 16696 16697 return !S.checkAddressOfFunctionIsAvailable(FD, 16698 /*Complain=*/true, 16699 SrcExpr->getBeginLoc()); 16700 } 16701 16702 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16703 SourceLocation Loc, 16704 QualType DstType, QualType SrcType, 16705 Expr *SrcExpr, AssignmentAction Action, 16706 bool *Complained) { 16707 if (Complained) 16708 *Complained = false; 16709 16710 // Decode the result (notice that AST's are still created for extensions). 16711 bool CheckInferredResultType = false; 16712 bool isInvalid = false; 16713 unsigned DiagKind = 0; 16714 ConversionFixItGenerator ConvHints; 16715 bool MayHaveConvFixit = false; 16716 bool MayHaveFunctionDiff = false; 16717 const ObjCInterfaceDecl *IFace = nullptr; 16718 const ObjCProtocolDecl *PDecl = nullptr; 16719 16720 switch (ConvTy) { 16721 case Compatible: 16722 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16723 return false; 16724 16725 case PointerToInt: 16726 if (getLangOpts().CPlusPlus) { 16727 DiagKind = diag::err_typecheck_convert_pointer_int; 16728 isInvalid = true; 16729 } else { 16730 DiagKind = diag::ext_typecheck_convert_pointer_int; 16731 } 16732 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16733 MayHaveConvFixit = true; 16734 break; 16735 case IntToPointer: 16736 if (getLangOpts().CPlusPlus) { 16737 DiagKind = diag::err_typecheck_convert_int_pointer; 16738 isInvalid = true; 16739 } else { 16740 DiagKind = diag::ext_typecheck_convert_int_pointer; 16741 } 16742 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16743 MayHaveConvFixit = true; 16744 break; 16745 case IncompatibleFunctionPointer: 16746 if (getLangOpts().CPlusPlus) { 16747 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16748 isInvalid = true; 16749 } else { 16750 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16751 } 16752 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16753 MayHaveConvFixit = true; 16754 break; 16755 case IncompatiblePointer: 16756 if (Action == AA_Passing_CFAudited) { 16757 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16758 } else if (getLangOpts().CPlusPlus) { 16759 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16760 isInvalid = true; 16761 } else { 16762 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16763 } 16764 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16765 SrcType->isObjCObjectPointerType(); 16766 if (!CheckInferredResultType) { 16767 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16768 } else if (CheckInferredResultType) { 16769 SrcType = SrcType.getUnqualifiedType(); 16770 DstType = DstType.getUnqualifiedType(); 16771 } 16772 MayHaveConvFixit = true; 16773 break; 16774 case IncompatiblePointerSign: 16775 if (getLangOpts().CPlusPlus) { 16776 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16777 isInvalid = true; 16778 } else { 16779 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16780 } 16781 break; 16782 case FunctionVoidPointer: 16783 if (getLangOpts().CPlusPlus) { 16784 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16785 isInvalid = true; 16786 } else { 16787 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16788 } 16789 break; 16790 case IncompatiblePointerDiscardsQualifiers: { 16791 // Perform array-to-pointer decay if necessary. 16792 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16793 16794 isInvalid = true; 16795 16796 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16797 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16798 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16799 DiagKind = diag::err_typecheck_incompatible_address_space; 16800 break; 16801 16802 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16803 DiagKind = diag::err_typecheck_incompatible_ownership; 16804 break; 16805 } 16806 16807 llvm_unreachable("unknown error case for discarding qualifiers!"); 16808 // fallthrough 16809 } 16810 case CompatiblePointerDiscardsQualifiers: 16811 // If the qualifiers lost were because we were applying the 16812 // (deprecated) C++ conversion from a string literal to a char* 16813 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16814 // Ideally, this check would be performed in 16815 // checkPointerTypesForAssignment. However, that would require a 16816 // bit of refactoring (so that the second argument is an 16817 // expression, rather than a type), which should be done as part 16818 // of a larger effort to fix checkPointerTypesForAssignment for 16819 // C++ semantics. 16820 if (getLangOpts().CPlusPlus && 16821 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16822 return false; 16823 if (getLangOpts().CPlusPlus) { 16824 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16825 isInvalid = true; 16826 } else { 16827 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16828 } 16829 16830 break; 16831 case IncompatibleNestedPointerQualifiers: 16832 if (getLangOpts().CPlusPlus) { 16833 isInvalid = true; 16834 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16835 } else { 16836 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16837 } 16838 break; 16839 case IncompatibleNestedPointerAddressSpaceMismatch: 16840 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16841 isInvalid = true; 16842 break; 16843 case IntToBlockPointer: 16844 DiagKind = diag::err_int_to_block_pointer; 16845 isInvalid = true; 16846 break; 16847 case IncompatibleBlockPointer: 16848 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16849 isInvalid = true; 16850 break; 16851 case IncompatibleObjCQualifiedId: { 16852 if (SrcType->isObjCQualifiedIdType()) { 16853 const ObjCObjectPointerType *srcOPT = 16854 SrcType->castAs<ObjCObjectPointerType>(); 16855 for (auto *srcProto : srcOPT->quals()) { 16856 PDecl = srcProto; 16857 break; 16858 } 16859 if (const ObjCInterfaceType *IFaceT = 16860 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16861 IFace = IFaceT->getDecl(); 16862 } 16863 else if (DstType->isObjCQualifiedIdType()) { 16864 const ObjCObjectPointerType *dstOPT = 16865 DstType->castAs<ObjCObjectPointerType>(); 16866 for (auto *dstProto : dstOPT->quals()) { 16867 PDecl = dstProto; 16868 break; 16869 } 16870 if (const ObjCInterfaceType *IFaceT = 16871 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16872 IFace = IFaceT->getDecl(); 16873 } 16874 if (getLangOpts().CPlusPlus) { 16875 DiagKind = diag::err_incompatible_qualified_id; 16876 isInvalid = true; 16877 } else { 16878 DiagKind = diag::warn_incompatible_qualified_id; 16879 } 16880 break; 16881 } 16882 case IncompatibleVectors: 16883 if (getLangOpts().CPlusPlus) { 16884 DiagKind = diag::err_incompatible_vectors; 16885 isInvalid = true; 16886 } else { 16887 DiagKind = diag::warn_incompatible_vectors; 16888 } 16889 break; 16890 case IncompatibleObjCWeakRef: 16891 DiagKind = diag::err_arc_weak_unavailable_assign; 16892 isInvalid = true; 16893 break; 16894 case Incompatible: 16895 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16896 if (Complained) 16897 *Complained = true; 16898 return true; 16899 } 16900 16901 DiagKind = diag::err_typecheck_convert_incompatible; 16902 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16903 MayHaveConvFixit = true; 16904 isInvalid = true; 16905 MayHaveFunctionDiff = true; 16906 break; 16907 } 16908 16909 QualType FirstType, SecondType; 16910 switch (Action) { 16911 case AA_Assigning: 16912 case AA_Initializing: 16913 // The destination type comes first. 16914 FirstType = DstType; 16915 SecondType = SrcType; 16916 break; 16917 16918 case AA_Returning: 16919 case AA_Passing: 16920 case AA_Passing_CFAudited: 16921 case AA_Converting: 16922 case AA_Sending: 16923 case AA_Casting: 16924 // The source type comes first. 16925 FirstType = SrcType; 16926 SecondType = DstType; 16927 break; 16928 } 16929 16930 PartialDiagnostic FDiag = PDiag(DiagKind); 16931 if (Action == AA_Passing_CFAudited) 16932 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16933 else 16934 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16935 16936 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16937 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16938 auto isPlainChar = [](const clang::Type *Type) { 16939 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16940 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16941 }; 16942 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16943 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16944 } 16945 16946 // If we can fix the conversion, suggest the FixIts. 16947 if (!ConvHints.isNull()) { 16948 for (FixItHint &H : ConvHints.Hints) 16949 FDiag << H; 16950 } 16951 16952 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16953 16954 if (MayHaveFunctionDiff) 16955 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16956 16957 Diag(Loc, FDiag); 16958 if ((DiagKind == diag::warn_incompatible_qualified_id || 16959 DiagKind == diag::err_incompatible_qualified_id) && 16960 PDecl && IFace && !IFace->hasDefinition()) 16961 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16962 << IFace << PDecl; 16963 16964 if (SecondType == Context.OverloadTy) 16965 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16966 FirstType, /*TakingAddress=*/true); 16967 16968 if (CheckInferredResultType) 16969 EmitRelatedResultTypeNote(SrcExpr); 16970 16971 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16972 EmitRelatedResultTypeNoteForReturn(DstType); 16973 16974 if (Complained) 16975 *Complained = true; 16976 return isInvalid; 16977 } 16978 16979 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16980 llvm::APSInt *Result, 16981 AllowFoldKind CanFold) { 16982 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16983 public: 16984 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16985 QualType T) override { 16986 return S.Diag(Loc, diag::err_ice_not_integral) 16987 << T << S.LangOpts.CPlusPlus; 16988 } 16989 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16990 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16991 } 16992 } Diagnoser; 16993 16994 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16995 } 16996 16997 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16998 llvm::APSInt *Result, 16999 unsigned DiagID, 17000 AllowFoldKind CanFold) { 17001 class IDDiagnoser : public VerifyICEDiagnoser { 17002 unsigned DiagID; 17003 17004 public: 17005 IDDiagnoser(unsigned DiagID) 17006 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 17007 17008 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 17009 return S.Diag(Loc, DiagID); 17010 } 17011 } Diagnoser(DiagID); 17012 17013 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 17014 } 17015 17016 Sema::SemaDiagnosticBuilder 17017 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 17018 QualType T) { 17019 return diagnoseNotICE(S, Loc); 17020 } 17021 17022 Sema::SemaDiagnosticBuilder 17023 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 17024 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 17025 } 17026 17027 ExprResult 17028 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 17029 VerifyICEDiagnoser &Diagnoser, 17030 AllowFoldKind CanFold) { 17031 SourceLocation DiagLoc = E->getBeginLoc(); 17032 17033 if (getLangOpts().CPlusPlus11) { 17034 // C++11 [expr.const]p5: 17035 // If an expression of literal class type is used in a context where an 17036 // integral constant expression is required, then that class type shall 17037 // have a single non-explicit conversion function to an integral or 17038 // unscoped enumeration type 17039 ExprResult Converted; 17040 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 17041 VerifyICEDiagnoser &BaseDiagnoser; 17042 public: 17043 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 17044 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 17045 BaseDiagnoser.Suppress, true), 17046 BaseDiagnoser(BaseDiagnoser) {} 17047 17048 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 17049 QualType T) override { 17050 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 17051 } 17052 17053 SemaDiagnosticBuilder diagnoseIncomplete( 17054 Sema &S, SourceLocation Loc, QualType T) override { 17055 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 17056 } 17057 17058 SemaDiagnosticBuilder diagnoseExplicitConv( 17059 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 17060 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 17061 } 17062 17063 SemaDiagnosticBuilder noteExplicitConv( 17064 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 17065 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 17066 << ConvTy->isEnumeralType() << ConvTy; 17067 } 17068 17069 SemaDiagnosticBuilder diagnoseAmbiguous( 17070 Sema &S, SourceLocation Loc, QualType T) override { 17071 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 17072 } 17073 17074 SemaDiagnosticBuilder noteAmbiguous( 17075 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 17076 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 17077 << ConvTy->isEnumeralType() << ConvTy; 17078 } 17079 17080 SemaDiagnosticBuilder diagnoseConversion( 17081 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 17082 llvm_unreachable("conversion functions are permitted"); 17083 } 17084 } ConvertDiagnoser(Diagnoser); 17085 17086 Converted = PerformContextualImplicitConversion(DiagLoc, E, 17087 ConvertDiagnoser); 17088 if (Converted.isInvalid()) 17089 return Converted; 17090 E = Converted.get(); 17091 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 17092 return ExprError(); 17093 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 17094 // An ICE must be of integral or unscoped enumeration type. 17095 if (!Diagnoser.Suppress) 17096 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 17097 << E->getSourceRange(); 17098 return ExprError(); 17099 } 17100 17101 ExprResult RValueExpr = DefaultLvalueConversion(E); 17102 if (RValueExpr.isInvalid()) 17103 return ExprError(); 17104 17105 E = RValueExpr.get(); 17106 17107 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 17108 // in the non-ICE case. 17109 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 17110 if (Result) 17111 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 17112 if (!isa<ConstantExpr>(E)) 17113 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 17114 : ConstantExpr::Create(Context, E); 17115 return E; 17116 } 17117 17118 Expr::EvalResult EvalResult; 17119 SmallVector<PartialDiagnosticAt, 8> Notes; 17120 EvalResult.Diag = &Notes; 17121 17122 // Try to evaluate the expression, and produce diagnostics explaining why it's 17123 // not a constant expression as a side-effect. 17124 bool Folded = 17125 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 17126 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 17127 17128 if (!isa<ConstantExpr>(E)) 17129 E = ConstantExpr::Create(Context, E, EvalResult.Val); 17130 17131 // In C++11, we can rely on diagnostics being produced for any expression 17132 // which is not a constant expression. If no diagnostics were produced, then 17133 // this is a constant expression. 17134 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 17135 if (Result) 17136 *Result = EvalResult.Val.getInt(); 17137 return E; 17138 } 17139 17140 // If our only note is the usual "invalid subexpression" note, just point 17141 // the caret at its location rather than producing an essentially 17142 // redundant note. 17143 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 17144 diag::note_invalid_subexpr_in_const_expr) { 17145 DiagLoc = Notes[0].first; 17146 Notes.clear(); 17147 } 17148 17149 if (!Folded || !CanFold) { 17150 if (!Diagnoser.Suppress) { 17151 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 17152 for (const PartialDiagnosticAt &Note : Notes) 17153 Diag(Note.first, Note.second); 17154 } 17155 17156 return ExprError(); 17157 } 17158 17159 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 17160 for (const PartialDiagnosticAt &Note : Notes) 17161 Diag(Note.first, Note.second); 17162 17163 if (Result) 17164 *Result = EvalResult.Val.getInt(); 17165 return E; 17166 } 17167 17168 namespace { 17169 // Handle the case where we conclude a expression which we speculatively 17170 // considered to be unevaluated is actually evaluated. 17171 class TransformToPE : public TreeTransform<TransformToPE> { 17172 typedef TreeTransform<TransformToPE> BaseTransform; 17173 17174 public: 17175 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 17176 17177 // Make sure we redo semantic analysis 17178 bool AlwaysRebuild() { return true; } 17179 bool ReplacingOriginal() { return true; } 17180 17181 // We need to special-case DeclRefExprs referring to FieldDecls which 17182 // are not part of a member pointer formation; normal TreeTransforming 17183 // doesn't catch this case because of the way we represent them in the AST. 17184 // FIXME: This is a bit ugly; is it really the best way to handle this 17185 // case? 17186 // 17187 // Error on DeclRefExprs referring to FieldDecls. 17188 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 17189 if (isa<FieldDecl>(E->getDecl()) && 17190 !SemaRef.isUnevaluatedContext()) 17191 return SemaRef.Diag(E->getLocation(), 17192 diag::err_invalid_non_static_member_use) 17193 << E->getDecl() << E->getSourceRange(); 17194 17195 return BaseTransform::TransformDeclRefExpr(E); 17196 } 17197 17198 // Exception: filter out member pointer formation 17199 ExprResult TransformUnaryOperator(UnaryOperator *E) { 17200 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 17201 return E; 17202 17203 return BaseTransform::TransformUnaryOperator(E); 17204 } 17205 17206 // The body of a lambda-expression is in a separate expression evaluation 17207 // context so never needs to be transformed. 17208 // FIXME: Ideally we wouldn't transform the closure type either, and would 17209 // just recreate the capture expressions and lambda expression. 17210 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 17211 return SkipLambdaBody(E, Body); 17212 } 17213 }; 17214 } 17215 17216 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 17217 assert(isUnevaluatedContext() && 17218 "Should only transform unevaluated expressions"); 17219 ExprEvalContexts.back().Context = 17220 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 17221 if (isUnevaluatedContext()) 17222 return E; 17223 return TransformToPE(*this).TransformExpr(E); 17224 } 17225 17226 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { 17227 assert(isUnevaluatedContext() && 17228 "Should only transform unevaluated expressions"); 17229 ExprEvalContexts.back().Context = 17230 ExprEvalContexts[ExprEvalContexts.size() - 2].Context; 17231 if (isUnevaluatedContext()) 17232 return TInfo; 17233 return TransformToPE(*this).TransformType(TInfo); 17234 } 17235 17236 void 17237 Sema::PushExpressionEvaluationContext( 17238 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 17239 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17240 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 17241 LambdaContextDecl, ExprContext); 17242 17243 // Discarded statements and immediate contexts nested in other 17244 // discarded statements or immediate context are themselves 17245 // a discarded statement or an immediate context, respectively. 17246 ExprEvalContexts.back().InDiscardedStatement = 17247 ExprEvalContexts[ExprEvalContexts.size() - 2] 17248 .isDiscardedStatementContext(); 17249 ExprEvalContexts.back().InImmediateFunctionContext = 17250 ExprEvalContexts[ExprEvalContexts.size() - 2] 17251 .isImmediateFunctionContext(); 17252 17253 Cleanup.reset(); 17254 if (!MaybeODRUseExprs.empty()) 17255 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 17256 } 17257 17258 void 17259 Sema::PushExpressionEvaluationContext( 17260 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 17261 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17262 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 17263 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 17264 } 17265 17266 namespace { 17267 17268 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 17269 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 17270 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 17271 if (E->getOpcode() == UO_Deref) 17272 return CheckPossibleDeref(S, E->getSubExpr()); 17273 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 17274 return CheckPossibleDeref(S, E->getBase()); 17275 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 17276 return CheckPossibleDeref(S, E->getBase()); 17277 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 17278 QualType Inner; 17279 QualType Ty = E->getType(); 17280 if (const auto *Ptr = Ty->getAs<PointerType>()) 17281 Inner = Ptr->getPointeeType(); 17282 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 17283 Inner = Arr->getElementType(); 17284 else 17285 return nullptr; 17286 17287 if (Inner->hasAttr(attr::NoDeref)) 17288 return E; 17289 } 17290 return nullptr; 17291 } 17292 17293 } // namespace 17294 17295 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 17296 for (const Expr *E : Rec.PossibleDerefs) { 17297 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 17298 if (DeclRef) { 17299 const ValueDecl *Decl = DeclRef->getDecl(); 17300 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 17301 << Decl->getName() << E->getSourceRange(); 17302 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 17303 } else { 17304 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 17305 << E->getSourceRange(); 17306 } 17307 } 17308 Rec.PossibleDerefs.clear(); 17309 } 17310 17311 /// Check whether E, which is either a discarded-value expression or an 17312 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 17313 /// and if so, remove it from the list of volatile-qualified assignments that 17314 /// we are going to warn are deprecated. 17315 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 17316 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 17317 return; 17318 17319 // Note: ignoring parens here is not justified by the standard rules, but 17320 // ignoring parentheses seems like a more reasonable approach, and this only 17321 // drives a deprecation warning so doesn't affect conformance. 17322 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 17323 if (BO->getOpcode() == BO_Assign) { 17324 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 17325 llvm::erase_value(LHSs, BO->getLHS()); 17326 } 17327 } 17328 } 17329 17330 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 17331 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 17332 !Decl->isConsteval() || isConstantEvaluated() || 17333 RebuildingImmediateInvocation || isImmediateFunctionContext()) 17334 return E; 17335 17336 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 17337 /// It's OK if this fails; we'll also remove this in 17338 /// HandleImmediateInvocations, but catching it here allows us to avoid 17339 /// walking the AST looking for it in simple cases. 17340 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 17341 if (auto *DeclRef = 17342 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 17343 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 17344 17345 E = MaybeCreateExprWithCleanups(E); 17346 17347 ConstantExpr *Res = ConstantExpr::Create( 17348 getASTContext(), E.get(), 17349 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 17350 getASTContext()), 17351 /*IsImmediateInvocation*/ true); 17352 /// Value-dependent constant expressions should not be immediately 17353 /// evaluated until they are instantiated. 17354 if (!Res->isValueDependent()) 17355 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 17356 return Res; 17357 } 17358 17359 static void EvaluateAndDiagnoseImmediateInvocation( 17360 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 17361 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 17362 Expr::EvalResult Eval; 17363 Eval.Diag = &Notes; 17364 ConstantExpr *CE = Candidate.getPointer(); 17365 bool Result = CE->EvaluateAsConstantExpr( 17366 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 17367 if (!Result || !Notes.empty()) { 17368 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 17369 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 17370 InnerExpr = FunctionalCast->getSubExpr(); 17371 FunctionDecl *FD = nullptr; 17372 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 17373 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 17374 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 17375 FD = Call->getConstructor(); 17376 else 17377 llvm_unreachable("unhandled decl kind"); 17378 assert(FD->isConsteval()); 17379 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 17380 for (auto &Note : Notes) 17381 SemaRef.Diag(Note.first, Note.second); 17382 return; 17383 } 17384 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 17385 } 17386 17387 static void RemoveNestedImmediateInvocation( 17388 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 17389 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 17390 struct ComplexRemove : TreeTransform<ComplexRemove> { 17391 using Base = TreeTransform<ComplexRemove>; 17392 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17393 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 17394 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 17395 CurrentII; 17396 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 17397 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 17398 SmallVector<Sema::ImmediateInvocationCandidate, 17399 4>::reverse_iterator Current) 17400 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 17401 void RemoveImmediateInvocation(ConstantExpr* E) { 17402 auto It = std::find_if(CurrentII, IISet.rend(), 17403 [E](Sema::ImmediateInvocationCandidate Elem) { 17404 return Elem.getPointer() == E; 17405 }); 17406 assert(It != IISet.rend() && 17407 "ConstantExpr marked IsImmediateInvocation should " 17408 "be present"); 17409 It->setInt(1); // Mark as deleted 17410 } 17411 ExprResult TransformConstantExpr(ConstantExpr *E) { 17412 if (!E->isImmediateInvocation()) 17413 return Base::TransformConstantExpr(E); 17414 RemoveImmediateInvocation(E); 17415 return Base::TransformExpr(E->getSubExpr()); 17416 } 17417 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 17418 /// we need to remove its DeclRefExpr from the DRSet. 17419 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 17420 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 17421 return Base::TransformCXXOperatorCallExpr(E); 17422 } 17423 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 17424 /// here. 17425 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 17426 if (!Init) 17427 return Init; 17428 /// ConstantExpr are the first layer of implicit node to be removed so if 17429 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 17430 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 17431 if (CE->isImmediateInvocation()) 17432 RemoveImmediateInvocation(CE); 17433 return Base::TransformInitializer(Init, NotCopyInit); 17434 } 17435 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 17436 DRSet.erase(E); 17437 return E; 17438 } 17439 bool AlwaysRebuild() { return false; } 17440 bool ReplacingOriginal() { return true; } 17441 bool AllowSkippingCXXConstructExpr() { 17442 bool Res = AllowSkippingFirstCXXConstructExpr; 17443 AllowSkippingFirstCXXConstructExpr = true; 17444 return Res; 17445 } 17446 bool AllowSkippingFirstCXXConstructExpr = true; 17447 } Transformer(SemaRef, Rec.ReferenceToConsteval, 17448 Rec.ImmediateInvocationCandidates, It); 17449 17450 /// CXXConstructExpr with a single argument are getting skipped by 17451 /// TreeTransform in some situtation because they could be implicit. This 17452 /// can only occur for the top-level CXXConstructExpr because it is used 17453 /// nowhere in the expression being transformed therefore will not be rebuilt. 17454 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 17455 /// skipping the first CXXConstructExpr. 17456 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 17457 Transformer.AllowSkippingFirstCXXConstructExpr = false; 17458 17459 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 17460 assert(Res.isUsable()); 17461 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 17462 It->getPointer()->setSubExpr(Res.get()); 17463 } 17464 17465 static void 17466 HandleImmediateInvocations(Sema &SemaRef, 17467 Sema::ExpressionEvaluationContextRecord &Rec) { 17468 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 17469 Rec.ReferenceToConsteval.size() == 0) || 17470 SemaRef.RebuildingImmediateInvocation) 17471 return; 17472 17473 /// When we have more then 1 ImmediateInvocationCandidates we need to check 17474 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 17475 /// need to remove ReferenceToConsteval in the immediate invocation. 17476 if (Rec.ImmediateInvocationCandidates.size() > 1) { 17477 17478 /// Prevent sema calls during the tree transform from adding pointers that 17479 /// are already in the sets. 17480 llvm::SaveAndRestore<bool> DisableIITracking( 17481 SemaRef.RebuildingImmediateInvocation, true); 17482 17483 /// Prevent diagnostic during tree transfrom as they are duplicates 17484 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 17485 17486 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 17487 It != Rec.ImmediateInvocationCandidates.rend(); It++) 17488 if (!It->getInt()) 17489 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 17490 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 17491 Rec.ReferenceToConsteval.size()) { 17492 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 17493 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17494 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 17495 bool VisitDeclRefExpr(DeclRefExpr *E) { 17496 DRSet.erase(E); 17497 return DRSet.size(); 17498 } 17499 } Visitor(Rec.ReferenceToConsteval); 17500 Visitor.TraverseStmt( 17501 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 17502 } 17503 for (auto CE : Rec.ImmediateInvocationCandidates) 17504 if (!CE.getInt()) 17505 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 17506 for (auto DR : Rec.ReferenceToConsteval) { 17507 auto *FD = cast<FunctionDecl>(DR->getDecl()); 17508 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 17509 << FD; 17510 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 17511 } 17512 } 17513 17514 void Sema::PopExpressionEvaluationContext() { 17515 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 17516 unsigned NumTypos = Rec.NumTypos; 17517 17518 if (!Rec.Lambdas.empty()) { 17519 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 17520 if (!getLangOpts().CPlusPlus20 && 17521 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 17522 Rec.isUnevaluated() || 17523 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 17524 unsigned D; 17525 if (Rec.isUnevaluated()) { 17526 // C++11 [expr.prim.lambda]p2: 17527 // A lambda-expression shall not appear in an unevaluated operand 17528 // (Clause 5). 17529 D = diag::err_lambda_unevaluated_operand; 17530 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 17531 // C++1y [expr.const]p2: 17532 // A conditional-expression e is a core constant expression unless the 17533 // evaluation of e, following the rules of the abstract machine, would 17534 // evaluate [...] a lambda-expression. 17535 D = diag::err_lambda_in_constant_expression; 17536 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 17537 // C++17 [expr.prim.lamda]p2: 17538 // A lambda-expression shall not appear [...] in a template-argument. 17539 D = diag::err_lambda_in_invalid_context; 17540 } else 17541 llvm_unreachable("Couldn't infer lambda error message."); 17542 17543 for (const auto *L : Rec.Lambdas) 17544 Diag(L->getBeginLoc(), D); 17545 } 17546 } 17547 17548 WarnOnPendingNoDerefs(Rec); 17549 HandleImmediateInvocations(*this, Rec); 17550 17551 // Warn on any volatile-qualified simple-assignments that are not discarded- 17552 // value expressions nor unevaluated operands (those cases get removed from 17553 // this list by CheckUnusedVolatileAssignment). 17554 for (auto *BO : Rec.VolatileAssignmentLHSs) 17555 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 17556 << BO->getType(); 17557 17558 // When are coming out of an unevaluated context, clear out any 17559 // temporaries that we may have created as part of the evaluation of 17560 // the expression in that context: they aren't relevant because they 17561 // will never be constructed. 17562 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 17563 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 17564 ExprCleanupObjects.end()); 17565 Cleanup = Rec.ParentCleanup; 17566 CleanupVarDeclMarking(); 17567 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 17568 // Otherwise, merge the contexts together. 17569 } else { 17570 Cleanup.mergeFrom(Rec.ParentCleanup); 17571 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 17572 Rec.SavedMaybeODRUseExprs.end()); 17573 } 17574 17575 // Pop the current expression evaluation context off the stack. 17576 ExprEvalContexts.pop_back(); 17577 17578 // The global expression evaluation context record is never popped. 17579 ExprEvalContexts.back().NumTypos += NumTypos; 17580 } 17581 17582 void Sema::DiscardCleanupsInEvaluationContext() { 17583 ExprCleanupObjects.erase( 17584 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 17585 ExprCleanupObjects.end()); 17586 Cleanup.reset(); 17587 MaybeODRUseExprs.clear(); 17588 } 17589 17590 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 17591 ExprResult Result = CheckPlaceholderExpr(E); 17592 if (Result.isInvalid()) 17593 return ExprError(); 17594 E = Result.get(); 17595 if (!E->getType()->isVariablyModifiedType()) 17596 return E; 17597 return TransformToPotentiallyEvaluated(E); 17598 } 17599 17600 /// Are we in a context that is potentially constant evaluated per C++20 17601 /// [expr.const]p12? 17602 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 17603 /// C++2a [expr.const]p12: 17604 // An expression or conversion is potentially constant evaluated if it is 17605 switch (SemaRef.ExprEvalContexts.back().Context) { 17606 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17607 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17608 17609 // -- a manifestly constant-evaluated expression, 17610 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17611 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17612 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17613 // -- a potentially-evaluated expression, 17614 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17615 // -- an immediate subexpression of a braced-init-list, 17616 17617 // -- [FIXME] an expression of the form & cast-expression that occurs 17618 // within a templated entity 17619 // -- a subexpression of one of the above that is not a subexpression of 17620 // a nested unevaluated operand. 17621 return true; 17622 17623 case Sema::ExpressionEvaluationContext::Unevaluated: 17624 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17625 // Expressions in this context are never evaluated. 17626 return false; 17627 } 17628 llvm_unreachable("Invalid context"); 17629 } 17630 17631 /// Return true if this function has a calling convention that requires mangling 17632 /// in the size of the parameter pack. 17633 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 17634 // These manglings don't do anything on non-Windows or non-x86 platforms, so 17635 // we don't need parameter type sizes. 17636 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 17637 if (!TT.isOSWindows() || !TT.isX86()) 17638 return false; 17639 17640 // If this is C++ and this isn't an extern "C" function, parameters do not 17641 // need to be complete. In this case, C++ mangling will apply, which doesn't 17642 // use the size of the parameters. 17643 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 17644 return false; 17645 17646 // Stdcall, fastcall, and vectorcall need this special treatment. 17647 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17648 switch (CC) { 17649 case CC_X86StdCall: 17650 case CC_X86FastCall: 17651 case CC_X86VectorCall: 17652 return true; 17653 default: 17654 break; 17655 } 17656 return false; 17657 } 17658 17659 /// Require that all of the parameter types of function be complete. Normally, 17660 /// parameter types are only required to be complete when a function is called 17661 /// or defined, but to mangle functions with certain calling conventions, the 17662 /// mangler needs to know the size of the parameter list. In this situation, 17663 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 17664 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 17665 /// result in a linker error. Clang doesn't implement this behavior, and instead 17666 /// attempts to error at compile time. 17667 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 17668 SourceLocation Loc) { 17669 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 17670 FunctionDecl *FD; 17671 ParmVarDecl *Param; 17672 17673 public: 17674 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 17675 : FD(FD), Param(Param) {} 17676 17677 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17678 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17679 StringRef CCName; 17680 switch (CC) { 17681 case CC_X86StdCall: 17682 CCName = "stdcall"; 17683 break; 17684 case CC_X86FastCall: 17685 CCName = "fastcall"; 17686 break; 17687 case CC_X86VectorCall: 17688 CCName = "vectorcall"; 17689 break; 17690 default: 17691 llvm_unreachable("CC does not need mangling"); 17692 } 17693 17694 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17695 << Param->getDeclName() << FD->getDeclName() << CCName; 17696 } 17697 }; 17698 17699 for (ParmVarDecl *Param : FD->parameters()) { 17700 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17701 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17702 } 17703 } 17704 17705 namespace { 17706 enum class OdrUseContext { 17707 /// Declarations in this context are not odr-used. 17708 None, 17709 /// Declarations in this context are formally odr-used, but this is a 17710 /// dependent context. 17711 Dependent, 17712 /// Declarations in this context are odr-used but not actually used (yet). 17713 FormallyOdrUsed, 17714 /// Declarations in this context are used. 17715 Used 17716 }; 17717 } 17718 17719 /// Are we within a context in which references to resolved functions or to 17720 /// variables result in odr-use? 17721 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17722 OdrUseContext Result; 17723 17724 switch (SemaRef.ExprEvalContexts.back().Context) { 17725 case Sema::ExpressionEvaluationContext::Unevaluated: 17726 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17727 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17728 return OdrUseContext::None; 17729 17730 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17731 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17732 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17733 Result = OdrUseContext::Used; 17734 break; 17735 17736 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17737 Result = OdrUseContext::FormallyOdrUsed; 17738 break; 17739 17740 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17741 // A default argument formally results in odr-use, but doesn't actually 17742 // result in a use in any real sense until it itself is used. 17743 Result = OdrUseContext::FormallyOdrUsed; 17744 break; 17745 } 17746 17747 if (SemaRef.CurContext->isDependentContext()) 17748 return OdrUseContext::Dependent; 17749 17750 return Result; 17751 } 17752 17753 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17754 if (!Func->isConstexpr()) 17755 return false; 17756 17757 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17758 return true; 17759 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17760 return CCD && CCD->getInheritedConstructor(); 17761 } 17762 17763 /// Mark a function referenced, and check whether it is odr-used 17764 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17765 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17766 bool MightBeOdrUse) { 17767 assert(Func && "No function?"); 17768 17769 Func->setReferenced(); 17770 17771 // Recursive functions aren't really used until they're used from some other 17772 // context. 17773 bool IsRecursiveCall = CurContext == Func; 17774 17775 // C++11 [basic.def.odr]p3: 17776 // A function whose name appears as a potentially-evaluated expression is 17777 // odr-used if it is the unique lookup result or the selected member of a 17778 // set of overloaded functions [...]. 17779 // 17780 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17781 // can just check that here. 17782 OdrUseContext OdrUse = 17783 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17784 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17785 OdrUse = OdrUseContext::FormallyOdrUsed; 17786 17787 // Trivial default constructors and destructors are never actually used. 17788 // FIXME: What about other special members? 17789 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17790 OdrUse == OdrUseContext::Used) { 17791 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17792 if (Constructor->isDefaultConstructor()) 17793 OdrUse = OdrUseContext::FormallyOdrUsed; 17794 if (isa<CXXDestructorDecl>(Func)) 17795 OdrUse = OdrUseContext::FormallyOdrUsed; 17796 } 17797 17798 // C++20 [expr.const]p12: 17799 // A function [...] is needed for constant evaluation if it is [...] a 17800 // constexpr function that is named by an expression that is potentially 17801 // constant evaluated 17802 bool NeededForConstantEvaluation = 17803 isPotentiallyConstantEvaluatedContext(*this) && 17804 isImplicitlyDefinableConstexprFunction(Func); 17805 17806 // Determine whether we require a function definition to exist, per 17807 // C++11 [temp.inst]p3: 17808 // Unless a function template specialization has been explicitly 17809 // instantiated or explicitly specialized, the function template 17810 // specialization is implicitly instantiated when the specialization is 17811 // referenced in a context that requires a function definition to exist. 17812 // C++20 [temp.inst]p7: 17813 // The existence of a definition of a [...] function is considered to 17814 // affect the semantics of the program if the [...] function is needed for 17815 // constant evaluation by an expression 17816 // C++20 [basic.def.odr]p10: 17817 // Every program shall contain exactly one definition of every non-inline 17818 // function or variable that is odr-used in that program outside of a 17819 // discarded statement 17820 // C++20 [special]p1: 17821 // The implementation will implicitly define [defaulted special members] 17822 // if they are odr-used or needed for constant evaluation. 17823 // 17824 // Note that we skip the implicit instantiation of templates that are only 17825 // used in unused default arguments or by recursive calls to themselves. 17826 // This is formally non-conforming, but seems reasonable in practice. 17827 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17828 NeededForConstantEvaluation); 17829 17830 // C++14 [temp.expl.spec]p6: 17831 // If a template [...] is explicitly specialized then that specialization 17832 // shall be declared before the first use of that specialization that would 17833 // cause an implicit instantiation to take place, in every translation unit 17834 // in which such a use occurs 17835 if (NeedDefinition && 17836 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17837 Func->getMemberSpecializationInfo())) 17838 checkSpecializationVisibility(Loc, Func); 17839 17840 if (getLangOpts().CUDA) 17841 CheckCUDACall(Loc, Func); 17842 17843 if (getLangOpts().SYCLIsDevice) 17844 checkSYCLDeviceFunction(Loc, Func); 17845 17846 // If we need a definition, try to create one. 17847 if (NeedDefinition && !Func->getBody()) { 17848 runWithSufficientStackSpace(Loc, [&] { 17849 if (CXXConstructorDecl *Constructor = 17850 dyn_cast<CXXConstructorDecl>(Func)) { 17851 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17852 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17853 if (Constructor->isDefaultConstructor()) { 17854 if (Constructor->isTrivial() && 17855 !Constructor->hasAttr<DLLExportAttr>()) 17856 return; 17857 DefineImplicitDefaultConstructor(Loc, Constructor); 17858 } else if (Constructor->isCopyConstructor()) { 17859 DefineImplicitCopyConstructor(Loc, Constructor); 17860 } else if (Constructor->isMoveConstructor()) { 17861 DefineImplicitMoveConstructor(Loc, Constructor); 17862 } 17863 } else if (Constructor->getInheritedConstructor()) { 17864 DefineInheritingConstructor(Loc, Constructor); 17865 } 17866 } else if (CXXDestructorDecl *Destructor = 17867 dyn_cast<CXXDestructorDecl>(Func)) { 17868 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17869 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17870 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17871 return; 17872 DefineImplicitDestructor(Loc, Destructor); 17873 } 17874 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17875 MarkVTableUsed(Loc, Destructor->getParent()); 17876 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17877 if (MethodDecl->isOverloadedOperator() && 17878 MethodDecl->getOverloadedOperator() == OO_Equal) { 17879 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17880 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17881 if (MethodDecl->isCopyAssignmentOperator()) 17882 DefineImplicitCopyAssignment(Loc, MethodDecl); 17883 else if (MethodDecl->isMoveAssignmentOperator()) 17884 DefineImplicitMoveAssignment(Loc, MethodDecl); 17885 } 17886 } else if (isa<CXXConversionDecl>(MethodDecl) && 17887 MethodDecl->getParent()->isLambda()) { 17888 CXXConversionDecl *Conversion = 17889 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17890 if (Conversion->isLambdaToBlockPointerConversion()) 17891 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17892 else 17893 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17894 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17895 MarkVTableUsed(Loc, MethodDecl->getParent()); 17896 } 17897 17898 if (Func->isDefaulted() && !Func->isDeleted()) { 17899 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17900 if (DCK != DefaultedComparisonKind::None) 17901 DefineDefaultedComparison(Loc, Func, DCK); 17902 } 17903 17904 // Implicit instantiation of function templates and member functions of 17905 // class templates. 17906 if (Func->isImplicitlyInstantiable()) { 17907 TemplateSpecializationKind TSK = 17908 Func->getTemplateSpecializationKindForInstantiation(); 17909 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17910 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17911 if (FirstInstantiation) { 17912 PointOfInstantiation = Loc; 17913 if (auto *MSI = Func->getMemberSpecializationInfo()) 17914 MSI->setPointOfInstantiation(Loc); 17915 // FIXME: Notify listener. 17916 else 17917 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17918 } else if (TSK != TSK_ImplicitInstantiation) { 17919 // Use the point of use as the point of instantiation, instead of the 17920 // point of explicit instantiation (which we track as the actual point 17921 // of instantiation). This gives better backtraces in diagnostics. 17922 PointOfInstantiation = Loc; 17923 } 17924 17925 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17926 Func->isConstexpr()) { 17927 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17928 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17929 CodeSynthesisContexts.size()) 17930 PendingLocalImplicitInstantiations.push_back( 17931 std::make_pair(Func, PointOfInstantiation)); 17932 else if (Func->isConstexpr()) 17933 // Do not defer instantiations of constexpr functions, to avoid the 17934 // expression evaluator needing to call back into Sema if it sees a 17935 // call to such a function. 17936 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17937 else { 17938 Func->setInstantiationIsPending(true); 17939 PendingInstantiations.push_back( 17940 std::make_pair(Func, PointOfInstantiation)); 17941 // Notify the consumer that a function was implicitly instantiated. 17942 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17943 } 17944 } 17945 } else { 17946 // Walk redefinitions, as some of them may be instantiable. 17947 for (auto i : Func->redecls()) { 17948 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17949 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17950 } 17951 } 17952 }); 17953 } 17954 17955 // C++14 [except.spec]p17: 17956 // An exception-specification is considered to be needed when: 17957 // - the function is odr-used or, if it appears in an unevaluated operand, 17958 // would be odr-used if the expression were potentially-evaluated; 17959 // 17960 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17961 // function is a pure virtual function we're calling, and in that case the 17962 // function was selected by overload resolution and we need to resolve its 17963 // exception specification for a different reason. 17964 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17965 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17966 ResolveExceptionSpec(Loc, FPT); 17967 17968 // If this is the first "real" use, act on that. 17969 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17970 // Keep track of used but undefined functions. 17971 if (!Func->isDefined()) { 17972 if (mightHaveNonExternalLinkage(Func)) 17973 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17974 else if (Func->getMostRecentDecl()->isInlined() && 17975 !LangOpts.GNUInline && 17976 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17977 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17978 else if (isExternalWithNoLinkageType(Func)) 17979 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17980 } 17981 17982 // Some x86 Windows calling conventions mangle the size of the parameter 17983 // pack into the name. Computing the size of the parameters requires the 17984 // parameter types to be complete. Check that now. 17985 if (funcHasParameterSizeMangling(*this, Func)) 17986 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17987 17988 // In the MS C++ ABI, the compiler emits destructor variants where they are 17989 // used. If the destructor is used here but defined elsewhere, mark the 17990 // virtual base destructors referenced. If those virtual base destructors 17991 // are inline, this will ensure they are defined when emitting the complete 17992 // destructor variant. This checking may be redundant if the destructor is 17993 // provided later in this TU. 17994 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17995 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17996 CXXRecordDecl *Parent = Dtor->getParent(); 17997 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17998 CheckCompleteDestructorVariant(Loc, Dtor); 17999 } 18000 } 18001 18002 Func->markUsed(Context); 18003 } 18004 } 18005 18006 /// Directly mark a variable odr-used. Given a choice, prefer to use 18007 /// MarkVariableReferenced since it does additional checks and then 18008 /// calls MarkVarDeclODRUsed. 18009 /// If the variable must be captured: 18010 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 18011 /// - else capture it in the DeclContext that maps to the 18012 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 18013 static void 18014 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 18015 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 18016 // Keep track of used but undefined variables. 18017 // FIXME: We shouldn't suppress this warning for static data members. 18018 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 18019 (!Var->isExternallyVisible() || Var->isInline() || 18020 SemaRef.isExternalWithNoLinkageType(Var)) && 18021 !(Var->isStaticDataMember() && Var->hasInit())) { 18022 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 18023 if (old.isInvalid()) 18024 old = Loc; 18025 } 18026 QualType CaptureType, DeclRefType; 18027 if (SemaRef.LangOpts.OpenMP) 18028 SemaRef.tryCaptureOpenMPLambdas(Var); 18029 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 18030 /*EllipsisLoc*/ SourceLocation(), 18031 /*BuildAndDiagnose*/ true, 18032 CaptureType, DeclRefType, 18033 FunctionScopeIndexToStopAt); 18034 18035 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { 18036 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 18037 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 18038 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 18039 if (VarTarget == Sema::CVT_Host && 18040 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 18041 UserTarget == Sema::CFT_Global)) { 18042 // Diagnose ODR-use of host global variables in device functions. 18043 // Reference of device global variables in host functions is allowed 18044 // through shadow variables therefore it is not diagnosed. 18045 if (SemaRef.LangOpts.CUDAIsDevice) { 18046 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 18047 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 18048 SemaRef.targetDiag(Var->getLocation(), 18049 Var->getType().isConstQualified() 18050 ? diag::note_cuda_const_var_unpromoted 18051 : diag::note_cuda_host_var); 18052 } 18053 } else if (VarTarget == Sema::CVT_Device && 18054 (UserTarget == Sema::CFT_Host || 18055 UserTarget == Sema::CFT_HostDevice)) { 18056 // Record a CUDA/HIP device side variable if it is ODR-used 18057 // by host code. This is done conservatively, when the variable is 18058 // referenced in any of the following contexts: 18059 // - a non-function context 18060 // - a host function 18061 // - a host device function 18062 // This makes the ODR-use of the device side variable by host code to 18063 // be visible in the device compilation for the compiler to be able to 18064 // emit template variables instantiated by host code only and to 18065 // externalize the static device side variable ODR-used by host code. 18066 if (!Var->hasExternalStorage()) 18067 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 18068 else if (SemaRef.LangOpts.GPURelocatableDeviceCode) 18069 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var); 18070 } 18071 } 18072 18073 Var->markUsed(SemaRef.Context); 18074 } 18075 18076 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 18077 SourceLocation Loc, 18078 unsigned CapturingScopeIndex) { 18079 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 18080 } 18081 18082 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 18083 ValueDecl *var) { 18084 DeclContext *VarDC = var->getDeclContext(); 18085 18086 // If the parameter still belongs to the translation unit, then 18087 // we're actually just using one parameter in the declaration of 18088 // the next. 18089 if (isa<ParmVarDecl>(var) && 18090 isa<TranslationUnitDecl>(VarDC)) 18091 return; 18092 18093 // For C code, don't diagnose about capture if we're not actually in code 18094 // right now; it's impossible to write a non-constant expression outside of 18095 // function context, so we'll get other (more useful) diagnostics later. 18096 // 18097 // For C++, things get a bit more nasty... it would be nice to suppress this 18098 // diagnostic for certain cases like using a local variable in an array bound 18099 // for a member of a local class, but the correct predicate is not obvious. 18100 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 18101 return; 18102 18103 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 18104 unsigned ContextKind = 3; // unknown 18105 if (isa<CXXMethodDecl>(VarDC) && 18106 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 18107 ContextKind = 2; 18108 } else if (isa<FunctionDecl>(VarDC)) { 18109 ContextKind = 0; 18110 } else if (isa<BlockDecl>(VarDC)) { 18111 ContextKind = 1; 18112 } 18113 18114 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 18115 << var << ValueKind << ContextKind << VarDC; 18116 S.Diag(var->getLocation(), diag::note_entity_declared_at) 18117 << var; 18118 18119 // FIXME: Add additional diagnostic info about class etc. which prevents 18120 // capture. 18121 } 18122 18123 18124 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 18125 bool &SubCapturesAreNested, 18126 QualType &CaptureType, 18127 QualType &DeclRefType) { 18128 // Check whether we've already captured it. 18129 if (CSI->CaptureMap.count(Var)) { 18130 // If we found a capture, any subcaptures are nested. 18131 SubCapturesAreNested = true; 18132 18133 // Retrieve the capture type for this variable. 18134 CaptureType = CSI->getCapture(Var).getCaptureType(); 18135 18136 // Compute the type of an expression that refers to this variable. 18137 DeclRefType = CaptureType.getNonReferenceType(); 18138 18139 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 18140 // are mutable in the sense that user can change their value - they are 18141 // private instances of the captured declarations. 18142 const Capture &Cap = CSI->getCapture(Var); 18143 if (Cap.isCopyCapture() && 18144 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 18145 !(isa<CapturedRegionScopeInfo>(CSI) && 18146 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 18147 DeclRefType.addConst(); 18148 return true; 18149 } 18150 return false; 18151 } 18152 18153 // Only block literals, captured statements, and lambda expressions can 18154 // capture; other scopes don't work. 18155 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 18156 SourceLocation Loc, 18157 const bool Diagnose, Sema &S) { 18158 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 18159 return getLambdaAwareParentOfDeclContext(DC); 18160 else if (Var->hasLocalStorage()) { 18161 if (Diagnose) 18162 diagnoseUncapturableValueReference(S, Loc, Var); 18163 } 18164 return nullptr; 18165 } 18166 18167 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18168 // certain types of variables (unnamed, variably modified types etc.) 18169 // so check for eligibility. 18170 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 18171 SourceLocation Loc, 18172 const bool Diagnose, Sema &S) { 18173 18174 bool IsBlock = isa<BlockScopeInfo>(CSI); 18175 bool IsLambda = isa<LambdaScopeInfo>(CSI); 18176 18177 // Lambdas are not allowed to capture unnamed variables 18178 // (e.g. anonymous unions). 18179 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 18180 // assuming that's the intent. 18181 if (IsLambda && !Var->getDeclName()) { 18182 if (Diagnose) { 18183 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 18184 S.Diag(Var->getLocation(), diag::note_declared_at); 18185 } 18186 return false; 18187 } 18188 18189 // Prohibit variably-modified types in blocks; they're difficult to deal with. 18190 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 18191 if (Diagnose) { 18192 S.Diag(Loc, diag::err_ref_vm_type); 18193 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18194 } 18195 return false; 18196 } 18197 // Prohibit structs with flexible array members too. 18198 // We cannot capture what is in the tail end of the struct. 18199 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 18200 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 18201 if (Diagnose) { 18202 if (IsBlock) 18203 S.Diag(Loc, diag::err_ref_flexarray_type); 18204 else 18205 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 18206 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18207 } 18208 return false; 18209 } 18210 } 18211 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18212 // Lambdas and captured statements are not allowed to capture __block 18213 // variables; they don't support the expected semantics. 18214 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 18215 if (Diagnose) { 18216 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 18217 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18218 } 18219 return false; 18220 } 18221 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 18222 if (S.getLangOpts().OpenCL && IsBlock && 18223 Var->getType()->isBlockPointerType()) { 18224 if (Diagnose) 18225 S.Diag(Loc, diag::err_opencl_block_ref_block); 18226 return false; 18227 } 18228 18229 return true; 18230 } 18231 18232 // Returns true if the capture by block was successful. 18233 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 18234 SourceLocation Loc, 18235 const bool BuildAndDiagnose, 18236 QualType &CaptureType, 18237 QualType &DeclRefType, 18238 const bool Nested, 18239 Sema &S, bool Invalid) { 18240 bool ByRef = false; 18241 18242 // Blocks are not allowed to capture arrays, excepting OpenCL. 18243 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 18244 // (decayed to pointers). 18245 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 18246 if (BuildAndDiagnose) { 18247 S.Diag(Loc, diag::err_ref_array_type); 18248 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18249 Invalid = true; 18250 } else { 18251 return false; 18252 } 18253 } 18254 18255 // Forbid the block-capture of autoreleasing variables. 18256 if (!Invalid && 18257 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18258 if (BuildAndDiagnose) { 18259 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 18260 << /*block*/ 0; 18261 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18262 Invalid = true; 18263 } else { 18264 return false; 18265 } 18266 } 18267 18268 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 18269 if (const auto *PT = CaptureType->getAs<PointerType>()) { 18270 QualType PointeeTy = PT->getPointeeType(); 18271 18272 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 18273 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 18274 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 18275 if (BuildAndDiagnose) { 18276 SourceLocation VarLoc = Var->getLocation(); 18277 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 18278 S.Diag(VarLoc, diag::note_declare_parameter_strong); 18279 } 18280 } 18281 } 18282 18283 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18284 if (HasBlocksAttr || CaptureType->isReferenceType() || 18285 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 18286 // Block capture by reference does not change the capture or 18287 // declaration reference types. 18288 ByRef = true; 18289 } else { 18290 // Block capture by copy introduces 'const'. 18291 CaptureType = CaptureType.getNonReferenceType().withConst(); 18292 DeclRefType = CaptureType; 18293 } 18294 18295 // Actually capture the variable. 18296 if (BuildAndDiagnose) 18297 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 18298 CaptureType, Invalid); 18299 18300 return !Invalid; 18301 } 18302 18303 18304 /// Capture the given variable in the captured region. 18305 static bool captureInCapturedRegion( 18306 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 18307 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 18308 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 18309 bool IsTopScope, Sema &S, bool Invalid) { 18310 // By default, capture variables by reference. 18311 bool ByRef = true; 18312 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18313 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18314 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 18315 // Using an LValue reference type is consistent with Lambdas (see below). 18316 if (S.isOpenMPCapturedDecl(Var)) { 18317 bool HasConst = DeclRefType.isConstQualified(); 18318 DeclRefType = DeclRefType.getUnqualifiedType(); 18319 // Don't lose diagnostics about assignments to const. 18320 if (HasConst) 18321 DeclRefType.addConst(); 18322 } 18323 // Do not capture firstprivates in tasks. 18324 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 18325 OMPC_unknown) 18326 return true; 18327 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 18328 RSI->OpenMPCaptureLevel); 18329 } 18330 18331 if (ByRef) 18332 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18333 else 18334 CaptureType = DeclRefType; 18335 18336 // Actually capture the variable. 18337 if (BuildAndDiagnose) 18338 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 18339 Loc, SourceLocation(), CaptureType, Invalid); 18340 18341 return !Invalid; 18342 } 18343 18344 /// Capture the given variable in the lambda. 18345 static bool captureInLambda(LambdaScopeInfo *LSI, 18346 VarDecl *Var, 18347 SourceLocation Loc, 18348 const bool BuildAndDiagnose, 18349 QualType &CaptureType, 18350 QualType &DeclRefType, 18351 const bool RefersToCapturedVariable, 18352 const Sema::TryCaptureKind Kind, 18353 SourceLocation EllipsisLoc, 18354 const bool IsTopScope, 18355 Sema &S, bool Invalid) { 18356 // Determine whether we are capturing by reference or by value. 18357 bool ByRef = false; 18358 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18359 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18360 } else { 18361 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 18362 } 18363 18364 // Compute the type of the field that will capture this variable. 18365 if (ByRef) { 18366 // C++11 [expr.prim.lambda]p15: 18367 // An entity is captured by reference if it is implicitly or 18368 // explicitly captured but not captured by copy. It is 18369 // unspecified whether additional unnamed non-static data 18370 // members are declared in the closure type for entities 18371 // captured by reference. 18372 // 18373 // FIXME: It is not clear whether we want to build an lvalue reference 18374 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 18375 // to do the former, while EDG does the latter. Core issue 1249 will 18376 // clarify, but for now we follow GCC because it's a more permissive and 18377 // easily defensible position. 18378 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18379 } else { 18380 // C++11 [expr.prim.lambda]p14: 18381 // For each entity captured by copy, an unnamed non-static 18382 // data member is declared in the closure type. The 18383 // declaration order of these members is unspecified. The type 18384 // of such a data member is the type of the corresponding 18385 // captured entity if the entity is not a reference to an 18386 // object, or the referenced type otherwise. [Note: If the 18387 // captured entity is a reference to a function, the 18388 // corresponding data member is also a reference to a 18389 // function. - end note ] 18390 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 18391 if (!RefType->getPointeeType()->isFunctionType()) 18392 CaptureType = RefType->getPointeeType(); 18393 } 18394 18395 // Forbid the lambda copy-capture of autoreleasing variables. 18396 if (!Invalid && 18397 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18398 if (BuildAndDiagnose) { 18399 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 18400 S.Diag(Var->getLocation(), diag::note_previous_decl) 18401 << Var->getDeclName(); 18402 Invalid = true; 18403 } else { 18404 return false; 18405 } 18406 } 18407 18408 // Make sure that by-copy captures are of a complete and non-abstract type. 18409 if (!Invalid && BuildAndDiagnose) { 18410 if (!CaptureType->isDependentType() && 18411 S.RequireCompleteSizedType( 18412 Loc, CaptureType, 18413 diag::err_capture_of_incomplete_or_sizeless_type, 18414 Var->getDeclName())) 18415 Invalid = true; 18416 else if (S.RequireNonAbstractType(Loc, CaptureType, 18417 diag::err_capture_of_abstract_type)) 18418 Invalid = true; 18419 } 18420 } 18421 18422 // Compute the type of a reference to this captured variable. 18423 if (ByRef) 18424 DeclRefType = CaptureType.getNonReferenceType(); 18425 else { 18426 // C++ [expr.prim.lambda]p5: 18427 // The closure type for a lambda-expression has a public inline 18428 // function call operator [...]. This function call operator is 18429 // declared const (9.3.1) if and only if the lambda-expression's 18430 // parameter-declaration-clause is not followed by mutable. 18431 DeclRefType = CaptureType.getNonReferenceType(); 18432 if (!LSI->Mutable && !CaptureType->isReferenceType()) 18433 DeclRefType.addConst(); 18434 } 18435 18436 // Add the capture. 18437 if (BuildAndDiagnose) 18438 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 18439 Loc, EllipsisLoc, CaptureType, Invalid); 18440 18441 return !Invalid; 18442 } 18443 18444 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 18445 // Offer a Copy fix even if the type is dependent. 18446 if (Var->getType()->isDependentType()) 18447 return true; 18448 QualType T = Var->getType().getNonReferenceType(); 18449 if (T.isTriviallyCopyableType(Context)) 18450 return true; 18451 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 18452 18453 if (!(RD = RD->getDefinition())) 18454 return false; 18455 if (RD->hasSimpleCopyConstructor()) 18456 return true; 18457 if (RD->hasUserDeclaredCopyConstructor()) 18458 for (CXXConstructorDecl *Ctor : RD->ctors()) 18459 if (Ctor->isCopyConstructor()) 18460 return !Ctor->isDeleted(); 18461 } 18462 return false; 18463 } 18464 18465 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 18466 /// default capture. Fixes may be omitted if they aren't allowed by the 18467 /// standard, for example we can't emit a default copy capture fix-it if we 18468 /// already explicitly copy capture capture another variable. 18469 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 18470 VarDecl *Var) { 18471 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 18472 // Don't offer Capture by copy of default capture by copy fixes if Var is 18473 // known not to be copy constructible. 18474 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 18475 18476 SmallString<32> FixBuffer; 18477 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 18478 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 18479 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 18480 if (ShouldOfferCopyFix) { 18481 // Offer fixes to insert an explicit capture for the variable. 18482 // [] -> [VarName] 18483 // [OtherCapture] -> [OtherCapture, VarName] 18484 FixBuffer.assign({Separator, Var->getName()}); 18485 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18486 << Var << /*value*/ 0 18487 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18488 } 18489 // As above but capture by reference. 18490 FixBuffer.assign({Separator, "&", Var->getName()}); 18491 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18492 << Var << /*reference*/ 1 18493 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18494 } 18495 18496 // Only try to offer default capture if there are no captures excluding this 18497 // and init captures. 18498 // [this]: OK. 18499 // [X = Y]: OK. 18500 // [&A, &B]: Don't offer. 18501 // [A, B]: Don't offer. 18502 if (llvm::any_of(LSI->Captures, [](Capture &C) { 18503 return !C.isThisCapture() && !C.isInitCapture(); 18504 })) 18505 return; 18506 18507 // The default capture specifiers, '=' or '&', must appear first in the 18508 // capture body. 18509 SourceLocation DefaultInsertLoc = 18510 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 18511 18512 if (ShouldOfferCopyFix) { 18513 bool CanDefaultCopyCapture = true; 18514 // [=, *this] OK since c++17 18515 // [=, this] OK since c++20 18516 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 18517 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 18518 ? LSI->getCXXThisCapture().isCopyCapture() 18519 : false; 18520 // We can't use default capture by copy if any captures already specified 18521 // capture by copy. 18522 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 18523 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 18524 })) { 18525 FixBuffer.assign({"=", Separator}); 18526 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 18527 << /*value*/ 0 18528 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 18529 } 18530 } 18531 18532 // We can't use default capture by reference if any captures already specified 18533 // capture by reference. 18534 if (llvm::none_of(LSI->Captures, [](Capture &C) { 18535 return !C.isInitCapture() && C.isReferenceCapture() && 18536 !C.isThisCapture(); 18537 })) { 18538 FixBuffer.assign({"&", Separator}); 18539 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 18540 << /*reference*/ 1 18541 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 18542 } 18543 } 18544 18545 static bool CheckCaptureUseBeforeLambdaQualifiers(Sema &S, VarDecl *Var, 18546 SourceLocation ExprLoc, 18547 LambdaScopeInfo *LSI) { 18548 if (Var->isInvalidDecl()) 18549 return false; 18550 18551 bool ByCopy = LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval; 18552 SourceLocation Loc = LSI->IntroducerRange.getBegin(); 18553 bool Explicitly = false; 18554 for (auto &&C : LSI->DelayedCaptures) { 18555 VarDecl *CV = C.second.Var; 18556 if (Var != CV) 18557 continue; 18558 ByCopy = C.second.Kind == LambdaCaptureKind::LCK_ByCopy; 18559 Loc = C.second.Loc; 18560 Explicitly = true; 18561 break; 18562 } 18563 if (ByCopy && LSI->BeforeLambdaQualifiersScope) { 18564 // This can only occur in a non-ODR context, so we need to diagnose eagerly, 18565 // even when BuildAndDiagnose is false 18566 S.Diag(ExprLoc, diag::err_lambda_used_before_capture) << Var; 18567 S.Diag(Loc, diag::note_var_explicitly_captured_here) << Var << Explicitly; 18568 if (!Var->isInitCapture()) 18569 S.Diag(Var->getBeginLoc(), diag::note_entity_declared_at) << Var; 18570 Var->setInvalidDecl(); 18571 return false; 18572 } 18573 return true; 18574 } 18575 18576 bool Sema::tryCaptureVariable( 18577 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 18578 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 18579 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 18580 // An init-capture is notionally from the context surrounding its 18581 // declaration, but its parent DC is the lambda class. 18582 DeclContext *VarDC = Var->getDeclContext(); 18583 if (Var->isInitCapture()) 18584 VarDC = VarDC->getParent(); 18585 18586 DeclContext *DC = CurContext; 18587 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 18588 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 18589 // We need to sync up the Declaration Context with the 18590 // FunctionScopeIndexToStopAt 18591 if (FunctionScopeIndexToStopAt) { 18592 unsigned FSIndex = FunctionScopes.size() - 1; 18593 while (FSIndex != MaxFunctionScopesIndex) { 18594 DC = getLambdaAwareParentOfDeclContext(DC); 18595 --FSIndex; 18596 } 18597 } 18598 18599 // Capture global variables if it is required to use private copy of this 18600 // variable. 18601 bool IsGlobal = !Var->hasLocalStorage(); 18602 if (IsGlobal && 18603 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 18604 MaxFunctionScopesIndex))) 18605 return true; 18606 Var = Var->getCanonicalDecl(); 18607 18608 // Walk up the stack to determine whether we can capture the variable, 18609 // performing the "simple" checks that don't depend on type. We stop when 18610 // we've either hit the declared scope of the variable or find an existing 18611 // capture of that variable. We start from the innermost capturing-entity 18612 // (the DC) and ensure that all intervening capturing-entities 18613 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 18614 // declcontext can either capture the variable or have already captured 18615 // the variable. 18616 CaptureType = Var->getType(); 18617 DeclRefType = CaptureType.getNonReferenceType(); 18618 bool Nested = false; 18619 bool Explicit = (Kind != TryCapture_Implicit); 18620 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 18621 bool IsInLambdaBeforeQualifiers; 18622 do { 18623 IsInLambdaBeforeQualifiers = false; 18624 18625 LambdaScopeInfo *LSI = nullptr; 18626 if (!FunctionScopes.empty()) 18627 LSI = dyn_cast_or_null<LambdaScopeInfo>( 18628 FunctionScopes[FunctionScopesIndex]); 18629 if (LSI && LSI->BeforeLambdaQualifiersScope) { 18630 if (isa<ParmVarDecl>(Var)) 18631 return true; 18632 IsInLambdaBeforeQualifiers = true; 18633 if (!CheckCaptureUseBeforeLambdaQualifiers(*this, Var, ExprLoc, LSI)) { 18634 break; 18635 } 18636 } 18637 18638 // If the variable is declared in the current context, there is no need to 18639 // capture it. 18640 if (!IsInLambdaBeforeQualifiers && 18641 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC) 18642 return true; 18643 18644 // Only block literals, captured statements, and lambda expressions can 18645 // capture; other scopes don't work. 18646 DeclContext *ParentDC = 18647 IsInLambdaBeforeQualifiers 18648 ? DC->getParent() 18649 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc, 18650 BuildAndDiagnose, *this); 18651 // We need to check for the parent *first* because, if we *have* 18652 // private-captured a global variable, we need to recursively capture it in 18653 // intermediate blocks, lambdas, etc. 18654 if (!ParentDC) { 18655 if (IsGlobal) { 18656 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 18657 break; 18658 } 18659 return true; 18660 } 18661 18662 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 18663 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 18664 18665 // Check whether we've already captured it. 18666 if (!IsInLambdaBeforeQualifiers && 18667 isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 18668 DeclRefType)) { 18669 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 18670 break; 18671 } 18672 // If we are instantiating a generic lambda call operator body, 18673 // we do not want to capture new variables. What was captured 18674 // during either a lambdas transformation or initial parsing 18675 // should be used. 18676 if (!IsInLambdaBeforeQualifiers && 18677 isGenericLambdaCallOperatorSpecialization(DC)) { 18678 if (BuildAndDiagnose) { 18679 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18680 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 18681 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18682 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18683 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18684 buildLambdaCaptureFixit(*this, LSI, Var); 18685 } else 18686 diagnoseUncapturableValueReference(*this, ExprLoc, Var); 18687 } 18688 return true; 18689 } 18690 18691 // Try to capture variable-length arrays types. 18692 if (!IsInLambdaBeforeQualifiers && 18693 Var->getType()->isVariablyModifiedType()) { 18694 // We're going to walk down into the type and look for VLA 18695 // expressions. 18696 QualType QTy = Var->getType(); 18697 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18698 QTy = PVD->getOriginalType(); 18699 captureVariablyModifiedType(Context, QTy, CSI); 18700 } 18701 18702 if (!IsInLambdaBeforeQualifiers && getLangOpts().OpenMP) { 18703 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18704 // OpenMP private variables should not be captured in outer scope, so 18705 // just break here. Similarly, global variables that are captured in a 18706 // target region should not be captured outside the scope of the region. 18707 if (RSI->CapRegionKind == CR_OpenMP) { 18708 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 18709 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 18710 // If the variable is private (i.e. not captured) and has variably 18711 // modified type, we still need to capture the type for correct 18712 // codegen in all regions, associated with the construct. Currently, 18713 // it is captured in the innermost captured region only. 18714 if (IsOpenMPPrivateDecl != OMPC_unknown && 18715 Var->getType()->isVariablyModifiedType()) { 18716 QualType QTy = Var->getType(); 18717 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18718 QTy = PVD->getOriginalType(); 18719 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 18720 I < E; ++I) { 18721 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 18722 FunctionScopes[FunctionScopesIndex - I]); 18723 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 18724 "Wrong number of captured regions associated with the " 18725 "OpenMP construct."); 18726 captureVariablyModifiedType(Context, QTy, OuterRSI); 18727 } 18728 } 18729 bool IsTargetCap = 18730 IsOpenMPPrivateDecl != OMPC_private && 18731 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 18732 RSI->OpenMPCaptureLevel); 18733 // Do not capture global if it is not privatized in outer regions. 18734 bool IsGlobalCap = 18735 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 18736 RSI->OpenMPCaptureLevel); 18737 18738 // When we detect target captures we are looking from inside the 18739 // target region, therefore we need to propagate the capture from the 18740 // enclosing region. Therefore, the capture is not initially nested. 18741 if (IsTargetCap) 18742 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18743 18744 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18745 (IsGlobal && !IsGlobalCap)) { 18746 Nested = !IsTargetCap; 18747 bool HasConst = DeclRefType.isConstQualified(); 18748 DeclRefType = DeclRefType.getUnqualifiedType(); 18749 // Don't lose diagnostics about assignments to const. 18750 if (HasConst) 18751 DeclRefType.addConst(); 18752 CaptureType = Context.getLValueReferenceType(DeclRefType); 18753 break; 18754 } 18755 } 18756 } 18757 } 18758 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18759 // No capture-default, and this is not an explicit capture 18760 // so cannot capture this variable. 18761 if (BuildAndDiagnose) { 18762 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18763 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18764 auto *LSI = cast<LambdaScopeInfo>(CSI); 18765 if (LSI->Lambda) { 18766 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18767 buildLambdaCaptureFixit(*this, LSI, Var); 18768 } 18769 // FIXME: If we error out because an outer lambda can not implicitly 18770 // capture a variable that an inner lambda explicitly captures, we 18771 // should have the inner lambda do the explicit capture - because 18772 // it makes for cleaner diagnostics later. This would purely be done 18773 // so that the diagnostic does not misleadingly claim that a variable 18774 // can not be captured by a lambda implicitly even though it is captured 18775 // explicitly. Suggestion: 18776 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18777 // at the function head 18778 // - cache the StartingDeclContext - this must be a lambda 18779 // - captureInLambda in the innermost lambda the variable. 18780 } 18781 return true; 18782 } 18783 Explicit = false; 18784 FunctionScopesIndex--; 18785 if (!IsInLambdaBeforeQualifiers) 18786 DC = ParentDC; 18787 } while (IsInLambdaBeforeQualifiers || !VarDC->Equals(DC)); 18788 18789 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18790 // computing the type of the capture at each step, checking type-specific 18791 // requirements, and adding captures if requested. 18792 // If the variable had already been captured previously, we start capturing 18793 // at the lambda nested within that one. 18794 bool Invalid = false; 18795 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18796 ++I) { 18797 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18798 18799 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18800 // certain types of variables (unnamed, variably modified types etc.) 18801 // so check for eligibility. 18802 if (!Invalid) 18803 Invalid = 18804 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18805 18806 // After encountering an error, if we're actually supposed to capture, keep 18807 // capturing in nested contexts to suppress any follow-on diagnostics. 18808 if (Invalid && !BuildAndDiagnose) 18809 return true; 18810 18811 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18812 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18813 DeclRefType, Nested, *this, Invalid); 18814 Nested = true; 18815 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18816 Invalid = !captureInCapturedRegion( 18817 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18818 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18819 Nested = true; 18820 } else { 18821 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18822 if (!CheckCaptureUseBeforeLambdaQualifiers(*this, Var, ExprLoc, LSI)) { 18823 return true; 18824 } 18825 Invalid = 18826 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18827 DeclRefType, Nested, Kind, EllipsisLoc, 18828 /*IsTopScope*/ I == N - 1, *this, Invalid); 18829 Nested = true; 18830 } 18831 18832 if (Invalid && !BuildAndDiagnose) 18833 return true; 18834 } 18835 return Invalid; 18836 } 18837 18838 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18839 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18840 QualType CaptureType; 18841 QualType DeclRefType; 18842 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18843 /*BuildAndDiagnose=*/true, CaptureType, 18844 DeclRefType, nullptr); 18845 } 18846 18847 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18848 QualType CaptureType; 18849 QualType DeclRefType; 18850 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18851 /*BuildAndDiagnose=*/false, CaptureType, 18852 DeclRefType, nullptr); 18853 } 18854 18855 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18856 QualType CaptureType; 18857 QualType DeclRefType; 18858 18859 // Determine whether we can capture this variable. 18860 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18861 /*BuildAndDiagnose=*/false, CaptureType, 18862 DeclRefType, nullptr)) 18863 return QualType(); 18864 18865 return DeclRefType; 18866 } 18867 18868 namespace { 18869 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18870 // The produced TemplateArgumentListInfo* points to data stored within this 18871 // object, so should only be used in contexts where the pointer will not be 18872 // used after the CopiedTemplateArgs object is destroyed. 18873 class CopiedTemplateArgs { 18874 bool HasArgs; 18875 TemplateArgumentListInfo TemplateArgStorage; 18876 public: 18877 template<typename RefExpr> 18878 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18879 if (HasArgs) 18880 E->copyTemplateArgumentsInto(TemplateArgStorage); 18881 } 18882 operator TemplateArgumentListInfo*() 18883 #ifdef __has_cpp_attribute 18884 #if __has_cpp_attribute(clang::lifetimebound) 18885 [[clang::lifetimebound]] 18886 #endif 18887 #endif 18888 { 18889 return HasArgs ? &TemplateArgStorage : nullptr; 18890 } 18891 }; 18892 } 18893 18894 /// Walk the set of potential results of an expression and mark them all as 18895 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18896 /// 18897 /// \return A new expression if we found any potential results, ExprEmpty() if 18898 /// not, and ExprError() if we diagnosed an error. 18899 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18900 NonOdrUseReason NOUR) { 18901 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18902 // an object that satisfies the requirements for appearing in a 18903 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18904 // is immediately applied." This function handles the lvalue-to-rvalue 18905 // conversion part. 18906 // 18907 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18908 // transform it into the relevant kind of non-odr-use node and rebuild the 18909 // tree of nodes leading to it. 18910 // 18911 // This is a mini-TreeTransform that only transforms a restricted subset of 18912 // nodes (and only certain operands of them). 18913 18914 // Rebuild a subexpression. 18915 auto Rebuild = [&](Expr *Sub) { 18916 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18917 }; 18918 18919 // Check whether a potential result satisfies the requirements of NOUR. 18920 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18921 // Any entity other than a VarDecl is always odr-used whenever it's named 18922 // in a potentially-evaluated expression. 18923 auto *VD = dyn_cast<VarDecl>(D); 18924 if (!VD) 18925 return true; 18926 18927 // C++2a [basic.def.odr]p4: 18928 // A variable x whose name appears as a potentially-evalauted expression 18929 // e is odr-used by e unless 18930 // -- x is a reference that is usable in constant expressions, or 18931 // -- x is a variable of non-reference type that is usable in constant 18932 // expressions and has no mutable subobjects, and e is an element of 18933 // the set of potential results of an expression of 18934 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18935 // conversion is applied, or 18936 // -- x is a variable of non-reference type, and e is an element of the 18937 // set of potential results of a discarded-value expression to which 18938 // the lvalue-to-rvalue conversion is not applied 18939 // 18940 // We check the first bullet and the "potentially-evaluated" condition in 18941 // BuildDeclRefExpr. We check the type requirements in the second bullet 18942 // in CheckLValueToRValueConversionOperand below. 18943 switch (NOUR) { 18944 case NOUR_None: 18945 case NOUR_Unevaluated: 18946 llvm_unreachable("unexpected non-odr-use-reason"); 18947 18948 case NOUR_Constant: 18949 // Constant references were handled when they were built. 18950 if (VD->getType()->isReferenceType()) 18951 return true; 18952 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18953 if (RD->hasMutableFields()) 18954 return true; 18955 if (!VD->isUsableInConstantExpressions(S.Context)) 18956 return true; 18957 break; 18958 18959 case NOUR_Discarded: 18960 if (VD->getType()->isReferenceType()) 18961 return true; 18962 break; 18963 } 18964 return false; 18965 }; 18966 18967 // Mark that this expression does not constitute an odr-use. 18968 auto MarkNotOdrUsed = [&] { 18969 S.MaybeODRUseExprs.remove(E); 18970 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18971 LSI->markVariableExprAsNonODRUsed(E); 18972 }; 18973 18974 // C++2a [basic.def.odr]p2: 18975 // The set of potential results of an expression e is defined as follows: 18976 switch (E->getStmtClass()) { 18977 // -- If e is an id-expression, ... 18978 case Expr::DeclRefExprClass: { 18979 auto *DRE = cast<DeclRefExpr>(E); 18980 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18981 break; 18982 18983 // Rebuild as a non-odr-use DeclRefExpr. 18984 MarkNotOdrUsed(); 18985 return DeclRefExpr::Create( 18986 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18987 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18988 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18989 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18990 } 18991 18992 case Expr::FunctionParmPackExprClass: { 18993 auto *FPPE = cast<FunctionParmPackExpr>(E); 18994 // If any of the declarations in the pack is odr-used, then the expression 18995 // as a whole constitutes an odr-use. 18996 for (VarDecl *D : *FPPE) 18997 if (IsPotentialResultOdrUsed(D)) 18998 return ExprEmpty(); 18999 19000 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 19001 // nothing cares about whether we marked this as an odr-use, but it might 19002 // be useful for non-compiler tools. 19003 MarkNotOdrUsed(); 19004 break; 19005 } 19006 19007 // -- If e is a subscripting operation with an array operand... 19008 case Expr::ArraySubscriptExprClass: { 19009 auto *ASE = cast<ArraySubscriptExpr>(E); 19010 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 19011 if (!OldBase->getType()->isArrayType()) 19012 break; 19013 ExprResult Base = Rebuild(OldBase); 19014 if (!Base.isUsable()) 19015 return Base; 19016 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 19017 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 19018 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 19019 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 19020 ASE->getRBracketLoc()); 19021 } 19022 19023 case Expr::MemberExprClass: { 19024 auto *ME = cast<MemberExpr>(E); 19025 // -- If e is a class member access expression [...] naming a non-static 19026 // data member... 19027 if (isa<FieldDecl>(ME->getMemberDecl())) { 19028 ExprResult Base = Rebuild(ME->getBase()); 19029 if (!Base.isUsable()) 19030 return Base; 19031 return MemberExpr::Create( 19032 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 19033 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 19034 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 19035 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 19036 ME->getObjectKind(), ME->isNonOdrUse()); 19037 } 19038 19039 if (ME->getMemberDecl()->isCXXInstanceMember()) 19040 break; 19041 19042 // -- If e is a class member access expression naming a static data member, 19043 // ... 19044 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 19045 break; 19046 19047 // Rebuild as a non-odr-use MemberExpr. 19048 MarkNotOdrUsed(); 19049 return MemberExpr::Create( 19050 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 19051 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 19052 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 19053 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 19054 } 19055 19056 case Expr::BinaryOperatorClass: { 19057 auto *BO = cast<BinaryOperator>(E); 19058 Expr *LHS = BO->getLHS(); 19059 Expr *RHS = BO->getRHS(); 19060 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 19061 if (BO->getOpcode() == BO_PtrMemD) { 19062 ExprResult Sub = Rebuild(LHS); 19063 if (!Sub.isUsable()) 19064 return Sub; 19065 LHS = Sub.get(); 19066 // -- If e is a comma expression, ... 19067 } else if (BO->getOpcode() == BO_Comma) { 19068 ExprResult Sub = Rebuild(RHS); 19069 if (!Sub.isUsable()) 19070 return Sub; 19071 RHS = Sub.get(); 19072 } else { 19073 break; 19074 } 19075 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 19076 LHS, RHS); 19077 } 19078 19079 // -- If e has the form (e1)... 19080 case Expr::ParenExprClass: { 19081 auto *PE = cast<ParenExpr>(E); 19082 ExprResult Sub = Rebuild(PE->getSubExpr()); 19083 if (!Sub.isUsable()) 19084 return Sub; 19085 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 19086 } 19087 19088 // -- If e is a glvalue conditional expression, ... 19089 // We don't apply this to a binary conditional operator. FIXME: Should we? 19090 case Expr::ConditionalOperatorClass: { 19091 auto *CO = cast<ConditionalOperator>(E); 19092 ExprResult LHS = Rebuild(CO->getLHS()); 19093 if (LHS.isInvalid()) 19094 return ExprError(); 19095 ExprResult RHS = Rebuild(CO->getRHS()); 19096 if (RHS.isInvalid()) 19097 return ExprError(); 19098 if (!LHS.isUsable() && !RHS.isUsable()) 19099 return ExprEmpty(); 19100 if (!LHS.isUsable()) 19101 LHS = CO->getLHS(); 19102 if (!RHS.isUsable()) 19103 RHS = CO->getRHS(); 19104 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 19105 CO->getCond(), LHS.get(), RHS.get()); 19106 } 19107 19108 // [Clang extension] 19109 // -- If e has the form __extension__ e1... 19110 case Expr::UnaryOperatorClass: { 19111 auto *UO = cast<UnaryOperator>(E); 19112 if (UO->getOpcode() != UO_Extension) 19113 break; 19114 ExprResult Sub = Rebuild(UO->getSubExpr()); 19115 if (!Sub.isUsable()) 19116 return Sub; 19117 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 19118 Sub.get()); 19119 } 19120 19121 // [Clang extension] 19122 // -- If e has the form _Generic(...), the set of potential results is the 19123 // union of the sets of potential results of the associated expressions. 19124 case Expr::GenericSelectionExprClass: { 19125 auto *GSE = cast<GenericSelectionExpr>(E); 19126 19127 SmallVector<Expr *, 4> AssocExprs; 19128 bool AnyChanged = false; 19129 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 19130 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 19131 if (AssocExpr.isInvalid()) 19132 return ExprError(); 19133 if (AssocExpr.isUsable()) { 19134 AssocExprs.push_back(AssocExpr.get()); 19135 AnyChanged = true; 19136 } else { 19137 AssocExprs.push_back(OrigAssocExpr); 19138 } 19139 } 19140 19141 return AnyChanged ? S.CreateGenericSelectionExpr( 19142 GSE->getGenericLoc(), GSE->getDefaultLoc(), 19143 GSE->getRParenLoc(), GSE->getControllingExpr(), 19144 GSE->getAssocTypeSourceInfos(), AssocExprs) 19145 : ExprEmpty(); 19146 } 19147 19148 // [Clang extension] 19149 // -- If e has the form __builtin_choose_expr(...), the set of potential 19150 // results is the union of the sets of potential results of the 19151 // second and third subexpressions. 19152 case Expr::ChooseExprClass: { 19153 auto *CE = cast<ChooseExpr>(E); 19154 19155 ExprResult LHS = Rebuild(CE->getLHS()); 19156 if (LHS.isInvalid()) 19157 return ExprError(); 19158 19159 ExprResult RHS = Rebuild(CE->getLHS()); 19160 if (RHS.isInvalid()) 19161 return ExprError(); 19162 19163 if (!LHS.get() && !RHS.get()) 19164 return ExprEmpty(); 19165 if (!LHS.isUsable()) 19166 LHS = CE->getLHS(); 19167 if (!RHS.isUsable()) 19168 RHS = CE->getRHS(); 19169 19170 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 19171 RHS.get(), CE->getRParenLoc()); 19172 } 19173 19174 // Step through non-syntactic nodes. 19175 case Expr::ConstantExprClass: { 19176 auto *CE = cast<ConstantExpr>(E); 19177 ExprResult Sub = Rebuild(CE->getSubExpr()); 19178 if (!Sub.isUsable()) 19179 return Sub; 19180 return ConstantExpr::Create(S.Context, Sub.get()); 19181 } 19182 19183 // We could mostly rely on the recursive rebuilding to rebuild implicit 19184 // casts, but not at the top level, so rebuild them here. 19185 case Expr::ImplicitCastExprClass: { 19186 auto *ICE = cast<ImplicitCastExpr>(E); 19187 // Only step through the narrow set of cast kinds we expect to encounter. 19188 // Anything else suggests we've left the region in which potential results 19189 // can be found. 19190 switch (ICE->getCastKind()) { 19191 case CK_NoOp: 19192 case CK_DerivedToBase: 19193 case CK_UncheckedDerivedToBase: { 19194 ExprResult Sub = Rebuild(ICE->getSubExpr()); 19195 if (!Sub.isUsable()) 19196 return Sub; 19197 CXXCastPath Path(ICE->path()); 19198 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 19199 ICE->getValueKind(), &Path); 19200 } 19201 19202 default: 19203 break; 19204 } 19205 break; 19206 } 19207 19208 default: 19209 break; 19210 } 19211 19212 // Can't traverse through this node. Nothing to do. 19213 return ExprEmpty(); 19214 } 19215 19216 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 19217 // Check whether the operand is or contains an object of non-trivial C union 19218 // type. 19219 if (E->getType().isVolatileQualified() && 19220 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 19221 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 19222 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 19223 Sema::NTCUC_LValueToRValueVolatile, 19224 NTCUK_Destruct|NTCUK_Copy); 19225 19226 // C++2a [basic.def.odr]p4: 19227 // [...] an expression of non-volatile-qualified non-class type to which 19228 // the lvalue-to-rvalue conversion is applied [...] 19229 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 19230 return E; 19231 19232 ExprResult Result = 19233 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 19234 if (Result.isInvalid()) 19235 return ExprError(); 19236 return Result.get() ? Result : E; 19237 } 19238 19239 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 19240 Res = CorrectDelayedTyposInExpr(Res); 19241 19242 if (!Res.isUsable()) 19243 return Res; 19244 19245 // If a constant-expression is a reference to a variable where we delay 19246 // deciding whether it is an odr-use, just assume we will apply the 19247 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 19248 // (a non-type template argument), we have special handling anyway. 19249 return CheckLValueToRValueConversionOperand(Res.get()); 19250 } 19251 19252 void Sema::CleanupVarDeclMarking() { 19253 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 19254 // call. 19255 MaybeODRUseExprSet LocalMaybeODRUseExprs; 19256 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 19257 19258 for (Expr *E : LocalMaybeODRUseExprs) { 19259 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 19260 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 19261 DRE->getLocation(), *this); 19262 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 19263 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 19264 *this); 19265 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 19266 for (VarDecl *VD : *FP) 19267 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 19268 } else { 19269 llvm_unreachable("Unexpected expression"); 19270 } 19271 } 19272 19273 assert(MaybeODRUseExprs.empty() && 19274 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 19275 } 19276 19277 static void DoMarkVarDeclReferenced( 19278 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 19279 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19280 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 19281 isa<FunctionParmPackExpr>(E)) && 19282 "Invalid Expr argument to DoMarkVarDeclReferenced"); 19283 Var->setReferenced(); 19284 19285 if (Var->isInvalidDecl()) 19286 return; 19287 19288 auto *MSI = Var->getMemberSpecializationInfo(); 19289 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 19290 : Var->getTemplateSpecializationKind(); 19291 19292 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 19293 bool UsableInConstantExpr = 19294 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 19295 19296 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 19297 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 19298 } 19299 19300 // C++20 [expr.const]p12: 19301 // A variable [...] is needed for constant evaluation if it is [...] a 19302 // variable whose name appears as a potentially constant evaluated 19303 // expression that is either a contexpr variable or is of non-volatile 19304 // const-qualified integral type or of reference type 19305 bool NeededForConstantEvaluation = 19306 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 19307 19308 bool NeedDefinition = 19309 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 19310 19311 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 19312 "Can't instantiate a partial template specialization."); 19313 19314 // If this might be a member specialization of a static data member, check 19315 // the specialization is visible. We already did the checks for variable 19316 // template specializations when we created them. 19317 if (NeedDefinition && TSK != TSK_Undeclared && 19318 !isa<VarTemplateSpecializationDecl>(Var)) 19319 SemaRef.checkSpecializationVisibility(Loc, Var); 19320 19321 // Perform implicit instantiation of static data members, static data member 19322 // templates of class templates, and variable template specializations. Delay 19323 // instantiations of variable templates, except for those that could be used 19324 // in a constant expression. 19325 if (NeedDefinition && isTemplateInstantiation(TSK)) { 19326 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 19327 // instantiation declaration if a variable is usable in a constant 19328 // expression (among other cases). 19329 bool TryInstantiating = 19330 TSK == TSK_ImplicitInstantiation || 19331 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 19332 19333 if (TryInstantiating) { 19334 SourceLocation PointOfInstantiation = 19335 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 19336 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 19337 if (FirstInstantiation) { 19338 PointOfInstantiation = Loc; 19339 if (MSI) 19340 MSI->setPointOfInstantiation(PointOfInstantiation); 19341 // FIXME: Notify listener. 19342 else 19343 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 19344 } 19345 19346 if (UsableInConstantExpr) { 19347 // Do not defer instantiations of variables that could be used in a 19348 // constant expression. 19349 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 19350 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 19351 }); 19352 19353 // Re-set the member to trigger a recomputation of the dependence bits 19354 // for the expression. 19355 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19356 DRE->setDecl(DRE->getDecl()); 19357 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 19358 ME->setMemberDecl(ME->getMemberDecl()); 19359 } else if (FirstInstantiation || 19360 isa<VarTemplateSpecializationDecl>(Var)) { 19361 // FIXME: For a specialization of a variable template, we don't 19362 // distinguish between "declaration and type implicitly instantiated" 19363 // and "implicit instantiation of definition requested", so we have 19364 // no direct way to avoid enqueueing the pending instantiation 19365 // multiple times. 19366 SemaRef.PendingInstantiations 19367 .push_back(std::make_pair(Var, PointOfInstantiation)); 19368 } 19369 } 19370 } 19371 19372 // C++2a [basic.def.odr]p4: 19373 // A variable x whose name appears as a potentially-evaluated expression e 19374 // is odr-used by e unless 19375 // -- x is a reference that is usable in constant expressions 19376 // -- x is a variable of non-reference type that is usable in constant 19377 // expressions and has no mutable subobjects [FIXME], and e is an 19378 // element of the set of potential results of an expression of 19379 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 19380 // conversion is applied 19381 // -- x is a variable of non-reference type, and e is an element of the set 19382 // of potential results of a discarded-value expression to which the 19383 // lvalue-to-rvalue conversion is not applied [FIXME] 19384 // 19385 // We check the first part of the second bullet here, and 19386 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 19387 // FIXME: To get the third bullet right, we need to delay this even for 19388 // variables that are not usable in constant expressions. 19389 19390 // If we already know this isn't an odr-use, there's nothing more to do. 19391 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19392 if (DRE->isNonOdrUse()) 19393 return; 19394 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 19395 if (ME->isNonOdrUse()) 19396 return; 19397 19398 switch (OdrUse) { 19399 case OdrUseContext::None: 19400 assert((!E || isa<FunctionParmPackExpr>(E)) && 19401 "missing non-odr-use marking for unevaluated decl ref"); 19402 break; 19403 19404 case OdrUseContext::FormallyOdrUsed: 19405 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 19406 // behavior. 19407 break; 19408 19409 case OdrUseContext::Used: 19410 // If we might later find that this expression isn't actually an odr-use, 19411 // delay the marking. 19412 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 19413 SemaRef.MaybeODRUseExprs.insert(E); 19414 else 19415 MarkVarDeclODRUsed(Var, Loc, SemaRef); 19416 break; 19417 19418 case OdrUseContext::Dependent: 19419 // If this is a dependent context, we don't need to mark variables as 19420 // odr-used, but we may still need to track them for lambda capture. 19421 // FIXME: Do we also need to do this inside dependent typeid expressions 19422 // (which are modeled as unevaluated at this point)? 19423 const bool RefersToEnclosingScope = 19424 (SemaRef.CurContext != Var->getDeclContext() && 19425 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 19426 if (RefersToEnclosingScope) { 19427 LambdaScopeInfo *const LSI = 19428 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 19429 if (LSI && (!LSI->CallOperator || 19430 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 19431 // If a variable could potentially be odr-used, defer marking it so 19432 // until we finish analyzing the full expression for any 19433 // lvalue-to-rvalue 19434 // or discarded value conversions that would obviate odr-use. 19435 // Add it to the list of potential captures that will be analyzed 19436 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 19437 // unless the variable is a reference that was initialized by a constant 19438 // expression (this will never need to be captured or odr-used). 19439 // 19440 // FIXME: We can simplify this a lot after implementing P0588R1. 19441 assert(E && "Capture variable should be used in an expression."); 19442 if (!Var->getType()->isReferenceType() || 19443 !Var->isUsableInConstantExpressions(SemaRef.Context)) 19444 LSI->addPotentialCapture(E->IgnoreParens()); 19445 } 19446 } 19447 break; 19448 } 19449 } 19450 19451 /// Mark a variable referenced, and check whether it is odr-used 19452 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 19453 /// used directly for normal expressions referring to VarDecl. 19454 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 19455 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 19456 } 19457 19458 static void 19459 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 19460 bool MightBeOdrUse, 19461 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19462 if (SemaRef.isInOpenMPDeclareTargetContext()) 19463 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 19464 19465 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 19466 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 19467 return; 19468 } 19469 19470 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 19471 19472 // If this is a call to a method via a cast, also mark the method in the 19473 // derived class used in case codegen can devirtualize the call. 19474 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 19475 if (!ME) 19476 return; 19477 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 19478 if (!MD) 19479 return; 19480 // Only attempt to devirtualize if this is truly a virtual call. 19481 bool IsVirtualCall = MD->isVirtual() && 19482 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 19483 if (!IsVirtualCall) 19484 return; 19485 19486 // If it's possible to devirtualize the call, mark the called function 19487 // referenced. 19488 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 19489 ME->getBase(), SemaRef.getLangOpts().AppleKext); 19490 if (DM) 19491 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 19492 } 19493 19494 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 19495 /// 19496 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 19497 /// handled with care if the DeclRefExpr is not newly-created. 19498 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 19499 // TODO: update this with DR# once a defect report is filed. 19500 // C++11 defect. The address of a pure member should not be an ODR use, even 19501 // if it's a qualified reference. 19502 bool OdrUse = true; 19503 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 19504 if (Method->isVirtual() && 19505 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 19506 OdrUse = false; 19507 19508 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 19509 if (!isUnevaluatedContext() && !isConstantEvaluated() && 19510 FD->isConsteval() && !RebuildingImmediateInvocation) 19511 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 19512 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 19513 RefsMinusAssignments); 19514 } 19515 19516 /// Perform reference-marking and odr-use handling for a MemberExpr. 19517 void Sema::MarkMemberReferenced(MemberExpr *E) { 19518 // C++11 [basic.def.odr]p2: 19519 // A non-overloaded function whose name appears as a potentially-evaluated 19520 // expression or a member of a set of candidate functions, if selected by 19521 // overload resolution when referred to from a potentially-evaluated 19522 // expression, is odr-used, unless it is a pure virtual function and its 19523 // name is not explicitly qualified. 19524 bool MightBeOdrUse = true; 19525 if (E->performsVirtualDispatch(getLangOpts())) { 19526 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 19527 if (Method->isPure()) 19528 MightBeOdrUse = false; 19529 } 19530 SourceLocation Loc = 19531 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 19532 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 19533 RefsMinusAssignments); 19534 } 19535 19536 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 19537 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 19538 for (VarDecl *VD : *E) 19539 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 19540 RefsMinusAssignments); 19541 } 19542 19543 /// Perform marking for a reference to an arbitrary declaration. It 19544 /// marks the declaration referenced, and performs odr-use checking for 19545 /// functions and variables. This method should not be used when building a 19546 /// normal expression which refers to a variable. 19547 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 19548 bool MightBeOdrUse) { 19549 if (MightBeOdrUse) { 19550 if (auto *VD = dyn_cast<VarDecl>(D)) { 19551 MarkVariableReferenced(Loc, VD); 19552 return; 19553 } 19554 } 19555 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 19556 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 19557 return; 19558 } 19559 D->setReferenced(); 19560 } 19561 19562 namespace { 19563 // Mark all of the declarations used by a type as referenced. 19564 // FIXME: Not fully implemented yet! We need to have a better understanding 19565 // of when we're entering a context we should not recurse into. 19566 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 19567 // TreeTransforms rebuilding the type in a new context. Rather than 19568 // duplicating the TreeTransform logic, we should consider reusing it here. 19569 // Currently that causes problems when rebuilding LambdaExprs. 19570 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 19571 Sema &S; 19572 SourceLocation Loc; 19573 19574 public: 19575 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 19576 19577 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 19578 19579 bool TraverseTemplateArgument(const TemplateArgument &Arg); 19580 }; 19581 } 19582 19583 bool MarkReferencedDecls::TraverseTemplateArgument( 19584 const TemplateArgument &Arg) { 19585 { 19586 // A non-type template argument is a constant-evaluated context. 19587 EnterExpressionEvaluationContext Evaluated( 19588 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 19589 if (Arg.getKind() == TemplateArgument::Declaration) { 19590 if (Decl *D = Arg.getAsDecl()) 19591 S.MarkAnyDeclReferenced(Loc, D, true); 19592 } else if (Arg.getKind() == TemplateArgument::Expression) { 19593 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 19594 } 19595 } 19596 19597 return Inherited::TraverseTemplateArgument(Arg); 19598 } 19599 19600 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 19601 MarkReferencedDecls Marker(*this, Loc); 19602 Marker.TraverseType(T); 19603 } 19604 19605 namespace { 19606 /// Helper class that marks all of the declarations referenced by 19607 /// potentially-evaluated subexpressions as "referenced". 19608 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 19609 public: 19610 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 19611 bool SkipLocalVariables; 19612 ArrayRef<const Expr *> StopAt; 19613 19614 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 19615 ArrayRef<const Expr *> StopAt) 19616 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 19617 19618 void visitUsedDecl(SourceLocation Loc, Decl *D) { 19619 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 19620 } 19621 19622 void Visit(Expr *E) { 19623 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end()) 19624 return; 19625 Inherited::Visit(E); 19626 } 19627 19628 void VisitDeclRefExpr(DeclRefExpr *E) { 19629 // If we were asked not to visit local variables, don't. 19630 if (SkipLocalVariables) { 19631 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 19632 if (VD->hasLocalStorage()) 19633 return; 19634 } 19635 19636 // FIXME: This can trigger the instantiation of the initializer of a 19637 // variable, which can cause the expression to become value-dependent 19638 // or error-dependent. Do we need to propagate the new dependence bits? 19639 S.MarkDeclRefReferenced(E); 19640 } 19641 19642 void VisitMemberExpr(MemberExpr *E) { 19643 S.MarkMemberReferenced(E); 19644 Visit(E->getBase()); 19645 } 19646 }; 19647 } // namespace 19648 19649 /// Mark any declarations that appear within this expression or any 19650 /// potentially-evaluated subexpressions as "referenced". 19651 /// 19652 /// \param SkipLocalVariables If true, don't mark local variables as 19653 /// 'referenced'. 19654 /// \param StopAt Subexpressions that we shouldn't recurse into. 19655 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 19656 bool SkipLocalVariables, 19657 ArrayRef<const Expr*> StopAt) { 19658 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 19659 } 19660 19661 /// Emit a diagnostic when statements are reachable. 19662 /// FIXME: check for reachability even in expressions for which we don't build a 19663 /// CFG (eg, in the initializer of a global or in a constant expression). 19664 /// For example, 19665 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 19666 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 19667 const PartialDiagnostic &PD) { 19668 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 19669 if (!FunctionScopes.empty()) 19670 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 19671 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 19672 return true; 19673 } 19674 19675 // The initializer of a constexpr variable or of the first declaration of a 19676 // static data member is not syntactically a constant evaluated constant, 19677 // but nonetheless is always required to be a constant expression, so we 19678 // can skip diagnosing. 19679 // FIXME: Using the mangling context here is a hack. 19680 if (auto *VD = dyn_cast_or_null<VarDecl>( 19681 ExprEvalContexts.back().ManglingContextDecl)) { 19682 if (VD->isConstexpr() || 19683 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 19684 return false; 19685 // FIXME: For any other kind of variable, we should build a CFG for its 19686 // initializer and check whether the context in question is reachable. 19687 } 19688 19689 Diag(Loc, PD); 19690 return true; 19691 } 19692 19693 /// Emit a diagnostic that describes an effect on the run-time behavior 19694 /// of the program being compiled. 19695 /// 19696 /// This routine emits the given diagnostic when the code currently being 19697 /// type-checked is "potentially evaluated", meaning that there is a 19698 /// possibility that the code will actually be executable. Code in sizeof() 19699 /// expressions, code used only during overload resolution, etc., are not 19700 /// potentially evaluated. This routine will suppress such diagnostics or, 19701 /// in the absolutely nutty case of potentially potentially evaluated 19702 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 19703 /// later. 19704 /// 19705 /// This routine should be used for all diagnostics that describe the run-time 19706 /// behavior of a program, such as passing a non-POD value through an ellipsis. 19707 /// Failure to do so will likely result in spurious diagnostics or failures 19708 /// during overload resolution or within sizeof/alignof/typeof/typeid. 19709 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 19710 const PartialDiagnostic &PD) { 19711 19712 if (ExprEvalContexts.back().isDiscardedStatementContext()) 19713 return false; 19714 19715 switch (ExprEvalContexts.back().Context) { 19716 case ExpressionEvaluationContext::Unevaluated: 19717 case ExpressionEvaluationContext::UnevaluatedList: 19718 case ExpressionEvaluationContext::UnevaluatedAbstract: 19719 case ExpressionEvaluationContext::DiscardedStatement: 19720 // The argument will never be evaluated, so don't complain. 19721 break; 19722 19723 case ExpressionEvaluationContext::ConstantEvaluated: 19724 case ExpressionEvaluationContext::ImmediateFunctionContext: 19725 // Relevant diagnostics should be produced by constant evaluation. 19726 break; 19727 19728 case ExpressionEvaluationContext::PotentiallyEvaluated: 19729 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 19730 return DiagIfReachable(Loc, Stmts, PD); 19731 } 19732 19733 return false; 19734 } 19735 19736 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 19737 const PartialDiagnostic &PD) { 19738 return DiagRuntimeBehavior( 19739 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 19740 } 19741 19742 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 19743 CallExpr *CE, FunctionDecl *FD) { 19744 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 19745 return false; 19746 19747 // If we're inside a decltype's expression, don't check for a valid return 19748 // type or construct temporaries until we know whether this is the last call. 19749 if (ExprEvalContexts.back().ExprContext == 19750 ExpressionEvaluationContextRecord::EK_Decltype) { 19751 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 19752 return false; 19753 } 19754 19755 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19756 FunctionDecl *FD; 19757 CallExpr *CE; 19758 19759 public: 19760 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19761 : FD(FD), CE(CE) { } 19762 19763 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19764 if (!FD) { 19765 S.Diag(Loc, diag::err_call_incomplete_return) 19766 << T << CE->getSourceRange(); 19767 return; 19768 } 19769 19770 S.Diag(Loc, diag::err_call_function_incomplete_return) 19771 << CE->getSourceRange() << FD << T; 19772 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19773 << FD->getDeclName(); 19774 } 19775 } Diagnoser(FD, CE); 19776 19777 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19778 return true; 19779 19780 return false; 19781 } 19782 19783 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19784 // will prevent this condition from triggering, which is what we want. 19785 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19786 SourceLocation Loc; 19787 19788 unsigned diagnostic = diag::warn_condition_is_assignment; 19789 bool IsOrAssign = false; 19790 19791 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19792 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19793 return; 19794 19795 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19796 19797 // Greylist some idioms by putting them into a warning subcategory. 19798 if (ObjCMessageExpr *ME 19799 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19800 Selector Sel = ME->getSelector(); 19801 19802 // self = [<foo> init...] 19803 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19804 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19805 19806 // <foo> = [<bar> nextObject] 19807 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19808 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19809 } 19810 19811 Loc = Op->getOperatorLoc(); 19812 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19813 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19814 return; 19815 19816 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19817 Loc = Op->getOperatorLoc(); 19818 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19819 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19820 else { 19821 // Not an assignment. 19822 return; 19823 } 19824 19825 Diag(Loc, diagnostic) << E->getSourceRange(); 19826 19827 SourceLocation Open = E->getBeginLoc(); 19828 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19829 Diag(Loc, diag::note_condition_assign_silence) 19830 << FixItHint::CreateInsertion(Open, "(") 19831 << FixItHint::CreateInsertion(Close, ")"); 19832 19833 if (IsOrAssign) 19834 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19835 << FixItHint::CreateReplacement(Loc, "!="); 19836 else 19837 Diag(Loc, diag::note_condition_assign_to_comparison) 19838 << FixItHint::CreateReplacement(Loc, "=="); 19839 } 19840 19841 /// Redundant parentheses over an equality comparison can indicate 19842 /// that the user intended an assignment used as condition. 19843 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19844 // Don't warn if the parens came from a macro. 19845 SourceLocation parenLoc = ParenE->getBeginLoc(); 19846 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19847 return; 19848 // Don't warn for dependent expressions. 19849 if (ParenE->isTypeDependent()) 19850 return; 19851 19852 Expr *E = ParenE->IgnoreParens(); 19853 19854 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19855 if (opE->getOpcode() == BO_EQ && 19856 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19857 == Expr::MLV_Valid) { 19858 SourceLocation Loc = opE->getOperatorLoc(); 19859 19860 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19861 SourceRange ParenERange = ParenE->getSourceRange(); 19862 Diag(Loc, diag::note_equality_comparison_silence) 19863 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19864 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19865 Diag(Loc, diag::note_equality_comparison_to_assign) 19866 << FixItHint::CreateReplacement(Loc, "="); 19867 } 19868 } 19869 19870 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19871 bool IsConstexpr) { 19872 DiagnoseAssignmentAsCondition(E); 19873 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19874 DiagnoseEqualityWithExtraParens(parenE); 19875 19876 ExprResult result = CheckPlaceholderExpr(E); 19877 if (result.isInvalid()) return ExprError(); 19878 E = result.get(); 19879 19880 if (!E->isTypeDependent()) { 19881 if (getLangOpts().CPlusPlus) 19882 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19883 19884 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19885 if (ERes.isInvalid()) 19886 return ExprError(); 19887 E = ERes.get(); 19888 19889 QualType T = E->getType(); 19890 if (!T->isScalarType()) { // C99 6.8.4.1p1 19891 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19892 << T << E->getSourceRange(); 19893 return ExprError(); 19894 } 19895 CheckBoolLikeConversion(E, Loc); 19896 } 19897 19898 return E; 19899 } 19900 19901 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19902 Expr *SubExpr, ConditionKind CK, 19903 bool MissingOK) { 19904 // MissingOK indicates whether having no condition expression is valid 19905 // (for loop) or invalid (e.g. while loop). 19906 if (!SubExpr) 19907 return MissingOK ? ConditionResult() : ConditionError(); 19908 19909 ExprResult Cond; 19910 switch (CK) { 19911 case ConditionKind::Boolean: 19912 Cond = CheckBooleanCondition(Loc, SubExpr); 19913 break; 19914 19915 case ConditionKind::ConstexprIf: 19916 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19917 break; 19918 19919 case ConditionKind::Switch: 19920 Cond = CheckSwitchCondition(Loc, SubExpr); 19921 break; 19922 } 19923 if (Cond.isInvalid()) { 19924 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19925 {SubExpr}, PreferredConditionType(CK)); 19926 if (!Cond.get()) 19927 return ConditionError(); 19928 } 19929 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19930 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19931 if (!FullExpr.get()) 19932 return ConditionError(); 19933 19934 return ConditionResult(*this, nullptr, FullExpr, 19935 CK == ConditionKind::ConstexprIf); 19936 } 19937 19938 namespace { 19939 /// A visitor for rebuilding a call to an __unknown_any expression 19940 /// to have an appropriate type. 19941 struct RebuildUnknownAnyFunction 19942 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19943 19944 Sema &S; 19945 19946 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19947 19948 ExprResult VisitStmt(Stmt *S) { 19949 llvm_unreachable("unexpected statement!"); 19950 } 19951 19952 ExprResult VisitExpr(Expr *E) { 19953 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19954 << E->getSourceRange(); 19955 return ExprError(); 19956 } 19957 19958 /// Rebuild an expression which simply semantically wraps another 19959 /// expression which it shares the type and value kind of. 19960 template <class T> ExprResult rebuildSugarExpr(T *E) { 19961 ExprResult SubResult = Visit(E->getSubExpr()); 19962 if (SubResult.isInvalid()) return ExprError(); 19963 19964 Expr *SubExpr = SubResult.get(); 19965 E->setSubExpr(SubExpr); 19966 E->setType(SubExpr->getType()); 19967 E->setValueKind(SubExpr->getValueKind()); 19968 assert(E->getObjectKind() == OK_Ordinary); 19969 return E; 19970 } 19971 19972 ExprResult VisitParenExpr(ParenExpr *E) { 19973 return rebuildSugarExpr(E); 19974 } 19975 19976 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19977 return rebuildSugarExpr(E); 19978 } 19979 19980 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19981 ExprResult SubResult = Visit(E->getSubExpr()); 19982 if (SubResult.isInvalid()) return ExprError(); 19983 19984 Expr *SubExpr = SubResult.get(); 19985 E->setSubExpr(SubExpr); 19986 E->setType(S.Context.getPointerType(SubExpr->getType())); 19987 assert(E->isPRValue()); 19988 assert(E->getObjectKind() == OK_Ordinary); 19989 return E; 19990 } 19991 19992 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19993 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19994 19995 E->setType(VD->getType()); 19996 19997 assert(E->isPRValue()); 19998 if (S.getLangOpts().CPlusPlus && 19999 !(isa<CXXMethodDecl>(VD) && 20000 cast<CXXMethodDecl>(VD)->isInstance())) 20001 E->setValueKind(VK_LValue); 20002 20003 return E; 20004 } 20005 20006 ExprResult VisitMemberExpr(MemberExpr *E) { 20007 return resolveDecl(E, E->getMemberDecl()); 20008 } 20009 20010 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 20011 return resolveDecl(E, E->getDecl()); 20012 } 20013 }; 20014 } 20015 20016 /// Given a function expression of unknown-any type, try to rebuild it 20017 /// to have a function type. 20018 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 20019 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 20020 if (Result.isInvalid()) return ExprError(); 20021 return S.DefaultFunctionArrayConversion(Result.get()); 20022 } 20023 20024 namespace { 20025 /// A visitor for rebuilding an expression of type __unknown_anytype 20026 /// into one which resolves the type directly on the referring 20027 /// expression. Strict preservation of the original source 20028 /// structure is not a goal. 20029 struct RebuildUnknownAnyExpr 20030 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 20031 20032 Sema &S; 20033 20034 /// The current destination type. 20035 QualType DestType; 20036 20037 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 20038 : S(S), DestType(CastType) {} 20039 20040 ExprResult VisitStmt(Stmt *S) { 20041 llvm_unreachable("unexpected statement!"); 20042 } 20043 20044 ExprResult VisitExpr(Expr *E) { 20045 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 20046 << E->getSourceRange(); 20047 return ExprError(); 20048 } 20049 20050 ExprResult VisitCallExpr(CallExpr *E); 20051 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 20052 20053 /// Rebuild an expression which simply semantically wraps another 20054 /// expression which it shares the type and value kind of. 20055 template <class T> ExprResult rebuildSugarExpr(T *E) { 20056 ExprResult SubResult = Visit(E->getSubExpr()); 20057 if (SubResult.isInvalid()) return ExprError(); 20058 Expr *SubExpr = SubResult.get(); 20059 E->setSubExpr(SubExpr); 20060 E->setType(SubExpr->getType()); 20061 E->setValueKind(SubExpr->getValueKind()); 20062 assert(E->getObjectKind() == OK_Ordinary); 20063 return E; 20064 } 20065 20066 ExprResult VisitParenExpr(ParenExpr *E) { 20067 return rebuildSugarExpr(E); 20068 } 20069 20070 ExprResult VisitUnaryExtension(UnaryOperator *E) { 20071 return rebuildSugarExpr(E); 20072 } 20073 20074 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 20075 const PointerType *Ptr = DestType->getAs<PointerType>(); 20076 if (!Ptr) { 20077 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 20078 << E->getSourceRange(); 20079 return ExprError(); 20080 } 20081 20082 if (isa<CallExpr>(E->getSubExpr())) { 20083 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 20084 << E->getSourceRange(); 20085 return ExprError(); 20086 } 20087 20088 assert(E->isPRValue()); 20089 assert(E->getObjectKind() == OK_Ordinary); 20090 E->setType(DestType); 20091 20092 // Build the sub-expression as if it were an object of the pointee type. 20093 DestType = Ptr->getPointeeType(); 20094 ExprResult SubResult = Visit(E->getSubExpr()); 20095 if (SubResult.isInvalid()) return ExprError(); 20096 E->setSubExpr(SubResult.get()); 20097 return E; 20098 } 20099 20100 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 20101 20102 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 20103 20104 ExprResult VisitMemberExpr(MemberExpr *E) { 20105 return resolveDecl(E, E->getMemberDecl()); 20106 } 20107 20108 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 20109 return resolveDecl(E, E->getDecl()); 20110 } 20111 }; 20112 } 20113 20114 /// Rebuilds a call expression which yielded __unknown_anytype. 20115 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 20116 Expr *CalleeExpr = E->getCallee(); 20117 20118 enum FnKind { 20119 FK_MemberFunction, 20120 FK_FunctionPointer, 20121 FK_BlockPointer 20122 }; 20123 20124 FnKind Kind; 20125 QualType CalleeType = CalleeExpr->getType(); 20126 if (CalleeType == S.Context.BoundMemberTy) { 20127 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 20128 Kind = FK_MemberFunction; 20129 CalleeType = Expr::findBoundMemberType(CalleeExpr); 20130 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 20131 CalleeType = Ptr->getPointeeType(); 20132 Kind = FK_FunctionPointer; 20133 } else { 20134 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 20135 Kind = FK_BlockPointer; 20136 } 20137 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 20138 20139 // Verify that this is a legal result type of a function. 20140 if (DestType->isArrayType() || DestType->isFunctionType()) { 20141 unsigned diagID = diag::err_func_returning_array_function; 20142 if (Kind == FK_BlockPointer) 20143 diagID = diag::err_block_returning_array_function; 20144 20145 S.Diag(E->getExprLoc(), diagID) 20146 << DestType->isFunctionType() << DestType; 20147 return ExprError(); 20148 } 20149 20150 // Otherwise, go ahead and set DestType as the call's result. 20151 E->setType(DestType.getNonLValueExprType(S.Context)); 20152 E->setValueKind(Expr::getValueKindForType(DestType)); 20153 assert(E->getObjectKind() == OK_Ordinary); 20154 20155 // Rebuild the function type, replacing the result type with DestType. 20156 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 20157 if (Proto) { 20158 // __unknown_anytype(...) is a special case used by the debugger when 20159 // it has no idea what a function's signature is. 20160 // 20161 // We want to build this call essentially under the K&R 20162 // unprototyped rules, but making a FunctionNoProtoType in C++ 20163 // would foul up all sorts of assumptions. However, we cannot 20164 // simply pass all arguments as variadic arguments, nor can we 20165 // portably just call the function under a non-variadic type; see 20166 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 20167 // However, it turns out that in practice it is generally safe to 20168 // call a function declared as "A foo(B,C,D);" under the prototype 20169 // "A foo(B,C,D,...);". The only known exception is with the 20170 // Windows ABI, where any variadic function is implicitly cdecl 20171 // regardless of its normal CC. Therefore we change the parameter 20172 // types to match the types of the arguments. 20173 // 20174 // This is a hack, but it is far superior to moving the 20175 // corresponding target-specific code from IR-gen to Sema/AST. 20176 20177 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 20178 SmallVector<QualType, 8> ArgTypes; 20179 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 20180 ArgTypes.reserve(E->getNumArgs()); 20181 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 20182 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 20183 } 20184 ParamTypes = ArgTypes; 20185 } 20186 DestType = S.Context.getFunctionType(DestType, ParamTypes, 20187 Proto->getExtProtoInfo()); 20188 } else { 20189 DestType = S.Context.getFunctionNoProtoType(DestType, 20190 FnType->getExtInfo()); 20191 } 20192 20193 // Rebuild the appropriate pointer-to-function type. 20194 switch (Kind) { 20195 case FK_MemberFunction: 20196 // Nothing to do. 20197 break; 20198 20199 case FK_FunctionPointer: 20200 DestType = S.Context.getPointerType(DestType); 20201 break; 20202 20203 case FK_BlockPointer: 20204 DestType = S.Context.getBlockPointerType(DestType); 20205 break; 20206 } 20207 20208 // Finally, we can recurse. 20209 ExprResult CalleeResult = Visit(CalleeExpr); 20210 if (!CalleeResult.isUsable()) return ExprError(); 20211 E->setCallee(CalleeResult.get()); 20212 20213 // Bind a temporary if necessary. 20214 return S.MaybeBindToTemporary(E); 20215 } 20216 20217 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 20218 // Verify that this is a legal result type of a call. 20219 if (DestType->isArrayType() || DestType->isFunctionType()) { 20220 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 20221 << DestType->isFunctionType() << DestType; 20222 return ExprError(); 20223 } 20224 20225 // Rewrite the method result type if available. 20226 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 20227 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 20228 Method->setReturnType(DestType); 20229 } 20230 20231 // Change the type of the message. 20232 E->setType(DestType.getNonReferenceType()); 20233 E->setValueKind(Expr::getValueKindForType(DestType)); 20234 20235 return S.MaybeBindToTemporary(E); 20236 } 20237 20238 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 20239 // The only case we should ever see here is a function-to-pointer decay. 20240 if (E->getCastKind() == CK_FunctionToPointerDecay) { 20241 assert(E->isPRValue()); 20242 assert(E->getObjectKind() == OK_Ordinary); 20243 20244 E->setType(DestType); 20245 20246 // Rebuild the sub-expression as the pointee (function) type. 20247 DestType = DestType->castAs<PointerType>()->getPointeeType(); 20248 20249 ExprResult Result = Visit(E->getSubExpr()); 20250 if (!Result.isUsable()) return ExprError(); 20251 20252 E->setSubExpr(Result.get()); 20253 return E; 20254 } else if (E->getCastKind() == CK_LValueToRValue) { 20255 assert(E->isPRValue()); 20256 assert(E->getObjectKind() == OK_Ordinary); 20257 20258 assert(isa<BlockPointerType>(E->getType())); 20259 20260 E->setType(DestType); 20261 20262 // The sub-expression has to be a lvalue reference, so rebuild it as such. 20263 DestType = S.Context.getLValueReferenceType(DestType); 20264 20265 ExprResult Result = Visit(E->getSubExpr()); 20266 if (!Result.isUsable()) return ExprError(); 20267 20268 E->setSubExpr(Result.get()); 20269 return E; 20270 } else { 20271 llvm_unreachable("Unhandled cast type!"); 20272 } 20273 } 20274 20275 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 20276 ExprValueKind ValueKind = VK_LValue; 20277 QualType Type = DestType; 20278 20279 // We know how to make this work for certain kinds of decls: 20280 20281 // - functions 20282 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 20283 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 20284 DestType = Ptr->getPointeeType(); 20285 ExprResult Result = resolveDecl(E, VD); 20286 if (Result.isInvalid()) return ExprError(); 20287 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 20288 VK_PRValue); 20289 } 20290 20291 if (!Type->isFunctionType()) { 20292 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 20293 << VD << E->getSourceRange(); 20294 return ExprError(); 20295 } 20296 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 20297 // We must match the FunctionDecl's type to the hack introduced in 20298 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 20299 // type. See the lengthy commentary in that routine. 20300 QualType FDT = FD->getType(); 20301 const FunctionType *FnType = FDT->castAs<FunctionType>(); 20302 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 20303 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 20304 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 20305 SourceLocation Loc = FD->getLocation(); 20306 FunctionDecl *NewFD = FunctionDecl::Create( 20307 S.Context, FD->getDeclContext(), Loc, Loc, 20308 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 20309 SC_None, S.getCurFPFeatures().isFPConstrained(), 20310 false /*isInlineSpecified*/, FD->hasPrototype(), 20311 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 20312 20313 if (FD->getQualifier()) 20314 NewFD->setQualifierInfo(FD->getQualifierLoc()); 20315 20316 SmallVector<ParmVarDecl*, 16> Params; 20317 for (const auto &AI : FT->param_types()) { 20318 ParmVarDecl *Param = 20319 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 20320 Param->setScopeInfo(0, Params.size()); 20321 Params.push_back(Param); 20322 } 20323 NewFD->setParams(Params); 20324 DRE->setDecl(NewFD); 20325 VD = DRE->getDecl(); 20326 } 20327 } 20328 20329 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 20330 if (MD->isInstance()) { 20331 ValueKind = VK_PRValue; 20332 Type = S.Context.BoundMemberTy; 20333 } 20334 20335 // Function references aren't l-values in C. 20336 if (!S.getLangOpts().CPlusPlus) 20337 ValueKind = VK_PRValue; 20338 20339 // - variables 20340 } else if (isa<VarDecl>(VD)) { 20341 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 20342 Type = RefTy->getPointeeType(); 20343 } else if (Type->isFunctionType()) { 20344 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 20345 << VD << E->getSourceRange(); 20346 return ExprError(); 20347 } 20348 20349 // - nothing else 20350 } else { 20351 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 20352 << VD << E->getSourceRange(); 20353 return ExprError(); 20354 } 20355 20356 // Modifying the declaration like this is friendly to IR-gen but 20357 // also really dangerous. 20358 VD->setType(DestType); 20359 E->setType(Type); 20360 E->setValueKind(ValueKind); 20361 return E; 20362 } 20363 20364 /// Check a cast of an unknown-any type. We intentionally only 20365 /// trigger this for C-style casts. 20366 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 20367 Expr *CastExpr, CastKind &CastKind, 20368 ExprValueKind &VK, CXXCastPath &Path) { 20369 // The type we're casting to must be either void or complete. 20370 if (!CastType->isVoidType() && 20371 RequireCompleteType(TypeRange.getBegin(), CastType, 20372 diag::err_typecheck_cast_to_incomplete)) 20373 return ExprError(); 20374 20375 // Rewrite the casted expression from scratch. 20376 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 20377 if (!result.isUsable()) return ExprError(); 20378 20379 CastExpr = result.get(); 20380 VK = CastExpr->getValueKind(); 20381 CastKind = CK_NoOp; 20382 20383 return CastExpr; 20384 } 20385 20386 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 20387 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 20388 } 20389 20390 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 20391 Expr *arg, QualType ¶mType) { 20392 // If the syntactic form of the argument is not an explicit cast of 20393 // any sort, just do default argument promotion. 20394 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 20395 if (!castArg) { 20396 ExprResult result = DefaultArgumentPromotion(arg); 20397 if (result.isInvalid()) return ExprError(); 20398 paramType = result.get()->getType(); 20399 return result; 20400 } 20401 20402 // Otherwise, use the type that was written in the explicit cast. 20403 assert(!arg->hasPlaceholderType()); 20404 paramType = castArg->getTypeAsWritten(); 20405 20406 // Copy-initialize a parameter of that type. 20407 InitializedEntity entity = 20408 InitializedEntity::InitializeParameter(Context, paramType, 20409 /*consumed*/ false); 20410 return PerformCopyInitialization(entity, callLoc, arg); 20411 } 20412 20413 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 20414 Expr *orig = E; 20415 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 20416 while (true) { 20417 E = E->IgnoreParenImpCasts(); 20418 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 20419 E = call->getCallee(); 20420 diagID = diag::err_uncasted_call_of_unknown_any; 20421 } else { 20422 break; 20423 } 20424 } 20425 20426 SourceLocation loc; 20427 NamedDecl *d; 20428 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 20429 loc = ref->getLocation(); 20430 d = ref->getDecl(); 20431 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 20432 loc = mem->getMemberLoc(); 20433 d = mem->getMemberDecl(); 20434 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 20435 diagID = diag::err_uncasted_call_of_unknown_any; 20436 loc = msg->getSelectorStartLoc(); 20437 d = msg->getMethodDecl(); 20438 if (!d) { 20439 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 20440 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 20441 << orig->getSourceRange(); 20442 return ExprError(); 20443 } 20444 } else { 20445 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 20446 << E->getSourceRange(); 20447 return ExprError(); 20448 } 20449 20450 S.Diag(loc, diagID) << d << orig->getSourceRange(); 20451 20452 // Never recoverable. 20453 return ExprError(); 20454 } 20455 20456 /// Check for operands with placeholder types and complain if found. 20457 /// Returns ExprError() if there was an error and no recovery was possible. 20458 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 20459 if (!Context.isDependenceAllowed()) { 20460 // C cannot handle TypoExpr nodes on either side of a binop because it 20461 // doesn't handle dependent types properly, so make sure any TypoExprs have 20462 // been dealt with before checking the operands. 20463 ExprResult Result = CorrectDelayedTyposInExpr(E); 20464 if (!Result.isUsable()) return ExprError(); 20465 E = Result.get(); 20466 } 20467 20468 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 20469 if (!placeholderType) return E; 20470 20471 switch (placeholderType->getKind()) { 20472 20473 // Overloaded expressions. 20474 case BuiltinType::Overload: { 20475 // Try to resolve a single function template specialization. 20476 // This is obligatory. 20477 ExprResult Result = E; 20478 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 20479 return Result; 20480 20481 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 20482 // leaves Result unchanged on failure. 20483 Result = E; 20484 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 20485 return Result; 20486 20487 // If that failed, try to recover with a call. 20488 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 20489 /*complain*/ true); 20490 return Result; 20491 } 20492 20493 // Bound member functions. 20494 case BuiltinType::BoundMember: { 20495 ExprResult result = E; 20496 const Expr *BME = E->IgnoreParens(); 20497 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 20498 // Try to give a nicer diagnostic if it is a bound member that we recognize. 20499 if (isa<CXXPseudoDestructorExpr>(BME)) { 20500 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 20501 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 20502 if (ME->getMemberNameInfo().getName().getNameKind() == 20503 DeclarationName::CXXDestructorName) 20504 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 20505 } 20506 tryToRecoverWithCall(result, PD, 20507 /*complain*/ true); 20508 return result; 20509 } 20510 20511 // ARC unbridged casts. 20512 case BuiltinType::ARCUnbridgedCast: { 20513 Expr *realCast = stripARCUnbridgedCast(E); 20514 diagnoseARCUnbridgedCast(realCast); 20515 return realCast; 20516 } 20517 20518 // Expressions of unknown type. 20519 case BuiltinType::UnknownAny: 20520 return diagnoseUnknownAnyExpr(*this, E); 20521 20522 // Pseudo-objects. 20523 case BuiltinType::PseudoObject: 20524 return checkPseudoObjectRValue(E); 20525 20526 case BuiltinType::BuiltinFn: { 20527 // Accept __noop without parens by implicitly converting it to a call expr. 20528 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 20529 if (DRE) { 20530 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 20531 unsigned BuiltinID = FD->getBuiltinID(); 20532 if (BuiltinID == Builtin::BI__noop) { 20533 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 20534 CK_BuiltinFnToFnPtr) 20535 .get(); 20536 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 20537 VK_PRValue, SourceLocation(), 20538 FPOptionsOverride()); 20539 } 20540 20541 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) { 20542 // Any use of these other than a direct call is ill-formed as of C++20, 20543 // because they are not addressable functions. In earlier language 20544 // modes, warn and force an instantiation of the real body. 20545 Diag(E->getBeginLoc(), 20546 getLangOpts().CPlusPlus20 20547 ? diag::err_use_of_unaddressable_function 20548 : diag::warn_cxx20_compat_use_of_unaddressable_function); 20549 if (FD->isImplicitlyInstantiable()) { 20550 // Require a definition here because a normal attempt at 20551 // instantiation for a builtin will be ignored, and we won't try 20552 // again later. We assume that the definition of the template 20553 // precedes this use. 20554 InstantiateFunctionDefinition(E->getBeginLoc(), FD, 20555 /*Recursive=*/false, 20556 /*DefinitionRequired=*/true, 20557 /*AtEndOfTU=*/false); 20558 } 20559 // Produce a properly-typed reference to the function. 20560 CXXScopeSpec SS; 20561 SS.Adopt(DRE->getQualifierLoc()); 20562 TemplateArgumentListInfo TemplateArgs; 20563 DRE->copyTemplateArgumentsInto(TemplateArgs); 20564 return BuildDeclRefExpr( 20565 FD, FD->getType(), VK_LValue, DRE->getNameInfo(), 20566 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(), 20567 DRE->getTemplateKeywordLoc(), 20568 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr); 20569 } 20570 } 20571 20572 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 20573 return ExprError(); 20574 } 20575 20576 case BuiltinType::IncompleteMatrixIdx: 20577 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 20578 ->getRowIdx() 20579 ->getBeginLoc(), 20580 diag::err_matrix_incomplete_index); 20581 return ExprError(); 20582 20583 // Expressions of unknown type. 20584 case BuiltinType::OMPArraySection: 20585 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 20586 return ExprError(); 20587 20588 // Expressions of unknown type. 20589 case BuiltinType::OMPArrayShaping: 20590 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 20591 20592 case BuiltinType::OMPIterator: 20593 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 20594 20595 // Everything else should be impossible. 20596 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 20597 case BuiltinType::Id: 20598 #include "clang/Basic/OpenCLImageTypes.def" 20599 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 20600 case BuiltinType::Id: 20601 #include "clang/Basic/OpenCLExtensionTypes.def" 20602 #define SVE_TYPE(Name, Id, SingletonId) \ 20603 case BuiltinType::Id: 20604 #include "clang/Basic/AArch64SVEACLETypes.def" 20605 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 20606 case BuiltinType::Id: 20607 #include "clang/Basic/PPCTypes.def" 20608 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 20609 #include "clang/Basic/RISCVVTypes.def" 20610 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 20611 #define PLACEHOLDER_TYPE(Id, SingletonId) 20612 #include "clang/AST/BuiltinTypes.def" 20613 break; 20614 } 20615 20616 llvm_unreachable("invalid placeholder type!"); 20617 } 20618 20619 bool Sema::CheckCaseExpression(Expr *E) { 20620 if (E->isTypeDependent()) 20621 return true; 20622 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 20623 return E->getType()->isIntegralOrEnumerationType(); 20624 return false; 20625 } 20626 20627 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 20628 ExprResult 20629 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 20630 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 20631 "Unknown Objective-C Boolean value!"); 20632 QualType BoolT = Context.ObjCBuiltinBoolTy; 20633 if (!Context.getBOOLDecl()) { 20634 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 20635 Sema::LookupOrdinaryName); 20636 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 20637 NamedDecl *ND = Result.getFoundDecl(); 20638 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 20639 Context.setBOOLDecl(TD); 20640 } 20641 } 20642 if (Context.getBOOLDecl()) 20643 BoolT = Context.getBOOLType(); 20644 return new (Context) 20645 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 20646 } 20647 20648 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 20649 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 20650 SourceLocation RParen) { 20651 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 20652 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20653 return Spec.getPlatform() == Platform; 20654 }); 20655 // Transcribe the "ios" availability check to "maccatalyst" when compiling 20656 // for "maccatalyst" if "maccatalyst" is not specified. 20657 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 20658 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20659 return Spec.getPlatform() == "ios"; 20660 }); 20661 } 20662 if (Spec == AvailSpecs.end()) 20663 return None; 20664 return Spec->getVersion(); 20665 }; 20666 20667 VersionTuple Version; 20668 if (auto MaybeVersion = 20669 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 20670 Version = *MaybeVersion; 20671 20672 // The use of `@available` in the enclosing context should be analyzed to 20673 // warn when it's used inappropriately (i.e. not if(@available)). 20674 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 20675 Context->HasPotentialAvailabilityViolations = true; 20676 20677 return new (Context) 20678 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 20679 } 20680 20681 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 20682 ArrayRef<Expr *> SubExprs, QualType T) { 20683 if (!Context.getLangOpts().RecoveryAST) 20684 return ExprError(); 20685 20686 if (isSFINAEContext()) 20687 return ExprError(); 20688 20689 if (T.isNull() || T->isUndeducedType() || 20690 !Context.getLangOpts().RecoveryASTType) 20691 // We don't know the concrete type, fallback to dependent type. 20692 T = Context.DependentTy; 20693 20694 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 20695 } 20696