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++ and C2x). 2558 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus && 2559 !getLangOpts().C2x) { 2560 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2561 if (D) R.addDecl(D); 2562 } 2563 2564 // Determine whether this name might be a candidate for 2565 // argument-dependent lookup. 2566 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2567 2568 if (R.empty() && !ADL) { 2569 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2570 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2571 TemplateKWLoc, TemplateArgs)) 2572 return E; 2573 } 2574 2575 // Don't diagnose an empty lookup for inline assembly. 2576 if (IsInlineAsmIdentifier) 2577 return ExprError(); 2578 2579 // If this name wasn't predeclared and if this is not a function 2580 // call, diagnose the problem. 2581 TypoExpr *TE = nullptr; 2582 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2583 : nullptr); 2584 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2585 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2586 "Typo correction callback misconfigured"); 2587 if (CCC) { 2588 // Make sure the callback knows what the typo being diagnosed is. 2589 CCC->setTypoName(II); 2590 if (SS.isValid()) 2591 CCC->setTypoNNS(SS.getScopeRep()); 2592 } 2593 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2594 // a template name, but we happen to have always already looked up the name 2595 // before we get here if it must be a template name. 2596 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2597 None, &TE)) { 2598 if (TE && KeywordReplacement) { 2599 auto &State = getTypoExprState(TE); 2600 auto BestTC = State.Consumer->getNextCorrection(); 2601 if (BestTC.isKeyword()) { 2602 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2603 if (State.DiagHandler) 2604 State.DiagHandler(BestTC); 2605 KeywordReplacement->startToken(); 2606 KeywordReplacement->setKind(II->getTokenID()); 2607 KeywordReplacement->setIdentifierInfo(II); 2608 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2609 // Clean up the state associated with the TypoExpr, since it has 2610 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2611 clearDelayedTypo(TE); 2612 // Signal that a correction to a keyword was performed by returning a 2613 // valid-but-null ExprResult. 2614 return (Expr*)nullptr; 2615 } 2616 State.Consumer->resetCorrectionStream(); 2617 } 2618 return TE ? TE : ExprError(); 2619 } 2620 2621 assert(!R.empty() && 2622 "DiagnoseEmptyLookup returned false but added no results"); 2623 2624 // If we found an Objective-C instance variable, let 2625 // LookupInObjCMethod build the appropriate expression to 2626 // reference the ivar. 2627 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2628 R.clear(); 2629 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2630 // In a hopelessly buggy code, Objective-C instance variable 2631 // lookup fails and no expression will be built to reference it. 2632 if (!E.isInvalid() && !E.get()) 2633 return ExprError(); 2634 return E; 2635 } 2636 } 2637 2638 // This is guaranteed from this point on. 2639 assert(!R.empty() || ADL); 2640 2641 // Check whether this might be a C++ implicit instance member access. 2642 // C++ [class.mfct.non-static]p3: 2643 // When an id-expression that is not part of a class member access 2644 // syntax and not used to form a pointer to member is used in the 2645 // body of a non-static member function of class X, if name lookup 2646 // resolves the name in the id-expression to a non-static non-type 2647 // member of some class C, the id-expression is transformed into a 2648 // class member access expression using (*this) as the 2649 // postfix-expression to the left of the . operator. 2650 // 2651 // But we don't actually need to do this for '&' operands if R 2652 // resolved to a function or overloaded function set, because the 2653 // expression is ill-formed if it actually works out to be a 2654 // non-static member function: 2655 // 2656 // C++ [expr.ref]p4: 2657 // Otherwise, if E1.E2 refers to a non-static member function. . . 2658 // [t]he expression can be used only as the left-hand operand of a 2659 // member function call. 2660 // 2661 // There are other safeguards against such uses, but it's important 2662 // to get this right here so that we don't end up making a 2663 // spuriously dependent expression if we're inside a dependent 2664 // instance method. 2665 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2666 bool MightBeImplicitMember; 2667 if (!IsAddressOfOperand) 2668 MightBeImplicitMember = true; 2669 else if (!SS.isEmpty()) 2670 MightBeImplicitMember = false; 2671 else if (R.isOverloadedResult()) 2672 MightBeImplicitMember = false; 2673 else if (R.isUnresolvableResult()) 2674 MightBeImplicitMember = true; 2675 else 2676 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2677 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2678 isa<MSPropertyDecl>(R.getFoundDecl()); 2679 2680 if (MightBeImplicitMember) 2681 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2682 R, TemplateArgs, S); 2683 } 2684 2685 if (TemplateArgs || TemplateKWLoc.isValid()) { 2686 2687 // In C++1y, if this is a variable template id, then check it 2688 // in BuildTemplateIdExpr(). 2689 // The single lookup result must be a variable template declaration. 2690 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2691 Id.TemplateId->Kind == TNK_Var_template) { 2692 assert(R.getAsSingle<VarTemplateDecl>() && 2693 "There should only be one declaration found."); 2694 } 2695 2696 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2697 } 2698 2699 return BuildDeclarationNameExpr(SS, R, ADL); 2700 } 2701 2702 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2703 /// declaration name, generally during template instantiation. 2704 /// There's a large number of things which don't need to be done along 2705 /// this path. 2706 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2707 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2708 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2709 DeclContext *DC = computeDeclContext(SS, false); 2710 if (!DC) 2711 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2712 NameInfo, /*TemplateArgs=*/nullptr); 2713 2714 if (RequireCompleteDeclContext(SS, DC)) 2715 return ExprError(); 2716 2717 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2718 LookupQualifiedName(R, DC); 2719 2720 if (R.isAmbiguous()) 2721 return ExprError(); 2722 2723 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2724 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2725 NameInfo, /*TemplateArgs=*/nullptr); 2726 2727 if (R.empty()) { 2728 // Don't diagnose problems with invalid record decl, the secondary no_member 2729 // diagnostic during template instantiation is likely bogus, e.g. if a class 2730 // is invalid because it's derived from an invalid base class, then missing 2731 // members were likely supposed to be inherited. 2732 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2733 if (CD->isInvalidDecl()) 2734 return ExprError(); 2735 Diag(NameInfo.getLoc(), diag::err_no_member) 2736 << NameInfo.getName() << DC << SS.getRange(); 2737 return ExprError(); 2738 } 2739 2740 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2741 // Diagnose a missing typename if this resolved unambiguously to a type in 2742 // a dependent context. If we can recover with a type, downgrade this to 2743 // a warning in Microsoft compatibility mode. 2744 unsigned DiagID = diag::err_typename_missing; 2745 if (RecoveryTSI && getLangOpts().MSVCCompat) 2746 DiagID = diag::ext_typename_missing; 2747 SourceLocation Loc = SS.getBeginLoc(); 2748 auto D = Diag(Loc, DiagID); 2749 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2750 << SourceRange(Loc, NameInfo.getEndLoc()); 2751 2752 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2753 // context. 2754 if (!RecoveryTSI) 2755 return ExprError(); 2756 2757 // Only issue the fixit if we're prepared to recover. 2758 D << FixItHint::CreateInsertion(Loc, "typename "); 2759 2760 // Recover by pretending this was an elaborated type. 2761 QualType Ty = Context.getTypeDeclType(TD); 2762 TypeLocBuilder TLB; 2763 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2764 2765 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2766 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2767 QTL.setElaboratedKeywordLoc(SourceLocation()); 2768 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2769 2770 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2771 2772 return ExprEmpty(); 2773 } 2774 2775 // Defend against this resolving to an implicit member access. We usually 2776 // won't get here if this might be a legitimate a class member (we end up in 2777 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2778 // a pointer-to-member or in an unevaluated context in C++11. 2779 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2780 return BuildPossibleImplicitMemberExpr(SS, 2781 /*TemplateKWLoc=*/SourceLocation(), 2782 R, /*TemplateArgs=*/nullptr, S); 2783 2784 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2785 } 2786 2787 /// The parser has read a name in, and Sema has detected that we're currently 2788 /// inside an ObjC method. Perform some additional checks and determine if we 2789 /// should form a reference to an ivar. 2790 /// 2791 /// Ideally, most of this would be done by lookup, but there's 2792 /// actually quite a lot of extra work involved. 2793 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2794 IdentifierInfo *II) { 2795 SourceLocation Loc = Lookup.getNameLoc(); 2796 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2797 2798 // Check for error condition which is already reported. 2799 if (!CurMethod) 2800 return DeclResult(true); 2801 2802 // There are two cases to handle here. 1) scoped lookup could have failed, 2803 // in which case we should look for an ivar. 2) scoped lookup could have 2804 // found a decl, but that decl is outside the current instance method (i.e. 2805 // a global variable). In these two cases, we do a lookup for an ivar with 2806 // this name, if the lookup sucedes, we replace it our current decl. 2807 2808 // If we're in a class method, we don't normally want to look for 2809 // ivars. But if we don't find anything else, and there's an 2810 // ivar, that's an error. 2811 bool IsClassMethod = CurMethod->isClassMethod(); 2812 2813 bool LookForIvars; 2814 if (Lookup.empty()) 2815 LookForIvars = true; 2816 else if (IsClassMethod) 2817 LookForIvars = false; 2818 else 2819 LookForIvars = (Lookup.isSingleResult() && 2820 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2821 ObjCInterfaceDecl *IFace = nullptr; 2822 if (LookForIvars) { 2823 IFace = CurMethod->getClassInterface(); 2824 ObjCInterfaceDecl *ClassDeclared; 2825 ObjCIvarDecl *IV = nullptr; 2826 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2827 // Diagnose using an ivar in a class method. 2828 if (IsClassMethod) { 2829 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2830 return DeclResult(true); 2831 } 2832 2833 // Diagnose the use of an ivar outside of the declaring class. 2834 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2835 !declaresSameEntity(ClassDeclared, IFace) && 2836 !getLangOpts().DebuggerSupport) 2837 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2838 2839 // Success. 2840 return IV; 2841 } 2842 } else if (CurMethod->isInstanceMethod()) { 2843 // We should warn if a local variable hides an ivar. 2844 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2845 ObjCInterfaceDecl *ClassDeclared; 2846 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2847 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2848 declaresSameEntity(IFace, ClassDeclared)) 2849 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2850 } 2851 } 2852 } else if (Lookup.isSingleResult() && 2853 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2854 // If accessing a stand-alone ivar in a class method, this is an error. 2855 if (const ObjCIvarDecl *IV = 2856 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2857 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2858 return DeclResult(true); 2859 } 2860 } 2861 2862 // Didn't encounter an error, didn't find an ivar. 2863 return DeclResult(false); 2864 } 2865 2866 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2867 ObjCIvarDecl *IV) { 2868 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2869 assert(CurMethod && CurMethod->isInstanceMethod() && 2870 "should not reference ivar from this context"); 2871 2872 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2873 assert(IFace && "should not reference ivar from this context"); 2874 2875 // If we're referencing an invalid decl, just return this as a silent 2876 // error node. The error diagnostic was already emitted on the decl. 2877 if (IV->isInvalidDecl()) 2878 return ExprError(); 2879 2880 // Check if referencing a field with __attribute__((deprecated)). 2881 if (DiagnoseUseOfDecl(IV, Loc)) 2882 return ExprError(); 2883 2884 // FIXME: This should use a new expr for a direct reference, don't 2885 // turn this into Self->ivar, just return a BareIVarExpr or something. 2886 IdentifierInfo &II = Context.Idents.get("self"); 2887 UnqualifiedId SelfName; 2888 SelfName.setImplicitSelfParam(&II); 2889 CXXScopeSpec SelfScopeSpec; 2890 SourceLocation TemplateKWLoc; 2891 ExprResult SelfExpr = 2892 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2893 /*HasTrailingLParen=*/false, 2894 /*IsAddressOfOperand=*/false); 2895 if (SelfExpr.isInvalid()) 2896 return ExprError(); 2897 2898 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2899 if (SelfExpr.isInvalid()) 2900 return ExprError(); 2901 2902 MarkAnyDeclReferenced(Loc, IV, true); 2903 2904 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2905 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2906 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2907 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2908 2909 ObjCIvarRefExpr *Result = new (Context) 2910 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2911 IV->getLocation(), SelfExpr.get(), true, true); 2912 2913 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2914 if (!isUnevaluatedContext() && 2915 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2916 getCurFunction()->recordUseOfWeak(Result); 2917 } 2918 if (getLangOpts().ObjCAutoRefCount) 2919 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2920 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2921 2922 return Result; 2923 } 2924 2925 /// The parser has read a name in, and Sema has detected that we're currently 2926 /// inside an ObjC method. Perform some additional checks and determine if we 2927 /// should form a reference to an ivar. If so, build an expression referencing 2928 /// that ivar. 2929 ExprResult 2930 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2931 IdentifierInfo *II, bool AllowBuiltinCreation) { 2932 // FIXME: Integrate this lookup step into LookupParsedName. 2933 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2934 if (Ivar.isInvalid()) 2935 return ExprError(); 2936 if (Ivar.isUsable()) 2937 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2938 cast<ObjCIvarDecl>(Ivar.get())); 2939 2940 if (Lookup.empty() && II && AllowBuiltinCreation) 2941 LookupBuiltin(Lookup); 2942 2943 // Sentinel value saying that we didn't do anything special. 2944 return ExprResult(false); 2945 } 2946 2947 /// Cast a base object to a member's actual type. 2948 /// 2949 /// There are two relevant checks: 2950 /// 2951 /// C++ [class.access.base]p7: 2952 /// 2953 /// If a class member access operator [...] is used to access a non-static 2954 /// data member or non-static member function, the reference is ill-formed if 2955 /// the left operand [...] cannot be implicitly converted to a pointer to the 2956 /// naming class of the right operand. 2957 /// 2958 /// C++ [expr.ref]p7: 2959 /// 2960 /// If E2 is a non-static data member or a non-static member function, the 2961 /// program is ill-formed if the class of which E2 is directly a member is an 2962 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2963 /// 2964 /// Note that the latter check does not consider access; the access of the 2965 /// "real" base class is checked as appropriate when checking the access of the 2966 /// member name. 2967 ExprResult 2968 Sema::PerformObjectMemberConversion(Expr *From, 2969 NestedNameSpecifier *Qualifier, 2970 NamedDecl *FoundDecl, 2971 NamedDecl *Member) { 2972 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2973 if (!RD) 2974 return From; 2975 2976 QualType DestRecordType; 2977 QualType DestType; 2978 QualType FromRecordType; 2979 QualType FromType = From->getType(); 2980 bool PointerConversions = false; 2981 if (isa<FieldDecl>(Member)) { 2982 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2983 auto FromPtrType = FromType->getAs<PointerType>(); 2984 DestRecordType = Context.getAddrSpaceQualType( 2985 DestRecordType, FromPtrType 2986 ? FromType->getPointeeType().getAddressSpace() 2987 : FromType.getAddressSpace()); 2988 2989 if (FromPtrType) { 2990 DestType = Context.getPointerType(DestRecordType); 2991 FromRecordType = FromPtrType->getPointeeType(); 2992 PointerConversions = true; 2993 } else { 2994 DestType = DestRecordType; 2995 FromRecordType = FromType; 2996 } 2997 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2998 if (Method->isStatic()) 2999 return From; 3000 3001 DestType = Method->getThisType(); 3002 DestRecordType = DestType->getPointeeType(); 3003 3004 if (FromType->getAs<PointerType>()) { 3005 FromRecordType = FromType->getPointeeType(); 3006 PointerConversions = true; 3007 } else { 3008 FromRecordType = FromType; 3009 DestType = DestRecordType; 3010 } 3011 3012 LangAS FromAS = FromRecordType.getAddressSpace(); 3013 LangAS DestAS = DestRecordType.getAddressSpace(); 3014 if (FromAS != DestAS) { 3015 QualType FromRecordTypeWithoutAS = 3016 Context.removeAddrSpaceQualType(FromRecordType); 3017 QualType FromTypeWithDestAS = 3018 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 3019 if (PointerConversions) 3020 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 3021 From = ImpCastExprToType(From, FromTypeWithDestAS, 3022 CK_AddressSpaceConversion, From->getValueKind()) 3023 .get(); 3024 } 3025 } else { 3026 // No conversion necessary. 3027 return From; 3028 } 3029 3030 if (DestType->isDependentType() || FromType->isDependentType()) 3031 return From; 3032 3033 // If the unqualified types are the same, no conversion is necessary. 3034 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3035 return From; 3036 3037 SourceRange FromRange = From->getSourceRange(); 3038 SourceLocation FromLoc = FromRange.getBegin(); 3039 3040 ExprValueKind VK = From->getValueKind(); 3041 3042 // C++ [class.member.lookup]p8: 3043 // [...] Ambiguities can often be resolved by qualifying a name with its 3044 // class name. 3045 // 3046 // If the member was a qualified name and the qualified referred to a 3047 // specific base subobject type, we'll cast to that intermediate type 3048 // first and then to the object in which the member is declared. That allows 3049 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3050 // 3051 // class Base { public: int x; }; 3052 // class Derived1 : public Base { }; 3053 // class Derived2 : public Base { }; 3054 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3055 // 3056 // void VeryDerived::f() { 3057 // x = 17; // error: ambiguous base subobjects 3058 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3059 // } 3060 if (Qualifier && Qualifier->getAsType()) { 3061 QualType QType = QualType(Qualifier->getAsType(), 0); 3062 assert(QType->isRecordType() && "lookup done with non-record type"); 3063 3064 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); 3065 3066 // In C++98, the qualifier type doesn't actually have to be a base 3067 // type of the object type, in which case we just ignore it. 3068 // Otherwise build the appropriate casts. 3069 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3070 CXXCastPath BasePath; 3071 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3072 FromLoc, FromRange, &BasePath)) 3073 return ExprError(); 3074 3075 if (PointerConversions) 3076 QType = Context.getPointerType(QType); 3077 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3078 VK, &BasePath).get(); 3079 3080 FromType = QType; 3081 FromRecordType = QRecordType; 3082 3083 // If the qualifier type was the same as the destination type, 3084 // we're done. 3085 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3086 return From; 3087 } 3088 } 3089 3090 CXXCastPath BasePath; 3091 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3092 FromLoc, FromRange, &BasePath, 3093 /*IgnoreAccess=*/true)) 3094 return ExprError(); 3095 3096 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3097 VK, &BasePath); 3098 } 3099 3100 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3101 const LookupResult &R, 3102 bool HasTrailingLParen) { 3103 // Only when used directly as the postfix-expression of a call. 3104 if (!HasTrailingLParen) 3105 return false; 3106 3107 // Never if a scope specifier was provided. 3108 if (SS.isSet()) 3109 return false; 3110 3111 // Only in C++ or ObjC++. 3112 if (!getLangOpts().CPlusPlus) 3113 return false; 3114 3115 // Turn off ADL when we find certain kinds of declarations during 3116 // normal lookup: 3117 for (NamedDecl *D : R) { 3118 // C++0x [basic.lookup.argdep]p3: 3119 // -- a declaration of a class member 3120 // Since using decls preserve this property, we check this on the 3121 // original decl. 3122 if (D->isCXXClassMember()) 3123 return false; 3124 3125 // C++0x [basic.lookup.argdep]p3: 3126 // -- a block-scope function declaration that is not a 3127 // using-declaration 3128 // NOTE: we also trigger this for function templates (in fact, we 3129 // don't check the decl type at all, since all other decl types 3130 // turn off ADL anyway). 3131 if (isa<UsingShadowDecl>(D)) 3132 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3133 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3134 return false; 3135 3136 // C++0x [basic.lookup.argdep]p3: 3137 // -- a declaration that is neither a function or a function 3138 // template 3139 // And also for builtin functions. 3140 if (isa<FunctionDecl>(D)) { 3141 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3142 3143 // But also builtin functions. 3144 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3145 return false; 3146 } else if (!isa<FunctionTemplateDecl>(D)) 3147 return false; 3148 } 3149 3150 return true; 3151 } 3152 3153 3154 /// Diagnoses obvious problems with the use of the given declaration 3155 /// as an expression. This is only actually called for lookups that 3156 /// were not overloaded, and it doesn't promise that the declaration 3157 /// will in fact be used. 3158 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3159 if (D->isInvalidDecl()) 3160 return true; 3161 3162 if (isa<TypedefNameDecl>(D)) { 3163 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3164 return true; 3165 } 3166 3167 if (isa<ObjCInterfaceDecl>(D)) { 3168 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3169 return true; 3170 } 3171 3172 if (isa<NamespaceDecl>(D)) { 3173 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3174 return true; 3175 } 3176 3177 return false; 3178 } 3179 3180 // Certain multiversion types should be treated as overloaded even when there is 3181 // only one result. 3182 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3183 assert(R.isSingleResult() && "Expected only a single result"); 3184 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3185 return FD && 3186 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3187 } 3188 3189 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3190 LookupResult &R, bool NeedsADL, 3191 bool AcceptInvalidDecl) { 3192 // If this is a single, fully-resolved result and we don't need ADL, 3193 // just build an ordinary singleton decl ref. 3194 if (!NeedsADL && R.isSingleResult() && 3195 !R.getAsSingle<FunctionTemplateDecl>() && 3196 !ShouldLookupResultBeMultiVersionOverload(R)) 3197 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3198 R.getRepresentativeDecl(), nullptr, 3199 AcceptInvalidDecl); 3200 3201 // We only need to check the declaration if there's exactly one 3202 // result, because in the overloaded case the results can only be 3203 // functions and function templates. 3204 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3205 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3206 return ExprError(); 3207 3208 // Otherwise, just build an unresolved lookup expression. Suppress 3209 // any lookup-related diagnostics; we'll hash these out later, when 3210 // we've picked a target. 3211 R.suppressDiagnostics(); 3212 3213 UnresolvedLookupExpr *ULE 3214 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3215 SS.getWithLocInContext(Context), 3216 R.getLookupNameInfo(), 3217 NeedsADL, R.isOverloadedResult(), 3218 R.begin(), R.end()); 3219 3220 return ULE; 3221 } 3222 3223 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3224 ValueDecl *var); 3225 3226 /// Complete semantic analysis for a reference to the given declaration. 3227 ExprResult Sema::BuildDeclarationNameExpr( 3228 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3229 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3230 bool AcceptInvalidDecl) { 3231 assert(D && "Cannot refer to a NULL declaration"); 3232 assert(!isa<FunctionTemplateDecl>(D) && 3233 "Cannot refer unambiguously to a function template"); 3234 3235 SourceLocation Loc = NameInfo.getLoc(); 3236 if (CheckDeclInExpr(*this, Loc, D)) { 3237 // Recovery from invalid cases (e.g. D is an invalid Decl). 3238 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up 3239 // diagnostics, as invalid decls use int as a fallback type. 3240 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {}); 3241 } 3242 3243 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3244 // Specifically diagnose references to class templates that are missing 3245 // a template argument list. 3246 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3247 return ExprError(); 3248 } 3249 3250 // Make sure that we're referring to a value. 3251 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3252 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3253 Diag(D->getLocation(), diag::note_declared_at); 3254 return ExprError(); 3255 } 3256 3257 // Check whether this declaration can be used. Note that we suppress 3258 // this check when we're going to perform argument-dependent lookup 3259 // on this function name, because this might not be the function 3260 // that overload resolution actually selects. 3261 if (DiagnoseUseOfDecl(D, Loc)) 3262 return ExprError(); 3263 3264 auto *VD = cast<ValueDecl>(D); 3265 3266 // Only create DeclRefExpr's for valid Decl's. 3267 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3268 return ExprError(); 3269 3270 // Handle members of anonymous structs and unions. If we got here, 3271 // and the reference is to a class member indirect field, then this 3272 // must be the subject of a pointer-to-member expression. 3273 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3274 if (!indirectField->isCXXClassMember()) 3275 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3276 indirectField); 3277 3278 QualType type = VD->getType(); 3279 if (type.isNull()) 3280 return ExprError(); 3281 ExprValueKind valueKind = VK_PRValue; 3282 3283 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3284 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3285 // is expanded by some outer '...' in the context of the use. 3286 type = type.getNonPackExpansionType(); 3287 3288 switch (D->getKind()) { 3289 // Ignore all the non-ValueDecl kinds. 3290 #define ABSTRACT_DECL(kind) 3291 #define VALUE(type, base) 3292 #define DECL(type, base) case Decl::type: 3293 #include "clang/AST/DeclNodes.inc" 3294 llvm_unreachable("invalid value decl kind"); 3295 3296 // These shouldn't make it here. 3297 case Decl::ObjCAtDefsField: 3298 llvm_unreachable("forming non-member reference to ivar?"); 3299 3300 // Enum constants are always r-values and never references. 3301 // Unresolved using declarations are dependent. 3302 case Decl::EnumConstant: 3303 case Decl::UnresolvedUsingValue: 3304 case Decl::OMPDeclareReduction: 3305 case Decl::OMPDeclareMapper: 3306 valueKind = VK_PRValue; 3307 break; 3308 3309 // Fields and indirect fields that got here must be for 3310 // pointer-to-member expressions; we just call them l-values for 3311 // internal consistency, because this subexpression doesn't really 3312 // exist in the high-level semantics. 3313 case Decl::Field: 3314 case Decl::IndirectField: 3315 case Decl::ObjCIvar: 3316 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3317 3318 // These can't have reference type in well-formed programs, but 3319 // for internal consistency we do this anyway. 3320 type = type.getNonReferenceType(); 3321 valueKind = VK_LValue; 3322 break; 3323 3324 // Non-type template parameters are either l-values or r-values 3325 // depending on the type. 3326 case Decl::NonTypeTemplateParm: { 3327 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3328 type = reftype->getPointeeType(); 3329 valueKind = VK_LValue; // even if the parameter is an r-value reference 3330 break; 3331 } 3332 3333 // [expr.prim.id.unqual]p2: 3334 // If the entity is a template parameter object for a template 3335 // parameter of type T, the type of the expression is const T. 3336 // [...] The expression is an lvalue if the entity is a [...] template 3337 // parameter object. 3338 if (type->isRecordType()) { 3339 type = type.getUnqualifiedType().withConst(); 3340 valueKind = VK_LValue; 3341 break; 3342 } 3343 3344 // For non-references, we need to strip qualifiers just in case 3345 // the template parameter was declared as 'const int' or whatever. 3346 valueKind = VK_PRValue; 3347 type = type.getUnqualifiedType(); 3348 break; 3349 } 3350 3351 case Decl::Var: 3352 case Decl::VarTemplateSpecialization: 3353 case Decl::VarTemplatePartialSpecialization: 3354 case Decl::Decomposition: 3355 case Decl::OMPCapturedExpr: 3356 // In C, "extern void blah;" is valid and is an r-value. 3357 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3358 type->isVoidType()) { 3359 valueKind = VK_PRValue; 3360 break; 3361 } 3362 LLVM_FALLTHROUGH; 3363 3364 case Decl::ImplicitParam: 3365 case Decl::ParmVar: { 3366 // These are always l-values. 3367 valueKind = VK_LValue; 3368 type = type.getNonReferenceType(); 3369 3370 // FIXME: Does the addition of const really only apply in 3371 // potentially-evaluated contexts? Since the variable isn't actually 3372 // captured in an unevaluated context, it seems that the answer is no. 3373 if (!isUnevaluatedContext()) { 3374 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3375 if (!CapturedType.isNull()) 3376 type = CapturedType; 3377 } 3378 3379 break; 3380 } 3381 3382 case Decl::Binding: { 3383 // These are always lvalues. 3384 valueKind = VK_LValue; 3385 type = type.getNonReferenceType(); 3386 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3387 // decides how that's supposed to work. 3388 auto *BD = cast<BindingDecl>(VD); 3389 if (BD->getDeclContext() != CurContext) { 3390 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3391 if (DD && DD->hasLocalStorage()) 3392 diagnoseUncapturableValueReference(*this, Loc, BD); 3393 } 3394 break; 3395 } 3396 3397 case Decl::Function: { 3398 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3399 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 3400 type = Context.BuiltinFnTy; 3401 valueKind = VK_PRValue; 3402 break; 3403 } 3404 } 3405 3406 const FunctionType *fty = type->castAs<FunctionType>(); 3407 3408 // If we're referring to a function with an __unknown_anytype 3409 // result type, make the entire expression __unknown_anytype. 3410 if (fty->getReturnType() == Context.UnknownAnyTy) { 3411 type = Context.UnknownAnyTy; 3412 valueKind = VK_PRValue; 3413 break; 3414 } 3415 3416 // Functions are l-values in C++. 3417 if (getLangOpts().CPlusPlus) { 3418 valueKind = VK_LValue; 3419 break; 3420 } 3421 3422 // C99 DR 316 says that, if a function type comes from a 3423 // function definition (without a prototype), that type is only 3424 // used for checking compatibility. Therefore, when referencing 3425 // the function, we pretend that we don't have the full function 3426 // type. 3427 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3428 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3429 fty->getExtInfo()); 3430 3431 // Functions are r-values in C. 3432 valueKind = VK_PRValue; 3433 break; 3434 } 3435 3436 case Decl::CXXDeductionGuide: 3437 llvm_unreachable("building reference to deduction guide"); 3438 3439 case Decl::MSProperty: 3440 case Decl::MSGuid: 3441 case Decl::TemplateParamObject: 3442 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3443 // capture in OpenMP, or duplicated between host and device? 3444 valueKind = VK_LValue; 3445 break; 3446 3447 case Decl::UnnamedGlobalConstant: 3448 valueKind = VK_LValue; 3449 break; 3450 3451 case Decl::CXXMethod: 3452 // If we're referring to a method with an __unknown_anytype 3453 // result type, make the entire expression __unknown_anytype. 3454 // This should only be possible with a type written directly. 3455 if (const FunctionProtoType *proto = 3456 dyn_cast<FunctionProtoType>(VD->getType())) 3457 if (proto->getReturnType() == Context.UnknownAnyTy) { 3458 type = Context.UnknownAnyTy; 3459 valueKind = VK_PRValue; 3460 break; 3461 } 3462 3463 // C++ methods are l-values if static, r-values if non-static. 3464 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3465 valueKind = VK_LValue; 3466 break; 3467 } 3468 LLVM_FALLTHROUGH; 3469 3470 case Decl::CXXConversion: 3471 case Decl::CXXDestructor: 3472 case Decl::CXXConstructor: 3473 valueKind = VK_PRValue; 3474 break; 3475 } 3476 3477 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3478 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3479 TemplateArgs); 3480 } 3481 3482 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3483 SmallString<32> &Target) { 3484 Target.resize(CharByteWidth * (Source.size() + 1)); 3485 char *ResultPtr = &Target[0]; 3486 const llvm::UTF8 *ErrorPtr; 3487 bool success = 3488 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3489 (void)success; 3490 assert(success); 3491 Target.resize(ResultPtr - &Target[0]); 3492 } 3493 3494 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3495 PredefinedExpr::IdentKind IK) { 3496 // Pick the current block, lambda, captured statement or function. 3497 Decl *currentDecl = nullptr; 3498 if (const BlockScopeInfo *BSI = getCurBlock()) 3499 currentDecl = BSI->TheDecl; 3500 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3501 currentDecl = LSI->CallOperator; 3502 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3503 currentDecl = CSI->TheCapturedDecl; 3504 else 3505 currentDecl = getCurFunctionOrMethodDecl(); 3506 3507 if (!currentDecl) { 3508 Diag(Loc, diag::ext_predef_outside_function); 3509 currentDecl = Context.getTranslationUnitDecl(); 3510 } 3511 3512 QualType ResTy; 3513 StringLiteral *SL = nullptr; 3514 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3515 ResTy = Context.DependentTy; 3516 else { 3517 // Pre-defined identifiers are of type char[x], where x is the length of 3518 // the string. 3519 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3520 unsigned Length = Str.length(); 3521 3522 llvm::APInt LengthI(32, Length + 1); 3523 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3524 ResTy = 3525 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3526 SmallString<32> RawChars; 3527 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3528 Str, RawChars); 3529 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3530 ArrayType::Normal, 3531 /*IndexTypeQuals*/ 0); 3532 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3533 /*Pascal*/ false, ResTy, Loc); 3534 } else { 3535 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3536 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3537 ArrayType::Normal, 3538 /*IndexTypeQuals*/ 0); 3539 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3540 /*Pascal*/ false, ResTy, Loc); 3541 } 3542 } 3543 3544 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3545 } 3546 3547 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3548 SourceLocation LParen, 3549 SourceLocation RParen, 3550 TypeSourceInfo *TSI) { 3551 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3552 } 3553 3554 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3555 SourceLocation LParen, 3556 SourceLocation RParen, 3557 ParsedType ParsedTy) { 3558 TypeSourceInfo *TSI = nullptr; 3559 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3560 3561 if (Ty.isNull()) 3562 return ExprError(); 3563 if (!TSI) 3564 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3565 3566 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3567 } 3568 3569 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3570 PredefinedExpr::IdentKind IK; 3571 3572 switch (Kind) { 3573 default: llvm_unreachable("Unknown simple primary expr!"); 3574 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3575 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3576 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3577 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3578 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3579 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3580 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3581 } 3582 3583 return BuildPredefinedExpr(Loc, IK); 3584 } 3585 3586 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3587 SmallString<16> CharBuffer; 3588 bool Invalid = false; 3589 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3590 if (Invalid) 3591 return ExprError(); 3592 3593 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3594 PP, Tok.getKind()); 3595 if (Literal.hadError()) 3596 return ExprError(); 3597 3598 QualType Ty; 3599 if (Literal.isWide()) 3600 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3601 else if (Literal.isUTF8() && getLangOpts().C2x) 3602 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x 3603 else if (Literal.isUTF8() && getLangOpts().Char8) 3604 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3605 else if (Literal.isUTF16()) 3606 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3607 else if (Literal.isUTF32()) 3608 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3609 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3610 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3611 else 3612 Ty = Context.CharTy; // 'x' -> char in C++; 3613 // u8'x' -> char in C11-C17 and in C++ without char8_t. 3614 3615 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3616 if (Literal.isWide()) 3617 Kind = CharacterLiteral::Wide; 3618 else if (Literal.isUTF16()) 3619 Kind = CharacterLiteral::UTF16; 3620 else if (Literal.isUTF32()) 3621 Kind = CharacterLiteral::UTF32; 3622 else if (Literal.isUTF8()) 3623 Kind = CharacterLiteral::UTF8; 3624 3625 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3626 Tok.getLocation()); 3627 3628 if (Literal.getUDSuffix().empty()) 3629 return Lit; 3630 3631 // We're building a user-defined literal. 3632 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3633 SourceLocation UDSuffixLoc = 3634 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3635 3636 // Make sure we're allowed user-defined literals here. 3637 if (!UDLScope) 3638 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3639 3640 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3641 // operator "" X (ch) 3642 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3643 Lit, Tok.getLocation()); 3644 } 3645 3646 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3647 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3648 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3649 Context.IntTy, Loc); 3650 } 3651 3652 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3653 QualType Ty, SourceLocation Loc) { 3654 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3655 3656 using llvm::APFloat; 3657 APFloat Val(Format); 3658 3659 APFloat::opStatus result = Literal.GetFloatValue(Val); 3660 3661 // Overflow is always an error, but underflow is only an error if 3662 // we underflowed to zero (APFloat reports denormals as underflow). 3663 if ((result & APFloat::opOverflow) || 3664 ((result & APFloat::opUnderflow) && Val.isZero())) { 3665 unsigned diagnostic; 3666 SmallString<20> buffer; 3667 if (result & APFloat::opOverflow) { 3668 diagnostic = diag::warn_float_overflow; 3669 APFloat::getLargest(Format).toString(buffer); 3670 } else { 3671 diagnostic = diag::warn_float_underflow; 3672 APFloat::getSmallest(Format).toString(buffer); 3673 } 3674 3675 S.Diag(Loc, diagnostic) 3676 << Ty 3677 << StringRef(buffer.data(), buffer.size()); 3678 } 3679 3680 bool isExact = (result == APFloat::opOK); 3681 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3682 } 3683 3684 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3685 assert(E && "Invalid expression"); 3686 3687 if (E->isValueDependent()) 3688 return false; 3689 3690 QualType QT = E->getType(); 3691 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3692 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3693 return true; 3694 } 3695 3696 llvm::APSInt ValueAPS; 3697 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3698 3699 if (R.isInvalid()) 3700 return true; 3701 3702 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3703 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3704 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3705 << toString(ValueAPS, 10) << ValueIsPositive; 3706 return true; 3707 } 3708 3709 return false; 3710 } 3711 3712 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3713 // Fast path for a single digit (which is quite common). A single digit 3714 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3715 if (Tok.getLength() == 1) { 3716 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3717 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3718 } 3719 3720 SmallString<128> SpellingBuffer; 3721 // NumericLiteralParser wants to overread by one character. Add padding to 3722 // the buffer in case the token is copied to the buffer. If getSpelling() 3723 // returns a StringRef to the memory buffer, it should have a null char at 3724 // the EOF, so it is also safe. 3725 SpellingBuffer.resize(Tok.getLength() + 1); 3726 3727 // Get the spelling of the token, which eliminates trigraphs, etc. 3728 bool Invalid = false; 3729 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3730 if (Invalid) 3731 return ExprError(); 3732 3733 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3734 PP.getSourceManager(), PP.getLangOpts(), 3735 PP.getTargetInfo(), PP.getDiagnostics()); 3736 if (Literal.hadError) 3737 return ExprError(); 3738 3739 if (Literal.hasUDSuffix()) { 3740 // We're building a user-defined literal. 3741 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3742 SourceLocation UDSuffixLoc = 3743 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3744 3745 // Make sure we're allowed user-defined literals here. 3746 if (!UDLScope) 3747 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3748 3749 QualType CookedTy; 3750 if (Literal.isFloatingLiteral()) { 3751 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3752 // long double, the literal is treated as a call of the form 3753 // operator "" X (f L) 3754 CookedTy = Context.LongDoubleTy; 3755 } else { 3756 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3757 // unsigned long long, the literal is treated as a call of the form 3758 // operator "" X (n ULL) 3759 CookedTy = Context.UnsignedLongLongTy; 3760 } 3761 3762 DeclarationName OpName = 3763 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3764 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3765 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3766 3767 SourceLocation TokLoc = Tok.getLocation(); 3768 3769 // Perform literal operator lookup to determine if we're building a raw 3770 // literal or a cooked one. 3771 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3772 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3773 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3774 /*AllowStringTemplatePack*/ false, 3775 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3776 case LOLR_ErrorNoDiagnostic: 3777 // Lookup failure for imaginary constants isn't fatal, there's still the 3778 // GNU extension producing _Complex types. 3779 break; 3780 case LOLR_Error: 3781 return ExprError(); 3782 case LOLR_Cooked: { 3783 Expr *Lit; 3784 if (Literal.isFloatingLiteral()) { 3785 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3786 } else { 3787 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3788 if (Literal.GetIntegerValue(ResultVal)) 3789 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3790 << /* Unsigned */ 1; 3791 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3792 Tok.getLocation()); 3793 } 3794 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3795 } 3796 3797 case LOLR_Raw: { 3798 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3799 // literal is treated as a call of the form 3800 // operator "" X ("n") 3801 unsigned Length = Literal.getUDSuffixOffset(); 3802 QualType StrTy = Context.getConstantArrayType( 3803 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3804 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3805 Expr *Lit = StringLiteral::Create( 3806 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3807 /*Pascal*/false, StrTy, &TokLoc, 1); 3808 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3809 } 3810 3811 case LOLR_Template: { 3812 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3813 // template), L is treated as a call fo the form 3814 // operator "" X <'c1', 'c2', ... 'ck'>() 3815 // where n is the source character sequence c1 c2 ... ck. 3816 TemplateArgumentListInfo ExplicitArgs; 3817 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3818 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3819 llvm::APSInt Value(CharBits, CharIsUnsigned); 3820 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3821 Value = TokSpelling[I]; 3822 TemplateArgument Arg(Context, Value, Context.CharTy); 3823 TemplateArgumentLocInfo ArgInfo; 3824 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3825 } 3826 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3827 &ExplicitArgs); 3828 } 3829 case LOLR_StringTemplatePack: 3830 llvm_unreachable("unexpected literal operator lookup result"); 3831 } 3832 } 3833 3834 Expr *Res; 3835 3836 if (Literal.isFixedPointLiteral()) { 3837 QualType Ty; 3838 3839 if (Literal.isAccum) { 3840 if (Literal.isHalf) { 3841 Ty = Context.ShortAccumTy; 3842 } else if (Literal.isLong) { 3843 Ty = Context.LongAccumTy; 3844 } else { 3845 Ty = Context.AccumTy; 3846 } 3847 } else if (Literal.isFract) { 3848 if (Literal.isHalf) { 3849 Ty = Context.ShortFractTy; 3850 } else if (Literal.isLong) { 3851 Ty = Context.LongFractTy; 3852 } else { 3853 Ty = Context.FractTy; 3854 } 3855 } 3856 3857 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3858 3859 bool isSigned = !Literal.isUnsigned; 3860 unsigned scale = Context.getFixedPointScale(Ty); 3861 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3862 3863 llvm::APInt Val(bit_width, 0, isSigned); 3864 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3865 bool ValIsZero = Val.isZero() && !Overflowed; 3866 3867 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3868 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3869 // Clause 6.4.4 - The value of a constant shall be in the range of 3870 // representable values for its type, with exception for constants of a 3871 // fract type with a value of exactly 1; such a constant shall denote 3872 // the maximal value for the type. 3873 --Val; 3874 else if (Val.ugt(MaxVal) || Overflowed) 3875 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3876 3877 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3878 Tok.getLocation(), scale); 3879 } else if (Literal.isFloatingLiteral()) { 3880 QualType Ty; 3881 if (Literal.isHalf){ 3882 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3883 Ty = Context.HalfTy; 3884 else { 3885 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3886 return ExprError(); 3887 } 3888 } else if (Literal.isFloat) 3889 Ty = Context.FloatTy; 3890 else if (Literal.isLong) 3891 Ty = Context.LongDoubleTy; 3892 else if (Literal.isFloat16) 3893 Ty = Context.Float16Ty; 3894 else if (Literal.isFloat128) 3895 Ty = Context.Float128Ty; 3896 else 3897 Ty = Context.DoubleTy; 3898 3899 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3900 3901 if (Ty == Context.DoubleTy) { 3902 if (getLangOpts().SinglePrecisionConstants) { 3903 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3904 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3905 } 3906 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3907 "cl_khr_fp64", getLangOpts())) { 3908 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3909 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3910 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3911 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3912 } 3913 } 3914 } else if (!Literal.isIntegerLiteral()) { 3915 return ExprError(); 3916 } else { 3917 QualType Ty; 3918 3919 // 'long long' is a C99 or C++11 feature. 3920 if (!getLangOpts().C99 && Literal.isLongLong) { 3921 if (getLangOpts().CPlusPlus) 3922 Diag(Tok.getLocation(), 3923 getLangOpts().CPlusPlus11 ? 3924 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3925 else 3926 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3927 } 3928 3929 // 'z/uz' literals are a C++2b feature. 3930 if (Literal.isSizeT) 3931 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3932 ? getLangOpts().CPlusPlus2b 3933 ? diag::warn_cxx20_compat_size_t_suffix 3934 : diag::ext_cxx2b_size_t_suffix 3935 : diag::err_cxx2b_size_t_suffix); 3936 3937 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++, 3938 // but we do not currently support the suffix in C++ mode because it's not 3939 // entirely clear whether WG21 will prefer this suffix to return a library 3940 // type such as std::bit_int instead of returning a _BitInt. 3941 if (Literal.isBitInt && !getLangOpts().CPlusPlus) 3942 PP.Diag(Tok.getLocation(), getLangOpts().C2x 3943 ? diag::warn_c2x_compat_bitint_suffix 3944 : diag::ext_c2x_bitint_suffix); 3945 3946 // Get the value in the widest-possible width. What is "widest" depends on 3947 // whether the literal is a bit-precise integer or not. For a bit-precise 3948 // integer type, try to scan the source to determine how many bits are 3949 // needed to represent the value. This may seem a bit expensive, but trying 3950 // to get the integer value from an overly-wide APInt is *extremely* 3951 // expensive, so the naive approach of assuming 3952 // llvm::IntegerType::MAX_INT_BITS is a big performance hit. 3953 unsigned BitsNeeded = 3954 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded( 3955 Literal.getLiteralDigits(), Literal.getRadix()) 3956 : Context.getTargetInfo().getIntMaxTWidth(); 3957 llvm::APInt ResultVal(BitsNeeded, 0); 3958 3959 if (Literal.GetIntegerValue(ResultVal)) { 3960 // If this value didn't fit into uintmax_t, error and force to ull. 3961 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3962 << /* Unsigned */ 1; 3963 Ty = Context.UnsignedLongLongTy; 3964 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3965 "long long is not intmax_t?"); 3966 } else { 3967 // If this value fits into a ULL, try to figure out what else it fits into 3968 // according to the rules of C99 6.4.4.1p5. 3969 3970 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3971 // be an unsigned int. 3972 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3973 3974 // Check from smallest to largest, picking the smallest type we can. 3975 unsigned Width = 0; 3976 3977 // Microsoft specific integer suffixes are explicitly sized. 3978 if (Literal.MicrosoftInteger) { 3979 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3980 Width = 8; 3981 Ty = Context.CharTy; 3982 } else { 3983 Width = Literal.MicrosoftInteger; 3984 Ty = Context.getIntTypeForBitwidth(Width, 3985 /*Signed=*/!Literal.isUnsigned); 3986 } 3987 } 3988 3989 // Bit-precise integer literals are automagically-sized based on the 3990 // width required by the literal. 3991 if (Literal.isBitInt) { 3992 // The signed version has one more bit for the sign value. There are no 3993 // zero-width bit-precise integers, even if the literal value is 0. 3994 Width = std::max(ResultVal.getActiveBits(), 1u) + 3995 (Literal.isUnsigned ? 0u : 1u); 3996 3997 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, 3998 // and reset the type to the largest supported width. 3999 unsigned int MaxBitIntWidth = 4000 Context.getTargetInfo().getMaxBitIntWidth(); 4001 if (Width > MaxBitIntWidth) { 4002 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 4003 << Literal.isUnsigned; 4004 Width = MaxBitIntWidth; 4005 } 4006 4007 // Reset the result value to the smaller APInt and select the correct 4008 // type to be used. Note, we zext even for signed values because the 4009 // literal itself is always an unsigned value (a preceeding - is a 4010 // unary operator, not part of the literal). 4011 ResultVal = ResultVal.zextOrTrunc(Width); 4012 Ty = Context.getBitIntType(Literal.isUnsigned, Width); 4013 } 4014 4015 // Check C++2b size_t literals. 4016 if (Literal.isSizeT) { 4017 assert(!Literal.MicrosoftInteger && 4018 "size_t literals can't be Microsoft literals"); 4019 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 4020 Context.getTargetInfo().getSizeType()); 4021 4022 // Does it fit in size_t? 4023 if (ResultVal.isIntN(SizeTSize)) { 4024 // Does it fit in ssize_t? 4025 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 4026 Ty = Context.getSignedSizeType(); 4027 else if (AllowUnsigned) 4028 Ty = Context.getSizeType(); 4029 Width = SizeTSize; 4030 } 4031 } 4032 4033 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 4034 !Literal.isSizeT) { 4035 // Are int/unsigned possibilities? 4036 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 4037 4038 // Does it fit in a unsigned int? 4039 if (ResultVal.isIntN(IntSize)) { 4040 // Does it fit in a signed int? 4041 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 4042 Ty = Context.IntTy; 4043 else if (AllowUnsigned) 4044 Ty = Context.UnsignedIntTy; 4045 Width = IntSize; 4046 } 4047 } 4048 4049 // Are long/unsigned long possibilities? 4050 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 4051 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 4052 4053 // Does it fit in a unsigned long? 4054 if (ResultVal.isIntN(LongSize)) { 4055 // Does it fit in a signed long? 4056 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 4057 Ty = Context.LongTy; 4058 else if (AllowUnsigned) 4059 Ty = Context.UnsignedLongTy; 4060 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 4061 // is compatible. 4062 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 4063 const unsigned LongLongSize = 4064 Context.getTargetInfo().getLongLongWidth(); 4065 Diag(Tok.getLocation(), 4066 getLangOpts().CPlusPlus 4067 ? Literal.isLong 4068 ? diag::warn_old_implicitly_unsigned_long_cxx 4069 : /*C++98 UB*/ diag:: 4070 ext_old_implicitly_unsigned_long_cxx 4071 : diag::warn_old_implicitly_unsigned_long) 4072 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4073 : /*will be ill-formed*/ 1); 4074 Ty = Context.UnsignedLongTy; 4075 } 4076 Width = LongSize; 4077 } 4078 } 4079 4080 // Check long long if needed. 4081 if (Ty.isNull() && !Literal.isSizeT) { 4082 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4083 4084 // Does it fit in a unsigned long long? 4085 if (ResultVal.isIntN(LongLongSize)) { 4086 // Does it fit in a signed long long? 4087 // To be compatible with MSVC, hex integer literals ending with the 4088 // LL or i64 suffix are always signed in Microsoft mode. 4089 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4090 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4091 Ty = Context.LongLongTy; 4092 else if (AllowUnsigned) 4093 Ty = Context.UnsignedLongLongTy; 4094 Width = LongLongSize; 4095 } 4096 } 4097 4098 // If we still couldn't decide a type, we either have 'size_t' literal 4099 // that is out of range, or a decimal literal that does not fit in a 4100 // signed long long and has no U suffix. 4101 if (Ty.isNull()) { 4102 if (Literal.isSizeT) 4103 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4104 << Literal.isUnsigned; 4105 else 4106 Diag(Tok.getLocation(), 4107 diag::ext_integer_literal_too_large_for_signed); 4108 Ty = Context.UnsignedLongLongTy; 4109 Width = Context.getTargetInfo().getLongLongWidth(); 4110 } 4111 4112 if (ResultVal.getBitWidth() != Width) 4113 ResultVal = ResultVal.trunc(Width); 4114 } 4115 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4116 } 4117 4118 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4119 if (Literal.isImaginary) { 4120 Res = new (Context) ImaginaryLiteral(Res, 4121 Context.getComplexType(Res->getType())); 4122 4123 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4124 } 4125 return Res; 4126 } 4127 4128 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4129 assert(E && "ActOnParenExpr() missing expr"); 4130 QualType ExprTy = E->getType(); 4131 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4132 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4133 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4134 return new (Context) ParenExpr(L, R, E); 4135 } 4136 4137 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4138 SourceLocation Loc, 4139 SourceRange ArgRange) { 4140 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4141 // scalar or vector data type argument..." 4142 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4143 // type (C99 6.2.5p18) or void. 4144 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4145 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4146 << T << ArgRange; 4147 return true; 4148 } 4149 4150 assert((T->isVoidType() || !T->isIncompleteType()) && 4151 "Scalar types should always be complete"); 4152 return false; 4153 } 4154 4155 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4156 SourceLocation Loc, 4157 SourceRange ArgRange, 4158 UnaryExprOrTypeTrait TraitKind) { 4159 // Invalid types must be hard errors for SFINAE in C++. 4160 if (S.LangOpts.CPlusPlus) 4161 return true; 4162 4163 // C99 6.5.3.4p1: 4164 if (T->isFunctionType() && 4165 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4166 TraitKind == UETT_PreferredAlignOf)) { 4167 // sizeof(function)/alignof(function) is allowed as an extension. 4168 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4169 << getTraitSpelling(TraitKind) << ArgRange; 4170 return false; 4171 } 4172 4173 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4174 // this is an error (OpenCL v1.1 s6.3.k) 4175 if (T->isVoidType()) { 4176 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4177 : diag::ext_sizeof_alignof_void_type; 4178 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4179 return false; 4180 } 4181 4182 return true; 4183 } 4184 4185 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4186 SourceLocation Loc, 4187 SourceRange ArgRange, 4188 UnaryExprOrTypeTrait TraitKind) { 4189 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4190 // runtime doesn't allow it. 4191 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4192 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4193 << T << (TraitKind == UETT_SizeOf) 4194 << ArgRange; 4195 return true; 4196 } 4197 4198 return false; 4199 } 4200 4201 /// Check whether E is a pointer from a decayed array type (the decayed 4202 /// pointer type is equal to T) and emit a warning if it is. 4203 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4204 Expr *E) { 4205 // Don't warn if the operation changed the type. 4206 if (T != E->getType()) 4207 return; 4208 4209 // Now look for array decays. 4210 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4211 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4212 return; 4213 4214 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4215 << ICE->getType() 4216 << ICE->getSubExpr()->getType(); 4217 } 4218 4219 /// Check the constraints on expression operands to unary type expression 4220 /// and type traits. 4221 /// 4222 /// Completes any types necessary and validates the constraints on the operand 4223 /// expression. The logic mostly mirrors the type-based overload, but may modify 4224 /// the expression as it completes the type for that expression through template 4225 /// instantiation, etc. 4226 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4227 UnaryExprOrTypeTrait ExprKind) { 4228 QualType ExprTy = E->getType(); 4229 assert(!ExprTy->isReferenceType()); 4230 4231 bool IsUnevaluatedOperand = 4232 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4233 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4234 if (IsUnevaluatedOperand) { 4235 ExprResult Result = CheckUnevaluatedOperand(E); 4236 if (Result.isInvalid()) 4237 return true; 4238 E = Result.get(); 4239 } 4240 4241 // The operand for sizeof and alignof is in an unevaluated expression context, 4242 // so side effects could result in unintended consequences. 4243 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4244 // used to build SFINAE gadgets. 4245 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4246 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4247 !E->isInstantiationDependent() && 4248 E->HasSideEffects(Context, false)) 4249 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4250 4251 if (ExprKind == UETT_VecStep) 4252 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4253 E->getSourceRange()); 4254 4255 // Explicitly list some types as extensions. 4256 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4257 E->getSourceRange(), ExprKind)) 4258 return false; 4259 4260 // 'alignof' applied to an expression only requires the base element type of 4261 // the expression to be complete. 'sizeof' requires the expression's type to 4262 // be complete (and will attempt to complete it if it's an array of unknown 4263 // bound). 4264 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4265 if (RequireCompleteSizedType( 4266 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4267 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4268 getTraitSpelling(ExprKind), E->getSourceRange())) 4269 return true; 4270 } else { 4271 if (RequireCompleteSizedExprType( 4272 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4273 getTraitSpelling(ExprKind), E->getSourceRange())) 4274 return true; 4275 } 4276 4277 // Completing the expression's type may have changed it. 4278 ExprTy = E->getType(); 4279 assert(!ExprTy->isReferenceType()); 4280 4281 if (ExprTy->isFunctionType()) { 4282 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4283 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4284 return true; 4285 } 4286 4287 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4288 E->getSourceRange(), ExprKind)) 4289 return true; 4290 4291 if (ExprKind == UETT_SizeOf) { 4292 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4293 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4294 QualType OType = PVD->getOriginalType(); 4295 QualType Type = PVD->getType(); 4296 if (Type->isPointerType() && OType->isArrayType()) { 4297 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4298 << Type << OType; 4299 Diag(PVD->getLocation(), diag::note_declared_at); 4300 } 4301 } 4302 } 4303 4304 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4305 // decays into a pointer and returns an unintended result. This is most 4306 // likely a typo for "sizeof(array) op x". 4307 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4308 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4309 BO->getLHS()); 4310 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4311 BO->getRHS()); 4312 } 4313 } 4314 4315 return false; 4316 } 4317 4318 /// Check the constraints on operands to unary expression and type 4319 /// traits. 4320 /// 4321 /// This will complete any types necessary, and validate the various constraints 4322 /// on those operands. 4323 /// 4324 /// The UsualUnaryConversions() function is *not* called by this routine. 4325 /// C99 6.3.2.1p[2-4] all state: 4326 /// Except when it is the operand of the sizeof operator ... 4327 /// 4328 /// C++ [expr.sizeof]p4 4329 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4330 /// standard conversions are not applied to the operand of sizeof. 4331 /// 4332 /// This policy is followed for all of the unary trait expressions. 4333 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4334 SourceLocation OpLoc, 4335 SourceRange ExprRange, 4336 UnaryExprOrTypeTrait ExprKind) { 4337 if (ExprType->isDependentType()) 4338 return false; 4339 4340 // C++ [expr.sizeof]p2: 4341 // When applied to a reference or a reference type, the result 4342 // is the size of the referenced type. 4343 // C++11 [expr.alignof]p3: 4344 // When alignof is applied to a reference type, the result 4345 // shall be the alignment of the referenced type. 4346 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4347 ExprType = Ref->getPointeeType(); 4348 4349 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4350 // When alignof or _Alignof is applied to an array type, the result 4351 // is the alignment of the element type. 4352 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4353 ExprKind == UETT_OpenMPRequiredSimdAlign) 4354 ExprType = Context.getBaseElementType(ExprType); 4355 4356 if (ExprKind == UETT_VecStep) 4357 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4358 4359 // Explicitly list some types as extensions. 4360 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4361 ExprKind)) 4362 return false; 4363 4364 if (RequireCompleteSizedType( 4365 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4366 getTraitSpelling(ExprKind), ExprRange)) 4367 return true; 4368 4369 if (ExprType->isFunctionType()) { 4370 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4371 << getTraitSpelling(ExprKind) << ExprRange; 4372 return true; 4373 } 4374 4375 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4376 ExprKind)) 4377 return true; 4378 4379 return false; 4380 } 4381 4382 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4383 // Cannot know anything else if the expression is dependent. 4384 if (E->isTypeDependent()) 4385 return false; 4386 4387 if (E->getObjectKind() == OK_BitField) { 4388 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4389 << 1 << E->getSourceRange(); 4390 return true; 4391 } 4392 4393 ValueDecl *D = nullptr; 4394 Expr *Inner = E->IgnoreParens(); 4395 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4396 D = DRE->getDecl(); 4397 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4398 D = ME->getMemberDecl(); 4399 } 4400 4401 // If it's a field, require the containing struct to have a 4402 // complete definition so that we can compute the layout. 4403 // 4404 // This can happen in C++11 onwards, either by naming the member 4405 // in a way that is not transformed into a member access expression 4406 // (in an unevaluated operand, for instance), or by naming the member 4407 // in a trailing-return-type. 4408 // 4409 // For the record, since __alignof__ on expressions is a GCC 4410 // extension, GCC seems to permit this but always gives the 4411 // nonsensical answer 0. 4412 // 4413 // We don't really need the layout here --- we could instead just 4414 // directly check for all the appropriate alignment-lowing 4415 // attributes --- but that would require duplicating a lot of 4416 // logic that just isn't worth duplicating for such a marginal 4417 // use-case. 4418 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4419 // Fast path this check, since we at least know the record has a 4420 // definition if we can find a member of it. 4421 if (!FD->getParent()->isCompleteDefinition()) { 4422 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4423 << E->getSourceRange(); 4424 return true; 4425 } 4426 4427 // Otherwise, if it's a field, and the field doesn't have 4428 // reference type, then it must have a complete type (or be a 4429 // flexible array member, which we explicitly want to 4430 // white-list anyway), which makes the following checks trivial. 4431 if (!FD->getType()->isReferenceType()) 4432 return false; 4433 } 4434 4435 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4436 } 4437 4438 bool Sema::CheckVecStepExpr(Expr *E) { 4439 E = E->IgnoreParens(); 4440 4441 // Cannot know anything else if the expression is dependent. 4442 if (E->isTypeDependent()) 4443 return false; 4444 4445 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4446 } 4447 4448 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4449 CapturingScopeInfo *CSI) { 4450 assert(T->isVariablyModifiedType()); 4451 assert(CSI != nullptr); 4452 4453 // We're going to walk down into the type and look for VLA expressions. 4454 do { 4455 const Type *Ty = T.getTypePtr(); 4456 switch (Ty->getTypeClass()) { 4457 #define TYPE(Class, Base) 4458 #define ABSTRACT_TYPE(Class, Base) 4459 #define NON_CANONICAL_TYPE(Class, Base) 4460 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4461 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4462 #include "clang/AST/TypeNodes.inc" 4463 T = QualType(); 4464 break; 4465 // These types are never variably-modified. 4466 case Type::Builtin: 4467 case Type::Complex: 4468 case Type::Vector: 4469 case Type::ExtVector: 4470 case Type::ConstantMatrix: 4471 case Type::Record: 4472 case Type::Enum: 4473 case Type::Elaborated: 4474 case Type::TemplateSpecialization: 4475 case Type::ObjCObject: 4476 case Type::ObjCInterface: 4477 case Type::ObjCObjectPointer: 4478 case Type::ObjCTypeParam: 4479 case Type::Pipe: 4480 case Type::BitInt: 4481 llvm_unreachable("type class is never variably-modified!"); 4482 case Type::Adjusted: 4483 T = cast<AdjustedType>(Ty)->getOriginalType(); 4484 break; 4485 case Type::Decayed: 4486 T = cast<DecayedType>(Ty)->getPointeeType(); 4487 break; 4488 case Type::Pointer: 4489 T = cast<PointerType>(Ty)->getPointeeType(); 4490 break; 4491 case Type::BlockPointer: 4492 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4493 break; 4494 case Type::LValueReference: 4495 case Type::RValueReference: 4496 T = cast<ReferenceType>(Ty)->getPointeeType(); 4497 break; 4498 case Type::MemberPointer: 4499 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4500 break; 4501 case Type::ConstantArray: 4502 case Type::IncompleteArray: 4503 // Losing element qualification here is fine. 4504 T = cast<ArrayType>(Ty)->getElementType(); 4505 break; 4506 case Type::VariableArray: { 4507 // Losing element qualification here is fine. 4508 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4509 4510 // Unknown size indication requires no size computation. 4511 // Otherwise, evaluate and record it. 4512 auto Size = VAT->getSizeExpr(); 4513 if (Size && !CSI->isVLATypeCaptured(VAT) && 4514 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4515 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4516 4517 T = VAT->getElementType(); 4518 break; 4519 } 4520 case Type::FunctionProto: 4521 case Type::FunctionNoProto: 4522 T = cast<FunctionType>(Ty)->getReturnType(); 4523 break; 4524 case Type::Paren: 4525 case Type::TypeOf: 4526 case Type::UnaryTransform: 4527 case Type::Attributed: 4528 case Type::BTFTagAttributed: 4529 case Type::SubstTemplateTypeParm: 4530 case Type::MacroQualified: 4531 // Keep walking after single level desugaring. 4532 T = T.getSingleStepDesugaredType(Context); 4533 break; 4534 case Type::Typedef: 4535 T = cast<TypedefType>(Ty)->desugar(); 4536 break; 4537 case Type::Decltype: 4538 T = cast<DecltypeType>(Ty)->desugar(); 4539 break; 4540 case Type::Using: 4541 T = cast<UsingType>(Ty)->desugar(); 4542 break; 4543 case Type::Auto: 4544 case Type::DeducedTemplateSpecialization: 4545 T = cast<DeducedType>(Ty)->getDeducedType(); 4546 break; 4547 case Type::TypeOfExpr: 4548 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4549 break; 4550 case Type::Atomic: 4551 T = cast<AtomicType>(Ty)->getValueType(); 4552 break; 4553 } 4554 } while (!T.isNull() && T->isVariablyModifiedType()); 4555 } 4556 4557 /// Build a sizeof or alignof expression given a type operand. 4558 ExprResult 4559 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4560 SourceLocation OpLoc, 4561 UnaryExprOrTypeTrait ExprKind, 4562 SourceRange R) { 4563 if (!TInfo) 4564 return ExprError(); 4565 4566 QualType T = TInfo->getType(); 4567 4568 if (!T->isDependentType() && 4569 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4570 return ExprError(); 4571 4572 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4573 if (auto *TT = T->getAs<TypedefType>()) { 4574 for (auto I = FunctionScopes.rbegin(), 4575 E = std::prev(FunctionScopes.rend()); 4576 I != E; ++I) { 4577 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4578 if (CSI == nullptr) 4579 break; 4580 DeclContext *DC = nullptr; 4581 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4582 DC = LSI->CallOperator; 4583 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4584 DC = CRSI->TheCapturedDecl; 4585 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4586 DC = BSI->TheDecl; 4587 if (DC) { 4588 if (DC->containsDecl(TT->getDecl())) 4589 break; 4590 captureVariablyModifiedType(Context, T, CSI); 4591 } 4592 } 4593 } 4594 } 4595 4596 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4597 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && 4598 TInfo->getType()->isVariablyModifiedType()) 4599 TInfo = TransformToPotentiallyEvaluated(TInfo); 4600 4601 return new (Context) UnaryExprOrTypeTraitExpr( 4602 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4603 } 4604 4605 /// Build a sizeof or alignof expression given an expression 4606 /// operand. 4607 ExprResult 4608 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4609 UnaryExprOrTypeTrait ExprKind) { 4610 ExprResult PE = CheckPlaceholderExpr(E); 4611 if (PE.isInvalid()) 4612 return ExprError(); 4613 4614 E = PE.get(); 4615 4616 // Verify that the operand is valid. 4617 bool isInvalid = false; 4618 if (E->isTypeDependent()) { 4619 // Delay type-checking for type-dependent expressions. 4620 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4621 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4622 } else if (ExprKind == UETT_VecStep) { 4623 isInvalid = CheckVecStepExpr(E); 4624 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4625 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4626 isInvalid = true; 4627 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4628 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4629 isInvalid = true; 4630 } else { 4631 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4632 } 4633 4634 if (isInvalid) 4635 return ExprError(); 4636 4637 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4638 PE = TransformToPotentiallyEvaluated(E); 4639 if (PE.isInvalid()) return ExprError(); 4640 E = PE.get(); 4641 } 4642 4643 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4644 return new (Context) UnaryExprOrTypeTraitExpr( 4645 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4646 } 4647 4648 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4649 /// expr and the same for @c alignof and @c __alignof 4650 /// Note that the ArgRange is invalid if isType is false. 4651 ExprResult 4652 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4653 UnaryExprOrTypeTrait ExprKind, bool IsType, 4654 void *TyOrEx, SourceRange ArgRange) { 4655 // If error parsing type, ignore. 4656 if (!TyOrEx) return ExprError(); 4657 4658 if (IsType) { 4659 TypeSourceInfo *TInfo; 4660 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4661 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4662 } 4663 4664 Expr *ArgEx = (Expr *)TyOrEx; 4665 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4666 return Result; 4667 } 4668 4669 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4670 bool IsReal) { 4671 if (V.get()->isTypeDependent()) 4672 return S.Context.DependentTy; 4673 4674 // _Real and _Imag are only l-values for normal l-values. 4675 if (V.get()->getObjectKind() != OK_Ordinary) { 4676 V = S.DefaultLvalueConversion(V.get()); 4677 if (V.isInvalid()) 4678 return QualType(); 4679 } 4680 4681 // These operators return the element type of a complex type. 4682 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4683 return CT->getElementType(); 4684 4685 // Otherwise they pass through real integer and floating point types here. 4686 if (V.get()->getType()->isArithmeticType()) 4687 return V.get()->getType(); 4688 4689 // Test for placeholders. 4690 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4691 if (PR.isInvalid()) return QualType(); 4692 if (PR.get() != V.get()) { 4693 V = PR; 4694 return CheckRealImagOperand(S, V, Loc, IsReal); 4695 } 4696 4697 // Reject anything else. 4698 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4699 << (IsReal ? "__real" : "__imag"); 4700 return QualType(); 4701 } 4702 4703 4704 4705 ExprResult 4706 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4707 tok::TokenKind Kind, Expr *Input) { 4708 UnaryOperatorKind Opc; 4709 switch (Kind) { 4710 default: llvm_unreachable("Unknown unary op!"); 4711 case tok::plusplus: Opc = UO_PostInc; break; 4712 case tok::minusminus: Opc = UO_PostDec; break; 4713 } 4714 4715 // Since this might is a postfix expression, get rid of ParenListExprs. 4716 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4717 if (Result.isInvalid()) return ExprError(); 4718 Input = Result.get(); 4719 4720 return BuildUnaryOp(S, OpLoc, Opc, Input); 4721 } 4722 4723 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4724 /// 4725 /// \return true on error 4726 static bool checkArithmeticOnObjCPointer(Sema &S, 4727 SourceLocation opLoc, 4728 Expr *op) { 4729 assert(op->getType()->isObjCObjectPointerType()); 4730 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4731 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4732 return false; 4733 4734 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4735 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4736 << op->getSourceRange(); 4737 return true; 4738 } 4739 4740 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4741 auto *BaseNoParens = Base->IgnoreParens(); 4742 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4743 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4744 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4745 } 4746 4747 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. 4748 // Typically this is DependentTy, but can sometimes be more precise. 4749 // 4750 // There are cases when we could determine a non-dependent type: 4751 // - LHS and RHS may have non-dependent types despite being type-dependent 4752 // (e.g. unbounded array static members of the current instantiation) 4753 // - one may be a dependent-sized array with known element type 4754 // - one may be a dependent-typed valid index (enum in current instantiation) 4755 // 4756 // We *always* return a dependent type, in such cases it is DependentTy. 4757 // This avoids creating type-dependent expressions with non-dependent types. 4758 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 4759 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, 4760 const ASTContext &Ctx) { 4761 assert(LHS->isTypeDependent() || RHS->isTypeDependent()); 4762 QualType LTy = LHS->getType(), RTy = RHS->getType(); 4763 QualType Result = Ctx.DependentTy; 4764 if (RTy->isIntegralOrUnscopedEnumerationType()) { 4765 if (const PointerType *PT = LTy->getAs<PointerType>()) 4766 Result = PT->getPointeeType(); 4767 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) 4768 Result = AT->getElementType(); 4769 } else if (LTy->isIntegralOrUnscopedEnumerationType()) { 4770 if (const PointerType *PT = RTy->getAs<PointerType>()) 4771 Result = PT->getPointeeType(); 4772 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) 4773 Result = AT->getElementType(); 4774 } 4775 // Ensure we return a dependent type. 4776 return Result->isDependentType() ? Result : Ctx.DependentTy; 4777 } 4778 4779 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args); 4780 4781 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, 4782 SourceLocation lbLoc, 4783 MultiExprArg ArgExprs, 4784 SourceLocation rbLoc) { 4785 4786 if (base && !base->getType().isNull() && 4787 base->hasPlaceholderType(BuiltinType::OMPArraySection)) 4788 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(), 4789 SourceLocation(), /*Length*/ nullptr, 4790 /*Stride=*/nullptr, rbLoc); 4791 4792 // Since this might be a postfix expression, get rid of ParenListExprs. 4793 if (isa<ParenListExpr>(base)) { 4794 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4795 if (result.isInvalid()) 4796 return ExprError(); 4797 base = result.get(); 4798 } 4799 4800 // Check if base and idx form a MatrixSubscriptExpr. 4801 // 4802 // Helper to check for comma expressions, which are not allowed as indices for 4803 // matrix subscript expressions. 4804 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4805 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4806 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4807 << SourceRange(base->getBeginLoc(), rbLoc); 4808 return true; 4809 } 4810 return false; 4811 }; 4812 // The matrix subscript operator ([][])is considered a single operator. 4813 // Separating the index expressions by parenthesis is not allowed. 4814 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) && 4815 !isa<MatrixSubscriptExpr>(base)) { 4816 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4817 << SourceRange(base->getBeginLoc(), rbLoc); 4818 return ExprError(); 4819 } 4820 // If the base is a MatrixSubscriptExpr, try to create a new 4821 // MatrixSubscriptExpr. 4822 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4823 if (matSubscriptE) { 4824 assert(ArgExprs.size() == 1); 4825 if (CheckAndReportCommaError(ArgExprs.front())) 4826 return ExprError(); 4827 4828 assert(matSubscriptE->isIncomplete() && 4829 "base has to be an incomplete matrix subscript"); 4830 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(), 4831 matSubscriptE->getRowIdx(), 4832 ArgExprs.front(), rbLoc); 4833 } 4834 4835 // Handle any non-overload placeholder types in the base and index 4836 // expressions. We can't handle overloads here because the other 4837 // operand might be an overloadable type, in which case the overload 4838 // resolution for the operator overload should get the first crack 4839 // at the overload. 4840 bool IsMSPropertySubscript = false; 4841 if (base->getType()->isNonOverloadPlaceholderType()) { 4842 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4843 if (!IsMSPropertySubscript) { 4844 ExprResult result = CheckPlaceholderExpr(base); 4845 if (result.isInvalid()) 4846 return ExprError(); 4847 base = result.get(); 4848 } 4849 } 4850 4851 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4852 if (base->getType()->isMatrixType()) { 4853 assert(ArgExprs.size() == 1); 4854 if (CheckAndReportCommaError(ArgExprs.front())) 4855 return ExprError(); 4856 4857 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr, 4858 rbLoc); 4859 } 4860 4861 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { 4862 Expr *idx = ArgExprs[0]; 4863 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4864 (isa<CXXOperatorCallExpr>(idx) && 4865 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) { 4866 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4867 << SourceRange(base->getBeginLoc(), rbLoc); 4868 } 4869 } 4870 4871 if (ArgExprs.size() == 1 && 4872 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { 4873 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]); 4874 if (result.isInvalid()) 4875 return ExprError(); 4876 ArgExprs[0] = result.get(); 4877 } else { 4878 if (checkArgsForPlaceholders(*this, ArgExprs)) 4879 return ExprError(); 4880 } 4881 4882 // Build an unanalyzed expression if either operand is type-dependent. 4883 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && 4884 (base->isTypeDependent() || 4885 Expr::hasAnyTypeDependentArguments(ArgExprs))) { 4886 return new (Context) ArraySubscriptExpr( 4887 base, ArgExprs.front(), 4888 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()), 4889 VK_LValue, OK_Ordinary, rbLoc); 4890 } 4891 4892 // MSDN, property (C++) 4893 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4894 // This attribute can also be used in the declaration of an empty array in a 4895 // class or structure definition. For example: 4896 // __declspec(property(get=GetX, put=PutX)) int x[]; 4897 // The above statement indicates that x[] can be used with one or more array 4898 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4899 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4900 if (IsMSPropertySubscript) { 4901 assert(ArgExprs.size() == 1); 4902 // Build MS property subscript expression if base is MS property reference 4903 // or MS property subscript. 4904 return new (Context) 4905 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, 4906 VK_LValue, OK_Ordinary, rbLoc); 4907 } 4908 4909 // Use C++ overloaded-operator rules if either operand has record 4910 // type. The spec says to do this if either type is *overloadable*, 4911 // but enum types can't declare subscript operators or conversion 4912 // operators, so there's nothing interesting for overload resolution 4913 // to do if there aren't any record types involved. 4914 // 4915 // ObjC pointers have their own subscripting logic that is not tied 4916 // to overload resolution and so should not take this path. 4917 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && 4918 ((base->getType()->isRecordType() || 4919 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) { 4920 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs); 4921 } 4922 4923 ExprResult Res = 4924 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc); 4925 4926 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4927 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4928 4929 return Res; 4930 } 4931 4932 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4933 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4934 InitializationKind Kind = 4935 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4936 InitializationSequence InitSeq(*this, Entity, Kind, E); 4937 return InitSeq.Perform(*this, Entity, Kind, E); 4938 } 4939 4940 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4941 Expr *ColumnIdx, 4942 SourceLocation RBLoc) { 4943 ExprResult BaseR = CheckPlaceholderExpr(Base); 4944 if (BaseR.isInvalid()) 4945 return BaseR; 4946 Base = BaseR.get(); 4947 4948 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4949 if (RowR.isInvalid()) 4950 return RowR; 4951 RowIdx = RowR.get(); 4952 4953 if (!ColumnIdx) 4954 return new (Context) MatrixSubscriptExpr( 4955 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4956 4957 // Build an unanalyzed expression if any of the operands is type-dependent. 4958 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4959 ColumnIdx->isTypeDependent()) 4960 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4961 Context.DependentTy, RBLoc); 4962 4963 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4964 if (ColumnR.isInvalid()) 4965 return ColumnR; 4966 ColumnIdx = ColumnR.get(); 4967 4968 // Check that IndexExpr is an integer expression. If it is a constant 4969 // expression, check that it is less than Dim (= the number of elements in the 4970 // corresponding dimension). 4971 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4972 bool IsColumnIdx) -> Expr * { 4973 if (!IndexExpr->getType()->isIntegerType() && 4974 !IndexExpr->isTypeDependent()) { 4975 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4976 << IsColumnIdx; 4977 return nullptr; 4978 } 4979 4980 if (Optional<llvm::APSInt> Idx = 4981 IndexExpr->getIntegerConstantExpr(Context)) { 4982 if ((*Idx < 0 || *Idx >= Dim)) { 4983 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4984 << IsColumnIdx << Dim; 4985 return nullptr; 4986 } 4987 } 4988 4989 ExprResult ConvExpr = 4990 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4991 assert(!ConvExpr.isInvalid() && 4992 "should be able to convert any integer type to size type"); 4993 return ConvExpr.get(); 4994 }; 4995 4996 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4997 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4998 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4999 if (!RowIdx || !ColumnIdx) 5000 return ExprError(); 5001 5002 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 5003 MTy->getElementType(), RBLoc); 5004 } 5005 5006 void Sema::CheckAddressOfNoDeref(const Expr *E) { 5007 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5008 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 5009 5010 // For expressions like `&(*s).b`, the base is recorded and what should be 5011 // checked. 5012 const MemberExpr *Member = nullptr; 5013 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 5014 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 5015 5016 LastRecord.PossibleDerefs.erase(StrippedExpr); 5017 } 5018 5019 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 5020 if (isUnevaluatedContext()) 5021 return; 5022 5023 QualType ResultTy = E->getType(); 5024 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5025 5026 // Bail if the element is an array since it is not memory access. 5027 if (isa<ArrayType>(ResultTy)) 5028 return; 5029 5030 if (ResultTy->hasAttr(attr::NoDeref)) { 5031 LastRecord.PossibleDerefs.insert(E); 5032 return; 5033 } 5034 5035 // Check if the base type is a pointer to a member access of a struct 5036 // marked with noderef. 5037 const Expr *Base = E->getBase(); 5038 QualType BaseTy = Base->getType(); 5039 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 5040 // Not a pointer access 5041 return; 5042 5043 const MemberExpr *Member = nullptr; 5044 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 5045 Member->isArrow()) 5046 Base = Member->getBase(); 5047 5048 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 5049 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 5050 LastRecord.PossibleDerefs.insert(E); 5051 } 5052 } 5053 5054 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 5055 Expr *LowerBound, 5056 SourceLocation ColonLocFirst, 5057 SourceLocation ColonLocSecond, 5058 Expr *Length, Expr *Stride, 5059 SourceLocation RBLoc) { 5060 if (Base->hasPlaceholderType() && 5061 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5062 ExprResult Result = CheckPlaceholderExpr(Base); 5063 if (Result.isInvalid()) 5064 return ExprError(); 5065 Base = Result.get(); 5066 } 5067 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 5068 ExprResult Result = CheckPlaceholderExpr(LowerBound); 5069 if (Result.isInvalid()) 5070 return ExprError(); 5071 Result = DefaultLvalueConversion(Result.get()); 5072 if (Result.isInvalid()) 5073 return ExprError(); 5074 LowerBound = Result.get(); 5075 } 5076 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 5077 ExprResult Result = CheckPlaceholderExpr(Length); 5078 if (Result.isInvalid()) 5079 return ExprError(); 5080 Result = DefaultLvalueConversion(Result.get()); 5081 if (Result.isInvalid()) 5082 return ExprError(); 5083 Length = Result.get(); 5084 } 5085 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 5086 ExprResult Result = CheckPlaceholderExpr(Stride); 5087 if (Result.isInvalid()) 5088 return ExprError(); 5089 Result = DefaultLvalueConversion(Result.get()); 5090 if (Result.isInvalid()) 5091 return ExprError(); 5092 Stride = Result.get(); 5093 } 5094 5095 // Build an unanalyzed expression if either operand is type-dependent. 5096 if (Base->isTypeDependent() || 5097 (LowerBound && 5098 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 5099 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 5100 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 5101 return new (Context) OMPArraySectionExpr( 5102 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 5103 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5104 } 5105 5106 // Perform default conversions. 5107 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 5108 QualType ResultTy; 5109 if (OriginalTy->isAnyPointerType()) { 5110 ResultTy = OriginalTy->getPointeeType(); 5111 } else if (OriginalTy->isArrayType()) { 5112 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 5113 } else { 5114 return ExprError( 5115 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 5116 << Base->getSourceRange()); 5117 } 5118 // C99 6.5.2.1p1 5119 if (LowerBound) { 5120 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 5121 LowerBound); 5122 if (Res.isInvalid()) 5123 return ExprError(Diag(LowerBound->getExprLoc(), 5124 diag::err_omp_typecheck_section_not_integer) 5125 << 0 << LowerBound->getSourceRange()); 5126 LowerBound = Res.get(); 5127 5128 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5129 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5130 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5131 << 0 << LowerBound->getSourceRange(); 5132 } 5133 if (Length) { 5134 auto Res = 5135 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5136 if (Res.isInvalid()) 5137 return ExprError(Diag(Length->getExprLoc(), 5138 diag::err_omp_typecheck_section_not_integer) 5139 << 1 << Length->getSourceRange()); 5140 Length = Res.get(); 5141 5142 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5143 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5144 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5145 << 1 << Length->getSourceRange(); 5146 } 5147 if (Stride) { 5148 ExprResult Res = 5149 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5150 if (Res.isInvalid()) 5151 return ExprError(Diag(Stride->getExprLoc(), 5152 diag::err_omp_typecheck_section_not_integer) 5153 << 1 << Stride->getSourceRange()); 5154 Stride = Res.get(); 5155 5156 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5157 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5158 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5159 << 1 << Stride->getSourceRange(); 5160 } 5161 5162 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5163 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5164 // type. Note that functions are not objects, and that (in C99 parlance) 5165 // incomplete types are not object types. 5166 if (ResultTy->isFunctionType()) { 5167 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5168 << ResultTy << Base->getSourceRange(); 5169 return ExprError(); 5170 } 5171 5172 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5173 diag::err_omp_section_incomplete_type, Base)) 5174 return ExprError(); 5175 5176 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5177 Expr::EvalResult Result; 5178 if (LowerBound->EvaluateAsInt(Result, Context)) { 5179 // OpenMP 5.0, [2.1.5 Array Sections] 5180 // The array section must be a subset of the original array. 5181 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5182 if (LowerBoundValue.isNegative()) { 5183 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5184 << LowerBound->getSourceRange(); 5185 return ExprError(); 5186 } 5187 } 5188 } 5189 5190 if (Length) { 5191 Expr::EvalResult Result; 5192 if (Length->EvaluateAsInt(Result, Context)) { 5193 // OpenMP 5.0, [2.1.5 Array Sections] 5194 // The length must evaluate to non-negative integers. 5195 llvm::APSInt LengthValue = Result.Val.getInt(); 5196 if (LengthValue.isNegative()) { 5197 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5198 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5199 << Length->getSourceRange(); 5200 return ExprError(); 5201 } 5202 } 5203 } else if (ColonLocFirst.isValid() && 5204 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5205 !OriginalTy->isVariableArrayType()))) { 5206 // OpenMP 5.0, [2.1.5 Array Sections] 5207 // When the size of the array dimension is not known, the length must be 5208 // specified explicitly. 5209 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5210 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5211 return ExprError(); 5212 } 5213 5214 if (Stride) { 5215 Expr::EvalResult Result; 5216 if (Stride->EvaluateAsInt(Result, Context)) { 5217 // OpenMP 5.0, [2.1.5 Array Sections] 5218 // The stride must evaluate to a positive integer. 5219 llvm::APSInt StrideValue = Result.Val.getInt(); 5220 if (!StrideValue.isStrictlyPositive()) { 5221 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5222 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5223 << Stride->getSourceRange(); 5224 return ExprError(); 5225 } 5226 } 5227 } 5228 5229 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5230 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5231 if (Result.isInvalid()) 5232 return ExprError(); 5233 Base = Result.get(); 5234 } 5235 return new (Context) OMPArraySectionExpr( 5236 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5237 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5238 } 5239 5240 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5241 SourceLocation RParenLoc, 5242 ArrayRef<Expr *> Dims, 5243 ArrayRef<SourceRange> Brackets) { 5244 if (Base->hasPlaceholderType()) { 5245 ExprResult Result = CheckPlaceholderExpr(Base); 5246 if (Result.isInvalid()) 5247 return ExprError(); 5248 Result = DefaultLvalueConversion(Result.get()); 5249 if (Result.isInvalid()) 5250 return ExprError(); 5251 Base = Result.get(); 5252 } 5253 QualType BaseTy = Base->getType(); 5254 // Delay analysis of the types/expressions if instantiation/specialization is 5255 // required. 5256 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5257 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5258 LParenLoc, RParenLoc, Dims, Brackets); 5259 if (!BaseTy->isPointerType() || 5260 (!Base->isTypeDependent() && 5261 BaseTy->getPointeeType()->isIncompleteType())) 5262 return ExprError(Diag(Base->getExprLoc(), 5263 diag::err_omp_non_pointer_type_array_shaping_base) 5264 << Base->getSourceRange()); 5265 5266 SmallVector<Expr *, 4> NewDims; 5267 bool ErrorFound = false; 5268 for (Expr *Dim : Dims) { 5269 if (Dim->hasPlaceholderType()) { 5270 ExprResult Result = CheckPlaceholderExpr(Dim); 5271 if (Result.isInvalid()) { 5272 ErrorFound = true; 5273 continue; 5274 } 5275 Result = DefaultLvalueConversion(Result.get()); 5276 if (Result.isInvalid()) { 5277 ErrorFound = true; 5278 continue; 5279 } 5280 Dim = Result.get(); 5281 } 5282 if (!Dim->isTypeDependent()) { 5283 ExprResult Result = 5284 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5285 if (Result.isInvalid()) { 5286 ErrorFound = true; 5287 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5288 << Dim->getSourceRange(); 5289 continue; 5290 } 5291 Dim = Result.get(); 5292 Expr::EvalResult EvResult; 5293 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5294 // OpenMP 5.0, [2.1.4 Array Shaping] 5295 // Each si is an integral type expression that must evaluate to a 5296 // positive integer. 5297 llvm::APSInt Value = EvResult.Val.getInt(); 5298 if (!Value.isStrictlyPositive()) { 5299 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5300 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5301 << Dim->getSourceRange(); 5302 ErrorFound = true; 5303 continue; 5304 } 5305 } 5306 } 5307 NewDims.push_back(Dim); 5308 } 5309 if (ErrorFound) 5310 return ExprError(); 5311 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5312 LParenLoc, RParenLoc, NewDims, Brackets); 5313 } 5314 5315 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5316 SourceLocation LLoc, SourceLocation RLoc, 5317 ArrayRef<OMPIteratorData> Data) { 5318 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5319 bool IsCorrect = true; 5320 for (const OMPIteratorData &D : Data) { 5321 TypeSourceInfo *TInfo = nullptr; 5322 SourceLocation StartLoc; 5323 QualType DeclTy; 5324 if (!D.Type.getAsOpaquePtr()) { 5325 // OpenMP 5.0, 2.1.6 Iterators 5326 // In an iterator-specifier, if the iterator-type is not specified then 5327 // the type of that iterator is of int type. 5328 DeclTy = Context.IntTy; 5329 StartLoc = D.DeclIdentLoc; 5330 } else { 5331 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5332 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5333 } 5334 5335 bool IsDeclTyDependent = DeclTy->isDependentType() || 5336 DeclTy->containsUnexpandedParameterPack() || 5337 DeclTy->isInstantiationDependentType(); 5338 if (!IsDeclTyDependent) { 5339 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5340 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5341 // The iterator-type must be an integral or pointer type. 5342 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5343 << DeclTy; 5344 IsCorrect = false; 5345 continue; 5346 } 5347 if (DeclTy.isConstant(Context)) { 5348 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5349 // The iterator-type must not be const qualified. 5350 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5351 << DeclTy; 5352 IsCorrect = false; 5353 continue; 5354 } 5355 } 5356 5357 // Iterator declaration. 5358 assert(D.DeclIdent && "Identifier expected."); 5359 // Always try to create iterator declarator to avoid extra error messages 5360 // about unknown declarations use. 5361 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5362 D.DeclIdent, DeclTy, TInfo, SC_None); 5363 VD->setImplicit(); 5364 if (S) { 5365 // Check for conflicting previous declaration. 5366 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5367 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5368 ForVisibleRedeclaration); 5369 Previous.suppressDiagnostics(); 5370 LookupName(Previous, S); 5371 5372 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5373 /*AllowInlineNamespace=*/false); 5374 if (!Previous.empty()) { 5375 NamedDecl *Old = Previous.getRepresentativeDecl(); 5376 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5377 Diag(Old->getLocation(), diag::note_previous_definition); 5378 } else { 5379 PushOnScopeChains(VD, S); 5380 } 5381 } else { 5382 CurContext->addDecl(VD); 5383 } 5384 Expr *Begin = D.Range.Begin; 5385 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5386 ExprResult BeginRes = 5387 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5388 Begin = BeginRes.get(); 5389 } 5390 Expr *End = D.Range.End; 5391 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5392 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5393 End = EndRes.get(); 5394 } 5395 Expr *Step = D.Range.Step; 5396 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5397 if (!Step->getType()->isIntegralType(Context)) { 5398 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5399 << Step << Step->getSourceRange(); 5400 IsCorrect = false; 5401 continue; 5402 } 5403 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5404 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5405 // If the step expression of a range-specification equals zero, the 5406 // behavior is unspecified. 5407 if (Result && Result->isZero()) { 5408 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5409 << Step << Step->getSourceRange(); 5410 IsCorrect = false; 5411 continue; 5412 } 5413 } 5414 if (!Begin || !End || !IsCorrect) { 5415 IsCorrect = false; 5416 continue; 5417 } 5418 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5419 IDElem.IteratorDecl = VD; 5420 IDElem.AssignmentLoc = D.AssignLoc; 5421 IDElem.Range.Begin = Begin; 5422 IDElem.Range.End = End; 5423 IDElem.Range.Step = Step; 5424 IDElem.ColonLoc = D.ColonLoc; 5425 IDElem.SecondColonLoc = D.SecColonLoc; 5426 } 5427 if (!IsCorrect) { 5428 // Invalidate all created iterator declarations if error is found. 5429 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5430 if (Decl *ID = D.IteratorDecl) 5431 ID->setInvalidDecl(); 5432 } 5433 return ExprError(); 5434 } 5435 SmallVector<OMPIteratorHelperData, 4> Helpers; 5436 if (!CurContext->isDependentContext()) { 5437 // Build number of ityeration for each iteration range. 5438 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5439 // ((Begini-Stepi-1-Endi) / -Stepi); 5440 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5441 // (Endi - Begini) 5442 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5443 D.Range.Begin); 5444 if(!Res.isUsable()) { 5445 IsCorrect = false; 5446 continue; 5447 } 5448 ExprResult St, St1; 5449 if (D.Range.Step) { 5450 St = D.Range.Step; 5451 // (Endi - Begini) + Stepi 5452 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5453 if (!Res.isUsable()) { 5454 IsCorrect = false; 5455 continue; 5456 } 5457 // (Endi - Begini) + Stepi - 1 5458 Res = 5459 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5460 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5461 if (!Res.isUsable()) { 5462 IsCorrect = false; 5463 continue; 5464 } 5465 // ((Endi - Begini) + Stepi - 1) / Stepi 5466 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5467 if (!Res.isUsable()) { 5468 IsCorrect = false; 5469 continue; 5470 } 5471 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5472 // (Begini - Endi) 5473 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5474 D.Range.Begin, D.Range.End); 5475 if (!Res1.isUsable()) { 5476 IsCorrect = false; 5477 continue; 5478 } 5479 // (Begini - Endi) - Stepi 5480 Res1 = 5481 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5482 if (!Res1.isUsable()) { 5483 IsCorrect = false; 5484 continue; 5485 } 5486 // (Begini - Endi) - Stepi - 1 5487 Res1 = 5488 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5489 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5490 if (!Res1.isUsable()) { 5491 IsCorrect = false; 5492 continue; 5493 } 5494 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5495 Res1 = 5496 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5497 if (!Res1.isUsable()) { 5498 IsCorrect = false; 5499 continue; 5500 } 5501 // Stepi > 0. 5502 ExprResult CmpRes = 5503 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5504 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5505 if (!CmpRes.isUsable()) { 5506 IsCorrect = false; 5507 continue; 5508 } 5509 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5510 Res.get(), Res1.get()); 5511 if (!Res.isUsable()) { 5512 IsCorrect = false; 5513 continue; 5514 } 5515 } 5516 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5517 if (!Res.isUsable()) { 5518 IsCorrect = false; 5519 continue; 5520 } 5521 5522 // Build counter update. 5523 // Build counter. 5524 auto *CounterVD = 5525 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5526 D.IteratorDecl->getBeginLoc(), nullptr, 5527 Res.get()->getType(), nullptr, SC_None); 5528 CounterVD->setImplicit(); 5529 ExprResult RefRes = 5530 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5531 D.IteratorDecl->getBeginLoc()); 5532 // Build counter update. 5533 // I = Begini + counter * Stepi; 5534 ExprResult UpdateRes; 5535 if (D.Range.Step) { 5536 UpdateRes = CreateBuiltinBinOp( 5537 D.AssignmentLoc, BO_Mul, 5538 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5539 } else { 5540 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5541 } 5542 if (!UpdateRes.isUsable()) { 5543 IsCorrect = false; 5544 continue; 5545 } 5546 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5547 UpdateRes.get()); 5548 if (!UpdateRes.isUsable()) { 5549 IsCorrect = false; 5550 continue; 5551 } 5552 ExprResult VDRes = 5553 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5554 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5555 D.IteratorDecl->getBeginLoc()); 5556 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5557 UpdateRes.get()); 5558 if (!UpdateRes.isUsable()) { 5559 IsCorrect = false; 5560 continue; 5561 } 5562 UpdateRes = 5563 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5564 if (!UpdateRes.isUsable()) { 5565 IsCorrect = false; 5566 continue; 5567 } 5568 ExprResult CounterUpdateRes = 5569 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5570 if (!CounterUpdateRes.isUsable()) { 5571 IsCorrect = false; 5572 continue; 5573 } 5574 CounterUpdateRes = 5575 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5576 if (!CounterUpdateRes.isUsable()) { 5577 IsCorrect = false; 5578 continue; 5579 } 5580 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5581 HD.CounterVD = CounterVD; 5582 HD.Upper = Res.get(); 5583 HD.Update = UpdateRes.get(); 5584 HD.CounterUpdate = CounterUpdateRes.get(); 5585 } 5586 } else { 5587 Helpers.assign(ID.size(), {}); 5588 } 5589 if (!IsCorrect) { 5590 // Invalidate all created iterator declarations if error is found. 5591 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5592 if (Decl *ID = D.IteratorDecl) 5593 ID->setInvalidDecl(); 5594 } 5595 return ExprError(); 5596 } 5597 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5598 LLoc, RLoc, ID, Helpers); 5599 } 5600 5601 ExprResult 5602 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5603 Expr *Idx, SourceLocation RLoc) { 5604 Expr *LHSExp = Base; 5605 Expr *RHSExp = Idx; 5606 5607 ExprValueKind VK = VK_LValue; 5608 ExprObjectKind OK = OK_Ordinary; 5609 5610 // Per C++ core issue 1213, the result is an xvalue if either operand is 5611 // a non-lvalue array, and an lvalue otherwise. 5612 if (getLangOpts().CPlusPlus11) { 5613 for (auto *Op : {LHSExp, RHSExp}) { 5614 Op = Op->IgnoreImplicit(); 5615 if (Op->getType()->isArrayType() && !Op->isLValue()) 5616 VK = VK_XValue; 5617 } 5618 } 5619 5620 // Perform default conversions. 5621 if (!LHSExp->getType()->getAs<VectorType>()) { 5622 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5623 if (Result.isInvalid()) 5624 return ExprError(); 5625 LHSExp = Result.get(); 5626 } 5627 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5628 if (Result.isInvalid()) 5629 return ExprError(); 5630 RHSExp = Result.get(); 5631 5632 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5633 5634 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5635 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5636 // in the subscript position. As a result, we need to derive the array base 5637 // and index from the expression types. 5638 Expr *BaseExpr, *IndexExpr; 5639 QualType ResultType; 5640 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5641 BaseExpr = LHSExp; 5642 IndexExpr = RHSExp; 5643 ResultType = 5644 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); 5645 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5646 BaseExpr = LHSExp; 5647 IndexExpr = RHSExp; 5648 ResultType = PTy->getPointeeType(); 5649 } else if (const ObjCObjectPointerType *PTy = 5650 LHSTy->getAs<ObjCObjectPointerType>()) { 5651 BaseExpr = LHSExp; 5652 IndexExpr = RHSExp; 5653 5654 // Use custom logic if this should be the pseudo-object subscript 5655 // expression. 5656 if (!LangOpts.isSubscriptPointerArithmetic()) 5657 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5658 nullptr); 5659 5660 ResultType = PTy->getPointeeType(); 5661 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5662 // Handle the uncommon case of "123[Ptr]". 5663 BaseExpr = RHSExp; 5664 IndexExpr = LHSExp; 5665 ResultType = PTy->getPointeeType(); 5666 } else if (const ObjCObjectPointerType *PTy = 5667 RHSTy->getAs<ObjCObjectPointerType>()) { 5668 // Handle the uncommon case of "123[Ptr]". 5669 BaseExpr = RHSExp; 5670 IndexExpr = LHSExp; 5671 ResultType = PTy->getPointeeType(); 5672 if (!LangOpts.isSubscriptPointerArithmetic()) { 5673 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5674 << ResultType << BaseExpr->getSourceRange(); 5675 return ExprError(); 5676 } 5677 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5678 BaseExpr = LHSExp; // vectors: V[123] 5679 IndexExpr = RHSExp; 5680 // We apply C++ DR1213 to vector subscripting too. 5681 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5682 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5683 if (Materialized.isInvalid()) 5684 return ExprError(); 5685 LHSExp = Materialized.get(); 5686 } 5687 VK = LHSExp->getValueKind(); 5688 if (VK != VK_PRValue) 5689 OK = OK_VectorComponent; 5690 5691 ResultType = VTy->getElementType(); 5692 QualType BaseType = BaseExpr->getType(); 5693 Qualifiers BaseQuals = BaseType.getQualifiers(); 5694 Qualifiers MemberQuals = ResultType.getQualifiers(); 5695 Qualifiers Combined = BaseQuals + MemberQuals; 5696 if (Combined != MemberQuals) 5697 ResultType = Context.getQualifiedType(ResultType, Combined); 5698 } else if (LHSTy->isBuiltinType() && 5699 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) { 5700 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>(); 5701 if (BTy->isSVEBool()) 5702 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t) 5703 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5704 5705 BaseExpr = LHSExp; 5706 IndexExpr = RHSExp; 5707 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5708 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5709 if (Materialized.isInvalid()) 5710 return ExprError(); 5711 LHSExp = Materialized.get(); 5712 } 5713 VK = LHSExp->getValueKind(); 5714 if (VK != VK_PRValue) 5715 OK = OK_VectorComponent; 5716 5717 ResultType = BTy->getSveEltType(Context); 5718 5719 QualType BaseType = BaseExpr->getType(); 5720 Qualifiers BaseQuals = BaseType.getQualifiers(); 5721 Qualifiers MemberQuals = ResultType.getQualifiers(); 5722 Qualifiers Combined = BaseQuals + MemberQuals; 5723 if (Combined != MemberQuals) 5724 ResultType = Context.getQualifiedType(ResultType, Combined); 5725 } else if (LHSTy->isArrayType()) { 5726 // If we see an array that wasn't promoted by 5727 // DefaultFunctionArrayLvalueConversion, it must be an array that 5728 // wasn't promoted because of the C90 rule that doesn't 5729 // allow promoting non-lvalue arrays. Warn, then 5730 // force the promotion here. 5731 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5732 << LHSExp->getSourceRange(); 5733 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5734 CK_ArrayToPointerDecay).get(); 5735 LHSTy = LHSExp->getType(); 5736 5737 BaseExpr = LHSExp; 5738 IndexExpr = RHSExp; 5739 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5740 } else if (RHSTy->isArrayType()) { 5741 // Same as previous, except for 123[f().a] case 5742 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5743 << RHSExp->getSourceRange(); 5744 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5745 CK_ArrayToPointerDecay).get(); 5746 RHSTy = RHSExp->getType(); 5747 5748 BaseExpr = RHSExp; 5749 IndexExpr = LHSExp; 5750 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5751 } else { 5752 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5753 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5754 } 5755 // C99 6.5.2.1p1 5756 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5757 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5758 << IndexExpr->getSourceRange()); 5759 5760 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5761 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5762 && !IndexExpr->isTypeDependent()) 5763 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5764 5765 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5766 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5767 // type. Note that Functions are not objects, and that (in C99 parlance) 5768 // incomplete types are not object types. 5769 if (ResultType->isFunctionType()) { 5770 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5771 << ResultType << BaseExpr->getSourceRange(); 5772 return ExprError(); 5773 } 5774 5775 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5776 // GNU extension: subscripting on pointer to void 5777 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5778 << BaseExpr->getSourceRange(); 5779 5780 // C forbids expressions of unqualified void type from being l-values. 5781 // See IsCForbiddenLValueType. 5782 if (!ResultType.hasQualifiers()) 5783 VK = VK_PRValue; 5784 } else if (!ResultType->isDependentType() && 5785 RequireCompleteSizedType( 5786 LLoc, ResultType, 5787 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5788 return ExprError(); 5789 5790 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5791 !ResultType.isCForbiddenLValueType()); 5792 5793 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5794 FunctionScopes.size() > 1) { 5795 if (auto *TT = 5796 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5797 for (auto I = FunctionScopes.rbegin(), 5798 E = std::prev(FunctionScopes.rend()); 5799 I != E; ++I) { 5800 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5801 if (CSI == nullptr) 5802 break; 5803 DeclContext *DC = nullptr; 5804 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5805 DC = LSI->CallOperator; 5806 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5807 DC = CRSI->TheCapturedDecl; 5808 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5809 DC = BSI->TheDecl; 5810 if (DC) { 5811 if (DC->containsDecl(TT->getDecl())) 5812 break; 5813 captureVariablyModifiedType( 5814 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5815 } 5816 } 5817 } 5818 } 5819 5820 return new (Context) 5821 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5822 } 5823 5824 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5825 ParmVarDecl *Param) { 5826 if (Param->hasUnparsedDefaultArg()) { 5827 // If we've already cleared out the location for the default argument, 5828 // that means we're parsing it right now. 5829 if (!UnparsedDefaultArgLocs.count(Param)) { 5830 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5831 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5832 Param->setInvalidDecl(); 5833 return true; 5834 } 5835 5836 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5837 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5838 Diag(UnparsedDefaultArgLocs[Param], 5839 diag::note_default_argument_declared_here); 5840 return true; 5841 } 5842 5843 if (Param->hasUninstantiatedDefaultArg() && 5844 InstantiateDefaultArgument(CallLoc, FD, Param)) 5845 return true; 5846 5847 assert(Param->hasInit() && "default argument but no initializer?"); 5848 5849 // If the default expression creates temporaries, we need to 5850 // push them to the current stack of expression temporaries so they'll 5851 // be properly destroyed. 5852 // FIXME: We should really be rebuilding the default argument with new 5853 // bound temporaries; see the comment in PR5810. 5854 // We don't need to do that with block decls, though, because 5855 // blocks in default argument expression can never capture anything. 5856 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5857 // Set the "needs cleanups" bit regardless of whether there are 5858 // any explicit objects. 5859 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5860 5861 // Append all the objects to the cleanup list. Right now, this 5862 // should always be a no-op, because blocks in default argument 5863 // expressions should never be able to capture anything. 5864 assert(!Init->getNumObjects() && 5865 "default argument expression has capturing blocks?"); 5866 } 5867 5868 // We already type-checked the argument, so we know it works. 5869 // Just mark all of the declarations in this potentially-evaluated expression 5870 // as being "referenced". 5871 EnterExpressionEvaluationContext EvalContext( 5872 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5873 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5874 /*SkipLocalVariables=*/true); 5875 return false; 5876 } 5877 5878 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5879 FunctionDecl *FD, ParmVarDecl *Param) { 5880 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5881 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5882 return ExprError(); 5883 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5884 } 5885 5886 Sema::VariadicCallType 5887 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5888 Expr *Fn) { 5889 if (Proto && Proto->isVariadic()) { 5890 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 5891 return VariadicConstructor; 5892 else if (Fn && Fn->getType()->isBlockPointerType()) 5893 return VariadicBlock; 5894 else if (FDecl) { 5895 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5896 if (Method->isInstance()) 5897 return VariadicMethod; 5898 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5899 return VariadicMethod; 5900 return VariadicFunction; 5901 } 5902 return VariadicDoesNotApply; 5903 } 5904 5905 namespace { 5906 class FunctionCallCCC final : public FunctionCallFilterCCC { 5907 public: 5908 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5909 unsigned NumArgs, MemberExpr *ME) 5910 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5911 FunctionName(FuncName) {} 5912 5913 bool ValidateCandidate(const TypoCorrection &candidate) override { 5914 if (!candidate.getCorrectionSpecifier() || 5915 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5916 return false; 5917 } 5918 5919 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5920 } 5921 5922 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5923 return std::make_unique<FunctionCallCCC>(*this); 5924 } 5925 5926 private: 5927 const IdentifierInfo *const FunctionName; 5928 }; 5929 } 5930 5931 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5932 FunctionDecl *FDecl, 5933 ArrayRef<Expr *> Args) { 5934 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5935 DeclarationName FuncName = FDecl->getDeclName(); 5936 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5937 5938 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5939 if (TypoCorrection Corrected = S.CorrectTypo( 5940 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5941 S.getScopeForContext(S.CurContext), nullptr, CCC, 5942 Sema::CTK_ErrorRecovery)) { 5943 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5944 if (Corrected.isOverloaded()) { 5945 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5946 OverloadCandidateSet::iterator Best; 5947 for (NamedDecl *CD : Corrected) { 5948 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5949 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5950 OCS); 5951 } 5952 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5953 case OR_Success: 5954 ND = Best->FoundDecl; 5955 Corrected.setCorrectionDecl(ND); 5956 break; 5957 default: 5958 break; 5959 } 5960 } 5961 ND = ND->getUnderlyingDecl(); 5962 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5963 return Corrected; 5964 } 5965 } 5966 return TypoCorrection(); 5967 } 5968 5969 /// ConvertArgumentsForCall - Converts the arguments specified in 5970 /// Args/NumArgs to the parameter types of the function FDecl with 5971 /// function prototype Proto. Call is the call expression itself, and 5972 /// Fn is the function expression. For a C++ member function, this 5973 /// routine does not attempt to convert the object argument. Returns 5974 /// true if the call is ill-formed. 5975 bool 5976 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5977 FunctionDecl *FDecl, 5978 const FunctionProtoType *Proto, 5979 ArrayRef<Expr *> Args, 5980 SourceLocation RParenLoc, 5981 bool IsExecConfig) { 5982 // Bail out early if calling a builtin with custom typechecking. 5983 if (FDecl) 5984 if (unsigned ID = FDecl->getBuiltinID()) 5985 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5986 return false; 5987 5988 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5989 // assignment, to the types of the corresponding parameter, ... 5990 unsigned NumParams = Proto->getNumParams(); 5991 bool Invalid = false; 5992 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5993 unsigned FnKind = Fn->getType()->isBlockPointerType() 5994 ? 1 /* block */ 5995 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5996 : 0 /* function */); 5997 5998 // If too few arguments are available (and we don't have default 5999 // arguments for the remaining parameters), don't make the call. 6000 if (Args.size() < NumParams) { 6001 if (Args.size() < MinArgs) { 6002 TypoCorrection TC; 6003 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6004 unsigned diag_id = 6005 MinArgs == NumParams && !Proto->isVariadic() 6006 ? diag::err_typecheck_call_too_few_args_suggest 6007 : diag::err_typecheck_call_too_few_args_at_least_suggest; 6008 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 6009 << static_cast<unsigned>(Args.size()) 6010 << TC.getCorrectionRange()); 6011 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 6012 Diag(RParenLoc, 6013 MinArgs == NumParams && !Proto->isVariadic() 6014 ? diag::err_typecheck_call_too_few_args_one 6015 : diag::err_typecheck_call_too_few_args_at_least_one) 6016 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 6017 else 6018 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 6019 ? diag::err_typecheck_call_too_few_args 6020 : diag::err_typecheck_call_too_few_args_at_least) 6021 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 6022 << Fn->getSourceRange(); 6023 6024 // Emit the location of the prototype. 6025 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6026 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6027 6028 return true; 6029 } 6030 // We reserve space for the default arguments when we create 6031 // the call expression, before calling ConvertArgumentsForCall. 6032 assert((Call->getNumArgs() == NumParams) && 6033 "We should have reserved space for the default arguments before!"); 6034 } 6035 6036 // If too many are passed and not variadic, error on the extras and drop 6037 // them. 6038 if (Args.size() > NumParams) { 6039 if (!Proto->isVariadic()) { 6040 TypoCorrection TC; 6041 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6042 unsigned diag_id = 6043 MinArgs == NumParams && !Proto->isVariadic() 6044 ? diag::err_typecheck_call_too_many_args_suggest 6045 : diag::err_typecheck_call_too_many_args_at_most_suggest; 6046 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 6047 << static_cast<unsigned>(Args.size()) 6048 << TC.getCorrectionRange()); 6049 } else if (NumParams == 1 && FDecl && 6050 FDecl->getParamDecl(0)->getDeclName()) 6051 Diag(Args[NumParams]->getBeginLoc(), 6052 MinArgs == NumParams 6053 ? diag::err_typecheck_call_too_many_args_one 6054 : diag::err_typecheck_call_too_many_args_at_most_one) 6055 << FnKind << FDecl->getParamDecl(0) 6056 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 6057 << SourceRange(Args[NumParams]->getBeginLoc(), 6058 Args.back()->getEndLoc()); 6059 else 6060 Diag(Args[NumParams]->getBeginLoc(), 6061 MinArgs == NumParams 6062 ? diag::err_typecheck_call_too_many_args 6063 : diag::err_typecheck_call_too_many_args_at_most) 6064 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 6065 << Fn->getSourceRange() 6066 << SourceRange(Args[NumParams]->getBeginLoc(), 6067 Args.back()->getEndLoc()); 6068 6069 // Emit the location of the prototype. 6070 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6071 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6072 6073 // This deletes the extra arguments. 6074 Call->shrinkNumArgs(NumParams); 6075 return true; 6076 } 6077 } 6078 SmallVector<Expr *, 8> AllArgs; 6079 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 6080 6081 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 6082 AllArgs, CallType); 6083 if (Invalid) 6084 return true; 6085 unsigned TotalNumArgs = AllArgs.size(); 6086 for (unsigned i = 0; i < TotalNumArgs; ++i) 6087 Call->setArg(i, AllArgs[i]); 6088 6089 Call->computeDependence(); 6090 return false; 6091 } 6092 6093 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 6094 const FunctionProtoType *Proto, 6095 unsigned FirstParam, ArrayRef<Expr *> Args, 6096 SmallVectorImpl<Expr *> &AllArgs, 6097 VariadicCallType CallType, bool AllowExplicit, 6098 bool IsListInitialization) { 6099 unsigned NumParams = Proto->getNumParams(); 6100 bool Invalid = false; 6101 size_t ArgIx = 0; 6102 // Continue to check argument types (even if we have too few/many args). 6103 for (unsigned i = FirstParam; i < NumParams; i++) { 6104 QualType ProtoArgType = Proto->getParamType(i); 6105 6106 Expr *Arg; 6107 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 6108 if (ArgIx < Args.size()) { 6109 Arg = Args[ArgIx++]; 6110 6111 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 6112 diag::err_call_incomplete_argument, Arg)) 6113 return true; 6114 6115 // Strip the unbridged-cast placeholder expression off, if applicable. 6116 bool CFAudited = false; 6117 if (Arg->getType() == Context.ARCUnbridgedCastTy && 6118 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6119 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6120 Arg = stripARCUnbridgedCast(Arg); 6121 else if (getLangOpts().ObjCAutoRefCount && 6122 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6123 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6124 CFAudited = true; 6125 6126 if (Proto->getExtParameterInfo(i).isNoEscape() && 6127 ProtoArgType->isBlockPointerType()) 6128 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 6129 BE->getBlockDecl()->setDoesNotEscape(); 6130 6131 InitializedEntity Entity = 6132 Param ? InitializedEntity::InitializeParameter(Context, Param, 6133 ProtoArgType) 6134 : InitializedEntity::InitializeParameter( 6135 Context, ProtoArgType, Proto->isParamConsumed(i)); 6136 6137 // Remember that parameter belongs to a CF audited API. 6138 if (CFAudited) 6139 Entity.setParameterCFAudited(); 6140 6141 ExprResult ArgE = PerformCopyInitialization( 6142 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 6143 if (ArgE.isInvalid()) 6144 return true; 6145 6146 Arg = ArgE.getAs<Expr>(); 6147 } else { 6148 assert(Param && "can't use default arguments without a known callee"); 6149 6150 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 6151 if (ArgExpr.isInvalid()) 6152 return true; 6153 6154 Arg = ArgExpr.getAs<Expr>(); 6155 } 6156 6157 // Check for array bounds violations for each argument to the call. This 6158 // check only triggers warnings when the argument isn't a more complex Expr 6159 // with its own checking, such as a BinaryOperator. 6160 CheckArrayAccess(Arg); 6161 6162 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6163 CheckStaticArrayArgument(CallLoc, Param, Arg); 6164 6165 AllArgs.push_back(Arg); 6166 } 6167 6168 // If this is a variadic call, handle args passed through "...". 6169 if (CallType != VariadicDoesNotApply) { 6170 // Assume that extern "C" functions with variadic arguments that 6171 // return __unknown_anytype aren't *really* variadic. 6172 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6173 FDecl->isExternC()) { 6174 for (Expr *A : Args.slice(ArgIx)) { 6175 QualType paramType; // ignored 6176 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6177 Invalid |= arg.isInvalid(); 6178 AllArgs.push_back(arg.get()); 6179 } 6180 6181 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6182 } else { 6183 for (Expr *A : Args.slice(ArgIx)) { 6184 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6185 Invalid |= Arg.isInvalid(); 6186 AllArgs.push_back(Arg.get()); 6187 } 6188 } 6189 6190 // Check for array bounds violations. 6191 for (Expr *A : Args.slice(ArgIx)) 6192 CheckArrayAccess(A); 6193 } 6194 return Invalid; 6195 } 6196 6197 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6198 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6199 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6200 TL = DTL.getOriginalLoc(); 6201 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6202 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6203 << ATL.getLocalSourceRange(); 6204 } 6205 6206 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6207 /// array parameter, check that it is non-null, and that if it is formed by 6208 /// array-to-pointer decay, the underlying array is sufficiently large. 6209 /// 6210 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6211 /// array type derivation, then for each call to the function, the value of the 6212 /// corresponding actual argument shall provide access to the first element of 6213 /// an array with at least as many elements as specified by the size expression. 6214 void 6215 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6216 ParmVarDecl *Param, 6217 const Expr *ArgExpr) { 6218 // Static array parameters are not supported in C++. 6219 if (!Param || getLangOpts().CPlusPlus) 6220 return; 6221 6222 QualType OrigTy = Param->getOriginalType(); 6223 6224 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6225 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6226 return; 6227 6228 if (ArgExpr->isNullPointerConstant(Context, 6229 Expr::NPC_NeverValueDependent)) { 6230 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6231 DiagnoseCalleeStaticArrayParam(*this, Param); 6232 return; 6233 } 6234 6235 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6236 if (!CAT) 6237 return; 6238 6239 const ConstantArrayType *ArgCAT = 6240 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6241 if (!ArgCAT) 6242 return; 6243 6244 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6245 ArgCAT->getElementType())) { 6246 if (ArgCAT->getSize().ult(CAT->getSize())) { 6247 Diag(CallLoc, diag::warn_static_array_too_small) 6248 << ArgExpr->getSourceRange() 6249 << (unsigned)ArgCAT->getSize().getZExtValue() 6250 << (unsigned)CAT->getSize().getZExtValue() << 0; 6251 DiagnoseCalleeStaticArrayParam(*this, Param); 6252 } 6253 return; 6254 } 6255 6256 Optional<CharUnits> ArgSize = 6257 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6258 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6259 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6260 Diag(CallLoc, diag::warn_static_array_too_small) 6261 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6262 << (unsigned)ParmSize->getQuantity() << 1; 6263 DiagnoseCalleeStaticArrayParam(*this, Param); 6264 } 6265 } 6266 6267 /// Given a function expression of unknown-any type, try to rebuild it 6268 /// to have a function type. 6269 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6270 6271 /// Is the given type a placeholder that we need to lower out 6272 /// immediately during argument processing? 6273 static bool isPlaceholderToRemoveAsArg(QualType type) { 6274 // Placeholders are never sugared. 6275 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6276 if (!placeholder) return false; 6277 6278 switch (placeholder->getKind()) { 6279 // Ignore all the non-placeholder types. 6280 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6281 case BuiltinType::Id: 6282 #include "clang/Basic/OpenCLImageTypes.def" 6283 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6284 case BuiltinType::Id: 6285 #include "clang/Basic/OpenCLExtensionTypes.def" 6286 // In practice we'll never use this, since all SVE types are sugared 6287 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6288 #define SVE_TYPE(Name, Id, SingletonId) \ 6289 case BuiltinType::Id: 6290 #include "clang/Basic/AArch64SVEACLETypes.def" 6291 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6292 case BuiltinType::Id: 6293 #include "clang/Basic/PPCTypes.def" 6294 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6295 #include "clang/Basic/RISCVVTypes.def" 6296 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6297 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6298 #include "clang/AST/BuiltinTypes.def" 6299 return false; 6300 6301 // We cannot lower out overload sets; they might validly be resolved 6302 // by the call machinery. 6303 case BuiltinType::Overload: 6304 return false; 6305 6306 // Unbridged casts in ARC can be handled in some call positions and 6307 // should be left in place. 6308 case BuiltinType::ARCUnbridgedCast: 6309 return false; 6310 6311 // Pseudo-objects should be converted as soon as possible. 6312 case BuiltinType::PseudoObject: 6313 return true; 6314 6315 // The debugger mode could theoretically but currently does not try 6316 // to resolve unknown-typed arguments based on known parameter types. 6317 case BuiltinType::UnknownAny: 6318 return true; 6319 6320 // These are always invalid as call arguments and should be reported. 6321 case BuiltinType::BoundMember: 6322 case BuiltinType::BuiltinFn: 6323 case BuiltinType::IncompleteMatrixIdx: 6324 case BuiltinType::OMPArraySection: 6325 case BuiltinType::OMPArrayShaping: 6326 case BuiltinType::OMPIterator: 6327 return true; 6328 6329 } 6330 llvm_unreachable("bad builtin type kind"); 6331 } 6332 6333 /// Check an argument list for placeholders that we won't try to 6334 /// handle later. 6335 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6336 // Apply this processing to all the arguments at once instead of 6337 // dying at the first failure. 6338 bool hasInvalid = false; 6339 for (size_t i = 0, e = args.size(); i != e; i++) { 6340 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6341 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6342 if (result.isInvalid()) hasInvalid = true; 6343 else args[i] = result.get(); 6344 } 6345 } 6346 return hasInvalid; 6347 } 6348 6349 /// If a builtin function has a pointer argument with no explicit address 6350 /// space, then it should be able to accept a pointer to any address 6351 /// space as input. In order to do this, we need to replace the 6352 /// standard builtin declaration with one that uses the same address space 6353 /// as the call. 6354 /// 6355 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6356 /// it does not contain any pointer arguments without 6357 /// an address space qualifer. Otherwise the rewritten 6358 /// FunctionDecl is returned. 6359 /// TODO: Handle pointer return types. 6360 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6361 FunctionDecl *FDecl, 6362 MultiExprArg ArgExprs) { 6363 6364 QualType DeclType = FDecl->getType(); 6365 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6366 6367 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6368 ArgExprs.size() < FT->getNumParams()) 6369 return nullptr; 6370 6371 bool NeedsNewDecl = false; 6372 unsigned i = 0; 6373 SmallVector<QualType, 8> OverloadParams; 6374 6375 for (QualType ParamType : FT->param_types()) { 6376 6377 // Convert array arguments to pointer to simplify type lookup. 6378 ExprResult ArgRes = 6379 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6380 if (ArgRes.isInvalid()) 6381 return nullptr; 6382 Expr *Arg = ArgRes.get(); 6383 QualType ArgType = Arg->getType(); 6384 if (!ParamType->isPointerType() || 6385 ParamType.hasAddressSpace() || 6386 !ArgType->isPointerType() || 6387 !ArgType->getPointeeType().hasAddressSpace()) { 6388 OverloadParams.push_back(ParamType); 6389 continue; 6390 } 6391 6392 QualType PointeeType = ParamType->getPointeeType(); 6393 if (PointeeType.hasAddressSpace()) 6394 continue; 6395 6396 NeedsNewDecl = true; 6397 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6398 6399 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6400 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6401 } 6402 6403 if (!NeedsNewDecl) 6404 return nullptr; 6405 6406 FunctionProtoType::ExtProtoInfo EPI; 6407 EPI.Variadic = FT->isVariadic(); 6408 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6409 OverloadParams, EPI); 6410 DeclContext *Parent = FDecl->getParent(); 6411 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6412 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6413 FDecl->getIdentifier(), OverloadTy, 6414 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6415 false, 6416 /*hasPrototype=*/true); 6417 SmallVector<ParmVarDecl*, 16> Params; 6418 FT = cast<FunctionProtoType>(OverloadTy); 6419 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6420 QualType ParamType = FT->getParamType(i); 6421 ParmVarDecl *Parm = 6422 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6423 SourceLocation(), nullptr, ParamType, 6424 /*TInfo=*/nullptr, SC_None, nullptr); 6425 Parm->setScopeInfo(0, i); 6426 Params.push_back(Parm); 6427 } 6428 OverloadDecl->setParams(Params); 6429 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6430 return OverloadDecl; 6431 } 6432 6433 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6434 FunctionDecl *Callee, 6435 MultiExprArg ArgExprs) { 6436 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6437 // similar attributes) really don't like it when functions are called with an 6438 // invalid number of args. 6439 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6440 /*PartialOverloading=*/false) && 6441 !Callee->isVariadic()) 6442 return; 6443 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6444 return; 6445 6446 if (const EnableIfAttr *Attr = 6447 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6448 S.Diag(Fn->getBeginLoc(), 6449 isa<CXXMethodDecl>(Callee) 6450 ? diag::err_ovl_no_viable_member_function_in_call 6451 : diag::err_ovl_no_viable_function_in_call) 6452 << Callee << Callee->getSourceRange(); 6453 S.Diag(Callee->getLocation(), 6454 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6455 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6456 return; 6457 } 6458 } 6459 6460 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6461 const UnresolvedMemberExpr *const UME, Sema &S) { 6462 6463 const auto GetFunctionLevelDCIfCXXClass = 6464 [](Sema &S) -> const CXXRecordDecl * { 6465 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6466 if (!DC || !DC->getParent()) 6467 return nullptr; 6468 6469 // If the call to some member function was made from within a member 6470 // function body 'M' return return 'M's parent. 6471 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6472 return MD->getParent()->getCanonicalDecl(); 6473 // else the call was made from within a default member initializer of a 6474 // class, so return the class. 6475 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6476 return RD->getCanonicalDecl(); 6477 return nullptr; 6478 }; 6479 // If our DeclContext is neither a member function nor a class (in the 6480 // case of a lambda in a default member initializer), we can't have an 6481 // enclosing 'this'. 6482 6483 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6484 if (!CurParentClass) 6485 return false; 6486 6487 // The naming class for implicit member functions call is the class in which 6488 // name lookup starts. 6489 const CXXRecordDecl *const NamingClass = 6490 UME->getNamingClass()->getCanonicalDecl(); 6491 assert(NamingClass && "Must have naming class even for implicit access"); 6492 6493 // If the unresolved member functions were found in a 'naming class' that is 6494 // related (either the same or derived from) to the class that contains the 6495 // member function that itself contained the implicit member access. 6496 6497 return CurParentClass == NamingClass || 6498 CurParentClass->isDerivedFrom(NamingClass); 6499 } 6500 6501 static void 6502 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6503 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6504 6505 if (!UME) 6506 return; 6507 6508 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6509 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6510 // already been captured, or if this is an implicit member function call (if 6511 // it isn't, an attempt to capture 'this' should already have been made). 6512 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6513 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6514 return; 6515 6516 // Check if the naming class in which the unresolved members were found is 6517 // related (same as or is a base of) to the enclosing class. 6518 6519 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6520 return; 6521 6522 6523 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6524 // If the enclosing function is not dependent, then this lambda is 6525 // capture ready, so if we can capture this, do so. 6526 if (!EnclosingFunctionCtx->isDependentContext()) { 6527 // If the current lambda and all enclosing lambdas can capture 'this' - 6528 // then go ahead and capture 'this' (since our unresolved overload set 6529 // contains at least one non-static member function). 6530 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6531 S.CheckCXXThisCapture(CallLoc); 6532 } else if (S.CurContext->isDependentContext()) { 6533 // ... since this is an implicit member reference, that might potentially 6534 // involve a 'this' capture, mark 'this' for potential capture in 6535 // enclosing lambdas. 6536 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6537 CurLSI->addPotentialThisCapture(CallLoc); 6538 } 6539 } 6540 6541 // Once a call is fully resolved, warn for unqualified calls to specific 6542 // C++ standard functions, like move and forward. 6543 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) { 6544 // We are only checking unary move and forward so exit early here. 6545 if (Call->getNumArgs() != 1) 6546 return; 6547 6548 Expr *E = Call->getCallee()->IgnoreParenImpCasts(); 6549 if (!E || isa<UnresolvedLookupExpr>(E)) 6550 return; 6551 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E); 6552 if (!DRE || !DRE->getLocation().isValid()) 6553 return; 6554 6555 if (DRE->getQualifier()) 6556 return; 6557 6558 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl()); 6559 if (!D || !D->isInStdNamespace()) 6560 return; 6561 6562 // Only warn for some functions deemed more frequent or problematic. 6563 static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"}; 6564 auto it = llvm::find(SpecialFunctions, D->getName()); 6565 if (it == std::end(SpecialFunctions)) 6566 return; 6567 6568 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function) 6569 << D->getQualifiedNameAsString() 6570 << FixItHint::CreateInsertion(DRE->getLocation(), "std::"); 6571 } 6572 6573 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6574 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6575 Expr *ExecConfig) { 6576 ExprResult Call = 6577 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6578 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6579 if (Call.isInvalid()) 6580 return Call; 6581 6582 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6583 // language modes. 6584 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6585 if (ULE->hasExplicitTemplateArgs() && 6586 ULE->decls_begin() == ULE->decls_end()) { 6587 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6588 ? diag::warn_cxx17_compat_adl_only_template_id 6589 : diag::ext_adl_only_template_id) 6590 << ULE->getName(); 6591 } 6592 } 6593 6594 if (LangOpts.OpenMP) 6595 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6596 ExecConfig); 6597 if (LangOpts.CPlusPlus) { 6598 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6599 if (CE) 6600 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE); 6601 } 6602 return Call; 6603 } 6604 6605 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6606 /// This provides the location of the left/right parens and a list of comma 6607 /// locations. 6608 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6609 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6610 Expr *ExecConfig, bool IsExecConfig, 6611 bool AllowRecovery) { 6612 // Since this might be a postfix expression, get rid of ParenListExprs. 6613 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6614 if (Result.isInvalid()) return ExprError(); 6615 Fn = Result.get(); 6616 6617 if (checkArgsForPlaceholders(*this, ArgExprs)) 6618 return ExprError(); 6619 6620 if (getLangOpts().CPlusPlus) { 6621 // If this is a pseudo-destructor expression, build the call immediately. 6622 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6623 if (!ArgExprs.empty()) { 6624 // Pseudo-destructor calls should not have any arguments. 6625 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6626 << FixItHint::CreateRemoval( 6627 SourceRange(ArgExprs.front()->getBeginLoc(), 6628 ArgExprs.back()->getEndLoc())); 6629 } 6630 6631 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6632 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6633 } 6634 if (Fn->getType() == Context.PseudoObjectTy) { 6635 ExprResult result = CheckPlaceholderExpr(Fn); 6636 if (result.isInvalid()) return ExprError(); 6637 Fn = result.get(); 6638 } 6639 6640 // Determine whether this is a dependent call inside a C++ template, 6641 // in which case we won't do any semantic analysis now. 6642 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6643 if (ExecConfig) { 6644 return CUDAKernelCallExpr::Create(Context, Fn, 6645 cast<CallExpr>(ExecConfig), ArgExprs, 6646 Context.DependentTy, VK_PRValue, 6647 RParenLoc, CurFPFeatureOverrides()); 6648 } else { 6649 6650 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6651 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6652 Fn->getBeginLoc()); 6653 6654 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6655 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6656 } 6657 } 6658 6659 // Determine whether this is a call to an object (C++ [over.call.object]). 6660 if (Fn->getType()->isRecordType()) 6661 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6662 RParenLoc); 6663 6664 if (Fn->getType() == Context.UnknownAnyTy) { 6665 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6666 if (result.isInvalid()) return ExprError(); 6667 Fn = result.get(); 6668 } 6669 6670 if (Fn->getType() == Context.BoundMemberTy) { 6671 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6672 RParenLoc, ExecConfig, IsExecConfig, 6673 AllowRecovery); 6674 } 6675 } 6676 6677 // Check for overloaded calls. This can happen even in C due to extensions. 6678 if (Fn->getType() == Context.OverloadTy) { 6679 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6680 6681 // We aren't supposed to apply this logic if there's an '&' involved. 6682 if (!find.HasFormOfMemberPointer) { 6683 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6684 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6685 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6686 OverloadExpr *ovl = find.Expression; 6687 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6688 return BuildOverloadedCallExpr( 6689 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6690 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6691 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6692 RParenLoc, ExecConfig, IsExecConfig, 6693 AllowRecovery); 6694 } 6695 } 6696 6697 // If we're directly calling a function, get the appropriate declaration. 6698 if (Fn->getType() == Context.UnknownAnyTy) { 6699 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6700 if (result.isInvalid()) return ExprError(); 6701 Fn = result.get(); 6702 } 6703 6704 Expr *NakedFn = Fn->IgnoreParens(); 6705 6706 bool CallingNDeclIndirectly = false; 6707 NamedDecl *NDecl = nullptr; 6708 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6709 if (UnOp->getOpcode() == UO_AddrOf) { 6710 CallingNDeclIndirectly = true; 6711 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6712 } 6713 } 6714 6715 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6716 NDecl = DRE->getDecl(); 6717 6718 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6719 if (FDecl && FDecl->getBuiltinID()) { 6720 // Rewrite the function decl for this builtin by replacing parameters 6721 // with no explicit address space with the address space of the arguments 6722 // in ArgExprs. 6723 if ((FDecl = 6724 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6725 NDecl = FDecl; 6726 Fn = DeclRefExpr::Create( 6727 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6728 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6729 nullptr, DRE->isNonOdrUse()); 6730 } 6731 } 6732 } else if (isa<MemberExpr>(NakedFn)) 6733 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6734 6735 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6736 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6737 FD, /*Complain=*/true, Fn->getBeginLoc())) 6738 return ExprError(); 6739 6740 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6741 6742 // If this expression is a call to a builtin function in HIP device 6743 // compilation, allow a pointer-type argument to default address space to be 6744 // passed as a pointer-type parameter to a non-default address space. 6745 // If Arg is declared in the default address space and Param is declared 6746 // in a non-default address space, perform an implicit address space cast to 6747 // the parameter type. 6748 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6749 FD->getBuiltinID()) { 6750 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6751 ParmVarDecl *Param = FD->getParamDecl(Idx); 6752 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6753 !ArgExprs[Idx]->getType()->isPointerType()) 6754 continue; 6755 6756 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6757 auto ArgTy = ArgExprs[Idx]->getType(); 6758 auto ArgPtTy = ArgTy->getPointeeType(); 6759 auto ArgAS = ArgPtTy.getAddressSpace(); 6760 6761 // Add address space cast if target address spaces are different 6762 bool NeedImplicitASC = 6763 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6764 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6765 // or from specific AS which has target AS matching that of Param. 6766 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6767 if (!NeedImplicitASC) 6768 continue; 6769 6770 // First, ensure that the Arg is an RValue. 6771 if (ArgExprs[Idx]->isGLValue()) { 6772 ArgExprs[Idx] = ImplicitCastExpr::Create( 6773 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6774 nullptr, VK_PRValue, FPOptionsOverride()); 6775 } 6776 6777 // Construct a new arg type with address space of Param 6778 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6779 ArgPtQuals.setAddressSpace(ParamAS); 6780 auto NewArgPtTy = 6781 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6782 auto NewArgTy = 6783 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6784 ArgTy.getQualifiers()); 6785 6786 // Finally perform an implicit address space cast 6787 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6788 CK_AddressSpaceConversion) 6789 .get(); 6790 } 6791 } 6792 } 6793 6794 if (Context.isDependenceAllowed() && 6795 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6796 assert(!getLangOpts().CPlusPlus); 6797 assert((Fn->containsErrors() || 6798 llvm::any_of(ArgExprs, 6799 [](clang::Expr *E) { return E->containsErrors(); })) && 6800 "should only occur in error-recovery path."); 6801 QualType ReturnType = 6802 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6803 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6804 : Context.DependentTy; 6805 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6806 Expr::getValueKindForType(ReturnType), RParenLoc, 6807 CurFPFeatureOverrides()); 6808 } 6809 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6810 ExecConfig, IsExecConfig); 6811 } 6812 6813 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6814 // with the specified CallArgs 6815 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6816 MultiExprArg CallArgs) { 6817 StringRef Name = Context.BuiltinInfo.getName(Id); 6818 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6819 Sema::LookupOrdinaryName); 6820 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6821 6822 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6823 assert(BuiltInDecl && "failed to find builtin declaration"); 6824 6825 ExprResult DeclRef = 6826 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6827 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6828 6829 ExprResult Call = 6830 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6831 6832 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6833 return Call.get(); 6834 } 6835 6836 /// Parse a __builtin_astype expression. 6837 /// 6838 /// __builtin_astype( value, dst type ) 6839 /// 6840 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6841 SourceLocation BuiltinLoc, 6842 SourceLocation RParenLoc) { 6843 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6844 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6845 } 6846 6847 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6848 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6849 SourceLocation BuiltinLoc, 6850 SourceLocation RParenLoc) { 6851 ExprValueKind VK = VK_PRValue; 6852 ExprObjectKind OK = OK_Ordinary; 6853 QualType SrcTy = E->getType(); 6854 if (!SrcTy->isDependentType() && 6855 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6856 return ExprError( 6857 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6858 << DestTy << SrcTy << E->getSourceRange()); 6859 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6860 } 6861 6862 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6863 /// provided arguments. 6864 /// 6865 /// __builtin_convertvector( value, dst type ) 6866 /// 6867 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6868 SourceLocation BuiltinLoc, 6869 SourceLocation RParenLoc) { 6870 TypeSourceInfo *TInfo; 6871 GetTypeFromParser(ParsedDestTy, &TInfo); 6872 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6873 } 6874 6875 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6876 /// i.e. an expression not of \p OverloadTy. The expression should 6877 /// unary-convert to an expression of function-pointer or 6878 /// block-pointer type. 6879 /// 6880 /// \param NDecl the declaration being called, if available 6881 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6882 SourceLocation LParenLoc, 6883 ArrayRef<Expr *> Args, 6884 SourceLocation RParenLoc, Expr *Config, 6885 bool IsExecConfig, ADLCallKind UsesADL) { 6886 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6887 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6888 6889 // Functions with 'interrupt' attribute cannot be called directly. 6890 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6891 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6892 return ExprError(); 6893 } 6894 6895 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6896 // so there's some risk when calling out to non-interrupt handler functions 6897 // that the callee might not preserve them. This is easy to diagnose here, 6898 // but can be very challenging to debug. 6899 // Likewise, X86 interrupt handlers may only call routines with attribute 6900 // no_caller_saved_registers since there is no efficient way to 6901 // save and restore the non-GPR state. 6902 if (auto *Caller = getCurFunctionDecl()) { 6903 if (Caller->hasAttr<ARMInterruptAttr>()) { 6904 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6905 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6906 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6907 if (FDecl) 6908 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6909 } 6910 } 6911 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6912 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6913 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6914 if (FDecl) 6915 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6916 } 6917 } 6918 6919 // Promote the function operand. 6920 // We special-case function promotion here because we only allow promoting 6921 // builtin functions to function pointers in the callee of a call. 6922 ExprResult Result; 6923 QualType ResultTy; 6924 if (BuiltinID && 6925 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6926 // Extract the return type from the (builtin) function pointer type. 6927 // FIXME Several builtins still have setType in 6928 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6929 // Builtins.def to ensure they are correct before removing setType calls. 6930 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6931 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6932 ResultTy = FDecl->getCallResultType(); 6933 } else { 6934 Result = CallExprUnaryConversions(Fn); 6935 ResultTy = Context.BoolTy; 6936 } 6937 if (Result.isInvalid()) 6938 return ExprError(); 6939 Fn = Result.get(); 6940 6941 // Check for a valid function type, but only if it is not a builtin which 6942 // requires custom type checking. These will be handled by 6943 // CheckBuiltinFunctionCall below just after creation of the call expression. 6944 const FunctionType *FuncT = nullptr; 6945 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6946 retry: 6947 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6948 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6949 // have type pointer to function". 6950 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6951 if (!FuncT) 6952 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6953 << Fn->getType() << Fn->getSourceRange()); 6954 } else if (const BlockPointerType *BPT = 6955 Fn->getType()->getAs<BlockPointerType>()) { 6956 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6957 } else { 6958 // Handle calls to expressions of unknown-any type. 6959 if (Fn->getType() == Context.UnknownAnyTy) { 6960 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6961 if (rewrite.isInvalid()) 6962 return ExprError(); 6963 Fn = rewrite.get(); 6964 goto retry; 6965 } 6966 6967 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6968 << Fn->getType() << Fn->getSourceRange()); 6969 } 6970 } 6971 6972 // Get the number of parameters in the function prototype, if any. 6973 // We will allocate space for max(Args.size(), NumParams) arguments 6974 // in the call expression. 6975 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6976 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6977 6978 CallExpr *TheCall; 6979 if (Config) { 6980 assert(UsesADL == ADLCallKind::NotADL && 6981 "CUDAKernelCallExpr should not use ADL"); 6982 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6983 Args, ResultTy, VK_PRValue, RParenLoc, 6984 CurFPFeatureOverrides(), NumParams); 6985 } else { 6986 TheCall = 6987 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6988 CurFPFeatureOverrides(), NumParams, UsesADL); 6989 } 6990 6991 if (!Context.isDependenceAllowed()) { 6992 // Forget about the nulled arguments since typo correction 6993 // do not handle them well. 6994 TheCall->shrinkNumArgs(Args.size()); 6995 // C cannot always handle TypoExpr nodes in builtin calls and direct 6996 // function calls as their argument checking don't necessarily handle 6997 // dependent types properly, so make sure any TypoExprs have been 6998 // dealt with. 6999 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 7000 if (!Result.isUsable()) return ExprError(); 7001 CallExpr *TheOldCall = TheCall; 7002 TheCall = dyn_cast<CallExpr>(Result.get()); 7003 bool CorrectedTypos = TheCall != TheOldCall; 7004 if (!TheCall) return Result; 7005 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 7006 7007 // A new call expression node was created if some typos were corrected. 7008 // However it may not have been constructed with enough storage. In this 7009 // case, rebuild the node with enough storage. The waste of space is 7010 // immaterial since this only happens when some typos were corrected. 7011 if (CorrectedTypos && Args.size() < NumParams) { 7012 if (Config) 7013 TheCall = CUDAKernelCallExpr::Create( 7014 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 7015 RParenLoc, CurFPFeatureOverrides(), NumParams); 7016 else 7017 TheCall = 7018 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 7019 CurFPFeatureOverrides(), NumParams, UsesADL); 7020 } 7021 // We can now handle the nulled arguments for the default arguments. 7022 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 7023 } 7024 7025 // Bail out early if calling a builtin with custom type checking. 7026 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 7027 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7028 7029 if (getLangOpts().CUDA) { 7030 if (Config) { 7031 // CUDA: Kernel calls must be to global functions 7032 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 7033 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 7034 << FDecl << Fn->getSourceRange()); 7035 7036 // CUDA: Kernel function must have 'void' return type 7037 if (!FuncT->getReturnType()->isVoidType() && 7038 !FuncT->getReturnType()->getAs<AutoType>() && 7039 !FuncT->getReturnType()->isInstantiationDependentType()) 7040 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 7041 << Fn->getType() << Fn->getSourceRange()); 7042 } else { 7043 // CUDA: Calls to global functions must be configured 7044 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 7045 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 7046 << FDecl << Fn->getSourceRange()); 7047 } 7048 } 7049 7050 // Check for a valid return type 7051 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 7052 FDecl)) 7053 return ExprError(); 7054 7055 // We know the result type of the call, set it. 7056 TheCall->setType(FuncT->getCallResultType(Context)); 7057 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 7058 7059 if (Proto) { 7060 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 7061 IsExecConfig)) 7062 return ExprError(); 7063 } else { 7064 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 7065 7066 if (FDecl) { 7067 // Check if we have too few/too many template arguments, based 7068 // on our knowledge of the function definition. 7069 const FunctionDecl *Def = nullptr; 7070 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 7071 Proto = Def->getType()->getAs<FunctionProtoType>(); 7072 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 7073 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 7074 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 7075 } 7076 7077 // If the function we're calling isn't a function prototype, but we have 7078 // a function prototype from a prior declaratiom, use that prototype. 7079 if (!FDecl->hasPrototype()) 7080 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 7081 } 7082 7083 // If we still haven't found a prototype to use but there are arguments to 7084 // the call, diagnose this as calling a function without a prototype. 7085 // However, if we found a function declaration, check to see if 7086 // -Wdeprecated-non-prototype was disabled where the function was declared. 7087 // If so, we will silence the diagnostic here on the assumption that this 7088 // interface is intentional and the user knows what they're doing. We will 7089 // also silence the diagnostic if there is a function declaration but it 7090 // was implicitly defined (the user already gets diagnostics about the 7091 // creation of the implicit function declaration, so the additional warning 7092 // is not helpful). 7093 if (!Proto && !Args.empty() && 7094 (!FDecl || (!FDecl->isImplicit() && 7095 !Diags.isIgnored(diag::warn_strict_uses_without_prototype, 7096 FDecl->getLocation())))) 7097 Diag(LParenLoc, diag::warn_strict_uses_without_prototype) 7098 << (FDecl != nullptr) << FDecl; 7099 7100 // Promote the arguments (C99 6.5.2.2p6). 7101 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7102 Expr *Arg = Args[i]; 7103 7104 if (Proto && i < Proto->getNumParams()) { 7105 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7106 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 7107 ExprResult ArgE = 7108 PerformCopyInitialization(Entity, SourceLocation(), Arg); 7109 if (ArgE.isInvalid()) 7110 return true; 7111 7112 Arg = ArgE.getAs<Expr>(); 7113 7114 } else { 7115 ExprResult ArgE = DefaultArgumentPromotion(Arg); 7116 7117 if (ArgE.isInvalid()) 7118 return true; 7119 7120 Arg = ArgE.getAs<Expr>(); 7121 } 7122 7123 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 7124 diag::err_call_incomplete_argument, Arg)) 7125 return ExprError(); 7126 7127 TheCall->setArg(i, Arg); 7128 } 7129 TheCall->computeDependence(); 7130 } 7131 7132 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 7133 if (!Method->isStatic()) 7134 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 7135 << Fn->getSourceRange()); 7136 7137 // Check for sentinels 7138 if (NDecl) 7139 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 7140 7141 // Warn for unions passing across security boundary (CMSE). 7142 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 7143 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7144 if (const auto *RT = 7145 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 7146 if (RT->getDecl()->isOrContainsUnion()) 7147 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 7148 << 0 << i; 7149 } 7150 } 7151 } 7152 7153 // Do special checking on direct calls to functions. 7154 if (FDecl) { 7155 if (CheckFunctionCall(FDecl, TheCall, Proto)) 7156 return ExprError(); 7157 7158 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 7159 7160 if (BuiltinID) 7161 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7162 } else if (NDecl) { 7163 if (CheckPointerCall(NDecl, TheCall, Proto)) 7164 return ExprError(); 7165 } else { 7166 if (CheckOtherCall(TheCall, Proto)) 7167 return ExprError(); 7168 } 7169 7170 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 7171 } 7172 7173 ExprResult 7174 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 7175 SourceLocation RParenLoc, Expr *InitExpr) { 7176 assert(Ty && "ActOnCompoundLiteral(): missing type"); 7177 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 7178 7179 TypeSourceInfo *TInfo; 7180 QualType literalType = GetTypeFromParser(Ty, &TInfo); 7181 if (!TInfo) 7182 TInfo = Context.getTrivialTypeSourceInfo(literalType); 7183 7184 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 7185 } 7186 7187 ExprResult 7188 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 7189 SourceLocation RParenLoc, Expr *LiteralExpr) { 7190 QualType literalType = TInfo->getType(); 7191 7192 if (literalType->isArrayType()) { 7193 if (RequireCompleteSizedType( 7194 LParenLoc, Context.getBaseElementType(literalType), 7195 diag::err_array_incomplete_or_sizeless_type, 7196 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7197 return ExprError(); 7198 if (literalType->isVariableArrayType()) { 7199 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 7200 diag::err_variable_object_no_init)) { 7201 return ExprError(); 7202 } 7203 } 7204 } else if (!literalType->isDependentType() && 7205 RequireCompleteType(LParenLoc, literalType, 7206 diag::err_typecheck_decl_incomplete_type, 7207 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7208 return ExprError(); 7209 7210 InitializedEntity Entity 7211 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 7212 InitializationKind Kind 7213 = InitializationKind::CreateCStyleCast(LParenLoc, 7214 SourceRange(LParenLoc, RParenLoc), 7215 /*InitList=*/true); 7216 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 7217 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 7218 &literalType); 7219 if (Result.isInvalid()) 7220 return ExprError(); 7221 LiteralExpr = Result.get(); 7222 7223 bool isFileScope = !CurContext->isFunctionOrMethod(); 7224 7225 // In C, compound literals are l-values for some reason. 7226 // For GCC compatibility, in C++, file-scope array compound literals with 7227 // constant initializers are also l-values, and compound literals are 7228 // otherwise prvalues. 7229 // 7230 // (GCC also treats C++ list-initialized file-scope array prvalues with 7231 // constant initializers as l-values, but that's non-conforming, so we don't 7232 // follow it there.) 7233 // 7234 // FIXME: It would be better to handle the lvalue cases as materializing and 7235 // lifetime-extending a temporary object, but our materialized temporaries 7236 // representation only supports lifetime extension from a variable, not "out 7237 // of thin air". 7238 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7239 // is bound to the result of applying array-to-pointer decay to the compound 7240 // literal. 7241 // FIXME: GCC supports compound literals of reference type, which should 7242 // obviously have a value kind derived from the kind of reference involved. 7243 ExprValueKind VK = 7244 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7245 ? VK_PRValue 7246 : VK_LValue; 7247 7248 if (isFileScope) 7249 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7250 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7251 Expr *Init = ILE->getInit(i); 7252 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7253 } 7254 7255 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7256 VK, LiteralExpr, isFileScope); 7257 if (isFileScope) { 7258 if (!LiteralExpr->isTypeDependent() && 7259 !LiteralExpr->isValueDependent() && 7260 !literalType->isDependentType()) // C99 6.5.2.5p3 7261 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7262 return ExprError(); 7263 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7264 literalType.getAddressSpace() != LangAS::Default) { 7265 // Embedded-C extensions to C99 6.5.2.5: 7266 // "If the compound literal occurs inside the body of a function, the 7267 // type name shall not be qualified by an address-space qualifier." 7268 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7269 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7270 return ExprError(); 7271 } 7272 7273 if (!isFileScope && !getLangOpts().CPlusPlus) { 7274 // Compound literals that have automatic storage duration are destroyed at 7275 // the end of the scope in C; in C++, they're just temporaries. 7276 7277 // Emit diagnostics if it is or contains a C union type that is non-trivial 7278 // to destruct. 7279 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7280 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7281 NTCUC_CompoundLiteral, NTCUK_Destruct); 7282 7283 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7284 if (literalType.isDestructedType()) { 7285 Cleanup.setExprNeedsCleanups(true); 7286 ExprCleanupObjects.push_back(E); 7287 getCurFunction()->setHasBranchProtectedScope(); 7288 } 7289 } 7290 7291 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7292 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7293 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7294 E->getInitializer()->getExprLoc()); 7295 7296 return MaybeBindToTemporary(E); 7297 } 7298 7299 ExprResult 7300 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7301 SourceLocation RBraceLoc) { 7302 // Only produce each kind of designated initialization diagnostic once. 7303 SourceLocation FirstDesignator; 7304 bool DiagnosedArrayDesignator = false; 7305 bool DiagnosedNestedDesignator = false; 7306 bool DiagnosedMixedDesignator = false; 7307 7308 // Check that any designated initializers are syntactically valid in the 7309 // current language mode. 7310 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7311 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7312 if (FirstDesignator.isInvalid()) 7313 FirstDesignator = DIE->getBeginLoc(); 7314 7315 if (!getLangOpts().CPlusPlus) 7316 break; 7317 7318 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7319 DiagnosedNestedDesignator = true; 7320 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7321 << DIE->getDesignatorsSourceRange(); 7322 } 7323 7324 for (auto &Desig : DIE->designators()) { 7325 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7326 DiagnosedArrayDesignator = true; 7327 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7328 << Desig.getSourceRange(); 7329 } 7330 } 7331 7332 if (!DiagnosedMixedDesignator && 7333 !isa<DesignatedInitExpr>(InitArgList[0])) { 7334 DiagnosedMixedDesignator = true; 7335 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7336 << DIE->getSourceRange(); 7337 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7338 << InitArgList[0]->getSourceRange(); 7339 } 7340 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7341 isa<DesignatedInitExpr>(InitArgList[0])) { 7342 DiagnosedMixedDesignator = true; 7343 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7344 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7345 << DIE->getSourceRange(); 7346 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7347 << InitArgList[I]->getSourceRange(); 7348 } 7349 } 7350 7351 if (FirstDesignator.isValid()) { 7352 // Only diagnose designated initiaization as a C++20 extension if we didn't 7353 // already diagnose use of (non-C++20) C99 designator syntax. 7354 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7355 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7356 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7357 ? diag::warn_cxx17_compat_designated_init 7358 : diag::ext_cxx_designated_init); 7359 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7360 Diag(FirstDesignator, diag::ext_designated_init); 7361 } 7362 } 7363 7364 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7365 } 7366 7367 ExprResult 7368 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7369 SourceLocation RBraceLoc) { 7370 // Semantic analysis for initializers is done by ActOnDeclarator() and 7371 // CheckInitializer() - it requires knowledge of the object being initialized. 7372 7373 // Immediately handle non-overload placeholders. Overloads can be 7374 // resolved contextually, but everything else here can't. 7375 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7376 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7377 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7378 7379 // Ignore failures; dropping the entire initializer list because 7380 // of one failure would be terrible for indexing/etc. 7381 if (result.isInvalid()) continue; 7382 7383 InitArgList[I] = result.get(); 7384 } 7385 } 7386 7387 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7388 RBraceLoc); 7389 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7390 return E; 7391 } 7392 7393 /// Do an explicit extend of the given block pointer if we're in ARC. 7394 void Sema::maybeExtendBlockObject(ExprResult &E) { 7395 assert(E.get()->getType()->isBlockPointerType()); 7396 assert(E.get()->isPRValue()); 7397 7398 // Only do this in an r-value context. 7399 if (!getLangOpts().ObjCAutoRefCount) return; 7400 7401 E = ImplicitCastExpr::Create( 7402 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7403 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7404 Cleanup.setExprNeedsCleanups(true); 7405 } 7406 7407 /// Prepare a conversion of the given expression to an ObjC object 7408 /// pointer type. 7409 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7410 QualType type = E.get()->getType(); 7411 if (type->isObjCObjectPointerType()) { 7412 return CK_BitCast; 7413 } else if (type->isBlockPointerType()) { 7414 maybeExtendBlockObject(E); 7415 return CK_BlockPointerToObjCPointerCast; 7416 } else { 7417 assert(type->isPointerType()); 7418 return CK_CPointerToObjCPointerCast; 7419 } 7420 } 7421 7422 /// Prepares for a scalar cast, performing all the necessary stages 7423 /// except the final cast and returning the kind required. 7424 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7425 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7426 // Also, callers should have filtered out the invalid cases with 7427 // pointers. Everything else should be possible. 7428 7429 QualType SrcTy = Src.get()->getType(); 7430 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7431 return CK_NoOp; 7432 7433 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7434 case Type::STK_MemberPointer: 7435 llvm_unreachable("member pointer type in C"); 7436 7437 case Type::STK_CPointer: 7438 case Type::STK_BlockPointer: 7439 case Type::STK_ObjCObjectPointer: 7440 switch (DestTy->getScalarTypeKind()) { 7441 case Type::STK_CPointer: { 7442 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7443 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7444 if (SrcAS != DestAS) 7445 return CK_AddressSpaceConversion; 7446 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7447 return CK_NoOp; 7448 return CK_BitCast; 7449 } 7450 case Type::STK_BlockPointer: 7451 return (SrcKind == Type::STK_BlockPointer 7452 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7453 case Type::STK_ObjCObjectPointer: 7454 if (SrcKind == Type::STK_ObjCObjectPointer) 7455 return CK_BitCast; 7456 if (SrcKind == Type::STK_CPointer) 7457 return CK_CPointerToObjCPointerCast; 7458 maybeExtendBlockObject(Src); 7459 return CK_BlockPointerToObjCPointerCast; 7460 case Type::STK_Bool: 7461 return CK_PointerToBoolean; 7462 case Type::STK_Integral: 7463 return CK_PointerToIntegral; 7464 case Type::STK_Floating: 7465 case Type::STK_FloatingComplex: 7466 case Type::STK_IntegralComplex: 7467 case Type::STK_MemberPointer: 7468 case Type::STK_FixedPoint: 7469 llvm_unreachable("illegal cast from pointer"); 7470 } 7471 llvm_unreachable("Should have returned before this"); 7472 7473 case Type::STK_FixedPoint: 7474 switch (DestTy->getScalarTypeKind()) { 7475 case Type::STK_FixedPoint: 7476 return CK_FixedPointCast; 7477 case Type::STK_Bool: 7478 return CK_FixedPointToBoolean; 7479 case Type::STK_Integral: 7480 return CK_FixedPointToIntegral; 7481 case Type::STK_Floating: 7482 return CK_FixedPointToFloating; 7483 case Type::STK_IntegralComplex: 7484 case Type::STK_FloatingComplex: 7485 Diag(Src.get()->getExprLoc(), 7486 diag::err_unimplemented_conversion_with_fixed_point_type) 7487 << DestTy; 7488 return CK_IntegralCast; 7489 case Type::STK_CPointer: 7490 case Type::STK_ObjCObjectPointer: 7491 case Type::STK_BlockPointer: 7492 case Type::STK_MemberPointer: 7493 llvm_unreachable("illegal cast to pointer type"); 7494 } 7495 llvm_unreachable("Should have returned before this"); 7496 7497 case Type::STK_Bool: // casting from bool is like casting from an integer 7498 case Type::STK_Integral: 7499 switch (DestTy->getScalarTypeKind()) { 7500 case Type::STK_CPointer: 7501 case Type::STK_ObjCObjectPointer: 7502 case Type::STK_BlockPointer: 7503 if (Src.get()->isNullPointerConstant(Context, 7504 Expr::NPC_ValueDependentIsNull)) 7505 return CK_NullToPointer; 7506 return CK_IntegralToPointer; 7507 case Type::STK_Bool: 7508 return CK_IntegralToBoolean; 7509 case Type::STK_Integral: 7510 return CK_IntegralCast; 7511 case Type::STK_Floating: 7512 return CK_IntegralToFloating; 7513 case Type::STK_IntegralComplex: 7514 Src = ImpCastExprToType(Src.get(), 7515 DestTy->castAs<ComplexType>()->getElementType(), 7516 CK_IntegralCast); 7517 return CK_IntegralRealToComplex; 7518 case Type::STK_FloatingComplex: 7519 Src = ImpCastExprToType(Src.get(), 7520 DestTy->castAs<ComplexType>()->getElementType(), 7521 CK_IntegralToFloating); 7522 return CK_FloatingRealToComplex; 7523 case Type::STK_MemberPointer: 7524 llvm_unreachable("member pointer type in C"); 7525 case Type::STK_FixedPoint: 7526 return CK_IntegralToFixedPoint; 7527 } 7528 llvm_unreachable("Should have returned before this"); 7529 7530 case Type::STK_Floating: 7531 switch (DestTy->getScalarTypeKind()) { 7532 case Type::STK_Floating: 7533 return CK_FloatingCast; 7534 case Type::STK_Bool: 7535 return CK_FloatingToBoolean; 7536 case Type::STK_Integral: 7537 return CK_FloatingToIntegral; 7538 case Type::STK_FloatingComplex: 7539 Src = ImpCastExprToType(Src.get(), 7540 DestTy->castAs<ComplexType>()->getElementType(), 7541 CK_FloatingCast); 7542 return CK_FloatingRealToComplex; 7543 case Type::STK_IntegralComplex: 7544 Src = ImpCastExprToType(Src.get(), 7545 DestTy->castAs<ComplexType>()->getElementType(), 7546 CK_FloatingToIntegral); 7547 return CK_IntegralRealToComplex; 7548 case Type::STK_CPointer: 7549 case Type::STK_ObjCObjectPointer: 7550 case Type::STK_BlockPointer: 7551 llvm_unreachable("valid float->pointer cast?"); 7552 case Type::STK_MemberPointer: 7553 llvm_unreachable("member pointer type in C"); 7554 case Type::STK_FixedPoint: 7555 return CK_FloatingToFixedPoint; 7556 } 7557 llvm_unreachable("Should have returned before this"); 7558 7559 case Type::STK_FloatingComplex: 7560 switch (DestTy->getScalarTypeKind()) { 7561 case Type::STK_FloatingComplex: 7562 return CK_FloatingComplexCast; 7563 case Type::STK_IntegralComplex: 7564 return CK_FloatingComplexToIntegralComplex; 7565 case Type::STK_Floating: { 7566 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7567 if (Context.hasSameType(ET, DestTy)) 7568 return CK_FloatingComplexToReal; 7569 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7570 return CK_FloatingCast; 7571 } 7572 case Type::STK_Bool: 7573 return CK_FloatingComplexToBoolean; 7574 case Type::STK_Integral: 7575 Src = ImpCastExprToType(Src.get(), 7576 SrcTy->castAs<ComplexType>()->getElementType(), 7577 CK_FloatingComplexToReal); 7578 return CK_FloatingToIntegral; 7579 case Type::STK_CPointer: 7580 case Type::STK_ObjCObjectPointer: 7581 case Type::STK_BlockPointer: 7582 llvm_unreachable("valid complex float->pointer cast?"); 7583 case Type::STK_MemberPointer: 7584 llvm_unreachable("member pointer type in C"); 7585 case Type::STK_FixedPoint: 7586 Diag(Src.get()->getExprLoc(), 7587 diag::err_unimplemented_conversion_with_fixed_point_type) 7588 << SrcTy; 7589 return CK_IntegralCast; 7590 } 7591 llvm_unreachable("Should have returned before this"); 7592 7593 case Type::STK_IntegralComplex: 7594 switch (DestTy->getScalarTypeKind()) { 7595 case Type::STK_FloatingComplex: 7596 return CK_IntegralComplexToFloatingComplex; 7597 case Type::STK_IntegralComplex: 7598 return CK_IntegralComplexCast; 7599 case Type::STK_Integral: { 7600 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7601 if (Context.hasSameType(ET, DestTy)) 7602 return CK_IntegralComplexToReal; 7603 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7604 return CK_IntegralCast; 7605 } 7606 case Type::STK_Bool: 7607 return CK_IntegralComplexToBoolean; 7608 case Type::STK_Floating: 7609 Src = ImpCastExprToType(Src.get(), 7610 SrcTy->castAs<ComplexType>()->getElementType(), 7611 CK_IntegralComplexToReal); 7612 return CK_IntegralToFloating; 7613 case Type::STK_CPointer: 7614 case Type::STK_ObjCObjectPointer: 7615 case Type::STK_BlockPointer: 7616 llvm_unreachable("valid complex int->pointer cast?"); 7617 case Type::STK_MemberPointer: 7618 llvm_unreachable("member pointer type in C"); 7619 case Type::STK_FixedPoint: 7620 Diag(Src.get()->getExprLoc(), 7621 diag::err_unimplemented_conversion_with_fixed_point_type) 7622 << SrcTy; 7623 return CK_IntegralCast; 7624 } 7625 llvm_unreachable("Should have returned before this"); 7626 } 7627 7628 llvm_unreachable("Unhandled scalar cast"); 7629 } 7630 7631 static bool breakDownVectorType(QualType type, uint64_t &len, 7632 QualType &eltType) { 7633 // Vectors are simple. 7634 if (const VectorType *vecType = type->getAs<VectorType>()) { 7635 len = vecType->getNumElements(); 7636 eltType = vecType->getElementType(); 7637 assert(eltType->isScalarType()); 7638 return true; 7639 } 7640 7641 // We allow lax conversion to and from non-vector types, but only if 7642 // they're real types (i.e. non-complex, non-pointer scalar types). 7643 if (!type->isRealType()) return false; 7644 7645 len = 1; 7646 eltType = type; 7647 return true; 7648 } 7649 7650 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7651 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7652 /// allowed? 7653 /// 7654 /// This will also return false if the two given types do not make sense from 7655 /// the perspective of SVE bitcasts. 7656 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7657 assert(srcTy->isVectorType() || destTy->isVectorType()); 7658 7659 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7660 if (!FirstType->isSizelessBuiltinType()) 7661 return false; 7662 7663 const auto *VecTy = SecondType->getAs<VectorType>(); 7664 return VecTy && 7665 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7666 }; 7667 7668 return ValidScalableConversion(srcTy, destTy) || 7669 ValidScalableConversion(destTy, srcTy); 7670 } 7671 7672 /// Are the two types matrix types and do they have the same dimensions i.e. 7673 /// do they have the same number of rows and the same number of columns? 7674 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7675 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7676 return false; 7677 7678 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7679 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7680 7681 return matSrcType->getNumRows() == matDestType->getNumRows() && 7682 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7683 } 7684 7685 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7686 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7687 7688 uint64_t SrcLen, DestLen; 7689 QualType SrcEltTy, DestEltTy; 7690 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7691 return false; 7692 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7693 return false; 7694 7695 // ASTContext::getTypeSize will return the size rounded up to a 7696 // power of 2, so instead of using that, we need to use the raw 7697 // element size multiplied by the element count. 7698 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7699 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7700 7701 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7702 } 7703 7704 /// Are the two types lax-compatible vector types? That is, given 7705 /// that one of them is a vector, do they have equal storage sizes, 7706 /// where the storage size is the number of elements times the element 7707 /// size? 7708 /// 7709 /// This will also return false if either of the types is neither a 7710 /// vector nor a real type. 7711 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7712 assert(destTy->isVectorType() || srcTy->isVectorType()); 7713 7714 // Disallow lax conversions between scalars and ExtVectors (these 7715 // conversions are allowed for other vector types because common headers 7716 // depend on them). Most scalar OP ExtVector cases are handled by the 7717 // splat path anyway, which does what we want (convert, not bitcast). 7718 // What this rules out for ExtVectors is crazy things like char4*float. 7719 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7720 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7721 7722 return areVectorTypesSameSize(srcTy, destTy); 7723 } 7724 7725 /// Is this a legal conversion between two types, one of which is 7726 /// known to be a vector type? 7727 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7728 assert(destTy->isVectorType() || srcTy->isVectorType()); 7729 7730 switch (Context.getLangOpts().getLaxVectorConversions()) { 7731 case LangOptions::LaxVectorConversionKind::None: 7732 return false; 7733 7734 case LangOptions::LaxVectorConversionKind::Integer: 7735 if (!srcTy->isIntegralOrEnumerationType()) { 7736 auto *Vec = srcTy->getAs<VectorType>(); 7737 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7738 return false; 7739 } 7740 if (!destTy->isIntegralOrEnumerationType()) { 7741 auto *Vec = destTy->getAs<VectorType>(); 7742 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7743 return false; 7744 } 7745 // OK, integer (vector) -> integer (vector) bitcast. 7746 break; 7747 7748 case LangOptions::LaxVectorConversionKind::All: 7749 break; 7750 } 7751 7752 return areLaxCompatibleVectorTypes(srcTy, destTy); 7753 } 7754 7755 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7756 CastKind &Kind) { 7757 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7758 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7759 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7760 << DestTy << SrcTy << R; 7761 } 7762 } else if (SrcTy->isMatrixType()) { 7763 return Diag(R.getBegin(), 7764 diag::err_invalid_conversion_between_matrix_and_type) 7765 << SrcTy << DestTy << R; 7766 } else if (DestTy->isMatrixType()) { 7767 return Diag(R.getBegin(), 7768 diag::err_invalid_conversion_between_matrix_and_type) 7769 << DestTy << SrcTy << R; 7770 } 7771 7772 Kind = CK_MatrixCast; 7773 return false; 7774 } 7775 7776 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7777 CastKind &Kind) { 7778 assert(VectorTy->isVectorType() && "Not a vector type!"); 7779 7780 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7781 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7782 return Diag(R.getBegin(), 7783 Ty->isVectorType() ? 7784 diag::err_invalid_conversion_between_vectors : 7785 diag::err_invalid_conversion_between_vector_and_integer) 7786 << VectorTy << Ty << R; 7787 } else 7788 return Diag(R.getBegin(), 7789 diag::err_invalid_conversion_between_vector_and_scalar) 7790 << VectorTy << Ty << R; 7791 7792 Kind = CK_BitCast; 7793 return false; 7794 } 7795 7796 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7797 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7798 7799 if (DestElemTy == SplattedExpr->getType()) 7800 return SplattedExpr; 7801 7802 assert(DestElemTy->isFloatingType() || 7803 DestElemTy->isIntegralOrEnumerationType()); 7804 7805 CastKind CK; 7806 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7807 // OpenCL requires that we convert `true` boolean expressions to -1, but 7808 // only when splatting vectors. 7809 if (DestElemTy->isFloatingType()) { 7810 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7811 // in two steps: boolean to signed integral, then to floating. 7812 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7813 CK_BooleanToSignedIntegral); 7814 SplattedExpr = CastExprRes.get(); 7815 CK = CK_IntegralToFloating; 7816 } else { 7817 CK = CK_BooleanToSignedIntegral; 7818 } 7819 } else { 7820 ExprResult CastExprRes = SplattedExpr; 7821 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7822 if (CastExprRes.isInvalid()) 7823 return ExprError(); 7824 SplattedExpr = CastExprRes.get(); 7825 } 7826 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7827 } 7828 7829 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7830 Expr *CastExpr, CastKind &Kind) { 7831 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7832 7833 QualType SrcTy = CastExpr->getType(); 7834 7835 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7836 // an ExtVectorType. 7837 // In OpenCL, casts between vectors of different types are not allowed. 7838 // (See OpenCL 6.2). 7839 if (SrcTy->isVectorType()) { 7840 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7841 (getLangOpts().OpenCL && 7842 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7843 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7844 << DestTy << SrcTy << R; 7845 return ExprError(); 7846 } 7847 Kind = CK_BitCast; 7848 return CastExpr; 7849 } 7850 7851 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7852 // conversion will take place first from scalar to elt type, and then 7853 // splat from elt type to vector. 7854 if (SrcTy->isPointerType()) 7855 return Diag(R.getBegin(), 7856 diag::err_invalid_conversion_between_vector_and_scalar) 7857 << DestTy << SrcTy << R; 7858 7859 Kind = CK_VectorSplat; 7860 return prepareVectorSplat(DestTy, CastExpr); 7861 } 7862 7863 ExprResult 7864 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7865 Declarator &D, ParsedType &Ty, 7866 SourceLocation RParenLoc, Expr *CastExpr) { 7867 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7868 "ActOnCastExpr(): missing type or expr"); 7869 7870 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7871 if (D.isInvalidType()) 7872 return ExprError(); 7873 7874 if (getLangOpts().CPlusPlus) { 7875 // Check that there are no default arguments (C++ only). 7876 CheckExtraCXXDefaultArguments(D); 7877 } else { 7878 // Make sure any TypoExprs have been dealt with. 7879 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7880 if (!Res.isUsable()) 7881 return ExprError(); 7882 CastExpr = Res.get(); 7883 } 7884 7885 checkUnusedDeclAttributes(D); 7886 7887 QualType castType = castTInfo->getType(); 7888 Ty = CreateParsedType(castType, castTInfo); 7889 7890 bool isVectorLiteral = false; 7891 7892 // Check for an altivec or OpenCL literal, 7893 // i.e. all the elements are integer constants. 7894 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7895 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7896 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7897 && castType->isVectorType() && (PE || PLE)) { 7898 if (PLE && PLE->getNumExprs() == 0) { 7899 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7900 return ExprError(); 7901 } 7902 if (PE || PLE->getNumExprs() == 1) { 7903 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7904 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7905 isVectorLiteral = true; 7906 } 7907 else 7908 isVectorLiteral = true; 7909 } 7910 7911 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7912 // then handle it as such. 7913 if (isVectorLiteral) 7914 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7915 7916 // If the Expr being casted is a ParenListExpr, handle it specially. 7917 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7918 // sequence of BinOp comma operators. 7919 if (isa<ParenListExpr>(CastExpr)) { 7920 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7921 if (Result.isInvalid()) return ExprError(); 7922 CastExpr = Result.get(); 7923 } 7924 7925 if (getLangOpts().CPlusPlus && !castType->isVoidType()) 7926 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7927 7928 CheckTollFreeBridgeCast(castType, CastExpr); 7929 7930 CheckObjCBridgeRelatedCast(castType, CastExpr); 7931 7932 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7933 7934 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7935 } 7936 7937 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7938 SourceLocation RParenLoc, Expr *E, 7939 TypeSourceInfo *TInfo) { 7940 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7941 "Expected paren or paren list expression"); 7942 7943 Expr **exprs; 7944 unsigned numExprs; 7945 Expr *subExpr; 7946 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7947 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7948 LiteralLParenLoc = PE->getLParenLoc(); 7949 LiteralRParenLoc = PE->getRParenLoc(); 7950 exprs = PE->getExprs(); 7951 numExprs = PE->getNumExprs(); 7952 } else { // isa<ParenExpr> by assertion at function entrance 7953 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7954 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7955 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7956 exprs = &subExpr; 7957 numExprs = 1; 7958 } 7959 7960 QualType Ty = TInfo->getType(); 7961 assert(Ty->isVectorType() && "Expected vector type"); 7962 7963 SmallVector<Expr *, 8> initExprs; 7964 const VectorType *VTy = Ty->castAs<VectorType>(); 7965 unsigned numElems = VTy->getNumElements(); 7966 7967 // '(...)' form of vector initialization in AltiVec: the number of 7968 // initializers must be one or must match the size of the vector. 7969 // If a single value is specified in the initializer then it will be 7970 // replicated to all the components of the vector 7971 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7972 VTy->getElementType())) 7973 return ExprError(); 7974 if (ShouldSplatAltivecScalarInCast(VTy)) { 7975 // The number of initializers must be one or must match the size of the 7976 // vector. If a single value is specified in the initializer then it will 7977 // be replicated to all the components of the vector 7978 if (numExprs == 1) { 7979 QualType ElemTy = VTy->getElementType(); 7980 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7981 if (Literal.isInvalid()) 7982 return ExprError(); 7983 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7984 PrepareScalarCast(Literal, ElemTy)); 7985 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7986 } 7987 else if (numExprs < numElems) { 7988 Diag(E->getExprLoc(), 7989 diag::err_incorrect_number_of_vector_initializers); 7990 return ExprError(); 7991 } 7992 else 7993 initExprs.append(exprs, exprs + numExprs); 7994 } 7995 else { 7996 // For OpenCL, when the number of initializers is a single value, 7997 // it will be replicated to all components of the vector. 7998 if (getLangOpts().OpenCL && 7999 VTy->getVectorKind() == VectorType::GenericVector && 8000 numExprs == 1) { 8001 QualType ElemTy = VTy->getElementType(); 8002 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 8003 if (Literal.isInvalid()) 8004 return ExprError(); 8005 Literal = ImpCastExprToType(Literal.get(), ElemTy, 8006 PrepareScalarCast(Literal, ElemTy)); 8007 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 8008 } 8009 8010 initExprs.append(exprs, exprs + numExprs); 8011 } 8012 // FIXME: This means that pretty-printing the final AST will produce curly 8013 // braces instead of the original commas. 8014 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 8015 initExprs, LiteralRParenLoc); 8016 initE->setType(Ty); 8017 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 8018 } 8019 8020 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 8021 /// the ParenListExpr into a sequence of comma binary operators. 8022 ExprResult 8023 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 8024 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 8025 if (!E) 8026 return OrigExpr; 8027 8028 ExprResult Result(E->getExpr(0)); 8029 8030 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 8031 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 8032 E->getExpr(i)); 8033 8034 if (Result.isInvalid()) return ExprError(); 8035 8036 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 8037 } 8038 8039 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 8040 SourceLocation R, 8041 MultiExprArg Val) { 8042 return ParenListExpr::Create(Context, L, Val, R); 8043 } 8044 8045 /// Emit a specialized diagnostic when one expression is a null pointer 8046 /// constant and the other is not a pointer. Returns true if a diagnostic is 8047 /// emitted. 8048 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 8049 SourceLocation QuestionLoc) { 8050 Expr *NullExpr = LHSExpr; 8051 Expr *NonPointerExpr = RHSExpr; 8052 Expr::NullPointerConstantKind NullKind = 8053 NullExpr->isNullPointerConstant(Context, 8054 Expr::NPC_ValueDependentIsNotNull); 8055 8056 if (NullKind == Expr::NPCK_NotNull) { 8057 NullExpr = RHSExpr; 8058 NonPointerExpr = LHSExpr; 8059 NullKind = 8060 NullExpr->isNullPointerConstant(Context, 8061 Expr::NPC_ValueDependentIsNotNull); 8062 } 8063 8064 if (NullKind == Expr::NPCK_NotNull) 8065 return false; 8066 8067 if (NullKind == Expr::NPCK_ZeroExpression) 8068 return false; 8069 8070 if (NullKind == Expr::NPCK_ZeroLiteral) { 8071 // In this case, check to make sure that we got here from a "NULL" 8072 // string in the source code. 8073 NullExpr = NullExpr->IgnoreParenImpCasts(); 8074 SourceLocation loc = NullExpr->getExprLoc(); 8075 if (!findMacroSpelling(loc, "NULL")) 8076 return false; 8077 } 8078 8079 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 8080 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 8081 << NonPointerExpr->getType() << DiagType 8082 << NonPointerExpr->getSourceRange(); 8083 return true; 8084 } 8085 8086 /// Return false if the condition expression is valid, true otherwise. 8087 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 8088 QualType CondTy = Cond->getType(); 8089 8090 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 8091 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 8092 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8093 << CondTy << Cond->getSourceRange(); 8094 return true; 8095 } 8096 8097 // C99 6.5.15p2 8098 if (CondTy->isScalarType()) return false; 8099 8100 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 8101 << CondTy << Cond->getSourceRange(); 8102 return true; 8103 } 8104 8105 /// Handle when one or both operands are void type. 8106 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 8107 ExprResult &RHS) { 8108 Expr *LHSExpr = LHS.get(); 8109 Expr *RHSExpr = RHS.get(); 8110 8111 if (!LHSExpr->getType()->isVoidType()) 8112 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8113 << RHSExpr->getSourceRange(); 8114 if (!RHSExpr->getType()->isVoidType()) 8115 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8116 << LHSExpr->getSourceRange(); 8117 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 8118 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 8119 return S.Context.VoidTy; 8120 } 8121 8122 /// Return false if the NullExpr can be promoted to PointerTy, 8123 /// true otherwise. 8124 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 8125 QualType PointerTy) { 8126 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 8127 !NullExpr.get()->isNullPointerConstant(S.Context, 8128 Expr::NPC_ValueDependentIsNull)) 8129 return true; 8130 8131 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 8132 return false; 8133 } 8134 8135 /// Checks compatibility between two pointers and return the resulting 8136 /// type. 8137 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 8138 ExprResult &RHS, 8139 SourceLocation Loc) { 8140 QualType LHSTy = LHS.get()->getType(); 8141 QualType RHSTy = RHS.get()->getType(); 8142 8143 if (S.Context.hasSameType(LHSTy, RHSTy)) { 8144 // Two identical pointers types are always compatible. 8145 return LHSTy; 8146 } 8147 8148 QualType lhptee, rhptee; 8149 8150 // Get the pointee types. 8151 bool IsBlockPointer = false; 8152 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 8153 lhptee = LHSBTy->getPointeeType(); 8154 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 8155 IsBlockPointer = true; 8156 } else { 8157 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8158 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8159 } 8160 8161 // C99 6.5.15p6: If both operands are pointers to compatible types or to 8162 // differently qualified versions of compatible types, the result type is 8163 // a pointer to an appropriately qualified version of the composite 8164 // type. 8165 8166 // Only CVR-qualifiers exist in the standard, and the differently-qualified 8167 // clause doesn't make sense for our extensions. E.g. address space 2 should 8168 // be incompatible with address space 3: they may live on different devices or 8169 // anything. 8170 Qualifiers lhQual = lhptee.getQualifiers(); 8171 Qualifiers rhQual = rhptee.getQualifiers(); 8172 8173 LangAS ResultAddrSpace = LangAS::Default; 8174 LangAS LAddrSpace = lhQual.getAddressSpace(); 8175 LangAS RAddrSpace = rhQual.getAddressSpace(); 8176 8177 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 8178 // spaces is disallowed. 8179 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 8180 ResultAddrSpace = LAddrSpace; 8181 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 8182 ResultAddrSpace = RAddrSpace; 8183 else { 8184 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8185 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 8186 << RHS.get()->getSourceRange(); 8187 return QualType(); 8188 } 8189 8190 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 8191 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 8192 lhQual.removeCVRQualifiers(); 8193 rhQual.removeCVRQualifiers(); 8194 8195 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 8196 // (C99 6.7.3) for address spaces. We assume that the check should behave in 8197 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 8198 // qual types are compatible iff 8199 // * corresponded types are compatible 8200 // * CVR qualifiers are equal 8201 // * address spaces are equal 8202 // Thus for conditional operator we merge CVR and address space unqualified 8203 // pointees and if there is a composite type we return a pointer to it with 8204 // merged qualifiers. 8205 LHSCastKind = 8206 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8207 RHSCastKind = 8208 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8209 lhQual.removeAddressSpace(); 8210 rhQual.removeAddressSpace(); 8211 8212 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 8213 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 8214 8215 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 8216 8217 if (CompositeTy.isNull()) { 8218 // In this situation, we assume void* type. No especially good 8219 // reason, but this is what gcc does, and we do have to pick 8220 // to get a consistent AST. 8221 QualType incompatTy; 8222 incompatTy = S.Context.getPointerType( 8223 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 8224 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 8225 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 8226 8227 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 8228 // for casts between types with incompatible address space qualifiers. 8229 // For the following code the compiler produces casts between global and 8230 // local address spaces of the corresponded innermost pointees: 8231 // local int *global *a; 8232 // global int *global *b; 8233 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8234 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8235 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8236 << RHS.get()->getSourceRange(); 8237 8238 return incompatTy; 8239 } 8240 8241 // The pointer types are compatible. 8242 // In case of OpenCL ResultTy should have the address space qualifier 8243 // which is a superset of address spaces of both the 2nd and the 3rd 8244 // operands of the conditional operator. 8245 QualType ResultTy = [&, ResultAddrSpace]() { 8246 if (S.getLangOpts().OpenCL) { 8247 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8248 CompositeQuals.setAddressSpace(ResultAddrSpace); 8249 return S.Context 8250 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8251 .withCVRQualifiers(MergedCVRQual); 8252 } 8253 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8254 }(); 8255 if (IsBlockPointer) 8256 ResultTy = S.Context.getBlockPointerType(ResultTy); 8257 else 8258 ResultTy = S.Context.getPointerType(ResultTy); 8259 8260 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8261 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8262 return ResultTy; 8263 } 8264 8265 /// Return the resulting type when the operands are both block pointers. 8266 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8267 ExprResult &LHS, 8268 ExprResult &RHS, 8269 SourceLocation Loc) { 8270 QualType LHSTy = LHS.get()->getType(); 8271 QualType RHSTy = RHS.get()->getType(); 8272 8273 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8274 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8275 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8276 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8277 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8278 return destType; 8279 } 8280 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8281 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8282 << RHS.get()->getSourceRange(); 8283 return QualType(); 8284 } 8285 8286 // We have 2 block pointer types. 8287 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8288 } 8289 8290 /// Return the resulting type when the operands are both pointers. 8291 static QualType 8292 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8293 ExprResult &RHS, 8294 SourceLocation Loc) { 8295 // get the pointer types 8296 QualType LHSTy = LHS.get()->getType(); 8297 QualType RHSTy = RHS.get()->getType(); 8298 8299 // get the "pointed to" types 8300 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8301 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8302 8303 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8304 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8305 // Figure out necessary qualifiers (C99 6.5.15p6) 8306 QualType destPointee 8307 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8308 QualType destType = S.Context.getPointerType(destPointee); 8309 // Add qualifiers if necessary. 8310 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8311 // Promote to void*. 8312 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8313 return destType; 8314 } 8315 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8316 QualType destPointee 8317 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8318 QualType destType = S.Context.getPointerType(destPointee); 8319 // Add qualifiers if necessary. 8320 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8321 // Promote to void*. 8322 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8323 return destType; 8324 } 8325 8326 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8327 } 8328 8329 /// Return false if the first expression is not an integer and the second 8330 /// expression is not a pointer, true otherwise. 8331 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8332 Expr* PointerExpr, SourceLocation Loc, 8333 bool IsIntFirstExpr) { 8334 if (!PointerExpr->getType()->isPointerType() || 8335 !Int.get()->getType()->isIntegerType()) 8336 return false; 8337 8338 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8339 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8340 8341 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8342 << Expr1->getType() << Expr2->getType() 8343 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8344 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8345 CK_IntegralToPointer); 8346 return true; 8347 } 8348 8349 /// Simple conversion between integer and floating point types. 8350 /// 8351 /// Used when handling the OpenCL conditional operator where the 8352 /// condition is a vector while the other operands are scalar. 8353 /// 8354 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8355 /// types are either integer or floating type. Between the two 8356 /// operands, the type with the higher rank is defined as the "result 8357 /// type". The other operand needs to be promoted to the same type. No 8358 /// other type promotion is allowed. We cannot use 8359 /// UsualArithmeticConversions() for this purpose, since it always 8360 /// promotes promotable types. 8361 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8362 ExprResult &RHS, 8363 SourceLocation QuestionLoc) { 8364 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8365 if (LHS.isInvalid()) 8366 return QualType(); 8367 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8368 if (RHS.isInvalid()) 8369 return QualType(); 8370 8371 // For conversion purposes, we ignore any qualifiers. 8372 // For example, "const float" and "float" are equivalent. 8373 QualType LHSType = 8374 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8375 QualType RHSType = 8376 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8377 8378 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8379 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8380 << LHSType << LHS.get()->getSourceRange(); 8381 return QualType(); 8382 } 8383 8384 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8385 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8386 << RHSType << RHS.get()->getSourceRange(); 8387 return QualType(); 8388 } 8389 8390 // If both types are identical, no conversion is needed. 8391 if (LHSType == RHSType) 8392 return LHSType; 8393 8394 // Now handle "real" floating types (i.e. float, double, long double). 8395 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8396 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8397 /*IsCompAssign = */ false); 8398 8399 // Finally, we have two differing integer types. 8400 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8401 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8402 } 8403 8404 /// Convert scalar operands to a vector that matches the 8405 /// condition in length. 8406 /// 8407 /// Used when handling the OpenCL conditional operator where the 8408 /// condition is a vector while the other operands are scalar. 8409 /// 8410 /// We first compute the "result type" for the scalar operands 8411 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8412 /// into a vector of that type where the length matches the condition 8413 /// vector type. s6.11.6 requires that the element types of the result 8414 /// and the condition must have the same number of bits. 8415 static QualType 8416 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8417 QualType CondTy, SourceLocation QuestionLoc) { 8418 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8419 if (ResTy.isNull()) return QualType(); 8420 8421 const VectorType *CV = CondTy->getAs<VectorType>(); 8422 assert(CV); 8423 8424 // Determine the vector result type 8425 unsigned NumElements = CV->getNumElements(); 8426 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8427 8428 // Ensure that all types have the same number of bits 8429 if (S.Context.getTypeSize(CV->getElementType()) 8430 != S.Context.getTypeSize(ResTy)) { 8431 // Since VectorTy is created internally, it does not pretty print 8432 // with an OpenCL name. Instead, we just print a description. 8433 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8434 SmallString<64> Str; 8435 llvm::raw_svector_ostream OS(Str); 8436 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8437 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8438 << CondTy << OS.str(); 8439 return QualType(); 8440 } 8441 8442 // Convert operands to the vector result type 8443 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8444 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8445 8446 return VectorTy; 8447 } 8448 8449 /// Return false if this is a valid OpenCL condition vector 8450 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8451 SourceLocation QuestionLoc) { 8452 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8453 // integral type. 8454 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8455 assert(CondTy); 8456 QualType EleTy = CondTy->getElementType(); 8457 if (EleTy->isIntegerType()) return false; 8458 8459 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8460 << Cond->getType() << Cond->getSourceRange(); 8461 return true; 8462 } 8463 8464 /// Return false if the vector condition type and the vector 8465 /// result type are compatible. 8466 /// 8467 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8468 /// number of elements, and their element types have the same number 8469 /// of bits. 8470 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8471 SourceLocation QuestionLoc) { 8472 const VectorType *CV = CondTy->getAs<VectorType>(); 8473 const VectorType *RV = VecResTy->getAs<VectorType>(); 8474 assert(CV && RV); 8475 8476 if (CV->getNumElements() != RV->getNumElements()) { 8477 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8478 << CondTy << VecResTy; 8479 return true; 8480 } 8481 8482 QualType CVE = CV->getElementType(); 8483 QualType RVE = RV->getElementType(); 8484 8485 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8486 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8487 << CondTy << VecResTy; 8488 return true; 8489 } 8490 8491 return false; 8492 } 8493 8494 /// Return the resulting type for the conditional operator in 8495 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8496 /// s6.3.i) when the condition is a vector type. 8497 static QualType 8498 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8499 ExprResult &LHS, ExprResult &RHS, 8500 SourceLocation QuestionLoc) { 8501 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8502 if (Cond.isInvalid()) 8503 return QualType(); 8504 QualType CondTy = Cond.get()->getType(); 8505 8506 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8507 return QualType(); 8508 8509 // If either operand is a vector then find the vector type of the 8510 // result as specified in OpenCL v1.1 s6.3.i. 8511 if (LHS.get()->getType()->isVectorType() || 8512 RHS.get()->getType()->isVectorType()) { 8513 bool IsBoolVecLang = 8514 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; 8515 QualType VecResTy = 8516 S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8517 /*isCompAssign*/ false, 8518 /*AllowBothBool*/ true, 8519 /*AllowBoolConversions*/ false, 8520 /*AllowBooleanOperation*/ IsBoolVecLang, 8521 /*ReportInvalid*/ true); 8522 if (VecResTy.isNull()) 8523 return QualType(); 8524 // The result type must match the condition type as specified in 8525 // OpenCL v1.1 s6.11.6. 8526 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8527 return QualType(); 8528 return VecResTy; 8529 } 8530 8531 // Both operands are scalar. 8532 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8533 } 8534 8535 /// Return true if the Expr is block type 8536 static bool checkBlockType(Sema &S, const Expr *E) { 8537 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8538 QualType Ty = CE->getCallee()->getType(); 8539 if (Ty->isBlockPointerType()) { 8540 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8541 return true; 8542 } 8543 } 8544 return false; 8545 } 8546 8547 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8548 /// In that case, LHS = cond. 8549 /// C99 6.5.15 8550 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8551 ExprResult &RHS, ExprValueKind &VK, 8552 ExprObjectKind &OK, 8553 SourceLocation QuestionLoc) { 8554 8555 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8556 if (!LHSResult.isUsable()) return QualType(); 8557 LHS = LHSResult; 8558 8559 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8560 if (!RHSResult.isUsable()) return QualType(); 8561 RHS = RHSResult; 8562 8563 // C++ is sufficiently different to merit its own checker. 8564 if (getLangOpts().CPlusPlus) 8565 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8566 8567 VK = VK_PRValue; 8568 OK = OK_Ordinary; 8569 8570 if (Context.isDependenceAllowed() && 8571 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8572 RHS.get()->isTypeDependent())) { 8573 assert(!getLangOpts().CPlusPlus); 8574 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8575 RHS.get()->containsErrors()) && 8576 "should only occur in error-recovery path."); 8577 return Context.DependentTy; 8578 } 8579 8580 // The OpenCL operator with a vector condition is sufficiently 8581 // different to merit its own checker. 8582 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8583 Cond.get()->getType()->isExtVectorType()) 8584 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8585 8586 // First, check the condition. 8587 Cond = UsualUnaryConversions(Cond.get()); 8588 if (Cond.isInvalid()) 8589 return QualType(); 8590 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8591 return QualType(); 8592 8593 // Now check the two expressions. 8594 if (LHS.get()->getType()->isVectorType() || 8595 RHS.get()->getType()->isVectorType()) 8596 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, 8597 /*AllowBothBool*/ true, 8598 /*AllowBoolConversions*/ false, 8599 /*AllowBooleanOperation*/ false, 8600 /*ReportInvalid*/ true); 8601 8602 QualType ResTy = 8603 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8604 if (LHS.isInvalid() || RHS.isInvalid()) 8605 return QualType(); 8606 8607 QualType LHSTy = LHS.get()->getType(); 8608 QualType RHSTy = RHS.get()->getType(); 8609 8610 // Diagnose attempts to convert between __ibm128, __float128 and long double 8611 // where such conversions currently can't be handled. 8612 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8613 Diag(QuestionLoc, 8614 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8615 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8616 return QualType(); 8617 } 8618 8619 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8620 // selection operator (?:). 8621 if (getLangOpts().OpenCL && 8622 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8623 return QualType(); 8624 } 8625 8626 // If both operands have arithmetic type, do the usual arithmetic conversions 8627 // to find a common type: C99 6.5.15p3,5. 8628 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8629 // Disallow invalid arithmetic conversions, such as those between bit- 8630 // precise integers types of different sizes, or between a bit-precise 8631 // integer and another type. 8632 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { 8633 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8634 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8635 << RHS.get()->getSourceRange(); 8636 return QualType(); 8637 } 8638 8639 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8640 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8641 8642 return ResTy; 8643 } 8644 8645 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8646 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8647 return LHSTy; 8648 } 8649 8650 // If both operands are the same structure or union type, the result is that 8651 // type. 8652 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8653 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8654 if (LHSRT->getDecl() == RHSRT->getDecl()) 8655 // "If both the operands have structure or union type, the result has 8656 // that type." This implies that CV qualifiers are dropped. 8657 return LHSTy.getUnqualifiedType(); 8658 // FIXME: Type of conditional expression must be complete in C mode. 8659 } 8660 8661 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8662 // The following || allows only one side to be void (a GCC-ism). 8663 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8664 return checkConditionalVoidType(*this, LHS, RHS); 8665 } 8666 8667 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8668 // the type of the other operand." 8669 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8670 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8671 8672 // All objective-c pointer type analysis is done here. 8673 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8674 QuestionLoc); 8675 if (LHS.isInvalid() || RHS.isInvalid()) 8676 return QualType(); 8677 if (!compositeType.isNull()) 8678 return compositeType; 8679 8680 8681 // Handle block pointer types. 8682 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8683 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8684 QuestionLoc); 8685 8686 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8687 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8688 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8689 QuestionLoc); 8690 8691 // GCC compatibility: soften pointer/integer mismatch. Note that 8692 // null pointers have been filtered out by this point. 8693 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8694 /*IsIntFirstExpr=*/true)) 8695 return RHSTy; 8696 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8697 /*IsIntFirstExpr=*/false)) 8698 return LHSTy; 8699 8700 // Allow ?: operations in which both operands have the same 8701 // built-in sizeless type. 8702 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8703 return LHSTy; 8704 8705 // Emit a better diagnostic if one of the expressions is a null pointer 8706 // constant and the other is not a pointer type. In this case, the user most 8707 // likely forgot to take the address of the other expression. 8708 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8709 return QualType(); 8710 8711 // Otherwise, the operands are not compatible. 8712 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8713 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8714 << RHS.get()->getSourceRange(); 8715 return QualType(); 8716 } 8717 8718 /// FindCompositeObjCPointerType - Helper method to find composite type of 8719 /// two objective-c pointer types of the two input expressions. 8720 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8721 SourceLocation QuestionLoc) { 8722 QualType LHSTy = LHS.get()->getType(); 8723 QualType RHSTy = RHS.get()->getType(); 8724 8725 // Handle things like Class and struct objc_class*. Here we case the result 8726 // to the pseudo-builtin, because that will be implicitly cast back to the 8727 // redefinition type if an attempt is made to access its fields. 8728 if (LHSTy->isObjCClassType() && 8729 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8730 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8731 return LHSTy; 8732 } 8733 if (RHSTy->isObjCClassType() && 8734 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8735 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8736 return RHSTy; 8737 } 8738 // And the same for struct objc_object* / id 8739 if (LHSTy->isObjCIdType() && 8740 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8741 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8742 return LHSTy; 8743 } 8744 if (RHSTy->isObjCIdType() && 8745 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8746 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8747 return RHSTy; 8748 } 8749 // And the same for struct objc_selector* / SEL 8750 if (Context.isObjCSelType(LHSTy) && 8751 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8752 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8753 return LHSTy; 8754 } 8755 if (Context.isObjCSelType(RHSTy) && 8756 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8757 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8758 return RHSTy; 8759 } 8760 // Check constraints for Objective-C object pointers types. 8761 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8762 8763 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8764 // Two identical object pointer types are always compatible. 8765 return LHSTy; 8766 } 8767 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8768 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8769 QualType compositeType = LHSTy; 8770 8771 // If both operands are interfaces and either operand can be 8772 // assigned to the other, use that type as the composite 8773 // type. This allows 8774 // xxx ? (A*) a : (B*) b 8775 // where B is a subclass of A. 8776 // 8777 // Additionally, as for assignment, if either type is 'id' 8778 // allow silent coercion. Finally, if the types are 8779 // incompatible then make sure to use 'id' as the composite 8780 // type so the result is acceptable for sending messages to. 8781 8782 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8783 // It could return the composite type. 8784 if (!(compositeType = 8785 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8786 // Nothing more to do. 8787 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8788 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8789 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8790 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8791 } else if ((LHSOPT->isObjCQualifiedIdType() || 8792 RHSOPT->isObjCQualifiedIdType()) && 8793 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8794 true)) { 8795 // Need to handle "id<xx>" explicitly. 8796 // GCC allows qualified id and any Objective-C type to devolve to 8797 // id. Currently localizing to here until clear this should be 8798 // part of ObjCQualifiedIdTypesAreCompatible. 8799 compositeType = Context.getObjCIdType(); 8800 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8801 compositeType = Context.getObjCIdType(); 8802 } else { 8803 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8804 << LHSTy << RHSTy 8805 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8806 QualType incompatTy = Context.getObjCIdType(); 8807 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8808 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8809 return incompatTy; 8810 } 8811 // The object pointer types are compatible. 8812 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8813 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8814 return compositeType; 8815 } 8816 // Check Objective-C object pointer types and 'void *' 8817 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8818 if (getLangOpts().ObjCAutoRefCount) { 8819 // ARC forbids the implicit conversion of object pointers to 'void *', 8820 // so these types are not compatible. 8821 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8822 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8823 LHS = RHS = true; 8824 return QualType(); 8825 } 8826 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8827 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8828 QualType destPointee 8829 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8830 QualType destType = Context.getPointerType(destPointee); 8831 // Add qualifiers if necessary. 8832 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8833 // Promote to void*. 8834 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8835 return destType; 8836 } 8837 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8838 if (getLangOpts().ObjCAutoRefCount) { 8839 // ARC forbids the implicit conversion of object pointers to 'void *', 8840 // so these types are not compatible. 8841 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8842 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8843 LHS = RHS = true; 8844 return QualType(); 8845 } 8846 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8847 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8848 QualType destPointee 8849 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8850 QualType destType = Context.getPointerType(destPointee); 8851 // Add qualifiers if necessary. 8852 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8853 // Promote to void*. 8854 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8855 return destType; 8856 } 8857 return QualType(); 8858 } 8859 8860 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8861 /// ParenRange in parentheses. 8862 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8863 const PartialDiagnostic &Note, 8864 SourceRange ParenRange) { 8865 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8866 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8867 EndLoc.isValid()) { 8868 Self.Diag(Loc, Note) 8869 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8870 << FixItHint::CreateInsertion(EndLoc, ")"); 8871 } else { 8872 // We can't display the parentheses, so just show the bare note. 8873 Self.Diag(Loc, Note) << ParenRange; 8874 } 8875 } 8876 8877 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8878 return BinaryOperator::isAdditiveOp(Opc) || 8879 BinaryOperator::isMultiplicativeOp(Opc) || 8880 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8881 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8882 // not any of the logical operators. Bitwise-xor is commonly used as a 8883 // logical-xor because there is no logical-xor operator. The logical 8884 // operators, including uses of xor, have a high false positive rate for 8885 // precedence warnings. 8886 } 8887 8888 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8889 /// expression, either using a built-in or overloaded operator, 8890 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8891 /// expression. 8892 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8893 Expr **RHSExprs) { 8894 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8895 E = E->IgnoreImpCasts(); 8896 E = E->IgnoreConversionOperatorSingleStep(); 8897 E = E->IgnoreImpCasts(); 8898 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8899 E = MTE->getSubExpr(); 8900 E = E->IgnoreImpCasts(); 8901 } 8902 8903 // Built-in binary operator. 8904 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8905 if (IsArithmeticOp(OP->getOpcode())) { 8906 *Opcode = OP->getOpcode(); 8907 *RHSExprs = OP->getRHS(); 8908 return true; 8909 } 8910 } 8911 8912 // Overloaded operator. 8913 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8914 if (Call->getNumArgs() != 2) 8915 return false; 8916 8917 // Make sure this is really a binary operator that is safe to pass into 8918 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8919 OverloadedOperatorKind OO = Call->getOperator(); 8920 if (OO < OO_Plus || OO > OO_Arrow || 8921 OO == OO_PlusPlus || OO == OO_MinusMinus) 8922 return false; 8923 8924 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8925 if (IsArithmeticOp(OpKind)) { 8926 *Opcode = OpKind; 8927 *RHSExprs = Call->getArg(1); 8928 return true; 8929 } 8930 } 8931 8932 return false; 8933 } 8934 8935 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8936 /// or is a logical expression such as (x==y) which has int type, but is 8937 /// commonly interpreted as boolean. 8938 static bool ExprLooksBoolean(Expr *E) { 8939 E = E->IgnoreParenImpCasts(); 8940 8941 if (E->getType()->isBooleanType()) 8942 return true; 8943 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8944 return OP->isComparisonOp() || OP->isLogicalOp(); 8945 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8946 return OP->getOpcode() == UO_LNot; 8947 if (E->getType()->isPointerType()) 8948 return true; 8949 // FIXME: What about overloaded operator calls returning "unspecified boolean 8950 // type"s (commonly pointer-to-members)? 8951 8952 return false; 8953 } 8954 8955 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8956 /// and binary operator are mixed in a way that suggests the programmer assumed 8957 /// the conditional operator has higher precedence, for example: 8958 /// "int x = a + someBinaryCondition ? 1 : 2". 8959 static void DiagnoseConditionalPrecedence(Sema &Self, 8960 SourceLocation OpLoc, 8961 Expr *Condition, 8962 Expr *LHSExpr, 8963 Expr *RHSExpr) { 8964 BinaryOperatorKind CondOpcode; 8965 Expr *CondRHS; 8966 8967 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8968 return; 8969 if (!ExprLooksBoolean(CondRHS)) 8970 return; 8971 8972 // The condition is an arithmetic binary expression, with a right- 8973 // hand side that looks boolean, so warn. 8974 8975 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8976 ? diag::warn_precedence_bitwise_conditional 8977 : diag::warn_precedence_conditional; 8978 8979 Self.Diag(OpLoc, DiagID) 8980 << Condition->getSourceRange() 8981 << BinaryOperator::getOpcodeStr(CondOpcode); 8982 8983 SuggestParentheses( 8984 Self, OpLoc, 8985 Self.PDiag(diag::note_precedence_silence) 8986 << BinaryOperator::getOpcodeStr(CondOpcode), 8987 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8988 8989 SuggestParentheses(Self, OpLoc, 8990 Self.PDiag(diag::note_precedence_conditional_first), 8991 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8992 } 8993 8994 /// Compute the nullability of a conditional expression. 8995 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8996 QualType LHSTy, QualType RHSTy, 8997 ASTContext &Ctx) { 8998 if (!ResTy->isAnyPointerType()) 8999 return ResTy; 9000 9001 auto GetNullability = [&Ctx](QualType Ty) { 9002 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 9003 if (Kind) { 9004 // For our purposes, treat _Nullable_result as _Nullable. 9005 if (*Kind == NullabilityKind::NullableResult) 9006 return NullabilityKind::Nullable; 9007 return *Kind; 9008 } 9009 return NullabilityKind::Unspecified; 9010 }; 9011 9012 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 9013 NullabilityKind MergedKind; 9014 9015 // Compute nullability of a binary conditional expression. 9016 if (IsBin) { 9017 if (LHSKind == NullabilityKind::NonNull) 9018 MergedKind = NullabilityKind::NonNull; 9019 else 9020 MergedKind = RHSKind; 9021 // Compute nullability of a normal conditional expression. 9022 } else { 9023 if (LHSKind == NullabilityKind::Nullable || 9024 RHSKind == NullabilityKind::Nullable) 9025 MergedKind = NullabilityKind::Nullable; 9026 else if (LHSKind == NullabilityKind::NonNull) 9027 MergedKind = RHSKind; 9028 else if (RHSKind == NullabilityKind::NonNull) 9029 MergedKind = LHSKind; 9030 else 9031 MergedKind = NullabilityKind::Unspecified; 9032 } 9033 9034 // Return if ResTy already has the correct nullability. 9035 if (GetNullability(ResTy) == MergedKind) 9036 return ResTy; 9037 9038 // Strip all nullability from ResTy. 9039 while (ResTy->getNullability(Ctx)) 9040 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 9041 9042 // Create a new AttributedType with the new nullability kind. 9043 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 9044 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 9045 } 9046 9047 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 9048 /// in the case of a the GNU conditional expr extension. 9049 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 9050 SourceLocation ColonLoc, 9051 Expr *CondExpr, Expr *LHSExpr, 9052 Expr *RHSExpr) { 9053 if (!Context.isDependenceAllowed()) { 9054 // C cannot handle TypoExpr nodes in the condition because it 9055 // doesn't handle dependent types properly, so make sure any TypoExprs have 9056 // been dealt with before checking the operands. 9057 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 9058 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 9059 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 9060 9061 if (!CondResult.isUsable()) 9062 return ExprError(); 9063 9064 if (LHSExpr) { 9065 if (!LHSResult.isUsable()) 9066 return ExprError(); 9067 } 9068 9069 if (!RHSResult.isUsable()) 9070 return ExprError(); 9071 9072 CondExpr = CondResult.get(); 9073 LHSExpr = LHSResult.get(); 9074 RHSExpr = RHSResult.get(); 9075 } 9076 9077 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 9078 // was the condition. 9079 OpaqueValueExpr *opaqueValue = nullptr; 9080 Expr *commonExpr = nullptr; 9081 if (!LHSExpr) { 9082 commonExpr = CondExpr; 9083 // Lower out placeholder types first. This is important so that we don't 9084 // try to capture a placeholder. This happens in few cases in C++; such 9085 // as Objective-C++'s dictionary subscripting syntax. 9086 if (commonExpr->hasPlaceholderType()) { 9087 ExprResult result = CheckPlaceholderExpr(commonExpr); 9088 if (!result.isUsable()) return ExprError(); 9089 commonExpr = result.get(); 9090 } 9091 // We usually want to apply unary conversions *before* saving, except 9092 // in the special case of a C++ l-value conditional. 9093 if (!(getLangOpts().CPlusPlus 9094 && !commonExpr->isTypeDependent() 9095 && commonExpr->getValueKind() == RHSExpr->getValueKind() 9096 && commonExpr->isGLValue() 9097 && commonExpr->isOrdinaryOrBitFieldObject() 9098 && RHSExpr->isOrdinaryOrBitFieldObject() 9099 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 9100 ExprResult commonRes = UsualUnaryConversions(commonExpr); 9101 if (commonRes.isInvalid()) 9102 return ExprError(); 9103 commonExpr = commonRes.get(); 9104 } 9105 9106 // If the common expression is a class or array prvalue, materialize it 9107 // so that we can safely refer to it multiple times. 9108 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 9109 commonExpr->getType()->isArrayType())) { 9110 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 9111 if (MatExpr.isInvalid()) 9112 return ExprError(); 9113 commonExpr = MatExpr.get(); 9114 } 9115 9116 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 9117 commonExpr->getType(), 9118 commonExpr->getValueKind(), 9119 commonExpr->getObjectKind(), 9120 commonExpr); 9121 LHSExpr = CondExpr = opaqueValue; 9122 } 9123 9124 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 9125 ExprValueKind VK = VK_PRValue; 9126 ExprObjectKind OK = OK_Ordinary; 9127 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 9128 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 9129 VK, OK, QuestionLoc); 9130 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 9131 RHS.isInvalid()) 9132 return ExprError(); 9133 9134 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 9135 RHS.get()); 9136 9137 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 9138 9139 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 9140 Context); 9141 9142 if (!commonExpr) 9143 return new (Context) 9144 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 9145 RHS.get(), result, VK, OK); 9146 9147 return new (Context) BinaryConditionalOperator( 9148 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 9149 ColonLoc, result, VK, OK); 9150 } 9151 9152 // Check if we have a conversion between incompatible cmse function pointer 9153 // types, that is, a conversion between a function pointer with the 9154 // cmse_nonsecure_call attribute and one without. 9155 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 9156 QualType ToType) { 9157 if (const auto *ToFn = 9158 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 9159 if (const auto *FromFn = 9160 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 9161 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 9162 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 9163 9164 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 9165 } 9166 } 9167 return false; 9168 } 9169 9170 // checkPointerTypesForAssignment - This is a very tricky routine (despite 9171 // being closely modeled after the C99 spec:-). The odd characteristic of this 9172 // routine is it effectively iqnores the qualifiers on the top level pointee. 9173 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 9174 // FIXME: add a couple examples in this comment. 9175 static Sema::AssignConvertType 9176 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 9177 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9178 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9179 9180 // get the "pointed to" type (ignoring qualifiers at the top level) 9181 const Type *lhptee, *rhptee; 9182 Qualifiers lhq, rhq; 9183 std::tie(lhptee, lhq) = 9184 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 9185 std::tie(rhptee, rhq) = 9186 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 9187 9188 Sema::AssignConvertType ConvTy = Sema::Compatible; 9189 9190 // C99 6.5.16.1p1: This following citation is common to constraints 9191 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 9192 // qualifiers of the type *pointed to* by the right; 9193 9194 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 9195 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 9196 lhq.compatiblyIncludesObjCLifetime(rhq)) { 9197 // Ignore lifetime for further calculation. 9198 lhq.removeObjCLifetime(); 9199 rhq.removeObjCLifetime(); 9200 } 9201 9202 if (!lhq.compatiblyIncludes(rhq)) { 9203 // Treat address-space mismatches as fatal. 9204 if (!lhq.isAddressSpaceSupersetOf(rhq)) 9205 return Sema::IncompatiblePointerDiscardsQualifiers; 9206 9207 // It's okay to add or remove GC or lifetime qualifiers when converting to 9208 // and from void*. 9209 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 9210 .compatiblyIncludes( 9211 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 9212 && (lhptee->isVoidType() || rhptee->isVoidType())) 9213 ; // keep old 9214 9215 // Treat lifetime mismatches as fatal. 9216 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 9217 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 9218 9219 // For GCC/MS compatibility, other qualifier mismatches are treated 9220 // as still compatible in C. 9221 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9222 } 9223 9224 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 9225 // incomplete type and the other is a pointer to a qualified or unqualified 9226 // version of void... 9227 if (lhptee->isVoidType()) { 9228 if (rhptee->isIncompleteOrObjectType()) 9229 return ConvTy; 9230 9231 // As an extension, we allow cast to/from void* to function pointer. 9232 assert(rhptee->isFunctionType()); 9233 return Sema::FunctionVoidPointer; 9234 } 9235 9236 if (rhptee->isVoidType()) { 9237 if (lhptee->isIncompleteOrObjectType()) 9238 return ConvTy; 9239 9240 // As an extension, we allow cast to/from void* to function pointer. 9241 assert(lhptee->isFunctionType()); 9242 return Sema::FunctionVoidPointer; 9243 } 9244 9245 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9246 // unqualified versions of compatible types, ... 9247 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9248 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9249 // Check if the pointee types are compatible ignoring the sign. 9250 // We explicitly check for char so that we catch "char" vs 9251 // "unsigned char" on systems where "char" is unsigned. 9252 if (lhptee->isCharType()) 9253 ltrans = S.Context.UnsignedCharTy; 9254 else if (lhptee->hasSignedIntegerRepresentation()) 9255 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9256 9257 if (rhptee->isCharType()) 9258 rtrans = S.Context.UnsignedCharTy; 9259 else if (rhptee->hasSignedIntegerRepresentation()) 9260 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9261 9262 if (ltrans == rtrans) { 9263 // Types are compatible ignoring the sign. Qualifier incompatibility 9264 // takes priority over sign incompatibility because the sign 9265 // warning can be disabled. 9266 if (ConvTy != Sema::Compatible) 9267 return ConvTy; 9268 9269 return Sema::IncompatiblePointerSign; 9270 } 9271 9272 // If we are a multi-level pointer, it's possible that our issue is simply 9273 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9274 // the eventual target type is the same and the pointers have the same 9275 // level of indirection, this must be the issue. 9276 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9277 do { 9278 std::tie(lhptee, lhq) = 9279 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9280 std::tie(rhptee, rhq) = 9281 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9282 9283 // Inconsistent address spaces at this point is invalid, even if the 9284 // address spaces would be compatible. 9285 // FIXME: This doesn't catch address space mismatches for pointers of 9286 // different nesting levels, like: 9287 // __local int *** a; 9288 // int ** b = a; 9289 // It's not clear how to actually determine when such pointers are 9290 // invalidly incompatible. 9291 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9292 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9293 9294 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9295 9296 if (lhptee == rhptee) 9297 return Sema::IncompatibleNestedPointerQualifiers; 9298 } 9299 9300 // General pointer incompatibility takes priority over qualifiers. 9301 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9302 return Sema::IncompatibleFunctionPointer; 9303 return Sema::IncompatiblePointer; 9304 } 9305 if (!S.getLangOpts().CPlusPlus && 9306 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9307 return Sema::IncompatibleFunctionPointer; 9308 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9309 return Sema::IncompatibleFunctionPointer; 9310 return ConvTy; 9311 } 9312 9313 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9314 /// block pointer types are compatible or whether a block and normal pointer 9315 /// are compatible. It is more restrict than comparing two function pointer 9316 // types. 9317 static Sema::AssignConvertType 9318 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9319 QualType RHSType) { 9320 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9321 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9322 9323 QualType lhptee, rhptee; 9324 9325 // get the "pointed to" type (ignoring qualifiers at the top level) 9326 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9327 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9328 9329 // In C++, the types have to match exactly. 9330 if (S.getLangOpts().CPlusPlus) 9331 return Sema::IncompatibleBlockPointer; 9332 9333 Sema::AssignConvertType ConvTy = Sema::Compatible; 9334 9335 // For blocks we enforce that qualifiers are identical. 9336 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9337 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9338 if (S.getLangOpts().OpenCL) { 9339 LQuals.removeAddressSpace(); 9340 RQuals.removeAddressSpace(); 9341 } 9342 if (LQuals != RQuals) 9343 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9344 9345 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9346 // assignment. 9347 // The current behavior is similar to C++ lambdas. A block might be 9348 // assigned to a variable iff its return type and parameters are compatible 9349 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9350 // an assignment. Presumably it should behave in way that a function pointer 9351 // assignment does in C, so for each parameter and return type: 9352 // * CVR and address space of LHS should be a superset of CVR and address 9353 // space of RHS. 9354 // * unqualified types should be compatible. 9355 if (S.getLangOpts().OpenCL) { 9356 if (!S.Context.typesAreBlockPointerCompatible( 9357 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9358 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9359 return Sema::IncompatibleBlockPointer; 9360 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9361 return Sema::IncompatibleBlockPointer; 9362 9363 return ConvTy; 9364 } 9365 9366 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9367 /// for assignment compatibility. 9368 static Sema::AssignConvertType 9369 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9370 QualType RHSType) { 9371 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9372 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9373 9374 if (LHSType->isObjCBuiltinType()) { 9375 // Class is not compatible with ObjC object pointers. 9376 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9377 !RHSType->isObjCQualifiedClassType()) 9378 return Sema::IncompatiblePointer; 9379 return Sema::Compatible; 9380 } 9381 if (RHSType->isObjCBuiltinType()) { 9382 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9383 !LHSType->isObjCQualifiedClassType()) 9384 return Sema::IncompatiblePointer; 9385 return Sema::Compatible; 9386 } 9387 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9388 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9389 9390 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9391 // make an exception for id<P> 9392 !LHSType->isObjCQualifiedIdType()) 9393 return Sema::CompatiblePointerDiscardsQualifiers; 9394 9395 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9396 return Sema::Compatible; 9397 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9398 return Sema::IncompatibleObjCQualifiedId; 9399 return Sema::IncompatiblePointer; 9400 } 9401 9402 Sema::AssignConvertType 9403 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9404 QualType LHSType, QualType RHSType) { 9405 // Fake up an opaque expression. We don't actually care about what 9406 // cast operations are required, so if CheckAssignmentConstraints 9407 // adds casts to this they'll be wasted, but fortunately that doesn't 9408 // usually happen on valid code. 9409 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9410 ExprResult RHSPtr = &RHSExpr; 9411 CastKind K; 9412 9413 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9414 } 9415 9416 /// This helper function returns true if QT is a vector type that has element 9417 /// type ElementType. 9418 static bool isVector(QualType QT, QualType ElementType) { 9419 if (const VectorType *VT = QT->getAs<VectorType>()) 9420 return VT->getElementType().getCanonicalType() == ElementType; 9421 return false; 9422 } 9423 9424 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9425 /// has code to accommodate several GCC extensions when type checking 9426 /// pointers. Here are some objectionable examples that GCC considers warnings: 9427 /// 9428 /// int a, *pint; 9429 /// short *pshort; 9430 /// struct foo *pfoo; 9431 /// 9432 /// pint = pshort; // warning: assignment from incompatible pointer type 9433 /// a = pint; // warning: assignment makes integer from pointer without a cast 9434 /// pint = a; // warning: assignment makes pointer from integer without a cast 9435 /// pint = pfoo; // warning: assignment from incompatible pointer type 9436 /// 9437 /// As a result, the code for dealing with pointers is more complex than the 9438 /// C99 spec dictates. 9439 /// 9440 /// Sets 'Kind' for any result kind except Incompatible. 9441 Sema::AssignConvertType 9442 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9443 CastKind &Kind, bool ConvertRHS) { 9444 QualType RHSType = RHS.get()->getType(); 9445 QualType OrigLHSType = LHSType; 9446 9447 // Get canonical types. We're not formatting these types, just comparing 9448 // them. 9449 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9450 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9451 9452 // Common case: no conversion required. 9453 if (LHSType == RHSType) { 9454 Kind = CK_NoOp; 9455 return Compatible; 9456 } 9457 9458 // If the LHS has an __auto_type, there are no additional type constraints 9459 // to be worried about. 9460 if (const auto *AT = dyn_cast<AutoType>(LHSType)) { 9461 if (AT->isGNUAutoType()) { 9462 Kind = CK_NoOp; 9463 return Compatible; 9464 } 9465 } 9466 9467 // If we have an atomic type, try a non-atomic assignment, then just add an 9468 // atomic qualification step. 9469 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9470 Sema::AssignConvertType result = 9471 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9472 if (result != Compatible) 9473 return result; 9474 if (Kind != CK_NoOp && ConvertRHS) 9475 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9476 Kind = CK_NonAtomicToAtomic; 9477 return Compatible; 9478 } 9479 9480 // If the left-hand side is a reference type, then we are in a 9481 // (rare!) case where we've allowed the use of references in C, 9482 // e.g., as a parameter type in a built-in function. In this case, 9483 // just make sure that the type referenced is compatible with the 9484 // right-hand side type. The caller is responsible for adjusting 9485 // LHSType so that the resulting expression does not have reference 9486 // type. 9487 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9488 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9489 Kind = CK_LValueBitCast; 9490 return Compatible; 9491 } 9492 return Incompatible; 9493 } 9494 9495 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9496 // to the same ExtVector type. 9497 if (LHSType->isExtVectorType()) { 9498 if (RHSType->isExtVectorType()) 9499 return Incompatible; 9500 if (RHSType->isArithmeticType()) { 9501 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9502 if (ConvertRHS) 9503 RHS = prepareVectorSplat(LHSType, RHS.get()); 9504 Kind = CK_VectorSplat; 9505 return Compatible; 9506 } 9507 } 9508 9509 // Conversions to or from vector type. 9510 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9511 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9512 // Allow assignments of an AltiVec vector type to an equivalent GCC 9513 // vector type and vice versa 9514 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9515 Kind = CK_BitCast; 9516 return Compatible; 9517 } 9518 9519 // If we are allowing lax vector conversions, and LHS and RHS are both 9520 // vectors, the total size only needs to be the same. This is a bitcast; 9521 // no bits are changed but the result type is different. 9522 if (isLaxVectorConversion(RHSType, LHSType)) { 9523 Kind = CK_BitCast; 9524 return IncompatibleVectors; 9525 } 9526 } 9527 9528 // When the RHS comes from another lax conversion (e.g. binops between 9529 // scalars and vectors) the result is canonicalized as a vector. When the 9530 // LHS is also a vector, the lax is allowed by the condition above. Handle 9531 // the case where LHS is a scalar. 9532 if (LHSType->isScalarType()) { 9533 const VectorType *VecType = RHSType->getAs<VectorType>(); 9534 if (VecType && VecType->getNumElements() == 1 && 9535 isLaxVectorConversion(RHSType, LHSType)) { 9536 ExprResult *VecExpr = &RHS; 9537 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9538 Kind = CK_BitCast; 9539 return Compatible; 9540 } 9541 } 9542 9543 // Allow assignments between fixed-length and sizeless SVE vectors. 9544 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9545 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9546 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9547 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9548 Kind = CK_BitCast; 9549 return Compatible; 9550 } 9551 9552 return Incompatible; 9553 } 9554 9555 // Diagnose attempts to convert between __ibm128, __float128 and long double 9556 // where such conversions currently can't be handled. 9557 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9558 return Incompatible; 9559 9560 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9561 // discards the imaginary part. 9562 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9563 !LHSType->getAs<ComplexType>()) 9564 return Incompatible; 9565 9566 // Arithmetic conversions. 9567 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9568 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9569 if (ConvertRHS) 9570 Kind = PrepareScalarCast(RHS, LHSType); 9571 return Compatible; 9572 } 9573 9574 // Conversions to normal pointers. 9575 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9576 // U* -> T* 9577 if (isa<PointerType>(RHSType)) { 9578 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9579 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9580 if (AddrSpaceL != AddrSpaceR) 9581 Kind = CK_AddressSpaceConversion; 9582 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9583 Kind = CK_NoOp; 9584 else 9585 Kind = CK_BitCast; 9586 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9587 } 9588 9589 // int -> T* 9590 if (RHSType->isIntegerType()) { 9591 Kind = CK_IntegralToPointer; // FIXME: null? 9592 return IntToPointer; 9593 } 9594 9595 // C pointers are not compatible with ObjC object pointers, 9596 // with two exceptions: 9597 if (isa<ObjCObjectPointerType>(RHSType)) { 9598 // - conversions to void* 9599 if (LHSPointer->getPointeeType()->isVoidType()) { 9600 Kind = CK_BitCast; 9601 return Compatible; 9602 } 9603 9604 // - conversions from 'Class' to the redefinition type 9605 if (RHSType->isObjCClassType() && 9606 Context.hasSameType(LHSType, 9607 Context.getObjCClassRedefinitionType())) { 9608 Kind = CK_BitCast; 9609 return Compatible; 9610 } 9611 9612 Kind = CK_BitCast; 9613 return IncompatiblePointer; 9614 } 9615 9616 // U^ -> void* 9617 if (RHSType->getAs<BlockPointerType>()) { 9618 if (LHSPointer->getPointeeType()->isVoidType()) { 9619 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9620 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9621 ->getPointeeType() 9622 .getAddressSpace(); 9623 Kind = 9624 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9625 return Compatible; 9626 } 9627 } 9628 9629 return Incompatible; 9630 } 9631 9632 // Conversions to block pointers. 9633 if (isa<BlockPointerType>(LHSType)) { 9634 // U^ -> T^ 9635 if (RHSType->isBlockPointerType()) { 9636 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9637 ->getPointeeType() 9638 .getAddressSpace(); 9639 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9640 ->getPointeeType() 9641 .getAddressSpace(); 9642 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9643 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9644 } 9645 9646 // int or null -> T^ 9647 if (RHSType->isIntegerType()) { 9648 Kind = CK_IntegralToPointer; // FIXME: null 9649 return IntToBlockPointer; 9650 } 9651 9652 // id -> T^ 9653 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9654 Kind = CK_AnyPointerToBlockPointerCast; 9655 return Compatible; 9656 } 9657 9658 // void* -> T^ 9659 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9660 if (RHSPT->getPointeeType()->isVoidType()) { 9661 Kind = CK_AnyPointerToBlockPointerCast; 9662 return Compatible; 9663 } 9664 9665 return Incompatible; 9666 } 9667 9668 // Conversions to Objective-C pointers. 9669 if (isa<ObjCObjectPointerType>(LHSType)) { 9670 // A* -> B* 9671 if (RHSType->isObjCObjectPointerType()) { 9672 Kind = CK_BitCast; 9673 Sema::AssignConvertType result = 9674 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9675 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9676 result == Compatible && 9677 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9678 result = IncompatibleObjCWeakRef; 9679 return result; 9680 } 9681 9682 // int or null -> A* 9683 if (RHSType->isIntegerType()) { 9684 Kind = CK_IntegralToPointer; // FIXME: null 9685 return IntToPointer; 9686 } 9687 9688 // In general, C pointers are not compatible with ObjC object pointers, 9689 // with two exceptions: 9690 if (isa<PointerType>(RHSType)) { 9691 Kind = CK_CPointerToObjCPointerCast; 9692 9693 // - conversions from 'void*' 9694 if (RHSType->isVoidPointerType()) { 9695 return Compatible; 9696 } 9697 9698 // - conversions to 'Class' from its redefinition type 9699 if (LHSType->isObjCClassType() && 9700 Context.hasSameType(RHSType, 9701 Context.getObjCClassRedefinitionType())) { 9702 return Compatible; 9703 } 9704 9705 return IncompatiblePointer; 9706 } 9707 9708 // Only under strict condition T^ is compatible with an Objective-C pointer. 9709 if (RHSType->isBlockPointerType() && 9710 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9711 if (ConvertRHS) 9712 maybeExtendBlockObject(RHS); 9713 Kind = CK_BlockPointerToObjCPointerCast; 9714 return Compatible; 9715 } 9716 9717 return Incompatible; 9718 } 9719 9720 // Conversions from pointers that are not covered by the above. 9721 if (isa<PointerType>(RHSType)) { 9722 // T* -> _Bool 9723 if (LHSType == Context.BoolTy) { 9724 Kind = CK_PointerToBoolean; 9725 return Compatible; 9726 } 9727 9728 // T* -> int 9729 if (LHSType->isIntegerType()) { 9730 Kind = CK_PointerToIntegral; 9731 return PointerToInt; 9732 } 9733 9734 return Incompatible; 9735 } 9736 9737 // Conversions from Objective-C pointers that are not covered by the above. 9738 if (isa<ObjCObjectPointerType>(RHSType)) { 9739 // T* -> _Bool 9740 if (LHSType == Context.BoolTy) { 9741 Kind = CK_PointerToBoolean; 9742 return Compatible; 9743 } 9744 9745 // T* -> int 9746 if (LHSType->isIntegerType()) { 9747 Kind = CK_PointerToIntegral; 9748 return PointerToInt; 9749 } 9750 9751 return Incompatible; 9752 } 9753 9754 // struct A -> struct B 9755 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9756 if (Context.typesAreCompatible(LHSType, RHSType)) { 9757 Kind = CK_NoOp; 9758 return Compatible; 9759 } 9760 } 9761 9762 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9763 Kind = CK_IntToOCLSampler; 9764 return Compatible; 9765 } 9766 9767 return Incompatible; 9768 } 9769 9770 /// Constructs a transparent union from an expression that is 9771 /// used to initialize the transparent union. 9772 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9773 ExprResult &EResult, QualType UnionType, 9774 FieldDecl *Field) { 9775 // Build an initializer list that designates the appropriate member 9776 // of the transparent union. 9777 Expr *E = EResult.get(); 9778 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9779 E, SourceLocation()); 9780 Initializer->setType(UnionType); 9781 Initializer->setInitializedFieldInUnion(Field); 9782 9783 // Build a compound literal constructing a value of the transparent 9784 // union type from this initializer list. 9785 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9786 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9787 VK_PRValue, Initializer, false); 9788 } 9789 9790 Sema::AssignConvertType 9791 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9792 ExprResult &RHS) { 9793 QualType RHSType = RHS.get()->getType(); 9794 9795 // If the ArgType is a Union type, we want to handle a potential 9796 // transparent_union GCC extension. 9797 const RecordType *UT = ArgType->getAsUnionType(); 9798 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9799 return Incompatible; 9800 9801 // The field to initialize within the transparent union. 9802 RecordDecl *UD = UT->getDecl(); 9803 FieldDecl *InitField = nullptr; 9804 // It's compatible if the expression matches any of the fields. 9805 for (auto *it : UD->fields()) { 9806 if (it->getType()->isPointerType()) { 9807 // If the transparent union contains a pointer type, we allow: 9808 // 1) void pointer 9809 // 2) null pointer constant 9810 if (RHSType->isPointerType()) 9811 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9812 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9813 InitField = it; 9814 break; 9815 } 9816 9817 if (RHS.get()->isNullPointerConstant(Context, 9818 Expr::NPC_ValueDependentIsNull)) { 9819 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9820 CK_NullToPointer); 9821 InitField = it; 9822 break; 9823 } 9824 } 9825 9826 CastKind Kind; 9827 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9828 == Compatible) { 9829 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9830 InitField = it; 9831 break; 9832 } 9833 } 9834 9835 if (!InitField) 9836 return Incompatible; 9837 9838 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9839 return Compatible; 9840 } 9841 9842 Sema::AssignConvertType 9843 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9844 bool Diagnose, 9845 bool DiagnoseCFAudited, 9846 bool ConvertRHS) { 9847 // We need to be able to tell the caller whether we diagnosed a problem, if 9848 // they ask us to issue diagnostics. 9849 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9850 9851 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9852 // we can't avoid *all* modifications at the moment, so we need some somewhere 9853 // to put the updated value. 9854 ExprResult LocalRHS = CallerRHS; 9855 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9856 9857 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9858 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9859 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9860 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9861 Diag(RHS.get()->getExprLoc(), 9862 diag::warn_noderef_to_dereferenceable_pointer) 9863 << RHS.get()->getSourceRange(); 9864 } 9865 } 9866 } 9867 9868 if (getLangOpts().CPlusPlus) { 9869 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9870 // C++ 5.17p3: If the left operand is not of class type, the 9871 // expression is implicitly converted (C++ 4) to the 9872 // cv-unqualified type of the left operand. 9873 QualType RHSType = RHS.get()->getType(); 9874 if (Diagnose) { 9875 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9876 AA_Assigning); 9877 } else { 9878 ImplicitConversionSequence ICS = 9879 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9880 /*SuppressUserConversions=*/false, 9881 AllowedExplicit::None, 9882 /*InOverloadResolution=*/false, 9883 /*CStyle=*/false, 9884 /*AllowObjCWritebackConversion=*/false); 9885 if (ICS.isFailure()) 9886 return Incompatible; 9887 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9888 ICS, AA_Assigning); 9889 } 9890 if (RHS.isInvalid()) 9891 return Incompatible; 9892 Sema::AssignConvertType result = Compatible; 9893 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9894 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9895 result = IncompatibleObjCWeakRef; 9896 return result; 9897 } 9898 9899 // FIXME: Currently, we fall through and treat C++ classes like C 9900 // structures. 9901 // FIXME: We also fall through for atomics; not sure what should 9902 // happen there, though. 9903 } else if (RHS.get()->getType() == Context.OverloadTy) { 9904 // As a set of extensions to C, we support overloading on functions. These 9905 // functions need to be resolved here. 9906 DeclAccessPair DAP; 9907 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9908 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9909 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9910 else 9911 return Incompatible; 9912 } 9913 9914 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9915 // a null pointer constant. 9916 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9917 LHSType->isBlockPointerType()) && 9918 RHS.get()->isNullPointerConstant(Context, 9919 Expr::NPC_ValueDependentIsNull)) { 9920 if (Diagnose || ConvertRHS) { 9921 CastKind Kind; 9922 CXXCastPath Path; 9923 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9924 /*IgnoreBaseAccess=*/false, Diagnose); 9925 if (ConvertRHS) 9926 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9927 } 9928 return Compatible; 9929 } 9930 9931 // OpenCL queue_t type assignment. 9932 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9933 Context, Expr::NPC_ValueDependentIsNull)) { 9934 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9935 return Compatible; 9936 } 9937 9938 // This check seems unnatural, however it is necessary to ensure the proper 9939 // conversion of functions/arrays. If the conversion were done for all 9940 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9941 // expressions that suppress this implicit conversion (&, sizeof). 9942 // 9943 // Suppress this for references: C++ 8.5.3p5. 9944 if (!LHSType->isReferenceType()) { 9945 // FIXME: We potentially allocate here even if ConvertRHS is false. 9946 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9947 if (RHS.isInvalid()) 9948 return Incompatible; 9949 } 9950 CastKind Kind; 9951 Sema::AssignConvertType result = 9952 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9953 9954 // C99 6.5.16.1p2: The value of the right operand is converted to the 9955 // type of the assignment expression. 9956 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9957 // so that we can use references in built-in functions even in C. 9958 // The getNonReferenceType() call makes sure that the resulting expression 9959 // does not have reference type. 9960 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9961 QualType Ty = LHSType.getNonLValueExprType(Context); 9962 Expr *E = RHS.get(); 9963 9964 // Check for various Objective-C errors. If we are not reporting 9965 // diagnostics and just checking for errors, e.g., during overload 9966 // resolution, return Incompatible to indicate the failure. 9967 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9968 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9969 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9970 if (!Diagnose) 9971 return Incompatible; 9972 } 9973 if (getLangOpts().ObjC && 9974 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9975 E->getType(), E, Diagnose) || 9976 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9977 if (!Diagnose) 9978 return Incompatible; 9979 // Replace the expression with a corrected version and continue so we 9980 // can find further errors. 9981 RHS = E; 9982 return Compatible; 9983 } 9984 9985 if (ConvertRHS) 9986 RHS = ImpCastExprToType(E, Ty, Kind); 9987 } 9988 9989 return result; 9990 } 9991 9992 namespace { 9993 /// The original operand to an operator, prior to the application of the usual 9994 /// arithmetic conversions and converting the arguments of a builtin operator 9995 /// candidate. 9996 struct OriginalOperand { 9997 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9998 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9999 Op = MTE->getSubExpr(); 10000 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 10001 Op = BTE->getSubExpr(); 10002 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 10003 Orig = ICE->getSubExprAsWritten(); 10004 Conversion = ICE->getConversionFunction(); 10005 } 10006 } 10007 10008 QualType getType() const { return Orig->getType(); } 10009 10010 Expr *Orig; 10011 NamedDecl *Conversion; 10012 }; 10013 } 10014 10015 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 10016 ExprResult &RHS) { 10017 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 10018 10019 Diag(Loc, diag::err_typecheck_invalid_operands) 10020 << OrigLHS.getType() << OrigRHS.getType() 10021 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10022 10023 // If a user-defined conversion was applied to either of the operands prior 10024 // to applying the built-in operator rules, tell the user about it. 10025 if (OrigLHS.Conversion) { 10026 Diag(OrigLHS.Conversion->getLocation(), 10027 diag::note_typecheck_invalid_operands_converted) 10028 << 0 << LHS.get()->getType(); 10029 } 10030 if (OrigRHS.Conversion) { 10031 Diag(OrigRHS.Conversion->getLocation(), 10032 diag::note_typecheck_invalid_operands_converted) 10033 << 1 << RHS.get()->getType(); 10034 } 10035 10036 return QualType(); 10037 } 10038 10039 // Diagnose cases where a scalar was implicitly converted to a vector and 10040 // diagnose the underlying types. Otherwise, diagnose the error 10041 // as invalid vector logical operands for non-C++ cases. 10042 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 10043 ExprResult &RHS) { 10044 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 10045 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 10046 10047 bool LHSNatVec = LHSType->isVectorType(); 10048 bool RHSNatVec = RHSType->isVectorType(); 10049 10050 if (!(LHSNatVec && RHSNatVec)) { 10051 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 10052 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 10053 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10054 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 10055 << Vector->getSourceRange(); 10056 return QualType(); 10057 } 10058 10059 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10060 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 10061 << RHS.get()->getSourceRange(); 10062 10063 return QualType(); 10064 } 10065 10066 /// Try to convert a value of non-vector type to a vector type by converting 10067 /// the type to the element type of the vector and then performing a splat. 10068 /// If the language is OpenCL, we only use conversions that promote scalar 10069 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 10070 /// for float->int. 10071 /// 10072 /// OpenCL V2.0 6.2.6.p2: 10073 /// An error shall occur if any scalar operand type has greater rank 10074 /// than the type of the vector element. 10075 /// 10076 /// \param scalar - if non-null, actually perform the conversions 10077 /// \return true if the operation fails (but without diagnosing the failure) 10078 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 10079 QualType scalarTy, 10080 QualType vectorEltTy, 10081 QualType vectorTy, 10082 unsigned &DiagID) { 10083 // The conversion to apply to the scalar before splatting it, 10084 // if necessary. 10085 CastKind scalarCast = CK_NoOp; 10086 10087 if (vectorEltTy->isIntegralType(S.Context)) { 10088 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 10089 (scalarTy->isIntegerType() && 10090 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 10091 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10092 return true; 10093 } 10094 if (!scalarTy->isIntegralType(S.Context)) 10095 return true; 10096 scalarCast = CK_IntegralCast; 10097 } else if (vectorEltTy->isRealFloatingType()) { 10098 if (scalarTy->isRealFloatingType()) { 10099 if (S.getLangOpts().OpenCL && 10100 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 10101 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10102 return true; 10103 } 10104 scalarCast = CK_FloatingCast; 10105 } 10106 else if (scalarTy->isIntegralType(S.Context)) 10107 scalarCast = CK_IntegralToFloating; 10108 else 10109 return true; 10110 } else { 10111 return true; 10112 } 10113 10114 // Adjust scalar if desired. 10115 if (scalar) { 10116 if (scalarCast != CK_NoOp) 10117 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 10118 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 10119 } 10120 return false; 10121 } 10122 10123 /// Convert vector E to a vector with the same number of elements but different 10124 /// element type. 10125 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 10126 const auto *VecTy = E->getType()->getAs<VectorType>(); 10127 assert(VecTy && "Expression E must be a vector"); 10128 QualType NewVecTy = 10129 VecTy->isExtVectorType() 10130 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements()) 10131 : S.Context.getVectorType(ElementType, VecTy->getNumElements(), 10132 VecTy->getVectorKind()); 10133 10134 // Look through the implicit cast. Return the subexpression if its type is 10135 // NewVecTy. 10136 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10137 if (ICE->getSubExpr()->getType() == NewVecTy) 10138 return ICE->getSubExpr(); 10139 10140 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 10141 return S.ImpCastExprToType(E, NewVecTy, Cast); 10142 } 10143 10144 /// Test if a (constant) integer Int can be casted to another integer type 10145 /// IntTy without losing precision. 10146 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 10147 QualType OtherIntTy) { 10148 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10149 10150 // Reject cases where the value of the Int is unknown as that would 10151 // possibly cause truncation, but accept cases where the scalar can be 10152 // demoted without loss of precision. 10153 Expr::EvalResult EVResult; 10154 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10155 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 10156 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 10157 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 10158 10159 if (CstInt) { 10160 // If the scalar is constant and is of a higher order and has more active 10161 // bits that the vector element type, reject it. 10162 llvm::APSInt Result = EVResult.Val.getInt(); 10163 unsigned NumBits = IntSigned 10164 ? (Result.isNegative() ? Result.getMinSignedBits() 10165 : Result.getActiveBits()) 10166 : Result.getActiveBits(); 10167 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 10168 return true; 10169 10170 // If the signedness of the scalar type and the vector element type 10171 // differs and the number of bits is greater than that of the vector 10172 // element reject it. 10173 return (IntSigned != OtherIntSigned && 10174 NumBits > S.Context.getIntWidth(OtherIntTy)); 10175 } 10176 10177 // Reject cases where the value of the scalar is not constant and it's 10178 // order is greater than that of the vector element type. 10179 return (Order < 0); 10180 } 10181 10182 /// Test if a (constant) integer Int can be casted to floating point type 10183 /// FloatTy without losing precision. 10184 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 10185 QualType FloatTy) { 10186 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10187 10188 // Determine if the integer constant can be expressed as a floating point 10189 // number of the appropriate type. 10190 Expr::EvalResult EVResult; 10191 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10192 10193 uint64_t Bits = 0; 10194 if (CstInt) { 10195 // Reject constants that would be truncated if they were converted to 10196 // the floating point type. Test by simple to/from conversion. 10197 // FIXME: Ideally the conversion to an APFloat and from an APFloat 10198 // could be avoided if there was a convertFromAPInt method 10199 // which could signal back if implicit truncation occurred. 10200 llvm::APSInt Result = EVResult.Val.getInt(); 10201 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 10202 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 10203 llvm::APFloat::rmTowardZero); 10204 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 10205 !IntTy->hasSignedIntegerRepresentation()); 10206 bool Ignored = false; 10207 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 10208 &Ignored); 10209 if (Result != ConvertBack) 10210 return true; 10211 } else { 10212 // Reject types that cannot be fully encoded into the mantissa of 10213 // the float. 10214 Bits = S.Context.getTypeSize(IntTy); 10215 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 10216 S.Context.getFloatTypeSemantics(FloatTy)); 10217 if (Bits > FloatPrec) 10218 return true; 10219 } 10220 10221 return false; 10222 } 10223 10224 /// Attempt to convert and splat Scalar into a vector whose types matches 10225 /// Vector following GCC conversion rules. The rule is that implicit 10226 /// conversion can occur when Scalar can be casted to match Vector's element 10227 /// type without causing truncation of Scalar. 10228 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 10229 ExprResult *Vector) { 10230 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 10231 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 10232 const auto *VT = VectorTy->castAs<VectorType>(); 10233 10234 assert(!isa<ExtVectorType>(VT) && 10235 "ExtVectorTypes should not be handled here!"); 10236 10237 QualType VectorEltTy = VT->getElementType(); 10238 10239 // Reject cases where the vector element type or the scalar element type are 10240 // not integral or floating point types. 10241 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 10242 return true; 10243 10244 // The conversion to apply to the scalar before splatting it, 10245 // if necessary. 10246 CastKind ScalarCast = CK_NoOp; 10247 10248 // Accept cases where the vector elements are integers and the scalar is 10249 // an integer. 10250 // FIXME: Notionally if the scalar was a floating point value with a precise 10251 // integral representation, we could cast it to an appropriate integer 10252 // type and then perform the rest of the checks here. GCC will perform 10253 // this conversion in some cases as determined by the input language. 10254 // We should accept it on a language independent basis. 10255 if (VectorEltTy->isIntegralType(S.Context) && 10256 ScalarTy->isIntegralType(S.Context) && 10257 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10258 10259 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10260 return true; 10261 10262 ScalarCast = CK_IntegralCast; 10263 } else if (VectorEltTy->isIntegralType(S.Context) && 10264 ScalarTy->isRealFloatingType()) { 10265 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10266 ScalarCast = CK_FloatingToIntegral; 10267 else 10268 return true; 10269 } else if (VectorEltTy->isRealFloatingType()) { 10270 if (ScalarTy->isRealFloatingType()) { 10271 10272 // Reject cases where the scalar type is not a constant and has a higher 10273 // Order than the vector element type. 10274 llvm::APFloat Result(0.0); 10275 10276 // Determine whether this is a constant scalar. In the event that the 10277 // value is dependent (and thus cannot be evaluated by the constant 10278 // evaluator), skip the evaluation. This will then diagnose once the 10279 // expression is instantiated. 10280 bool CstScalar = Scalar->get()->isValueDependent() || 10281 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10282 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10283 if (!CstScalar && Order < 0) 10284 return true; 10285 10286 // If the scalar cannot be safely casted to the vector element type, 10287 // reject it. 10288 if (CstScalar) { 10289 bool Truncated = false; 10290 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10291 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10292 if (Truncated) 10293 return true; 10294 } 10295 10296 ScalarCast = CK_FloatingCast; 10297 } else if (ScalarTy->isIntegralType(S.Context)) { 10298 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10299 return true; 10300 10301 ScalarCast = CK_IntegralToFloating; 10302 } else 10303 return true; 10304 } else if (ScalarTy->isEnumeralType()) 10305 return true; 10306 10307 // Adjust scalar if desired. 10308 if (Scalar) { 10309 if (ScalarCast != CK_NoOp) 10310 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10311 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10312 } 10313 return false; 10314 } 10315 10316 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10317 SourceLocation Loc, bool IsCompAssign, 10318 bool AllowBothBool, 10319 bool AllowBoolConversions, 10320 bool AllowBoolOperation, 10321 bool ReportInvalid) { 10322 if (!IsCompAssign) { 10323 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10324 if (LHS.isInvalid()) 10325 return QualType(); 10326 } 10327 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10328 if (RHS.isInvalid()) 10329 return QualType(); 10330 10331 // For conversion purposes, we ignore any qualifiers. 10332 // For example, "const float" and "float" are equivalent. 10333 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10334 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10335 10336 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10337 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10338 assert(LHSVecType || RHSVecType); 10339 10340 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10341 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10342 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10343 10344 // AltiVec-style "vector bool op vector bool" combinations are allowed 10345 // for some operators but not others. 10346 if (!AllowBothBool && 10347 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10348 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10349 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10350 10351 // This operation may not be performed on boolean vectors. 10352 if (!AllowBoolOperation && 10353 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) 10354 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10355 10356 // If the vector types are identical, return. 10357 if (Context.hasSameType(LHSType, RHSType)) 10358 return LHSType; 10359 10360 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10361 if (LHSVecType && RHSVecType && 10362 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10363 if (isa<ExtVectorType>(LHSVecType)) { 10364 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10365 return LHSType; 10366 } 10367 10368 if (!IsCompAssign) 10369 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10370 return RHSType; 10371 } 10372 10373 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10374 // can be mixed, with the result being the non-bool type. The non-bool 10375 // operand must have integer element type. 10376 if (AllowBoolConversions && LHSVecType && RHSVecType && 10377 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10378 (Context.getTypeSize(LHSVecType->getElementType()) == 10379 Context.getTypeSize(RHSVecType->getElementType()))) { 10380 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10381 LHSVecType->getElementType()->isIntegerType() && 10382 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10383 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10384 return LHSType; 10385 } 10386 if (!IsCompAssign && 10387 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10388 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10389 RHSVecType->getElementType()->isIntegerType()) { 10390 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10391 return RHSType; 10392 } 10393 } 10394 10395 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10396 // since the ambiguity can affect the ABI. 10397 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10398 const VectorType *VecType = SecondType->getAs<VectorType>(); 10399 return FirstType->isSizelessBuiltinType() && VecType && 10400 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10401 VecType->getVectorKind() == 10402 VectorType::SveFixedLengthPredicateVector); 10403 }; 10404 10405 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10406 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10407 return QualType(); 10408 } 10409 10410 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10411 // since the ambiguity can affect the ABI. 10412 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10413 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10414 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10415 10416 if (FirstVecType && SecondVecType) 10417 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10418 (SecondVecType->getVectorKind() == 10419 VectorType::SveFixedLengthDataVector || 10420 SecondVecType->getVectorKind() == 10421 VectorType::SveFixedLengthPredicateVector); 10422 10423 return FirstType->isSizelessBuiltinType() && SecondVecType && 10424 SecondVecType->getVectorKind() == VectorType::GenericVector; 10425 }; 10426 10427 if (IsSveGnuConversion(LHSType, RHSType) || 10428 IsSveGnuConversion(RHSType, LHSType)) { 10429 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10430 return QualType(); 10431 } 10432 10433 // If there's a vector type and a scalar, try to convert the scalar to 10434 // the vector element type and splat. 10435 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10436 if (!RHSVecType) { 10437 if (isa<ExtVectorType>(LHSVecType)) { 10438 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10439 LHSVecType->getElementType(), LHSType, 10440 DiagID)) 10441 return LHSType; 10442 } else { 10443 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10444 return LHSType; 10445 } 10446 } 10447 if (!LHSVecType) { 10448 if (isa<ExtVectorType>(RHSVecType)) { 10449 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10450 LHSType, RHSVecType->getElementType(), 10451 RHSType, DiagID)) 10452 return RHSType; 10453 } else { 10454 if (LHS.get()->isLValue() || 10455 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10456 return RHSType; 10457 } 10458 } 10459 10460 // FIXME: The code below also handles conversion between vectors and 10461 // non-scalars, we should break this down into fine grained specific checks 10462 // and emit proper diagnostics. 10463 QualType VecType = LHSVecType ? LHSType : RHSType; 10464 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10465 QualType OtherType = LHSVecType ? RHSType : LHSType; 10466 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10467 if (isLaxVectorConversion(OtherType, VecType)) { 10468 // If we're allowing lax vector conversions, only the total (data) size 10469 // needs to be the same. For non compound assignment, if one of the types is 10470 // scalar, the result is always the vector type. 10471 if (!IsCompAssign) { 10472 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10473 return VecType; 10474 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10475 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10476 // type. Note that this is already done by non-compound assignments in 10477 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10478 // <1 x T> -> T. The result is also a vector type. 10479 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10480 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10481 ExprResult *RHSExpr = &RHS; 10482 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10483 return VecType; 10484 } 10485 } 10486 10487 // Okay, the expression is invalid. 10488 10489 // If there's a non-vector, non-real operand, diagnose that. 10490 if ((!RHSVecType && !RHSType->isRealType()) || 10491 (!LHSVecType && !LHSType->isRealType())) { 10492 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10493 << LHSType << RHSType 10494 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10495 return QualType(); 10496 } 10497 10498 // OpenCL V1.1 6.2.6.p1: 10499 // If the operands are of more than one vector type, then an error shall 10500 // occur. Implicit conversions between vector types are not permitted, per 10501 // section 6.2.1. 10502 if (getLangOpts().OpenCL && 10503 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10504 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10505 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10506 << RHSType; 10507 return QualType(); 10508 } 10509 10510 10511 // If there is a vector type that is not a ExtVector and a scalar, we reach 10512 // this point if scalar could not be converted to the vector's element type 10513 // without truncation. 10514 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10515 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10516 QualType Scalar = LHSVecType ? RHSType : LHSType; 10517 QualType Vector = LHSVecType ? LHSType : RHSType; 10518 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10519 Diag(Loc, 10520 diag::err_typecheck_vector_not_convertable_implict_truncation) 10521 << ScalarOrVector << Scalar << Vector; 10522 10523 return QualType(); 10524 } 10525 10526 // Otherwise, use the generic diagnostic. 10527 Diag(Loc, DiagID) 10528 << LHSType << RHSType 10529 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10530 return QualType(); 10531 } 10532 10533 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, 10534 SourceLocation Loc, 10535 bool IsCompAssign, 10536 ArithConvKind OperationKind) { 10537 if (!IsCompAssign) { 10538 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10539 if (LHS.isInvalid()) 10540 return QualType(); 10541 } 10542 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10543 if (RHS.isInvalid()) 10544 return QualType(); 10545 10546 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10547 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10548 10549 unsigned DiagID = diag::err_typecheck_invalid_operands; 10550 if ((OperationKind == ACK_Arithmetic) && 10551 (LHSType->castAs<BuiltinType>()->isSVEBool() || 10552 RHSType->castAs<BuiltinType>()->isSVEBool())) { 10553 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10554 << RHS.get()->getSourceRange(); 10555 return QualType(); 10556 } 10557 10558 if (Context.hasSameType(LHSType, RHSType)) 10559 return LHSType; 10560 10561 auto tryScalableVectorConvert = [this](ExprResult *Src, QualType SrcType, 10562 QualType DestType) { 10563 const QualType DestBaseType = DestType->getSveEltType(Context); 10564 if (DestBaseType->getUnqualifiedDesugaredType() == 10565 SrcType->getUnqualifiedDesugaredType()) { 10566 unsigned DiagID = diag::err_typecheck_invalid_operands; 10567 if (!tryVectorConvertAndSplat(*this, Src, SrcType, DestBaseType, DestType, 10568 DiagID)) 10569 return DestType; 10570 } 10571 return QualType(); 10572 }; 10573 10574 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) { 10575 auto DestType = tryScalableVectorConvert(&RHS, RHSType, LHSType); 10576 if (DestType == QualType()) 10577 return InvalidOperands(Loc, LHS, RHS); 10578 return DestType; 10579 } 10580 10581 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) { 10582 auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS), 10583 LHSType, RHSType); 10584 if (DestType == QualType()) 10585 return InvalidOperands(Loc, LHS, RHS); 10586 return DestType; 10587 } 10588 10589 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10590 << RHS.get()->getSourceRange(); 10591 return QualType(); 10592 } 10593 10594 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10595 // expression. These are mainly cases where the null pointer is used as an 10596 // integer instead of a pointer. 10597 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10598 SourceLocation Loc, bool IsCompare) { 10599 // The canonical way to check for a GNU null is with isNullPointerConstant, 10600 // but we use a bit of a hack here for speed; this is a relatively 10601 // hot path, and isNullPointerConstant is slow. 10602 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10603 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10604 10605 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10606 10607 // Avoid analyzing cases where the result will either be invalid (and 10608 // diagnosed as such) or entirely valid and not something to warn about. 10609 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10610 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10611 return; 10612 10613 // Comparison operations would not make sense with a null pointer no matter 10614 // what the other expression is. 10615 if (!IsCompare) { 10616 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10617 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10618 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10619 return; 10620 } 10621 10622 // The rest of the operations only make sense with a null pointer 10623 // if the other expression is a pointer. 10624 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10625 NonNullType->canDecayToPointerType()) 10626 return; 10627 10628 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10629 << LHSNull /* LHS is NULL */ << NonNullType 10630 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10631 } 10632 10633 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10634 SourceLocation Loc) { 10635 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10636 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10637 if (!LUE || !RUE) 10638 return; 10639 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10640 RUE->getKind() != UETT_SizeOf) 10641 return; 10642 10643 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10644 QualType LHSTy = LHSArg->getType(); 10645 QualType RHSTy; 10646 10647 if (RUE->isArgumentType()) 10648 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10649 else 10650 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10651 10652 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10653 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10654 return; 10655 10656 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10657 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10658 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10659 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10660 << LHSArgDecl; 10661 } 10662 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10663 QualType ArrayElemTy = ArrayTy->getElementType(); 10664 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10665 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10666 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10667 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10668 return; 10669 S.Diag(Loc, diag::warn_division_sizeof_array) 10670 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10671 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10672 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10673 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10674 << LHSArgDecl; 10675 } 10676 10677 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10678 } 10679 } 10680 10681 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10682 ExprResult &RHS, 10683 SourceLocation Loc, bool IsDiv) { 10684 // Check for division/remainder by zero. 10685 Expr::EvalResult RHSValue; 10686 if (!RHS.get()->isValueDependent() && 10687 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10688 RHSValue.Val.getInt() == 0) 10689 S.DiagRuntimeBehavior(Loc, RHS.get(), 10690 S.PDiag(diag::warn_remainder_division_by_zero) 10691 << IsDiv << RHS.get()->getSourceRange()); 10692 } 10693 10694 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10695 SourceLocation Loc, 10696 bool IsCompAssign, bool IsDiv) { 10697 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10698 10699 QualType LHSTy = LHS.get()->getType(); 10700 QualType RHSTy = RHS.get()->getType(); 10701 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10702 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10703 /*AllowBothBool*/ getLangOpts().AltiVec, 10704 /*AllowBoolConversions*/ false, 10705 /*AllowBooleanOperation*/ false, 10706 /*ReportInvalid*/ true); 10707 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType()) 10708 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 10709 ACK_Arithmetic); 10710 if (!IsDiv && 10711 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10712 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10713 // For division, only matrix-by-scalar is supported. Other combinations with 10714 // matrix types are invalid. 10715 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10716 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10717 10718 QualType compType = UsualArithmeticConversions( 10719 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10720 if (LHS.isInvalid() || RHS.isInvalid()) 10721 return QualType(); 10722 10723 10724 if (compType.isNull() || !compType->isArithmeticType()) 10725 return InvalidOperands(Loc, LHS, RHS); 10726 if (IsDiv) { 10727 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10728 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10729 } 10730 return compType; 10731 } 10732 10733 QualType Sema::CheckRemainderOperands( 10734 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10735 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10736 10737 if (LHS.get()->getType()->isVectorType() || 10738 RHS.get()->getType()->isVectorType()) { 10739 if (LHS.get()->getType()->hasIntegerRepresentation() && 10740 RHS.get()->getType()->hasIntegerRepresentation()) 10741 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10742 /*AllowBothBool*/ getLangOpts().AltiVec, 10743 /*AllowBoolConversions*/ false, 10744 /*AllowBooleanOperation*/ false, 10745 /*ReportInvalid*/ true); 10746 return InvalidOperands(Loc, LHS, RHS); 10747 } 10748 10749 if (LHS.get()->getType()->isVLSTBuiltinType() || 10750 RHS.get()->getType()->isVLSTBuiltinType()) { 10751 if (LHS.get()->getType()->hasIntegerRepresentation() && 10752 RHS.get()->getType()->hasIntegerRepresentation()) 10753 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 10754 ACK_Arithmetic); 10755 10756 return InvalidOperands(Loc, LHS, RHS); 10757 } 10758 10759 QualType compType = UsualArithmeticConversions( 10760 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10761 if (LHS.isInvalid() || RHS.isInvalid()) 10762 return QualType(); 10763 10764 if (compType.isNull() || !compType->isIntegerType()) 10765 return InvalidOperands(Loc, LHS, RHS); 10766 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10767 return compType; 10768 } 10769 10770 /// Diagnose invalid arithmetic on two void pointers. 10771 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10772 Expr *LHSExpr, Expr *RHSExpr) { 10773 S.Diag(Loc, S.getLangOpts().CPlusPlus 10774 ? diag::err_typecheck_pointer_arith_void_type 10775 : diag::ext_gnu_void_ptr) 10776 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10777 << RHSExpr->getSourceRange(); 10778 } 10779 10780 /// Diagnose invalid arithmetic on a void pointer. 10781 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10782 Expr *Pointer) { 10783 S.Diag(Loc, S.getLangOpts().CPlusPlus 10784 ? diag::err_typecheck_pointer_arith_void_type 10785 : diag::ext_gnu_void_ptr) 10786 << 0 /* one pointer */ << Pointer->getSourceRange(); 10787 } 10788 10789 /// Diagnose invalid arithmetic on a null pointer. 10790 /// 10791 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10792 /// idiom, which we recognize as a GNU extension. 10793 /// 10794 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10795 Expr *Pointer, bool IsGNUIdiom) { 10796 if (IsGNUIdiom) 10797 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10798 << Pointer->getSourceRange(); 10799 else 10800 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10801 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10802 } 10803 10804 /// Diagnose invalid subraction on a null pointer. 10805 /// 10806 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10807 Expr *Pointer, bool BothNull) { 10808 // Null - null is valid in C++ [expr.add]p7 10809 if (BothNull && S.getLangOpts().CPlusPlus) 10810 return; 10811 10812 // Is this s a macro from a system header? 10813 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10814 return; 10815 10816 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10817 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10818 } 10819 10820 /// Diagnose invalid arithmetic on two function pointers. 10821 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10822 Expr *LHS, Expr *RHS) { 10823 assert(LHS->getType()->isAnyPointerType()); 10824 assert(RHS->getType()->isAnyPointerType()); 10825 S.Diag(Loc, S.getLangOpts().CPlusPlus 10826 ? diag::err_typecheck_pointer_arith_function_type 10827 : diag::ext_gnu_ptr_func_arith) 10828 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10829 // We only show the second type if it differs from the first. 10830 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10831 RHS->getType()) 10832 << RHS->getType()->getPointeeType() 10833 << LHS->getSourceRange() << RHS->getSourceRange(); 10834 } 10835 10836 /// Diagnose invalid arithmetic on a function pointer. 10837 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10838 Expr *Pointer) { 10839 assert(Pointer->getType()->isAnyPointerType()); 10840 S.Diag(Loc, S.getLangOpts().CPlusPlus 10841 ? diag::err_typecheck_pointer_arith_function_type 10842 : diag::ext_gnu_ptr_func_arith) 10843 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10844 << 0 /* one pointer, so only one type */ 10845 << Pointer->getSourceRange(); 10846 } 10847 10848 /// Emit error if Operand is incomplete pointer type 10849 /// 10850 /// \returns True if pointer has incomplete type 10851 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10852 Expr *Operand) { 10853 QualType ResType = Operand->getType(); 10854 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10855 ResType = ResAtomicType->getValueType(); 10856 10857 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10858 QualType PointeeTy = ResType->getPointeeType(); 10859 return S.RequireCompleteSizedType( 10860 Loc, PointeeTy, 10861 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10862 Operand->getSourceRange()); 10863 } 10864 10865 /// Check the validity of an arithmetic pointer operand. 10866 /// 10867 /// If the operand has pointer type, this code will check for pointer types 10868 /// which are invalid in arithmetic operations. These will be diagnosed 10869 /// appropriately, including whether or not the use is supported as an 10870 /// extension. 10871 /// 10872 /// \returns True when the operand is valid to use (even if as an extension). 10873 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10874 Expr *Operand) { 10875 QualType ResType = Operand->getType(); 10876 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10877 ResType = ResAtomicType->getValueType(); 10878 10879 if (!ResType->isAnyPointerType()) return true; 10880 10881 QualType PointeeTy = ResType->getPointeeType(); 10882 if (PointeeTy->isVoidType()) { 10883 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10884 return !S.getLangOpts().CPlusPlus; 10885 } 10886 if (PointeeTy->isFunctionType()) { 10887 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10888 return !S.getLangOpts().CPlusPlus; 10889 } 10890 10891 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10892 10893 return true; 10894 } 10895 10896 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10897 /// operands. 10898 /// 10899 /// This routine will diagnose any invalid arithmetic on pointer operands much 10900 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10901 /// for emitting a single diagnostic even for operations where both LHS and RHS 10902 /// are (potentially problematic) pointers. 10903 /// 10904 /// \returns True when the operand is valid to use (even if as an extension). 10905 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10906 Expr *LHSExpr, Expr *RHSExpr) { 10907 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10908 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10909 if (!isLHSPointer && !isRHSPointer) return true; 10910 10911 QualType LHSPointeeTy, RHSPointeeTy; 10912 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10913 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10914 10915 // if both are pointers check if operation is valid wrt address spaces 10916 if (isLHSPointer && isRHSPointer) { 10917 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10918 S.Diag(Loc, 10919 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10920 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10921 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10922 return false; 10923 } 10924 } 10925 10926 // Check for arithmetic on pointers to incomplete types. 10927 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10928 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10929 if (isLHSVoidPtr || isRHSVoidPtr) { 10930 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10931 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10932 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10933 10934 return !S.getLangOpts().CPlusPlus; 10935 } 10936 10937 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10938 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10939 if (isLHSFuncPtr || isRHSFuncPtr) { 10940 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10941 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10942 RHSExpr); 10943 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10944 10945 return !S.getLangOpts().CPlusPlus; 10946 } 10947 10948 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10949 return false; 10950 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10951 return false; 10952 10953 return true; 10954 } 10955 10956 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10957 /// literal. 10958 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10959 Expr *LHSExpr, Expr *RHSExpr) { 10960 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10961 Expr* IndexExpr = RHSExpr; 10962 if (!StrExpr) { 10963 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10964 IndexExpr = LHSExpr; 10965 } 10966 10967 bool IsStringPlusInt = StrExpr && 10968 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10969 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10970 return; 10971 10972 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10973 Self.Diag(OpLoc, diag::warn_string_plus_int) 10974 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10975 10976 // Only print a fixit for "str" + int, not for int + "str". 10977 if (IndexExpr == RHSExpr) { 10978 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10979 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10980 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10981 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10982 << FixItHint::CreateInsertion(EndLoc, "]"); 10983 } else 10984 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10985 } 10986 10987 /// Emit a warning when adding a char literal to a string. 10988 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10989 Expr *LHSExpr, Expr *RHSExpr) { 10990 const Expr *StringRefExpr = LHSExpr; 10991 const CharacterLiteral *CharExpr = 10992 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10993 10994 if (!CharExpr) { 10995 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10996 StringRefExpr = RHSExpr; 10997 } 10998 10999 if (!CharExpr || !StringRefExpr) 11000 return; 11001 11002 const QualType StringType = StringRefExpr->getType(); 11003 11004 // Return if not a PointerType. 11005 if (!StringType->isAnyPointerType()) 11006 return; 11007 11008 // Return if not a CharacterType. 11009 if (!StringType->getPointeeType()->isAnyCharacterType()) 11010 return; 11011 11012 ASTContext &Ctx = Self.getASTContext(); 11013 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 11014 11015 const QualType CharType = CharExpr->getType(); 11016 if (!CharType->isAnyCharacterType() && 11017 CharType->isIntegerType() && 11018 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 11019 Self.Diag(OpLoc, diag::warn_string_plus_char) 11020 << DiagRange << Ctx.CharTy; 11021 } else { 11022 Self.Diag(OpLoc, diag::warn_string_plus_char) 11023 << DiagRange << CharExpr->getType(); 11024 } 11025 11026 // Only print a fixit for str + char, not for char + str. 11027 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 11028 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 11029 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 11030 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 11031 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 11032 << FixItHint::CreateInsertion(EndLoc, "]"); 11033 } else { 11034 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 11035 } 11036 } 11037 11038 /// Emit error when two pointers are incompatible. 11039 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 11040 Expr *LHSExpr, Expr *RHSExpr) { 11041 assert(LHSExpr->getType()->isAnyPointerType()); 11042 assert(RHSExpr->getType()->isAnyPointerType()); 11043 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 11044 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 11045 << RHSExpr->getSourceRange(); 11046 } 11047 11048 // C99 6.5.6 11049 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 11050 SourceLocation Loc, BinaryOperatorKind Opc, 11051 QualType* CompLHSTy) { 11052 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11053 11054 if (LHS.get()->getType()->isVectorType() || 11055 RHS.get()->getType()->isVectorType()) { 11056 QualType compType = 11057 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11058 /*AllowBothBool*/ getLangOpts().AltiVec, 11059 /*AllowBoolConversions*/ getLangOpts().ZVector, 11060 /*AllowBooleanOperation*/ false, 11061 /*ReportInvalid*/ true); 11062 if (CompLHSTy) *CompLHSTy = compType; 11063 return compType; 11064 } 11065 11066 if (LHS.get()->getType()->isVLSTBuiltinType() || 11067 RHS.get()->getType()->isVLSTBuiltinType()) { 11068 QualType compType = 11069 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11070 if (CompLHSTy) 11071 *CompLHSTy = compType; 11072 return compType; 11073 } 11074 11075 if (LHS.get()->getType()->isConstantMatrixType() || 11076 RHS.get()->getType()->isConstantMatrixType()) { 11077 QualType compType = 11078 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11079 if (CompLHSTy) 11080 *CompLHSTy = compType; 11081 return compType; 11082 } 11083 11084 QualType compType = UsualArithmeticConversions( 11085 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11086 if (LHS.isInvalid() || RHS.isInvalid()) 11087 return QualType(); 11088 11089 // Diagnose "string literal" '+' int and string '+' "char literal". 11090 if (Opc == BO_Add) { 11091 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 11092 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 11093 } 11094 11095 // handle the common case first (both operands are arithmetic). 11096 if (!compType.isNull() && compType->isArithmeticType()) { 11097 if (CompLHSTy) *CompLHSTy = compType; 11098 return compType; 11099 } 11100 11101 // Type-checking. Ultimately the pointer's going to be in PExp; 11102 // note that we bias towards the LHS being the pointer. 11103 Expr *PExp = LHS.get(), *IExp = RHS.get(); 11104 11105 bool isObjCPointer; 11106 if (PExp->getType()->isPointerType()) { 11107 isObjCPointer = false; 11108 } else if (PExp->getType()->isObjCObjectPointerType()) { 11109 isObjCPointer = true; 11110 } else { 11111 std::swap(PExp, IExp); 11112 if (PExp->getType()->isPointerType()) { 11113 isObjCPointer = false; 11114 } else if (PExp->getType()->isObjCObjectPointerType()) { 11115 isObjCPointer = true; 11116 } else { 11117 return InvalidOperands(Loc, LHS, RHS); 11118 } 11119 } 11120 assert(PExp->getType()->isAnyPointerType()); 11121 11122 if (!IExp->getType()->isIntegerType()) 11123 return InvalidOperands(Loc, LHS, RHS); 11124 11125 // Adding to a null pointer results in undefined behavior. 11126 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 11127 Context, Expr::NPC_ValueDependentIsNotNull)) { 11128 // In C++ adding zero to a null pointer is defined. 11129 Expr::EvalResult KnownVal; 11130 if (!getLangOpts().CPlusPlus || 11131 (!IExp->isValueDependent() && 11132 (!IExp->EvaluateAsInt(KnownVal, Context) || 11133 KnownVal.Val.getInt() != 0))) { 11134 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 11135 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 11136 Context, BO_Add, PExp, IExp); 11137 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 11138 } 11139 } 11140 11141 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 11142 return QualType(); 11143 11144 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 11145 return QualType(); 11146 11147 // Check array bounds for pointer arithemtic 11148 CheckArrayAccess(PExp, IExp); 11149 11150 if (CompLHSTy) { 11151 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 11152 if (LHSTy.isNull()) { 11153 LHSTy = LHS.get()->getType(); 11154 if (LHSTy->isPromotableIntegerType()) 11155 LHSTy = Context.getPromotedIntegerType(LHSTy); 11156 } 11157 *CompLHSTy = LHSTy; 11158 } 11159 11160 return PExp->getType(); 11161 } 11162 11163 // C99 6.5.6 11164 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 11165 SourceLocation Loc, 11166 QualType* CompLHSTy) { 11167 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11168 11169 if (LHS.get()->getType()->isVectorType() || 11170 RHS.get()->getType()->isVectorType()) { 11171 QualType compType = 11172 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11173 /*AllowBothBool*/ getLangOpts().AltiVec, 11174 /*AllowBoolConversions*/ getLangOpts().ZVector, 11175 /*AllowBooleanOperation*/ false, 11176 /*ReportInvalid*/ true); 11177 if (CompLHSTy) *CompLHSTy = compType; 11178 return compType; 11179 } 11180 11181 if (LHS.get()->getType()->isVLSTBuiltinType() || 11182 RHS.get()->getType()->isVLSTBuiltinType()) { 11183 QualType compType = 11184 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11185 if (CompLHSTy) 11186 *CompLHSTy = compType; 11187 return compType; 11188 } 11189 11190 if (LHS.get()->getType()->isConstantMatrixType() || 11191 RHS.get()->getType()->isConstantMatrixType()) { 11192 QualType compType = 11193 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11194 if (CompLHSTy) 11195 *CompLHSTy = compType; 11196 return compType; 11197 } 11198 11199 QualType compType = UsualArithmeticConversions( 11200 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11201 if (LHS.isInvalid() || RHS.isInvalid()) 11202 return QualType(); 11203 11204 // Enforce type constraints: C99 6.5.6p3. 11205 11206 // Handle the common case first (both operands are arithmetic). 11207 if (!compType.isNull() && compType->isArithmeticType()) { 11208 if (CompLHSTy) *CompLHSTy = compType; 11209 return compType; 11210 } 11211 11212 // Either ptr - int or ptr - ptr. 11213 if (LHS.get()->getType()->isAnyPointerType()) { 11214 QualType lpointee = LHS.get()->getType()->getPointeeType(); 11215 11216 // Diagnose bad cases where we step over interface counts. 11217 if (LHS.get()->getType()->isObjCObjectPointerType() && 11218 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 11219 return QualType(); 11220 11221 // The result type of a pointer-int computation is the pointer type. 11222 if (RHS.get()->getType()->isIntegerType()) { 11223 // Subtracting from a null pointer should produce a warning. 11224 // The last argument to the diagnose call says this doesn't match the 11225 // GNU int-to-pointer idiom. 11226 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 11227 Expr::NPC_ValueDependentIsNotNull)) { 11228 // In C++ adding zero to a null pointer is defined. 11229 Expr::EvalResult KnownVal; 11230 if (!getLangOpts().CPlusPlus || 11231 (!RHS.get()->isValueDependent() && 11232 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 11233 KnownVal.Val.getInt() != 0))) { 11234 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 11235 } 11236 } 11237 11238 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 11239 return QualType(); 11240 11241 // Check array bounds for pointer arithemtic 11242 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 11243 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 11244 11245 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11246 return LHS.get()->getType(); 11247 } 11248 11249 // Handle pointer-pointer subtractions. 11250 if (const PointerType *RHSPTy 11251 = RHS.get()->getType()->getAs<PointerType>()) { 11252 QualType rpointee = RHSPTy->getPointeeType(); 11253 11254 if (getLangOpts().CPlusPlus) { 11255 // Pointee types must be the same: C++ [expr.add] 11256 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 11257 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11258 } 11259 } else { 11260 // Pointee types must be compatible C99 6.5.6p3 11261 if (!Context.typesAreCompatible( 11262 Context.getCanonicalType(lpointee).getUnqualifiedType(), 11263 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 11264 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11265 return QualType(); 11266 } 11267 } 11268 11269 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 11270 LHS.get(), RHS.get())) 11271 return QualType(); 11272 11273 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11274 Context, Expr::NPC_ValueDependentIsNotNull); 11275 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11276 Context, Expr::NPC_ValueDependentIsNotNull); 11277 11278 // Subtracting nullptr or from nullptr is suspect 11279 if (LHSIsNullPtr) 11280 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 11281 if (RHSIsNullPtr) 11282 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 11283 11284 // The pointee type may have zero size. As an extension, a structure or 11285 // union may have zero size or an array may have zero length. In this 11286 // case subtraction does not make sense. 11287 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 11288 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 11289 if (ElementSize.isZero()) { 11290 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 11291 << rpointee.getUnqualifiedType() 11292 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11293 } 11294 } 11295 11296 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11297 return Context.getPointerDiffType(); 11298 } 11299 } 11300 11301 return InvalidOperands(Loc, LHS, RHS); 11302 } 11303 11304 static bool isScopedEnumerationType(QualType T) { 11305 if (const EnumType *ET = T->getAs<EnumType>()) 11306 return ET->getDecl()->isScoped(); 11307 return false; 11308 } 11309 11310 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 11311 SourceLocation Loc, BinaryOperatorKind Opc, 11312 QualType LHSType) { 11313 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 11314 // so skip remaining warnings as we don't want to modify values within Sema. 11315 if (S.getLangOpts().OpenCL) 11316 return; 11317 11318 // Check right/shifter operand 11319 Expr::EvalResult RHSResult; 11320 if (RHS.get()->isValueDependent() || 11321 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 11322 return; 11323 llvm::APSInt Right = RHSResult.Val.getInt(); 11324 11325 if (Right.isNegative()) { 11326 S.DiagRuntimeBehavior(Loc, RHS.get(), 11327 S.PDiag(diag::warn_shift_negative) 11328 << RHS.get()->getSourceRange()); 11329 return; 11330 } 11331 11332 QualType LHSExprType = LHS.get()->getType(); 11333 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 11334 if (LHSExprType->isBitIntType()) 11335 LeftSize = S.Context.getIntWidth(LHSExprType); 11336 else if (LHSExprType->isFixedPointType()) { 11337 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 11338 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 11339 } 11340 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 11341 if (Right.uge(LeftBits)) { 11342 S.DiagRuntimeBehavior(Loc, RHS.get(), 11343 S.PDiag(diag::warn_shift_gt_typewidth) 11344 << RHS.get()->getSourceRange()); 11345 return; 11346 } 11347 11348 // FIXME: We probably need to handle fixed point types specially here. 11349 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 11350 return; 11351 11352 // When left shifting an ICE which is signed, we can check for overflow which 11353 // according to C++ standards prior to C++2a has undefined behavior 11354 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 11355 // more than the maximum value representable in the result type, so never 11356 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11357 // expression is still probably a bug.) 11358 Expr::EvalResult LHSResult; 11359 if (LHS.get()->isValueDependent() || 11360 LHSType->hasUnsignedIntegerRepresentation() || 11361 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11362 return; 11363 llvm::APSInt Left = LHSResult.Val.getInt(); 11364 11365 // If LHS does not have a signed type and non-negative value 11366 // then, the behavior is undefined before C++2a. Warn about it. 11367 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11368 !S.getLangOpts().CPlusPlus20) { 11369 S.DiagRuntimeBehavior(Loc, LHS.get(), 11370 S.PDiag(diag::warn_shift_lhs_negative) 11371 << LHS.get()->getSourceRange()); 11372 return; 11373 } 11374 11375 llvm::APInt ResultBits = 11376 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11377 if (LeftBits.uge(ResultBits)) 11378 return; 11379 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11380 Result = Result.shl(Right); 11381 11382 // Print the bit representation of the signed integer as an unsigned 11383 // hexadecimal number. 11384 SmallString<40> HexResult; 11385 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11386 11387 // If we are only missing a sign bit, this is less likely to result in actual 11388 // bugs -- if the result is cast back to an unsigned type, it will have the 11389 // expected value. Thus we place this behind a different warning that can be 11390 // turned off separately if needed. 11391 if (LeftBits == ResultBits - 1) { 11392 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11393 << HexResult << LHSType 11394 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11395 return; 11396 } 11397 11398 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11399 << HexResult.str() << Result.getMinSignedBits() << LHSType 11400 << Left.getBitWidth() << LHS.get()->getSourceRange() 11401 << RHS.get()->getSourceRange(); 11402 } 11403 11404 /// Return the resulting type when a vector is shifted 11405 /// by a scalar or vector shift amount. 11406 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11407 SourceLocation Loc, bool IsCompAssign) { 11408 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11409 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11410 !LHS.get()->getType()->isVectorType()) { 11411 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11412 << RHS.get()->getType() << LHS.get()->getType() 11413 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11414 return QualType(); 11415 } 11416 11417 if (!IsCompAssign) { 11418 LHS = S.UsualUnaryConversions(LHS.get()); 11419 if (LHS.isInvalid()) return QualType(); 11420 } 11421 11422 RHS = S.UsualUnaryConversions(RHS.get()); 11423 if (RHS.isInvalid()) return QualType(); 11424 11425 QualType LHSType = LHS.get()->getType(); 11426 // Note that LHS might be a scalar because the routine calls not only in 11427 // OpenCL case. 11428 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11429 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11430 11431 // Note that RHS might not be a vector. 11432 QualType RHSType = RHS.get()->getType(); 11433 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11434 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11435 11436 // Do not allow shifts for boolean vectors. 11437 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || 11438 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { 11439 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11440 << LHS.get()->getType() << RHS.get()->getType() 11441 << LHS.get()->getSourceRange(); 11442 return QualType(); 11443 } 11444 11445 // The operands need to be integers. 11446 if (!LHSEleType->isIntegerType()) { 11447 S.Diag(Loc, diag::err_typecheck_expect_int) 11448 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11449 return QualType(); 11450 } 11451 11452 if (!RHSEleType->isIntegerType()) { 11453 S.Diag(Loc, diag::err_typecheck_expect_int) 11454 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11455 return QualType(); 11456 } 11457 11458 if (!LHSVecTy) { 11459 assert(RHSVecTy); 11460 if (IsCompAssign) 11461 return RHSType; 11462 if (LHSEleType != RHSEleType) { 11463 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11464 LHSEleType = RHSEleType; 11465 } 11466 QualType VecTy = 11467 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11468 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11469 LHSType = VecTy; 11470 } else if (RHSVecTy) { 11471 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11472 // are applied component-wise. So if RHS is a vector, then ensure 11473 // that the number of elements is the same as LHS... 11474 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11475 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11476 << LHS.get()->getType() << RHS.get()->getType() 11477 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11478 return QualType(); 11479 } 11480 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11481 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11482 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11483 if (LHSBT != RHSBT && 11484 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11485 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11486 << LHS.get()->getType() << RHS.get()->getType() 11487 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11488 } 11489 } 11490 } else { 11491 // ...else expand RHS to match the number of elements in LHS. 11492 QualType VecTy = 11493 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11494 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11495 } 11496 11497 return LHSType; 11498 } 11499 11500 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, 11501 ExprResult &RHS, SourceLocation Loc, 11502 bool IsCompAssign) { 11503 if (!IsCompAssign) { 11504 LHS = S.UsualUnaryConversions(LHS.get()); 11505 if (LHS.isInvalid()) 11506 return QualType(); 11507 } 11508 11509 RHS = S.UsualUnaryConversions(RHS.get()); 11510 if (RHS.isInvalid()) 11511 return QualType(); 11512 11513 QualType LHSType = LHS.get()->getType(); 11514 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 11515 QualType LHSEleType = LHSType->isVLSTBuiltinType() 11516 ? LHSBuiltinTy->getSveEltType(S.getASTContext()) 11517 : LHSType; 11518 11519 // Note that RHS might not be a vector 11520 QualType RHSType = RHS.get()->getType(); 11521 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); 11522 QualType RHSEleType = RHSType->isVLSTBuiltinType() 11523 ? RHSBuiltinTy->getSveEltType(S.getASTContext()) 11524 : RHSType; 11525 11526 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || 11527 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) { 11528 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11529 << LHSType << RHSType << LHS.get()->getSourceRange(); 11530 return QualType(); 11531 } 11532 11533 if (!LHSEleType->isIntegerType()) { 11534 S.Diag(Loc, diag::err_typecheck_expect_int) 11535 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11536 return QualType(); 11537 } 11538 11539 if (!RHSEleType->isIntegerType()) { 11540 S.Diag(Loc, diag::err_typecheck_expect_int) 11541 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11542 return QualType(); 11543 } 11544 11545 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() && 11546 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != 11547 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) { 11548 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11549 << LHSType << RHSType << LHS.get()->getSourceRange() 11550 << RHS.get()->getSourceRange(); 11551 return QualType(); 11552 } 11553 11554 if (!LHSType->isVLSTBuiltinType()) { 11555 assert(RHSType->isVLSTBuiltinType()); 11556 if (IsCompAssign) 11557 return RHSType; 11558 if (LHSEleType != RHSEleType) { 11559 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast); 11560 LHSEleType = RHSEleType; 11561 } 11562 const llvm::ElementCount VecSize = 11563 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC; 11564 QualType VecTy = 11565 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue()); 11566 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat); 11567 LHSType = VecTy; 11568 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) { 11569 if (S.Context.getTypeSize(RHSBuiltinTy) != 11570 S.Context.getTypeSize(LHSBuiltinTy)) { 11571 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11572 << LHSType << RHSType << LHS.get()->getSourceRange() 11573 << RHS.get()->getSourceRange(); 11574 return QualType(); 11575 } 11576 } else { 11577 const llvm::ElementCount VecSize = 11578 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC; 11579 if (LHSEleType != RHSEleType) { 11580 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast); 11581 RHSEleType = LHSEleType; 11582 } 11583 QualType VecTy = 11584 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue()); 11585 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11586 } 11587 11588 return LHSType; 11589 } 11590 11591 // C99 6.5.7 11592 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11593 SourceLocation Loc, BinaryOperatorKind Opc, 11594 bool IsCompAssign) { 11595 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11596 11597 // Vector shifts promote their scalar inputs to vector type. 11598 if (LHS.get()->getType()->isVectorType() || 11599 RHS.get()->getType()->isVectorType()) { 11600 if (LangOpts.ZVector) { 11601 // The shift operators for the z vector extensions work basically 11602 // like general shifts, except that neither the LHS nor the RHS is 11603 // allowed to be a "vector bool". 11604 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11605 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11606 return InvalidOperands(Loc, LHS, RHS); 11607 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11608 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11609 return InvalidOperands(Loc, LHS, RHS); 11610 } 11611 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11612 } 11613 11614 if (LHS.get()->getType()->isVLSTBuiltinType() || 11615 RHS.get()->getType()->isVLSTBuiltinType()) 11616 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11617 11618 // Shifts don't perform usual arithmetic conversions, they just do integer 11619 // promotions on each operand. C99 6.5.7p3 11620 11621 // For the LHS, do usual unary conversions, but then reset them away 11622 // if this is a compound assignment. 11623 ExprResult OldLHS = LHS; 11624 LHS = UsualUnaryConversions(LHS.get()); 11625 if (LHS.isInvalid()) 11626 return QualType(); 11627 QualType LHSType = LHS.get()->getType(); 11628 if (IsCompAssign) LHS = OldLHS; 11629 11630 // The RHS is simpler. 11631 RHS = UsualUnaryConversions(RHS.get()); 11632 if (RHS.isInvalid()) 11633 return QualType(); 11634 QualType RHSType = RHS.get()->getType(); 11635 11636 // C99 6.5.7p2: Each of the operands shall have integer type. 11637 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11638 if ((!LHSType->isFixedPointOrIntegerType() && 11639 !LHSType->hasIntegerRepresentation()) || 11640 !RHSType->hasIntegerRepresentation()) 11641 return InvalidOperands(Loc, LHS, RHS); 11642 11643 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11644 // hasIntegerRepresentation() above instead of this. 11645 if (isScopedEnumerationType(LHSType) || 11646 isScopedEnumerationType(RHSType)) { 11647 return InvalidOperands(Loc, LHS, RHS); 11648 } 11649 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11650 11651 // "The type of the result is that of the promoted left operand." 11652 return LHSType; 11653 } 11654 11655 /// Diagnose bad pointer comparisons. 11656 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11657 ExprResult &LHS, ExprResult &RHS, 11658 bool IsError) { 11659 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11660 : diag::ext_typecheck_comparison_of_distinct_pointers) 11661 << LHS.get()->getType() << RHS.get()->getType() 11662 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11663 } 11664 11665 /// Returns false if the pointers are converted to a composite type, 11666 /// true otherwise. 11667 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11668 ExprResult &LHS, ExprResult &RHS) { 11669 // C++ [expr.rel]p2: 11670 // [...] Pointer conversions (4.10) and qualification 11671 // conversions (4.4) are performed on pointer operands (or on 11672 // a pointer operand and a null pointer constant) to bring 11673 // them to their composite pointer type. [...] 11674 // 11675 // C++ [expr.eq]p1 uses the same notion for (in)equality 11676 // comparisons of pointers. 11677 11678 QualType LHSType = LHS.get()->getType(); 11679 QualType RHSType = RHS.get()->getType(); 11680 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11681 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11682 11683 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11684 if (T.isNull()) { 11685 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11686 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11687 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11688 else 11689 S.InvalidOperands(Loc, LHS, RHS); 11690 return true; 11691 } 11692 11693 return false; 11694 } 11695 11696 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11697 ExprResult &LHS, 11698 ExprResult &RHS, 11699 bool IsError) { 11700 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11701 : diag::ext_typecheck_comparison_of_fptr_to_void) 11702 << LHS.get()->getType() << RHS.get()->getType() 11703 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11704 } 11705 11706 static bool isObjCObjectLiteral(ExprResult &E) { 11707 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11708 case Stmt::ObjCArrayLiteralClass: 11709 case Stmt::ObjCDictionaryLiteralClass: 11710 case Stmt::ObjCStringLiteralClass: 11711 case Stmt::ObjCBoxedExprClass: 11712 return true; 11713 default: 11714 // Note that ObjCBoolLiteral is NOT an object literal! 11715 return false; 11716 } 11717 } 11718 11719 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11720 const ObjCObjectPointerType *Type = 11721 LHS->getType()->getAs<ObjCObjectPointerType>(); 11722 11723 // If this is not actually an Objective-C object, bail out. 11724 if (!Type) 11725 return false; 11726 11727 // Get the LHS object's interface type. 11728 QualType InterfaceType = Type->getPointeeType(); 11729 11730 // If the RHS isn't an Objective-C object, bail out. 11731 if (!RHS->getType()->isObjCObjectPointerType()) 11732 return false; 11733 11734 // Try to find the -isEqual: method. 11735 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11736 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11737 InterfaceType, 11738 /*IsInstance=*/true); 11739 if (!Method) { 11740 if (Type->isObjCIdType()) { 11741 // For 'id', just check the global pool. 11742 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11743 /*receiverId=*/true); 11744 } else { 11745 // Check protocols. 11746 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11747 /*IsInstance=*/true); 11748 } 11749 } 11750 11751 if (!Method) 11752 return false; 11753 11754 QualType T = Method->parameters()[0]->getType(); 11755 if (!T->isObjCObjectPointerType()) 11756 return false; 11757 11758 QualType R = Method->getReturnType(); 11759 if (!R->isScalarType()) 11760 return false; 11761 11762 return true; 11763 } 11764 11765 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11766 FromE = FromE->IgnoreParenImpCasts(); 11767 switch (FromE->getStmtClass()) { 11768 default: 11769 break; 11770 case Stmt::ObjCStringLiteralClass: 11771 // "string literal" 11772 return LK_String; 11773 case Stmt::ObjCArrayLiteralClass: 11774 // "array literal" 11775 return LK_Array; 11776 case Stmt::ObjCDictionaryLiteralClass: 11777 // "dictionary literal" 11778 return LK_Dictionary; 11779 case Stmt::BlockExprClass: 11780 return LK_Block; 11781 case Stmt::ObjCBoxedExprClass: { 11782 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11783 switch (Inner->getStmtClass()) { 11784 case Stmt::IntegerLiteralClass: 11785 case Stmt::FloatingLiteralClass: 11786 case Stmt::CharacterLiteralClass: 11787 case Stmt::ObjCBoolLiteralExprClass: 11788 case Stmt::CXXBoolLiteralExprClass: 11789 // "numeric literal" 11790 return LK_Numeric; 11791 case Stmt::ImplicitCastExprClass: { 11792 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11793 // Boolean literals can be represented by implicit casts. 11794 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11795 return LK_Numeric; 11796 break; 11797 } 11798 default: 11799 break; 11800 } 11801 return LK_Boxed; 11802 } 11803 } 11804 return LK_None; 11805 } 11806 11807 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11808 ExprResult &LHS, ExprResult &RHS, 11809 BinaryOperator::Opcode Opc){ 11810 Expr *Literal; 11811 Expr *Other; 11812 if (isObjCObjectLiteral(LHS)) { 11813 Literal = LHS.get(); 11814 Other = RHS.get(); 11815 } else { 11816 Literal = RHS.get(); 11817 Other = LHS.get(); 11818 } 11819 11820 // Don't warn on comparisons against nil. 11821 Other = Other->IgnoreParenCasts(); 11822 if (Other->isNullPointerConstant(S.getASTContext(), 11823 Expr::NPC_ValueDependentIsNotNull)) 11824 return; 11825 11826 // This should be kept in sync with warn_objc_literal_comparison. 11827 // LK_String should always be after the other literals, since it has its own 11828 // warning flag. 11829 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11830 assert(LiteralKind != Sema::LK_Block); 11831 if (LiteralKind == Sema::LK_None) { 11832 llvm_unreachable("Unknown Objective-C object literal kind"); 11833 } 11834 11835 if (LiteralKind == Sema::LK_String) 11836 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11837 << Literal->getSourceRange(); 11838 else 11839 S.Diag(Loc, diag::warn_objc_literal_comparison) 11840 << LiteralKind << Literal->getSourceRange(); 11841 11842 if (BinaryOperator::isEqualityOp(Opc) && 11843 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11844 SourceLocation Start = LHS.get()->getBeginLoc(); 11845 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11846 CharSourceRange OpRange = 11847 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11848 11849 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11850 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11851 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11852 << FixItHint::CreateInsertion(End, "]"); 11853 } 11854 } 11855 11856 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11857 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11858 ExprResult &RHS, SourceLocation Loc, 11859 BinaryOperatorKind Opc) { 11860 // Check that left hand side is !something. 11861 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11862 if (!UO || UO->getOpcode() != UO_LNot) return; 11863 11864 // Only check if the right hand side is non-bool arithmetic type. 11865 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11866 11867 // Make sure that the something in !something is not bool. 11868 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11869 if (SubExpr->isKnownToHaveBooleanValue()) return; 11870 11871 // Emit warning. 11872 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11873 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11874 << Loc << IsBitwiseOp; 11875 11876 // First note suggest !(x < y) 11877 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11878 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11879 FirstClose = S.getLocForEndOfToken(FirstClose); 11880 if (FirstClose.isInvalid()) 11881 FirstOpen = SourceLocation(); 11882 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11883 << IsBitwiseOp 11884 << FixItHint::CreateInsertion(FirstOpen, "(") 11885 << FixItHint::CreateInsertion(FirstClose, ")"); 11886 11887 // Second note suggests (!x) < y 11888 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11889 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11890 SecondClose = S.getLocForEndOfToken(SecondClose); 11891 if (SecondClose.isInvalid()) 11892 SecondOpen = SourceLocation(); 11893 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11894 << FixItHint::CreateInsertion(SecondOpen, "(") 11895 << FixItHint::CreateInsertion(SecondClose, ")"); 11896 } 11897 11898 // Returns true if E refers to a non-weak array. 11899 static bool checkForArray(const Expr *E) { 11900 const ValueDecl *D = nullptr; 11901 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11902 D = DR->getDecl(); 11903 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11904 if (Mem->isImplicitAccess()) 11905 D = Mem->getMemberDecl(); 11906 } 11907 if (!D) 11908 return false; 11909 return D->getType()->isArrayType() && !D->isWeak(); 11910 } 11911 11912 /// Diagnose some forms of syntactically-obvious tautological comparison. 11913 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11914 Expr *LHS, Expr *RHS, 11915 BinaryOperatorKind Opc) { 11916 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11917 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11918 11919 QualType LHSType = LHS->getType(); 11920 QualType RHSType = RHS->getType(); 11921 if (LHSType->hasFloatingRepresentation() || 11922 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11923 S.inTemplateInstantiation()) 11924 return; 11925 11926 // Comparisons between two array types are ill-formed for operator<=>, so 11927 // we shouldn't emit any additional warnings about it. 11928 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11929 return; 11930 11931 // For non-floating point types, check for self-comparisons of the form 11932 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11933 // often indicate logic errors in the program. 11934 // 11935 // NOTE: Don't warn about comparison expressions resulting from macro 11936 // expansion. Also don't warn about comparisons which are only self 11937 // comparisons within a template instantiation. The warnings should catch 11938 // obvious cases in the definition of the template anyways. The idea is to 11939 // warn when the typed comparison operator will always evaluate to the same 11940 // result. 11941 11942 // Used for indexing into %select in warn_comparison_always 11943 enum { 11944 AlwaysConstant, 11945 AlwaysTrue, 11946 AlwaysFalse, 11947 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11948 }; 11949 11950 // C++2a [depr.array.comp]: 11951 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11952 // operands of array type are deprecated. 11953 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11954 RHSStripped->getType()->isArrayType()) { 11955 S.Diag(Loc, diag::warn_depr_array_comparison) 11956 << LHS->getSourceRange() << RHS->getSourceRange() 11957 << LHSStripped->getType() << RHSStripped->getType(); 11958 // Carry on to produce the tautological comparison warning, if this 11959 // expression is potentially-evaluated, we can resolve the array to a 11960 // non-weak declaration, and so on. 11961 } 11962 11963 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11964 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11965 unsigned Result; 11966 switch (Opc) { 11967 case BO_EQ: 11968 case BO_LE: 11969 case BO_GE: 11970 Result = AlwaysTrue; 11971 break; 11972 case BO_NE: 11973 case BO_LT: 11974 case BO_GT: 11975 Result = AlwaysFalse; 11976 break; 11977 case BO_Cmp: 11978 Result = AlwaysEqual; 11979 break; 11980 default: 11981 Result = AlwaysConstant; 11982 break; 11983 } 11984 S.DiagRuntimeBehavior(Loc, nullptr, 11985 S.PDiag(diag::warn_comparison_always) 11986 << 0 /*self-comparison*/ 11987 << Result); 11988 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11989 // What is it always going to evaluate to? 11990 unsigned Result; 11991 switch (Opc) { 11992 case BO_EQ: // e.g. array1 == array2 11993 Result = AlwaysFalse; 11994 break; 11995 case BO_NE: // e.g. array1 != array2 11996 Result = AlwaysTrue; 11997 break; 11998 default: // e.g. array1 <= array2 11999 // The best we can say is 'a constant' 12000 Result = AlwaysConstant; 12001 break; 12002 } 12003 S.DiagRuntimeBehavior(Loc, nullptr, 12004 S.PDiag(diag::warn_comparison_always) 12005 << 1 /*array comparison*/ 12006 << Result); 12007 } 12008 } 12009 12010 if (isa<CastExpr>(LHSStripped)) 12011 LHSStripped = LHSStripped->IgnoreParenCasts(); 12012 if (isa<CastExpr>(RHSStripped)) 12013 RHSStripped = RHSStripped->IgnoreParenCasts(); 12014 12015 // Warn about comparisons against a string constant (unless the other 12016 // operand is null); the user probably wants string comparison function. 12017 Expr *LiteralString = nullptr; 12018 Expr *LiteralStringStripped = nullptr; 12019 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 12020 !RHSStripped->isNullPointerConstant(S.Context, 12021 Expr::NPC_ValueDependentIsNull)) { 12022 LiteralString = LHS; 12023 LiteralStringStripped = LHSStripped; 12024 } else if ((isa<StringLiteral>(RHSStripped) || 12025 isa<ObjCEncodeExpr>(RHSStripped)) && 12026 !LHSStripped->isNullPointerConstant(S.Context, 12027 Expr::NPC_ValueDependentIsNull)) { 12028 LiteralString = RHS; 12029 LiteralStringStripped = RHSStripped; 12030 } 12031 12032 if (LiteralString) { 12033 S.DiagRuntimeBehavior(Loc, nullptr, 12034 S.PDiag(diag::warn_stringcompare) 12035 << isa<ObjCEncodeExpr>(LiteralStringStripped) 12036 << LiteralString->getSourceRange()); 12037 } 12038 } 12039 12040 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 12041 switch (CK) { 12042 default: { 12043 #ifndef NDEBUG 12044 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 12045 << "\n"; 12046 #endif 12047 llvm_unreachable("unhandled cast kind"); 12048 } 12049 case CK_UserDefinedConversion: 12050 return ICK_Identity; 12051 case CK_LValueToRValue: 12052 return ICK_Lvalue_To_Rvalue; 12053 case CK_ArrayToPointerDecay: 12054 return ICK_Array_To_Pointer; 12055 case CK_FunctionToPointerDecay: 12056 return ICK_Function_To_Pointer; 12057 case CK_IntegralCast: 12058 return ICK_Integral_Conversion; 12059 case CK_FloatingCast: 12060 return ICK_Floating_Conversion; 12061 case CK_IntegralToFloating: 12062 case CK_FloatingToIntegral: 12063 return ICK_Floating_Integral; 12064 case CK_IntegralComplexCast: 12065 case CK_FloatingComplexCast: 12066 case CK_FloatingComplexToIntegralComplex: 12067 case CK_IntegralComplexToFloatingComplex: 12068 return ICK_Complex_Conversion; 12069 case CK_FloatingComplexToReal: 12070 case CK_FloatingRealToComplex: 12071 case CK_IntegralComplexToReal: 12072 case CK_IntegralRealToComplex: 12073 return ICK_Complex_Real; 12074 } 12075 } 12076 12077 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 12078 QualType FromType, 12079 SourceLocation Loc) { 12080 // Check for a narrowing implicit conversion. 12081 StandardConversionSequence SCS; 12082 SCS.setAsIdentityConversion(); 12083 SCS.setToType(0, FromType); 12084 SCS.setToType(1, ToType); 12085 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 12086 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 12087 12088 APValue PreNarrowingValue; 12089 QualType PreNarrowingType; 12090 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 12091 PreNarrowingType, 12092 /*IgnoreFloatToIntegralConversion*/ true)) { 12093 case NK_Dependent_Narrowing: 12094 // Implicit conversion to a narrower type, but the expression is 12095 // value-dependent so we can't tell whether it's actually narrowing. 12096 case NK_Not_Narrowing: 12097 return false; 12098 12099 case NK_Constant_Narrowing: 12100 // Implicit conversion to a narrower type, and the value is not a constant 12101 // expression. 12102 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12103 << /*Constant*/ 1 12104 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 12105 return true; 12106 12107 case NK_Variable_Narrowing: 12108 // Implicit conversion to a narrower type, and the value is not a constant 12109 // expression. 12110 case NK_Type_Narrowing: 12111 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12112 << /*Constant*/ 0 << FromType << ToType; 12113 // TODO: It's not a constant expression, but what if the user intended it 12114 // to be? Can we produce notes to help them figure out why it isn't? 12115 return true; 12116 } 12117 llvm_unreachable("unhandled case in switch"); 12118 } 12119 12120 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 12121 ExprResult &LHS, 12122 ExprResult &RHS, 12123 SourceLocation Loc) { 12124 QualType LHSType = LHS.get()->getType(); 12125 QualType RHSType = RHS.get()->getType(); 12126 // Dig out the original argument type and expression before implicit casts 12127 // were applied. These are the types/expressions we need to check the 12128 // [expr.spaceship] requirements against. 12129 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 12130 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 12131 QualType LHSStrippedType = LHSStripped.get()->getType(); 12132 QualType RHSStrippedType = RHSStripped.get()->getType(); 12133 12134 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 12135 // other is not, the program is ill-formed. 12136 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 12137 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12138 return QualType(); 12139 } 12140 12141 // FIXME: Consider combining this with checkEnumArithmeticConversions. 12142 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 12143 RHSStrippedType->isEnumeralType(); 12144 if (NumEnumArgs == 1) { 12145 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 12146 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 12147 if (OtherTy->hasFloatingRepresentation()) { 12148 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12149 return QualType(); 12150 } 12151 } 12152 if (NumEnumArgs == 2) { 12153 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 12154 // type E, the operator yields the result of converting the operands 12155 // to the underlying type of E and applying <=> to the converted operands. 12156 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 12157 S.InvalidOperands(Loc, LHS, RHS); 12158 return QualType(); 12159 } 12160 QualType IntType = 12161 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 12162 assert(IntType->isArithmeticType()); 12163 12164 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 12165 // promote the boolean type, and all other promotable integer types, to 12166 // avoid this. 12167 if (IntType->isPromotableIntegerType()) 12168 IntType = S.Context.getPromotedIntegerType(IntType); 12169 12170 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 12171 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 12172 LHSType = RHSType = IntType; 12173 } 12174 12175 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 12176 // usual arithmetic conversions are applied to the operands. 12177 QualType Type = 12178 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12179 if (LHS.isInvalid() || RHS.isInvalid()) 12180 return QualType(); 12181 if (Type.isNull()) 12182 return S.InvalidOperands(Loc, LHS, RHS); 12183 12184 Optional<ComparisonCategoryType> CCT = 12185 getComparisonCategoryForBuiltinCmp(Type); 12186 if (!CCT) 12187 return S.InvalidOperands(Loc, LHS, RHS); 12188 12189 bool HasNarrowing = checkThreeWayNarrowingConversion( 12190 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 12191 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 12192 RHS.get()->getBeginLoc()); 12193 if (HasNarrowing) 12194 return QualType(); 12195 12196 assert(!Type.isNull() && "composite type for <=> has not been set"); 12197 12198 return S.CheckComparisonCategoryType( 12199 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 12200 } 12201 12202 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 12203 ExprResult &RHS, 12204 SourceLocation Loc, 12205 BinaryOperatorKind Opc) { 12206 if (Opc == BO_Cmp) 12207 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 12208 12209 // C99 6.5.8p3 / C99 6.5.9p4 12210 QualType Type = 12211 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12212 if (LHS.isInvalid() || RHS.isInvalid()) 12213 return QualType(); 12214 if (Type.isNull()) 12215 return S.InvalidOperands(Loc, LHS, RHS); 12216 assert(Type->isArithmeticType() || Type->isEnumeralType()); 12217 12218 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 12219 return S.InvalidOperands(Loc, LHS, RHS); 12220 12221 // Check for comparisons of floating point operands using != and ==. 12222 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 12223 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12224 12225 // The result of comparisons is 'bool' in C++, 'int' in C. 12226 return S.Context.getLogicalOperationType(); 12227 } 12228 12229 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 12230 if (!NullE.get()->getType()->isAnyPointerType()) 12231 return; 12232 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 12233 if (!E.get()->getType()->isAnyPointerType() && 12234 E.get()->isNullPointerConstant(Context, 12235 Expr::NPC_ValueDependentIsNotNull) == 12236 Expr::NPCK_ZeroExpression) { 12237 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 12238 if (CL->getValue() == 0) 12239 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12240 << NullValue 12241 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12242 NullValue ? "NULL" : "(void *)0"); 12243 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 12244 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 12245 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 12246 if (T == Context.CharTy) 12247 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12248 << NullValue 12249 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12250 NullValue ? "NULL" : "(void *)0"); 12251 } 12252 } 12253 } 12254 12255 // C99 6.5.8, C++ [expr.rel] 12256 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 12257 SourceLocation Loc, 12258 BinaryOperatorKind Opc) { 12259 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 12260 bool IsThreeWay = Opc == BO_Cmp; 12261 bool IsOrdered = IsRelational || IsThreeWay; 12262 auto IsAnyPointerType = [](ExprResult E) { 12263 QualType Ty = E.get()->getType(); 12264 return Ty->isPointerType() || Ty->isMemberPointerType(); 12265 }; 12266 12267 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 12268 // type, array-to-pointer, ..., conversions are performed on both operands to 12269 // bring them to their composite type. 12270 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 12271 // any type-related checks. 12272 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 12273 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12274 if (LHS.isInvalid()) 12275 return QualType(); 12276 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12277 if (RHS.isInvalid()) 12278 return QualType(); 12279 } else { 12280 LHS = DefaultLvalueConversion(LHS.get()); 12281 if (LHS.isInvalid()) 12282 return QualType(); 12283 RHS = DefaultLvalueConversion(RHS.get()); 12284 if (RHS.isInvalid()) 12285 return QualType(); 12286 } 12287 12288 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 12289 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 12290 CheckPtrComparisonWithNullChar(LHS, RHS); 12291 CheckPtrComparisonWithNullChar(RHS, LHS); 12292 } 12293 12294 // Handle vector comparisons separately. 12295 if (LHS.get()->getType()->isVectorType() || 12296 RHS.get()->getType()->isVectorType()) 12297 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 12298 12299 if (LHS.get()->getType()->isVLSTBuiltinType() || 12300 RHS.get()->getType()->isVLSTBuiltinType()) 12301 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc); 12302 12303 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12304 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12305 12306 QualType LHSType = LHS.get()->getType(); 12307 QualType RHSType = RHS.get()->getType(); 12308 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 12309 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 12310 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 12311 12312 const Expr::NullPointerConstantKind LHSNullKind = 12313 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12314 const Expr::NullPointerConstantKind RHSNullKind = 12315 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12316 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 12317 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 12318 12319 auto computeResultTy = [&]() { 12320 if (Opc != BO_Cmp) 12321 return Context.getLogicalOperationType(); 12322 assert(getLangOpts().CPlusPlus); 12323 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 12324 12325 QualType CompositeTy = LHS.get()->getType(); 12326 assert(!CompositeTy->isReferenceType()); 12327 12328 Optional<ComparisonCategoryType> CCT = 12329 getComparisonCategoryForBuiltinCmp(CompositeTy); 12330 if (!CCT) 12331 return InvalidOperands(Loc, LHS, RHS); 12332 12333 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 12334 // P0946R0: Comparisons between a null pointer constant and an object 12335 // pointer result in std::strong_equality, which is ill-formed under 12336 // P1959R0. 12337 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 12338 << (LHSIsNull ? LHS.get()->getSourceRange() 12339 : RHS.get()->getSourceRange()); 12340 return QualType(); 12341 } 12342 12343 return CheckComparisonCategoryType( 12344 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 12345 }; 12346 12347 if (!IsOrdered && LHSIsNull != RHSIsNull) { 12348 bool IsEquality = Opc == BO_EQ; 12349 if (RHSIsNull) 12350 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 12351 RHS.get()->getSourceRange()); 12352 else 12353 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 12354 LHS.get()->getSourceRange()); 12355 } 12356 12357 if (IsOrdered && LHSType->isFunctionPointerType() && 12358 RHSType->isFunctionPointerType()) { 12359 // Valid unless a relational comparison of function pointers 12360 bool IsError = Opc == BO_Cmp; 12361 auto DiagID = 12362 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 12363 : getLangOpts().CPlusPlus 12364 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 12365 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 12366 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 12367 << RHS.get()->getSourceRange(); 12368 if (IsError) 12369 return QualType(); 12370 } 12371 12372 if ((LHSType->isIntegerType() && !LHSIsNull) || 12373 (RHSType->isIntegerType() && !RHSIsNull)) { 12374 // Skip normal pointer conversion checks in this case; we have better 12375 // diagnostics for this below. 12376 } else if (getLangOpts().CPlusPlus) { 12377 // Equality comparison of a function pointer to a void pointer is invalid, 12378 // but we allow it as an extension. 12379 // FIXME: If we really want to allow this, should it be part of composite 12380 // pointer type computation so it works in conditionals too? 12381 if (!IsOrdered && 12382 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 12383 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 12384 // This is a gcc extension compatibility comparison. 12385 // In a SFINAE context, we treat this as a hard error to maintain 12386 // conformance with the C++ standard. 12387 diagnoseFunctionPointerToVoidComparison( 12388 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 12389 12390 if (isSFINAEContext()) 12391 return QualType(); 12392 12393 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12394 return computeResultTy(); 12395 } 12396 12397 // C++ [expr.eq]p2: 12398 // If at least one operand is a pointer [...] bring them to their 12399 // composite pointer type. 12400 // C++ [expr.spaceship]p6 12401 // If at least one of the operands is of pointer type, [...] bring them 12402 // to their composite pointer type. 12403 // C++ [expr.rel]p2: 12404 // If both operands are pointers, [...] bring them to their composite 12405 // pointer type. 12406 // For <=>, the only valid non-pointer types are arrays and functions, and 12407 // we already decayed those, so this is really the same as the relational 12408 // comparison rule. 12409 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 12410 (IsOrdered ? 2 : 1) && 12411 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 12412 RHSType->isObjCObjectPointerType()))) { 12413 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12414 return QualType(); 12415 return computeResultTy(); 12416 } 12417 } else if (LHSType->isPointerType() && 12418 RHSType->isPointerType()) { // C99 6.5.8p2 12419 // All of the following pointer-related warnings are GCC extensions, except 12420 // when handling null pointer constants. 12421 QualType LCanPointeeTy = 12422 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12423 QualType RCanPointeeTy = 12424 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12425 12426 // C99 6.5.9p2 and C99 6.5.8p2 12427 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 12428 RCanPointeeTy.getUnqualifiedType())) { 12429 if (IsRelational) { 12430 // Pointers both need to point to complete or incomplete types 12431 if ((LCanPointeeTy->isIncompleteType() != 12432 RCanPointeeTy->isIncompleteType()) && 12433 !getLangOpts().C11) { 12434 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 12435 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 12436 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 12437 << RCanPointeeTy->isIncompleteType(); 12438 } 12439 } 12440 } else if (!IsRelational && 12441 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 12442 // Valid unless comparison between non-null pointer and function pointer 12443 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 12444 && !LHSIsNull && !RHSIsNull) 12445 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 12446 /*isError*/false); 12447 } else { 12448 // Invalid 12449 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 12450 } 12451 if (LCanPointeeTy != RCanPointeeTy) { 12452 // Treat NULL constant as a special case in OpenCL. 12453 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 12454 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 12455 Diag(Loc, 12456 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 12457 << LHSType << RHSType << 0 /* comparison */ 12458 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12459 } 12460 } 12461 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 12462 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12463 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12464 : CK_BitCast; 12465 if (LHSIsNull && !RHSIsNull) 12466 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12467 else 12468 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12469 } 12470 return computeResultTy(); 12471 } 12472 12473 if (getLangOpts().CPlusPlus) { 12474 // C++ [expr.eq]p4: 12475 // Two operands of type std::nullptr_t or one operand of type 12476 // std::nullptr_t and the other a null pointer constant compare equal. 12477 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12478 if (LHSType->isNullPtrType()) { 12479 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12480 return computeResultTy(); 12481 } 12482 if (RHSType->isNullPtrType()) { 12483 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12484 return computeResultTy(); 12485 } 12486 } 12487 12488 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12489 // These aren't covered by the composite pointer type rules. 12490 if (!IsOrdered && RHSType->isNullPtrType() && 12491 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12492 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12493 return computeResultTy(); 12494 } 12495 if (!IsOrdered && LHSType->isNullPtrType() && 12496 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12497 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12498 return computeResultTy(); 12499 } 12500 12501 if (IsRelational && 12502 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12503 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12504 // HACK: Relational comparison of nullptr_t against a pointer type is 12505 // invalid per DR583, but we allow it within std::less<> and friends, 12506 // since otherwise common uses of it break. 12507 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12508 // friends to have std::nullptr_t overload candidates. 12509 DeclContext *DC = CurContext; 12510 if (isa<FunctionDecl>(DC)) 12511 DC = DC->getParent(); 12512 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12513 if (CTSD->isInStdNamespace() && 12514 llvm::StringSwitch<bool>(CTSD->getName()) 12515 .Cases("less", "less_equal", "greater", "greater_equal", true) 12516 .Default(false)) { 12517 if (RHSType->isNullPtrType()) 12518 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12519 else 12520 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12521 return computeResultTy(); 12522 } 12523 } 12524 } 12525 12526 // C++ [expr.eq]p2: 12527 // If at least one operand is a pointer to member, [...] bring them to 12528 // their composite pointer type. 12529 if (!IsOrdered && 12530 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12531 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12532 return QualType(); 12533 else 12534 return computeResultTy(); 12535 } 12536 } 12537 12538 // Handle block pointer types. 12539 if (!IsOrdered && LHSType->isBlockPointerType() && 12540 RHSType->isBlockPointerType()) { 12541 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12542 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12543 12544 if (!LHSIsNull && !RHSIsNull && 12545 !Context.typesAreCompatible(lpointee, rpointee)) { 12546 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12547 << LHSType << RHSType << LHS.get()->getSourceRange() 12548 << RHS.get()->getSourceRange(); 12549 } 12550 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12551 return computeResultTy(); 12552 } 12553 12554 // Allow block pointers to be compared with null pointer constants. 12555 if (!IsOrdered 12556 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12557 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12558 if (!LHSIsNull && !RHSIsNull) { 12559 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12560 ->getPointeeType()->isVoidType()) 12561 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12562 ->getPointeeType()->isVoidType()))) 12563 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12564 << LHSType << RHSType << LHS.get()->getSourceRange() 12565 << RHS.get()->getSourceRange(); 12566 } 12567 if (LHSIsNull && !RHSIsNull) 12568 LHS = ImpCastExprToType(LHS.get(), RHSType, 12569 RHSType->isPointerType() ? CK_BitCast 12570 : CK_AnyPointerToBlockPointerCast); 12571 else 12572 RHS = ImpCastExprToType(RHS.get(), LHSType, 12573 LHSType->isPointerType() ? CK_BitCast 12574 : CK_AnyPointerToBlockPointerCast); 12575 return computeResultTy(); 12576 } 12577 12578 if (LHSType->isObjCObjectPointerType() || 12579 RHSType->isObjCObjectPointerType()) { 12580 const PointerType *LPT = LHSType->getAs<PointerType>(); 12581 const PointerType *RPT = RHSType->getAs<PointerType>(); 12582 if (LPT || RPT) { 12583 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12584 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12585 12586 if (!LPtrToVoid && !RPtrToVoid && 12587 !Context.typesAreCompatible(LHSType, RHSType)) { 12588 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12589 /*isError*/false); 12590 } 12591 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12592 // the RHS, but we have test coverage for this behavior. 12593 // FIXME: Consider using convertPointersToCompositeType in C++. 12594 if (LHSIsNull && !RHSIsNull) { 12595 Expr *E = LHS.get(); 12596 if (getLangOpts().ObjCAutoRefCount) 12597 CheckObjCConversion(SourceRange(), RHSType, E, 12598 CCK_ImplicitConversion); 12599 LHS = ImpCastExprToType(E, RHSType, 12600 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12601 } 12602 else { 12603 Expr *E = RHS.get(); 12604 if (getLangOpts().ObjCAutoRefCount) 12605 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12606 /*Diagnose=*/true, 12607 /*DiagnoseCFAudited=*/false, Opc); 12608 RHS = ImpCastExprToType(E, LHSType, 12609 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12610 } 12611 return computeResultTy(); 12612 } 12613 if (LHSType->isObjCObjectPointerType() && 12614 RHSType->isObjCObjectPointerType()) { 12615 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12616 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12617 /*isError*/false); 12618 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12619 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12620 12621 if (LHSIsNull && !RHSIsNull) 12622 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12623 else 12624 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12625 return computeResultTy(); 12626 } 12627 12628 if (!IsOrdered && LHSType->isBlockPointerType() && 12629 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12630 LHS = ImpCastExprToType(LHS.get(), RHSType, 12631 CK_BlockPointerToObjCPointerCast); 12632 return computeResultTy(); 12633 } else if (!IsOrdered && 12634 LHSType->isBlockCompatibleObjCPointerType(Context) && 12635 RHSType->isBlockPointerType()) { 12636 RHS = ImpCastExprToType(RHS.get(), LHSType, 12637 CK_BlockPointerToObjCPointerCast); 12638 return computeResultTy(); 12639 } 12640 } 12641 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12642 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12643 unsigned DiagID = 0; 12644 bool isError = false; 12645 if (LangOpts.DebuggerSupport) { 12646 // Under a debugger, allow the comparison of pointers to integers, 12647 // since users tend to want to compare addresses. 12648 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12649 (RHSIsNull && RHSType->isIntegerType())) { 12650 if (IsOrdered) { 12651 isError = getLangOpts().CPlusPlus; 12652 DiagID = 12653 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12654 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12655 } 12656 } else if (getLangOpts().CPlusPlus) { 12657 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12658 isError = true; 12659 } else if (IsOrdered) 12660 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12661 else 12662 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12663 12664 if (DiagID) { 12665 Diag(Loc, DiagID) 12666 << LHSType << RHSType << LHS.get()->getSourceRange() 12667 << RHS.get()->getSourceRange(); 12668 if (isError) 12669 return QualType(); 12670 } 12671 12672 if (LHSType->isIntegerType()) 12673 LHS = ImpCastExprToType(LHS.get(), RHSType, 12674 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12675 else 12676 RHS = ImpCastExprToType(RHS.get(), LHSType, 12677 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12678 return computeResultTy(); 12679 } 12680 12681 // Handle block pointers. 12682 if (!IsOrdered && RHSIsNull 12683 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12684 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12685 return computeResultTy(); 12686 } 12687 if (!IsOrdered && LHSIsNull 12688 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12689 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12690 return computeResultTy(); 12691 } 12692 12693 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12694 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12695 return computeResultTy(); 12696 } 12697 12698 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12699 return computeResultTy(); 12700 } 12701 12702 if (LHSIsNull && RHSType->isQueueT()) { 12703 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12704 return computeResultTy(); 12705 } 12706 12707 if (LHSType->isQueueT() && RHSIsNull) { 12708 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12709 return computeResultTy(); 12710 } 12711 } 12712 12713 return InvalidOperands(Loc, LHS, RHS); 12714 } 12715 12716 // Return a signed ext_vector_type that is of identical size and number of 12717 // elements. For floating point vectors, return an integer type of identical 12718 // size and number of elements. In the non ext_vector_type case, search from 12719 // the largest type to the smallest type to avoid cases where long long == long, 12720 // where long gets picked over long long. 12721 QualType Sema::GetSignedVectorType(QualType V) { 12722 const VectorType *VTy = V->castAs<VectorType>(); 12723 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12724 12725 if (isa<ExtVectorType>(VTy)) { 12726 if (VTy->isExtVectorBoolType()) 12727 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements()); 12728 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12729 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12730 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12731 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12732 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12733 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12734 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12735 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); 12736 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12737 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12738 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12739 "Unhandled vector element size in vector compare"); 12740 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12741 } 12742 12743 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12744 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), 12745 VectorType::GenericVector); 12746 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12747 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12748 VectorType::GenericVector); 12749 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12750 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12751 VectorType::GenericVector); 12752 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12753 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12754 VectorType::GenericVector); 12755 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12756 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12757 VectorType::GenericVector); 12758 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12759 "Unhandled vector element size in vector compare"); 12760 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12761 VectorType::GenericVector); 12762 } 12763 12764 QualType Sema::GetSignedSizelessVectorType(QualType V) { 12765 const BuiltinType *VTy = V->castAs<BuiltinType>(); 12766 assert(VTy->isSizelessBuiltinType() && "expected sizeless type"); 12767 12768 const QualType ETy = V->getSveEltType(Context); 12769 const auto TypeSize = Context.getTypeSize(ETy); 12770 12771 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true); 12772 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC; 12773 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue()); 12774 } 12775 12776 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12777 /// operates on extended vector types. Instead of producing an IntTy result, 12778 /// like a scalar comparison, a vector comparison produces a vector of integer 12779 /// types. 12780 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12781 SourceLocation Loc, 12782 BinaryOperatorKind Opc) { 12783 if (Opc == BO_Cmp) { 12784 Diag(Loc, diag::err_three_way_vector_comparison); 12785 return QualType(); 12786 } 12787 12788 // Check to make sure we're operating on vectors of the same type and width, 12789 // Allowing one side to be a scalar of element type. 12790 QualType vType = 12791 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false, 12792 /*AllowBothBool*/ true, 12793 /*AllowBoolConversions*/ getLangOpts().ZVector, 12794 /*AllowBooleanOperation*/ true, 12795 /*ReportInvalid*/ true); 12796 if (vType.isNull()) 12797 return vType; 12798 12799 QualType LHSType = LHS.get()->getType(); 12800 12801 // Determine the return type of a vector compare. By default clang will return 12802 // a scalar for all vector compares except vector bool and vector pixel. 12803 // With the gcc compiler we will always return a vector type and with the xl 12804 // compiler we will always return a scalar type. This switch allows choosing 12805 // which behavior is prefered. 12806 if (getLangOpts().AltiVec) { 12807 switch (getLangOpts().getAltivecSrcCompat()) { 12808 case LangOptions::AltivecSrcCompatKind::Mixed: 12809 // If AltiVec, the comparison results in a numeric type, i.e. 12810 // bool for C++, int for C 12811 if (vType->castAs<VectorType>()->getVectorKind() == 12812 VectorType::AltiVecVector) 12813 return Context.getLogicalOperationType(); 12814 else 12815 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12816 break; 12817 case LangOptions::AltivecSrcCompatKind::GCC: 12818 // For GCC we always return the vector type. 12819 break; 12820 case LangOptions::AltivecSrcCompatKind::XL: 12821 return Context.getLogicalOperationType(); 12822 break; 12823 } 12824 } 12825 12826 // For non-floating point types, check for self-comparisons of the form 12827 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12828 // often indicate logic errors in the program. 12829 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12830 12831 // Check for comparisons of floating point operands using != and ==. 12832 if (BinaryOperator::isEqualityOp(Opc) && 12833 LHSType->hasFloatingRepresentation()) { 12834 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12835 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12836 } 12837 12838 // Return a signed type for the vector. 12839 return GetSignedVectorType(vType); 12840 } 12841 12842 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS, 12843 ExprResult &RHS, 12844 SourceLocation Loc, 12845 BinaryOperatorKind Opc) { 12846 if (Opc == BO_Cmp) { 12847 Diag(Loc, diag::err_three_way_vector_comparison); 12848 return QualType(); 12849 } 12850 12851 // Check to make sure we're operating on vectors of the same type and width, 12852 // Allowing one side to be a scalar of element type. 12853 QualType vType = CheckSizelessVectorOperands( 12854 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison); 12855 12856 if (vType.isNull()) 12857 return vType; 12858 12859 QualType LHSType = LHS.get()->getType(); 12860 12861 // For non-floating point types, check for self-comparisons of the form 12862 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12863 // often indicate logic errors in the program. 12864 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12865 12866 // Check for comparisons of floating point operands using != and ==. 12867 if (BinaryOperator::isEqualityOp(Opc) && 12868 LHSType->hasFloatingRepresentation()) { 12869 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12870 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12871 } 12872 12873 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 12874 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>(); 12875 12876 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() && 12877 RHSBuiltinTy->isSVEBool()) 12878 return LHSType; 12879 12880 // Return a signed type for the vector. 12881 return GetSignedSizelessVectorType(vType); 12882 } 12883 12884 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12885 const ExprResult &XorRHS, 12886 const SourceLocation Loc) { 12887 // Do not diagnose macros. 12888 if (Loc.isMacroID()) 12889 return; 12890 12891 // Do not diagnose if both LHS and RHS are macros. 12892 if (XorLHS.get()->getExprLoc().isMacroID() && 12893 XorRHS.get()->getExprLoc().isMacroID()) 12894 return; 12895 12896 bool Negative = false; 12897 bool ExplicitPlus = false; 12898 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12899 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12900 12901 if (!LHSInt) 12902 return; 12903 if (!RHSInt) { 12904 // Check negative literals. 12905 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12906 UnaryOperatorKind Opc = UO->getOpcode(); 12907 if (Opc != UO_Minus && Opc != UO_Plus) 12908 return; 12909 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12910 if (!RHSInt) 12911 return; 12912 Negative = (Opc == UO_Minus); 12913 ExplicitPlus = !Negative; 12914 } else { 12915 return; 12916 } 12917 } 12918 12919 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12920 llvm::APInt RightSideValue = RHSInt->getValue(); 12921 if (LeftSideValue != 2 && LeftSideValue != 10) 12922 return; 12923 12924 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12925 return; 12926 12927 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12928 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12929 llvm::StringRef ExprStr = 12930 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12931 12932 CharSourceRange XorRange = 12933 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12934 llvm::StringRef XorStr = 12935 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12936 // Do not diagnose if xor keyword/macro is used. 12937 if (XorStr == "xor") 12938 return; 12939 12940 std::string LHSStr = std::string(Lexer::getSourceText( 12941 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12942 S.getSourceManager(), S.getLangOpts())); 12943 std::string RHSStr = std::string(Lexer::getSourceText( 12944 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12945 S.getSourceManager(), S.getLangOpts())); 12946 12947 if (Negative) { 12948 RightSideValue = -RightSideValue; 12949 RHSStr = "-" + RHSStr; 12950 } else if (ExplicitPlus) { 12951 RHSStr = "+" + RHSStr; 12952 } 12953 12954 StringRef LHSStrRef = LHSStr; 12955 StringRef RHSStrRef = RHSStr; 12956 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12957 // literals. 12958 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12959 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12960 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12961 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12962 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12963 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12964 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12965 return; 12966 12967 bool SuggestXor = 12968 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12969 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12970 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12971 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12972 std::string SuggestedExpr = "1 << " + RHSStr; 12973 bool Overflow = false; 12974 llvm::APInt One = (LeftSideValue - 1); 12975 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12976 if (Overflow) { 12977 if (RightSideIntValue < 64) 12978 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12979 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12980 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12981 else if (RightSideIntValue == 64) 12982 S.Diag(Loc, diag::warn_xor_used_as_pow) 12983 << ExprStr << toString(XorValue, 10, true); 12984 else 12985 return; 12986 } else { 12987 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12988 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12989 << toString(PowValue, 10, true) 12990 << FixItHint::CreateReplacement( 12991 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12992 } 12993 12994 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12995 << ("0x2 ^ " + RHSStr) << SuggestXor; 12996 } else if (LeftSideValue == 10) { 12997 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12998 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12999 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 13000 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 13001 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 13002 << ("0xA ^ " + RHSStr) << SuggestXor; 13003 } 13004 } 13005 13006 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13007 SourceLocation Loc) { 13008 // Ensure that either both operands are of the same vector type, or 13009 // one operand is of a vector type and the other is of its element type. 13010 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 13011 /*AllowBothBool*/ true, 13012 /*AllowBoolConversions*/ false, 13013 /*AllowBooleanOperation*/ false, 13014 /*ReportInvalid*/ false); 13015 if (vType.isNull()) 13016 return InvalidOperands(Loc, LHS, RHS); 13017 if (getLangOpts().OpenCL && 13018 getLangOpts().getOpenCLCompatibleVersion() < 120 && 13019 vType->hasFloatingRepresentation()) 13020 return InvalidOperands(Loc, LHS, RHS); 13021 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 13022 // usage of the logical operators && and || with vectors in C. This 13023 // check could be notionally dropped. 13024 if (!getLangOpts().CPlusPlus && 13025 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 13026 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 13027 13028 return GetSignedVectorType(LHS.get()->getType()); 13029 } 13030 13031 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 13032 SourceLocation Loc, 13033 bool IsCompAssign) { 13034 if (!IsCompAssign) { 13035 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13036 if (LHS.isInvalid()) 13037 return QualType(); 13038 } 13039 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13040 if (RHS.isInvalid()) 13041 return QualType(); 13042 13043 // For conversion purposes, we ignore any qualifiers. 13044 // For example, "const float" and "float" are equivalent. 13045 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 13046 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 13047 13048 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 13049 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 13050 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13051 13052 if (Context.hasSameType(LHSType, RHSType)) 13053 return LHSType; 13054 13055 // Type conversion may change LHS/RHS. Keep copies to the original results, in 13056 // case we have to return InvalidOperands. 13057 ExprResult OriginalLHS = LHS; 13058 ExprResult OriginalRHS = RHS; 13059 if (LHSMatType && !RHSMatType) { 13060 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 13061 if (!RHS.isInvalid()) 13062 return LHSType; 13063 13064 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13065 } 13066 13067 if (!LHSMatType && RHSMatType) { 13068 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 13069 if (!LHS.isInvalid()) 13070 return RHSType; 13071 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13072 } 13073 13074 return InvalidOperands(Loc, LHS, RHS); 13075 } 13076 13077 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 13078 SourceLocation Loc, 13079 bool IsCompAssign) { 13080 if (!IsCompAssign) { 13081 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13082 if (LHS.isInvalid()) 13083 return QualType(); 13084 } 13085 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13086 if (RHS.isInvalid()) 13087 return QualType(); 13088 13089 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 13090 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 13091 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13092 13093 if (LHSMatType && RHSMatType) { 13094 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 13095 return InvalidOperands(Loc, LHS, RHS); 13096 13097 if (!Context.hasSameType(LHSMatType->getElementType(), 13098 RHSMatType->getElementType())) 13099 return InvalidOperands(Loc, LHS, RHS); 13100 13101 return Context.getConstantMatrixType(LHSMatType->getElementType(), 13102 LHSMatType->getNumRows(), 13103 RHSMatType->getNumColumns()); 13104 } 13105 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 13106 } 13107 13108 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { 13109 switch (Opc) { 13110 default: 13111 return false; 13112 case BO_And: 13113 case BO_AndAssign: 13114 case BO_Or: 13115 case BO_OrAssign: 13116 case BO_Xor: 13117 case BO_XorAssign: 13118 return true; 13119 } 13120 } 13121 13122 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 13123 SourceLocation Loc, 13124 BinaryOperatorKind Opc) { 13125 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 13126 13127 bool IsCompAssign = 13128 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 13129 13130 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); 13131 13132 if (LHS.get()->getType()->isVectorType() || 13133 RHS.get()->getType()->isVectorType()) { 13134 if (LHS.get()->getType()->hasIntegerRepresentation() && 13135 RHS.get()->getType()->hasIntegerRepresentation()) 13136 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 13137 /*AllowBothBool*/ true, 13138 /*AllowBoolConversions*/ getLangOpts().ZVector, 13139 /*AllowBooleanOperation*/ LegalBoolVecOperator, 13140 /*ReportInvalid*/ true); 13141 return InvalidOperands(Loc, LHS, RHS); 13142 } 13143 13144 if (LHS.get()->getType()->isVLSTBuiltinType() || 13145 RHS.get()->getType()->isVLSTBuiltinType()) { 13146 if (LHS.get()->getType()->hasIntegerRepresentation() && 13147 RHS.get()->getType()->hasIntegerRepresentation()) 13148 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13149 ACK_BitwiseOp); 13150 return InvalidOperands(Loc, LHS, RHS); 13151 } 13152 13153 if (LHS.get()->getType()->isVLSTBuiltinType() || 13154 RHS.get()->getType()->isVLSTBuiltinType()) { 13155 if (LHS.get()->getType()->hasIntegerRepresentation() && 13156 RHS.get()->getType()->hasIntegerRepresentation()) 13157 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13158 ACK_BitwiseOp); 13159 return InvalidOperands(Loc, LHS, RHS); 13160 } 13161 13162 if (Opc == BO_And) 13163 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 13164 13165 if (LHS.get()->getType()->hasFloatingRepresentation() || 13166 RHS.get()->getType()->hasFloatingRepresentation()) 13167 return InvalidOperands(Loc, LHS, RHS); 13168 13169 ExprResult LHSResult = LHS, RHSResult = RHS; 13170 QualType compType = UsualArithmeticConversions( 13171 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 13172 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 13173 return QualType(); 13174 LHS = LHSResult.get(); 13175 RHS = RHSResult.get(); 13176 13177 if (Opc == BO_Xor) 13178 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 13179 13180 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 13181 return compType; 13182 return InvalidOperands(Loc, LHS, RHS); 13183 } 13184 13185 // C99 6.5.[13,14] 13186 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13187 SourceLocation Loc, 13188 BinaryOperatorKind Opc) { 13189 // Check vector operands differently. 13190 if (LHS.get()->getType()->isVectorType() || 13191 RHS.get()->getType()->isVectorType()) 13192 return CheckVectorLogicalOperands(LHS, RHS, Loc); 13193 13194 bool EnumConstantInBoolContext = false; 13195 for (const ExprResult &HS : {LHS, RHS}) { 13196 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 13197 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 13198 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 13199 EnumConstantInBoolContext = true; 13200 } 13201 } 13202 13203 if (EnumConstantInBoolContext) 13204 Diag(Loc, diag::warn_enum_constant_in_bool_context); 13205 13206 // Diagnose cases where the user write a logical and/or but probably meant a 13207 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 13208 // is a constant. 13209 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 13210 !LHS.get()->getType()->isBooleanType() && 13211 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 13212 // Don't warn in macros or template instantiations. 13213 !Loc.isMacroID() && !inTemplateInstantiation()) { 13214 // If the RHS can be constant folded, and if it constant folds to something 13215 // that isn't 0 or 1 (which indicate a potential logical operation that 13216 // happened to fold to true/false) then warn. 13217 // Parens on the RHS are ignored. 13218 Expr::EvalResult EVResult; 13219 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 13220 llvm::APSInt Result = EVResult.Val.getInt(); 13221 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 13222 !RHS.get()->getExprLoc().isMacroID()) || 13223 (Result != 0 && Result != 1)) { 13224 Diag(Loc, diag::warn_logical_instead_of_bitwise) 13225 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||"); 13226 // Suggest replacing the logical operator with the bitwise version 13227 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 13228 << (Opc == BO_LAnd ? "&" : "|") 13229 << FixItHint::CreateReplacement( 13230 SourceRange(Loc, getLocForEndOfToken(Loc)), 13231 Opc == BO_LAnd ? "&" : "|"); 13232 if (Opc == BO_LAnd) 13233 // Suggest replacing "Foo() && kNonZero" with "Foo()" 13234 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 13235 << FixItHint::CreateRemoval( 13236 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 13237 RHS.get()->getEndLoc())); 13238 } 13239 } 13240 } 13241 13242 if (!Context.getLangOpts().CPlusPlus) { 13243 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 13244 // not operate on the built-in scalar and vector float types. 13245 if (Context.getLangOpts().OpenCL && 13246 Context.getLangOpts().OpenCLVersion < 120) { 13247 if (LHS.get()->getType()->isFloatingType() || 13248 RHS.get()->getType()->isFloatingType()) 13249 return InvalidOperands(Loc, LHS, RHS); 13250 } 13251 13252 LHS = UsualUnaryConversions(LHS.get()); 13253 if (LHS.isInvalid()) 13254 return QualType(); 13255 13256 RHS = UsualUnaryConversions(RHS.get()); 13257 if (RHS.isInvalid()) 13258 return QualType(); 13259 13260 if (!LHS.get()->getType()->isScalarType() || 13261 !RHS.get()->getType()->isScalarType()) 13262 return InvalidOperands(Loc, LHS, RHS); 13263 13264 return Context.IntTy; 13265 } 13266 13267 // The following is safe because we only use this method for 13268 // non-overloadable operands. 13269 13270 // C++ [expr.log.and]p1 13271 // C++ [expr.log.or]p1 13272 // The operands are both contextually converted to type bool. 13273 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 13274 if (LHSRes.isInvalid()) 13275 return InvalidOperands(Loc, LHS, RHS); 13276 LHS = LHSRes; 13277 13278 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 13279 if (RHSRes.isInvalid()) 13280 return InvalidOperands(Loc, LHS, RHS); 13281 RHS = RHSRes; 13282 13283 // C++ [expr.log.and]p2 13284 // C++ [expr.log.or]p2 13285 // The result is a bool. 13286 return Context.BoolTy; 13287 } 13288 13289 static bool IsReadonlyMessage(Expr *E, Sema &S) { 13290 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13291 if (!ME) return false; 13292 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 13293 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 13294 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 13295 if (!Base) return false; 13296 return Base->getMethodDecl() != nullptr; 13297 } 13298 13299 /// Is the given expression (which must be 'const') a reference to a 13300 /// variable which was originally non-const, but which has become 13301 /// 'const' due to being captured within a block? 13302 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 13303 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 13304 assert(E->isLValue() && E->getType().isConstQualified()); 13305 E = E->IgnoreParens(); 13306 13307 // Must be a reference to a declaration from an enclosing scope. 13308 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 13309 if (!DRE) return NCCK_None; 13310 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 13311 13312 // The declaration must be a variable which is not declared 'const'. 13313 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 13314 if (!var) return NCCK_None; 13315 if (var->getType().isConstQualified()) return NCCK_None; 13316 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 13317 13318 // Decide whether the first capture was for a block or a lambda. 13319 DeclContext *DC = S.CurContext, *Prev = nullptr; 13320 // Decide whether the first capture was for a block or a lambda. 13321 while (DC) { 13322 // For init-capture, it is possible that the variable belongs to the 13323 // template pattern of the current context. 13324 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 13325 if (var->isInitCapture() && 13326 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 13327 break; 13328 if (DC == var->getDeclContext()) 13329 break; 13330 Prev = DC; 13331 DC = DC->getParent(); 13332 } 13333 // Unless we have an init-capture, we've gone one step too far. 13334 if (!var->isInitCapture()) 13335 DC = Prev; 13336 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 13337 } 13338 13339 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 13340 Ty = Ty.getNonReferenceType(); 13341 if (IsDereference && Ty->isPointerType()) 13342 Ty = Ty->getPointeeType(); 13343 return !Ty.isConstQualified(); 13344 } 13345 13346 // Update err_typecheck_assign_const and note_typecheck_assign_const 13347 // when this enum is changed. 13348 enum { 13349 ConstFunction, 13350 ConstVariable, 13351 ConstMember, 13352 ConstMethod, 13353 NestedConstMember, 13354 ConstUnknown, // Keep as last element 13355 }; 13356 13357 /// Emit the "read-only variable not assignable" error and print notes to give 13358 /// more information about why the variable is not assignable, such as pointing 13359 /// to the declaration of a const variable, showing that a method is const, or 13360 /// that the function is returning a const reference. 13361 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 13362 SourceLocation Loc) { 13363 SourceRange ExprRange = E->getSourceRange(); 13364 13365 // Only emit one error on the first const found. All other consts will emit 13366 // a note to the error. 13367 bool DiagnosticEmitted = false; 13368 13369 // Track if the current expression is the result of a dereference, and if the 13370 // next checked expression is the result of a dereference. 13371 bool IsDereference = false; 13372 bool NextIsDereference = false; 13373 13374 // Loop to process MemberExpr chains. 13375 while (true) { 13376 IsDereference = NextIsDereference; 13377 13378 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 13379 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13380 NextIsDereference = ME->isArrow(); 13381 const ValueDecl *VD = ME->getMemberDecl(); 13382 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 13383 // Mutable fields can be modified even if the class is const. 13384 if (Field->isMutable()) { 13385 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 13386 break; 13387 } 13388 13389 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 13390 if (!DiagnosticEmitted) { 13391 S.Diag(Loc, diag::err_typecheck_assign_const) 13392 << ExprRange << ConstMember << false /*static*/ << Field 13393 << Field->getType(); 13394 DiagnosticEmitted = true; 13395 } 13396 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13397 << ConstMember << false /*static*/ << Field << Field->getType() 13398 << Field->getSourceRange(); 13399 } 13400 E = ME->getBase(); 13401 continue; 13402 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 13403 if (VDecl->getType().isConstQualified()) { 13404 if (!DiagnosticEmitted) { 13405 S.Diag(Loc, diag::err_typecheck_assign_const) 13406 << ExprRange << ConstMember << true /*static*/ << VDecl 13407 << VDecl->getType(); 13408 DiagnosticEmitted = true; 13409 } 13410 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13411 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 13412 << VDecl->getSourceRange(); 13413 } 13414 // Static fields do not inherit constness from parents. 13415 break; 13416 } 13417 break; // End MemberExpr 13418 } else if (const ArraySubscriptExpr *ASE = 13419 dyn_cast<ArraySubscriptExpr>(E)) { 13420 E = ASE->getBase()->IgnoreParenImpCasts(); 13421 continue; 13422 } else if (const ExtVectorElementExpr *EVE = 13423 dyn_cast<ExtVectorElementExpr>(E)) { 13424 E = EVE->getBase()->IgnoreParenImpCasts(); 13425 continue; 13426 } 13427 break; 13428 } 13429 13430 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 13431 // Function calls 13432 const FunctionDecl *FD = CE->getDirectCallee(); 13433 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 13434 if (!DiagnosticEmitted) { 13435 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13436 << ConstFunction << FD; 13437 DiagnosticEmitted = true; 13438 } 13439 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 13440 diag::note_typecheck_assign_const) 13441 << ConstFunction << FD << FD->getReturnType() 13442 << FD->getReturnTypeSourceRange(); 13443 } 13444 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13445 // Point to variable declaration. 13446 if (const ValueDecl *VD = DRE->getDecl()) { 13447 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 13448 if (!DiagnosticEmitted) { 13449 S.Diag(Loc, diag::err_typecheck_assign_const) 13450 << ExprRange << ConstVariable << VD << VD->getType(); 13451 DiagnosticEmitted = true; 13452 } 13453 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13454 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 13455 } 13456 } 13457 } else if (isa<CXXThisExpr>(E)) { 13458 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 13459 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 13460 if (MD->isConst()) { 13461 if (!DiagnosticEmitted) { 13462 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13463 << ConstMethod << MD; 13464 DiagnosticEmitted = true; 13465 } 13466 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 13467 << ConstMethod << MD << MD->getSourceRange(); 13468 } 13469 } 13470 } 13471 } 13472 13473 if (DiagnosticEmitted) 13474 return; 13475 13476 // Can't determine a more specific message, so display the generic error. 13477 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 13478 } 13479 13480 enum OriginalExprKind { 13481 OEK_Variable, 13482 OEK_Member, 13483 OEK_LValue 13484 }; 13485 13486 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 13487 const RecordType *Ty, 13488 SourceLocation Loc, SourceRange Range, 13489 OriginalExprKind OEK, 13490 bool &DiagnosticEmitted) { 13491 std::vector<const RecordType *> RecordTypeList; 13492 RecordTypeList.push_back(Ty); 13493 unsigned NextToCheckIndex = 0; 13494 // We walk the record hierarchy breadth-first to ensure that we print 13495 // diagnostics in field nesting order. 13496 while (RecordTypeList.size() > NextToCheckIndex) { 13497 bool IsNested = NextToCheckIndex > 0; 13498 for (const FieldDecl *Field : 13499 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 13500 // First, check every field for constness. 13501 QualType FieldTy = Field->getType(); 13502 if (FieldTy.isConstQualified()) { 13503 if (!DiagnosticEmitted) { 13504 S.Diag(Loc, diag::err_typecheck_assign_const) 13505 << Range << NestedConstMember << OEK << VD 13506 << IsNested << Field; 13507 DiagnosticEmitted = true; 13508 } 13509 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 13510 << NestedConstMember << IsNested << Field 13511 << FieldTy << Field->getSourceRange(); 13512 } 13513 13514 // Then we append it to the list to check next in order. 13515 FieldTy = FieldTy.getCanonicalType(); 13516 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 13517 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 13518 RecordTypeList.push_back(FieldRecTy); 13519 } 13520 } 13521 ++NextToCheckIndex; 13522 } 13523 } 13524 13525 /// Emit an error for the case where a record we are trying to assign to has a 13526 /// const-qualified field somewhere in its hierarchy. 13527 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 13528 SourceLocation Loc) { 13529 QualType Ty = E->getType(); 13530 assert(Ty->isRecordType() && "lvalue was not record?"); 13531 SourceRange Range = E->getSourceRange(); 13532 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 13533 bool DiagEmitted = false; 13534 13535 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 13536 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 13537 Range, OEK_Member, DiagEmitted); 13538 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13539 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 13540 Range, OEK_Variable, DiagEmitted); 13541 else 13542 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 13543 Range, OEK_LValue, DiagEmitted); 13544 if (!DiagEmitted) 13545 DiagnoseConstAssignment(S, E, Loc); 13546 } 13547 13548 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 13549 /// emit an error and return true. If so, return false. 13550 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 13551 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 13552 13553 S.CheckShadowingDeclModification(E, Loc); 13554 13555 SourceLocation OrigLoc = Loc; 13556 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 13557 &Loc); 13558 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 13559 IsLV = Expr::MLV_InvalidMessageExpression; 13560 if (IsLV == Expr::MLV_Valid) 13561 return false; 13562 13563 unsigned DiagID = 0; 13564 bool NeedType = false; 13565 switch (IsLV) { // C99 6.5.16p2 13566 case Expr::MLV_ConstQualified: 13567 // Use a specialized diagnostic when we're assigning to an object 13568 // from an enclosing function or block. 13569 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13570 if (NCCK == NCCK_Block) 13571 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13572 else 13573 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13574 break; 13575 } 13576 13577 // In ARC, use some specialized diagnostics for occasions where we 13578 // infer 'const'. These are always pseudo-strong variables. 13579 if (S.getLangOpts().ObjCAutoRefCount) { 13580 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13581 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13582 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13583 13584 // Use the normal diagnostic if it's pseudo-__strong but the 13585 // user actually wrote 'const'. 13586 if (var->isARCPseudoStrong() && 13587 (!var->getTypeSourceInfo() || 13588 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13589 // There are three pseudo-strong cases: 13590 // - self 13591 ObjCMethodDecl *method = S.getCurMethodDecl(); 13592 if (method && var == method->getSelfDecl()) { 13593 DiagID = method->isClassMethod() 13594 ? diag::err_typecheck_arc_assign_self_class_method 13595 : diag::err_typecheck_arc_assign_self; 13596 13597 // - Objective-C externally_retained attribute. 13598 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13599 isa<ParmVarDecl>(var)) { 13600 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13601 13602 // - fast enumeration variables 13603 } else { 13604 DiagID = diag::err_typecheck_arr_assign_enumeration; 13605 } 13606 13607 SourceRange Assign; 13608 if (Loc != OrigLoc) 13609 Assign = SourceRange(OrigLoc, OrigLoc); 13610 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13611 // We need to preserve the AST regardless, so migration tool 13612 // can do its job. 13613 return false; 13614 } 13615 } 13616 } 13617 13618 // If none of the special cases above are triggered, then this is a 13619 // simple const assignment. 13620 if (DiagID == 0) { 13621 DiagnoseConstAssignment(S, E, Loc); 13622 return true; 13623 } 13624 13625 break; 13626 case Expr::MLV_ConstAddrSpace: 13627 DiagnoseConstAssignment(S, E, Loc); 13628 return true; 13629 case Expr::MLV_ConstQualifiedField: 13630 DiagnoseRecursiveConstFields(S, E, Loc); 13631 return true; 13632 case Expr::MLV_ArrayType: 13633 case Expr::MLV_ArrayTemporary: 13634 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13635 NeedType = true; 13636 break; 13637 case Expr::MLV_NotObjectType: 13638 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13639 NeedType = true; 13640 break; 13641 case Expr::MLV_LValueCast: 13642 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13643 break; 13644 case Expr::MLV_Valid: 13645 llvm_unreachable("did not take early return for MLV_Valid"); 13646 case Expr::MLV_InvalidExpression: 13647 case Expr::MLV_MemberFunction: 13648 case Expr::MLV_ClassTemporary: 13649 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13650 break; 13651 case Expr::MLV_IncompleteType: 13652 case Expr::MLV_IncompleteVoidType: 13653 return S.RequireCompleteType(Loc, E->getType(), 13654 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13655 case Expr::MLV_DuplicateVectorComponents: 13656 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13657 break; 13658 case Expr::MLV_NoSetterProperty: 13659 llvm_unreachable("readonly properties should be processed differently"); 13660 case Expr::MLV_InvalidMessageExpression: 13661 DiagID = diag::err_readonly_message_assignment; 13662 break; 13663 case Expr::MLV_SubObjCPropertySetting: 13664 DiagID = diag::err_no_subobject_property_setting; 13665 break; 13666 } 13667 13668 SourceRange Assign; 13669 if (Loc != OrigLoc) 13670 Assign = SourceRange(OrigLoc, OrigLoc); 13671 if (NeedType) 13672 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13673 else 13674 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13675 return true; 13676 } 13677 13678 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13679 SourceLocation Loc, 13680 Sema &Sema) { 13681 if (Sema.inTemplateInstantiation()) 13682 return; 13683 if (Sema.isUnevaluatedContext()) 13684 return; 13685 if (Loc.isInvalid() || Loc.isMacroID()) 13686 return; 13687 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13688 return; 13689 13690 // C / C++ fields 13691 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13692 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13693 if (ML && MR) { 13694 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13695 return; 13696 const ValueDecl *LHSDecl = 13697 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13698 const ValueDecl *RHSDecl = 13699 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13700 if (LHSDecl != RHSDecl) 13701 return; 13702 if (LHSDecl->getType().isVolatileQualified()) 13703 return; 13704 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13705 if (RefTy->getPointeeType().isVolatileQualified()) 13706 return; 13707 13708 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13709 } 13710 13711 // Objective-C instance variables 13712 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13713 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13714 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13715 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13716 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13717 if (RL && RR && RL->getDecl() == RR->getDecl()) 13718 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13719 } 13720 } 13721 13722 // C99 6.5.16.1 13723 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13724 SourceLocation Loc, 13725 QualType CompoundType) { 13726 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13727 13728 // Verify that LHS is a modifiable lvalue, and emit error if not. 13729 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13730 return QualType(); 13731 13732 QualType LHSType = LHSExpr->getType(); 13733 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13734 CompoundType; 13735 // OpenCL v1.2 s6.1.1.1 p2: 13736 // The half data type can only be used to declare a pointer to a buffer that 13737 // contains half values 13738 if (getLangOpts().OpenCL && 13739 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13740 LHSType->isHalfType()) { 13741 Diag(Loc, diag::err_opencl_half_load_store) << 1 13742 << LHSType.getUnqualifiedType(); 13743 return QualType(); 13744 } 13745 13746 AssignConvertType ConvTy; 13747 if (CompoundType.isNull()) { 13748 Expr *RHSCheck = RHS.get(); 13749 13750 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13751 13752 QualType LHSTy(LHSType); 13753 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13754 if (RHS.isInvalid()) 13755 return QualType(); 13756 // Special case of NSObject attributes on c-style pointer types. 13757 if (ConvTy == IncompatiblePointer && 13758 ((Context.isObjCNSObjectType(LHSType) && 13759 RHSType->isObjCObjectPointerType()) || 13760 (Context.isObjCNSObjectType(RHSType) && 13761 LHSType->isObjCObjectPointerType()))) 13762 ConvTy = Compatible; 13763 13764 if (ConvTy == Compatible && 13765 LHSType->isObjCObjectType()) 13766 Diag(Loc, diag::err_objc_object_assignment) 13767 << LHSType; 13768 13769 // If the RHS is a unary plus or minus, check to see if they = and + are 13770 // right next to each other. If so, the user may have typo'd "x =+ 4" 13771 // instead of "x += 4". 13772 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13773 RHSCheck = ICE->getSubExpr(); 13774 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13775 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13776 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13777 // Only if the two operators are exactly adjacent. 13778 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13779 // And there is a space or other character before the subexpr of the 13780 // unary +/-. We don't want to warn on "x=-1". 13781 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13782 UO->getSubExpr()->getBeginLoc().isFileID()) { 13783 Diag(Loc, diag::warn_not_compound_assign) 13784 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13785 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13786 } 13787 } 13788 13789 if (ConvTy == Compatible) { 13790 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13791 // Warn about retain cycles where a block captures the LHS, but 13792 // not if the LHS is a simple variable into which the block is 13793 // being stored...unless that variable can be captured by reference! 13794 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13795 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13796 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13797 checkRetainCycles(LHSExpr, RHS.get()); 13798 } 13799 13800 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13801 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13802 // It is safe to assign a weak reference into a strong variable. 13803 // Although this code can still have problems: 13804 // id x = self.weakProp; 13805 // id y = self.weakProp; 13806 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13807 // paths through the function. This should be revisited if 13808 // -Wrepeated-use-of-weak is made flow-sensitive. 13809 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13810 // variable, which will be valid for the current autorelease scope. 13811 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13812 RHS.get()->getBeginLoc())) 13813 getCurFunction()->markSafeWeakUse(RHS.get()); 13814 13815 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13816 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13817 } 13818 } 13819 } else { 13820 // Compound assignment "x += y" 13821 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13822 } 13823 13824 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13825 RHS.get(), AA_Assigning)) 13826 return QualType(); 13827 13828 CheckForNullPointerDereference(*this, LHSExpr); 13829 13830 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13831 if (CompoundType.isNull()) { 13832 // C++2a [expr.ass]p5: 13833 // A simple-assignment whose left operand is of a volatile-qualified 13834 // type is deprecated unless the assignment is either a discarded-value 13835 // expression or an unevaluated operand 13836 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13837 } else { 13838 // C++2a [expr.ass]p6: 13839 // [Compound-assignment] expressions are deprecated if E1 has 13840 // volatile-qualified type 13841 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13842 } 13843 } 13844 13845 // C11 6.5.16p3: The type of an assignment expression is the type of the 13846 // left operand would have after lvalue conversion. 13847 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has 13848 // qualified type, the value has the unqualified version of the type of the 13849 // lvalue; additionally, if the lvalue has atomic type, the value has the 13850 // non-atomic version of the type of the lvalue. 13851 // C++ 5.17p1: the type of the assignment expression is that of its left 13852 // operand. 13853 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); 13854 } 13855 13856 // Only ignore explicit casts to void. 13857 static bool IgnoreCommaOperand(const Expr *E) { 13858 E = E->IgnoreParens(); 13859 13860 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13861 if (CE->getCastKind() == CK_ToVoid) { 13862 return true; 13863 } 13864 13865 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13866 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13867 CE->getSubExpr()->getType()->isDependentType()) { 13868 return true; 13869 } 13870 } 13871 13872 return false; 13873 } 13874 13875 // Look for instances where it is likely the comma operator is confused with 13876 // another operator. There is an explicit list of acceptable expressions for 13877 // the left hand side of the comma operator, otherwise emit a warning. 13878 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13879 // No warnings in macros 13880 if (Loc.isMacroID()) 13881 return; 13882 13883 // Don't warn in template instantiations. 13884 if (inTemplateInstantiation()) 13885 return; 13886 13887 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13888 // instead, skip more than needed, then call back into here with the 13889 // CommaVisitor in SemaStmt.cpp. 13890 // The listed locations are the initialization and increment portions 13891 // of a for loop. The additional checks are on the condition of 13892 // if statements, do/while loops, and for loops. 13893 // Differences in scope flags for C89 mode requires the extra logic. 13894 const unsigned ForIncrementFlags = 13895 getLangOpts().C99 || getLangOpts().CPlusPlus 13896 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13897 : Scope::ContinueScope | Scope::BreakScope; 13898 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13899 const unsigned ScopeFlags = getCurScope()->getFlags(); 13900 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13901 (ScopeFlags & ForInitFlags) == ForInitFlags) 13902 return; 13903 13904 // If there are multiple comma operators used together, get the RHS of the 13905 // of the comma operator as the LHS. 13906 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13907 if (BO->getOpcode() != BO_Comma) 13908 break; 13909 LHS = BO->getRHS(); 13910 } 13911 13912 // Only allow some expressions on LHS to not warn. 13913 if (IgnoreCommaOperand(LHS)) 13914 return; 13915 13916 Diag(Loc, diag::warn_comma_operator); 13917 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13918 << LHS->getSourceRange() 13919 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13920 LangOpts.CPlusPlus ? "static_cast<void>(" 13921 : "(void)(") 13922 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13923 ")"); 13924 } 13925 13926 // C99 6.5.17 13927 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13928 SourceLocation Loc) { 13929 LHS = S.CheckPlaceholderExpr(LHS.get()); 13930 RHS = S.CheckPlaceholderExpr(RHS.get()); 13931 if (LHS.isInvalid() || RHS.isInvalid()) 13932 return QualType(); 13933 13934 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13935 // operands, but not unary promotions. 13936 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13937 13938 // So we treat the LHS as a ignored value, and in C++ we allow the 13939 // containing site to determine what should be done with the RHS. 13940 LHS = S.IgnoredValueConversions(LHS.get()); 13941 if (LHS.isInvalid()) 13942 return QualType(); 13943 13944 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13945 13946 if (!S.getLangOpts().CPlusPlus) { 13947 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13948 if (RHS.isInvalid()) 13949 return QualType(); 13950 if (!RHS.get()->getType()->isVoidType()) 13951 S.RequireCompleteType(Loc, RHS.get()->getType(), 13952 diag::err_incomplete_type); 13953 } 13954 13955 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13956 S.DiagnoseCommaOperator(LHS.get(), Loc); 13957 13958 return RHS.get()->getType(); 13959 } 13960 13961 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13962 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13963 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13964 ExprValueKind &VK, 13965 ExprObjectKind &OK, 13966 SourceLocation OpLoc, 13967 bool IsInc, bool IsPrefix) { 13968 if (Op->isTypeDependent()) 13969 return S.Context.DependentTy; 13970 13971 QualType ResType = Op->getType(); 13972 // Atomic types can be used for increment / decrement where the non-atomic 13973 // versions can, so ignore the _Atomic() specifier for the purpose of 13974 // checking. 13975 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13976 ResType = ResAtomicType->getValueType(); 13977 13978 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13979 13980 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13981 // Decrement of bool is not allowed. 13982 if (!IsInc) { 13983 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13984 return QualType(); 13985 } 13986 // Increment of bool sets it to true, but is deprecated. 13987 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13988 : diag::warn_increment_bool) 13989 << Op->getSourceRange(); 13990 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13991 // Error on enum increments and decrements in C++ mode 13992 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13993 return QualType(); 13994 } else if (ResType->isRealType()) { 13995 // OK! 13996 } else if (ResType->isPointerType()) { 13997 // C99 6.5.2.4p2, 6.5.6p2 13998 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13999 return QualType(); 14000 } else if (ResType->isObjCObjectPointerType()) { 14001 // On modern runtimes, ObjC pointer arithmetic is forbidden. 14002 // Otherwise, we just need a complete type. 14003 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 14004 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 14005 return QualType(); 14006 } else if (ResType->isAnyComplexType()) { 14007 // C99 does not support ++/-- on complex types, we allow as an extension. 14008 S.Diag(OpLoc, diag::ext_integer_increment_complex) 14009 << ResType << Op->getSourceRange(); 14010 } else if (ResType->isPlaceholderType()) { 14011 ExprResult PR = S.CheckPlaceholderExpr(Op); 14012 if (PR.isInvalid()) return QualType(); 14013 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 14014 IsInc, IsPrefix); 14015 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 14016 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 14017 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 14018 (ResType->castAs<VectorType>()->getVectorKind() != 14019 VectorType::AltiVecBool)) { 14020 // The z vector extensions allow ++ and -- for non-bool vectors. 14021 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 14022 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 14023 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 14024 } else { 14025 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 14026 << ResType << int(IsInc) << Op->getSourceRange(); 14027 return QualType(); 14028 } 14029 // At this point, we know we have a real, complex or pointer type. 14030 // Now make sure the operand is a modifiable lvalue. 14031 if (CheckForModifiableLvalue(Op, OpLoc, S)) 14032 return QualType(); 14033 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 14034 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 14035 // An operand with volatile-qualified type is deprecated 14036 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 14037 << IsInc << ResType; 14038 } 14039 // In C++, a prefix increment is the same type as the operand. Otherwise 14040 // (in C or with postfix), the increment is the unqualified type of the 14041 // operand. 14042 if (IsPrefix && S.getLangOpts().CPlusPlus) { 14043 VK = VK_LValue; 14044 OK = Op->getObjectKind(); 14045 return ResType; 14046 } else { 14047 VK = VK_PRValue; 14048 return ResType.getUnqualifiedType(); 14049 } 14050 } 14051 14052 14053 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 14054 /// This routine allows us to typecheck complex/recursive expressions 14055 /// where the declaration is needed for type checking. We only need to 14056 /// handle cases when the expression references a function designator 14057 /// or is an lvalue. Here are some examples: 14058 /// - &(x) => x 14059 /// - &*****f => f for f a function designator. 14060 /// - &s.xx => s 14061 /// - &s.zz[1].yy -> s, if zz is an array 14062 /// - *(x + 1) -> x, if x is an array 14063 /// - &"123"[2] -> 0 14064 /// - & __real__ x -> x 14065 /// 14066 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 14067 /// members. 14068 static ValueDecl *getPrimaryDecl(Expr *E) { 14069 switch (E->getStmtClass()) { 14070 case Stmt::DeclRefExprClass: 14071 return cast<DeclRefExpr>(E)->getDecl(); 14072 case Stmt::MemberExprClass: 14073 // If this is an arrow operator, the address is an offset from 14074 // the base's value, so the object the base refers to is 14075 // irrelevant. 14076 if (cast<MemberExpr>(E)->isArrow()) 14077 return nullptr; 14078 // Otherwise, the expression refers to a part of the base 14079 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 14080 case Stmt::ArraySubscriptExprClass: { 14081 // FIXME: This code shouldn't be necessary! We should catch the implicit 14082 // promotion of register arrays earlier. 14083 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 14084 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 14085 if (ICE->getSubExpr()->getType()->isArrayType()) 14086 return getPrimaryDecl(ICE->getSubExpr()); 14087 } 14088 return nullptr; 14089 } 14090 case Stmt::UnaryOperatorClass: { 14091 UnaryOperator *UO = cast<UnaryOperator>(E); 14092 14093 switch(UO->getOpcode()) { 14094 case UO_Real: 14095 case UO_Imag: 14096 case UO_Extension: 14097 return getPrimaryDecl(UO->getSubExpr()); 14098 default: 14099 return nullptr; 14100 } 14101 } 14102 case Stmt::ParenExprClass: 14103 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 14104 case Stmt::ImplicitCastExprClass: 14105 // If the result of an implicit cast is an l-value, we care about 14106 // the sub-expression; otherwise, the result here doesn't matter. 14107 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 14108 case Stmt::CXXUuidofExprClass: 14109 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 14110 default: 14111 return nullptr; 14112 } 14113 } 14114 14115 namespace { 14116 enum { 14117 AO_Bit_Field = 0, 14118 AO_Vector_Element = 1, 14119 AO_Property_Expansion = 2, 14120 AO_Register_Variable = 3, 14121 AO_Matrix_Element = 4, 14122 AO_No_Error = 5 14123 }; 14124 } 14125 /// Diagnose invalid operand for address of operations. 14126 /// 14127 /// \param Type The type of operand which cannot have its address taken. 14128 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 14129 Expr *E, unsigned Type) { 14130 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 14131 } 14132 14133 /// CheckAddressOfOperand - The operand of & must be either a function 14134 /// designator or an lvalue designating an object. If it is an lvalue, the 14135 /// object cannot be declared with storage class register or be a bit field. 14136 /// Note: The usual conversions are *not* applied to the operand of the & 14137 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 14138 /// In C++, the operand might be an overloaded function name, in which case 14139 /// we allow the '&' but retain the overloaded-function type. 14140 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 14141 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 14142 if (PTy->getKind() == BuiltinType::Overload) { 14143 Expr *E = OrigOp.get()->IgnoreParens(); 14144 if (!isa<OverloadExpr>(E)) { 14145 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 14146 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 14147 << OrigOp.get()->getSourceRange(); 14148 return QualType(); 14149 } 14150 14151 OverloadExpr *Ovl = cast<OverloadExpr>(E); 14152 if (isa<UnresolvedMemberExpr>(Ovl)) 14153 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 14154 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14155 << OrigOp.get()->getSourceRange(); 14156 return QualType(); 14157 } 14158 14159 return Context.OverloadTy; 14160 } 14161 14162 if (PTy->getKind() == BuiltinType::UnknownAny) 14163 return Context.UnknownAnyTy; 14164 14165 if (PTy->getKind() == BuiltinType::BoundMember) { 14166 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14167 << OrigOp.get()->getSourceRange(); 14168 return QualType(); 14169 } 14170 14171 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 14172 if (OrigOp.isInvalid()) return QualType(); 14173 } 14174 14175 if (OrigOp.get()->isTypeDependent()) 14176 return Context.DependentTy; 14177 14178 assert(!OrigOp.get()->hasPlaceholderType()); 14179 14180 // Make sure to ignore parentheses in subsequent checks 14181 Expr *op = OrigOp.get()->IgnoreParens(); 14182 14183 // In OpenCL captures for blocks called as lambda functions 14184 // are located in the private address space. Blocks used in 14185 // enqueue_kernel can be located in a different address space 14186 // depending on a vendor implementation. Thus preventing 14187 // taking an address of the capture to avoid invalid AS casts. 14188 if (LangOpts.OpenCL) { 14189 auto* VarRef = dyn_cast<DeclRefExpr>(op); 14190 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 14191 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 14192 return QualType(); 14193 } 14194 } 14195 14196 if (getLangOpts().C99) { 14197 // Implement C99-only parts of addressof rules. 14198 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 14199 if (uOp->getOpcode() == UO_Deref) 14200 // Per C99 6.5.3.2, the address of a deref always returns a valid result 14201 // (assuming the deref expression is valid). 14202 return uOp->getSubExpr()->getType(); 14203 } 14204 // Technically, there should be a check for array subscript 14205 // expressions here, but the result of one is always an lvalue anyway. 14206 } 14207 ValueDecl *dcl = getPrimaryDecl(op); 14208 14209 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 14210 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 14211 op->getBeginLoc())) 14212 return QualType(); 14213 14214 Expr::LValueClassification lval = op->ClassifyLValue(Context); 14215 unsigned AddressOfError = AO_No_Error; 14216 14217 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 14218 bool sfinae = (bool)isSFINAEContext(); 14219 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 14220 : diag::ext_typecheck_addrof_temporary) 14221 << op->getType() << op->getSourceRange(); 14222 if (sfinae) 14223 return QualType(); 14224 // Materialize the temporary as an lvalue so that we can take its address. 14225 OrigOp = op = 14226 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 14227 } else if (isa<ObjCSelectorExpr>(op)) { 14228 return Context.getPointerType(op->getType()); 14229 } else if (lval == Expr::LV_MemberFunction) { 14230 // If it's an instance method, make a member pointer. 14231 // The expression must have exactly the form &A::foo. 14232 14233 // If the underlying expression isn't a decl ref, give up. 14234 if (!isa<DeclRefExpr>(op)) { 14235 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14236 << OrigOp.get()->getSourceRange(); 14237 return QualType(); 14238 } 14239 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 14240 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 14241 14242 // The id-expression was parenthesized. 14243 if (OrigOp.get() != DRE) { 14244 Diag(OpLoc, diag::err_parens_pointer_member_function) 14245 << OrigOp.get()->getSourceRange(); 14246 14247 // The method was named without a qualifier. 14248 } else if (!DRE->getQualifier()) { 14249 if (MD->getParent()->getName().empty()) 14250 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14251 << op->getSourceRange(); 14252 else { 14253 SmallString<32> Str; 14254 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 14255 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14256 << op->getSourceRange() 14257 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 14258 } 14259 } 14260 14261 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 14262 if (isa<CXXDestructorDecl>(MD)) 14263 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 14264 14265 QualType MPTy = Context.getMemberPointerType( 14266 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 14267 // Under the MS ABI, lock down the inheritance model now. 14268 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14269 (void)isCompleteType(OpLoc, MPTy); 14270 return MPTy; 14271 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 14272 // C99 6.5.3.2p1 14273 // The operand must be either an l-value or a function designator 14274 if (!op->getType()->isFunctionType()) { 14275 // Use a special diagnostic for loads from property references. 14276 if (isa<PseudoObjectExpr>(op)) { 14277 AddressOfError = AO_Property_Expansion; 14278 } else { 14279 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 14280 << op->getType() << op->getSourceRange(); 14281 return QualType(); 14282 } 14283 } 14284 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 14285 // The operand cannot be a bit-field 14286 AddressOfError = AO_Bit_Field; 14287 } else if (op->getObjectKind() == OK_VectorComponent) { 14288 // The operand cannot be an element of a vector 14289 AddressOfError = AO_Vector_Element; 14290 } else if (op->getObjectKind() == OK_MatrixComponent) { 14291 // The operand cannot be an element of a matrix. 14292 AddressOfError = AO_Matrix_Element; 14293 } else if (dcl) { // C99 6.5.3.2p1 14294 // We have an lvalue with a decl. Make sure the decl is not declared 14295 // with the register storage-class specifier. 14296 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 14297 // in C++ it is not error to take address of a register 14298 // variable (c++03 7.1.1P3) 14299 if (vd->getStorageClass() == SC_Register && 14300 !getLangOpts().CPlusPlus) { 14301 AddressOfError = AO_Register_Variable; 14302 } 14303 } else if (isa<MSPropertyDecl>(dcl)) { 14304 AddressOfError = AO_Property_Expansion; 14305 } else if (isa<FunctionTemplateDecl>(dcl)) { 14306 return Context.OverloadTy; 14307 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 14308 // Okay: we can take the address of a field. 14309 // Could be a pointer to member, though, if there is an explicit 14310 // scope qualifier for the class. 14311 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 14312 DeclContext *Ctx = dcl->getDeclContext(); 14313 if (Ctx && Ctx->isRecord()) { 14314 if (dcl->getType()->isReferenceType()) { 14315 Diag(OpLoc, 14316 diag::err_cannot_form_pointer_to_member_of_reference_type) 14317 << dcl->getDeclName() << dcl->getType(); 14318 return QualType(); 14319 } 14320 14321 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 14322 Ctx = Ctx->getParent(); 14323 14324 QualType MPTy = Context.getMemberPointerType( 14325 op->getType(), 14326 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 14327 // Under the MS ABI, lock down the inheritance model now. 14328 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14329 (void)isCompleteType(OpLoc, MPTy); 14330 return MPTy; 14331 } 14332 } 14333 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, 14334 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl)) 14335 llvm_unreachable("Unknown/unexpected decl type"); 14336 } 14337 14338 if (AddressOfError != AO_No_Error) { 14339 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 14340 return QualType(); 14341 } 14342 14343 if (lval == Expr::LV_IncompleteVoidType) { 14344 // Taking the address of a void variable is technically illegal, but we 14345 // allow it in cases which are otherwise valid. 14346 // Example: "extern void x; void* y = &x;". 14347 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 14348 } 14349 14350 // If the operand has type "type", the result has type "pointer to type". 14351 if (op->getType()->isObjCObjectType()) 14352 return Context.getObjCObjectPointerType(op->getType()); 14353 14354 CheckAddressOfPackedMember(op); 14355 14356 return Context.getPointerType(op->getType()); 14357 } 14358 14359 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 14360 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 14361 if (!DRE) 14362 return; 14363 const Decl *D = DRE->getDecl(); 14364 if (!D) 14365 return; 14366 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 14367 if (!Param) 14368 return; 14369 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 14370 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 14371 return; 14372 if (FunctionScopeInfo *FD = S.getCurFunction()) 14373 if (!FD->ModifiedNonNullParams.count(Param)) 14374 FD->ModifiedNonNullParams.insert(Param); 14375 } 14376 14377 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 14378 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 14379 SourceLocation OpLoc) { 14380 if (Op->isTypeDependent()) 14381 return S.Context.DependentTy; 14382 14383 ExprResult ConvResult = S.UsualUnaryConversions(Op); 14384 if (ConvResult.isInvalid()) 14385 return QualType(); 14386 Op = ConvResult.get(); 14387 QualType OpTy = Op->getType(); 14388 QualType Result; 14389 14390 if (isa<CXXReinterpretCastExpr>(Op)) { 14391 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 14392 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 14393 Op->getSourceRange()); 14394 } 14395 14396 if (const PointerType *PT = OpTy->getAs<PointerType>()) 14397 { 14398 Result = PT->getPointeeType(); 14399 } 14400 else if (const ObjCObjectPointerType *OPT = 14401 OpTy->getAs<ObjCObjectPointerType>()) 14402 Result = OPT->getPointeeType(); 14403 else { 14404 ExprResult PR = S.CheckPlaceholderExpr(Op); 14405 if (PR.isInvalid()) return QualType(); 14406 if (PR.get() != Op) 14407 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 14408 } 14409 14410 if (Result.isNull()) { 14411 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 14412 << OpTy << Op->getSourceRange(); 14413 return QualType(); 14414 } 14415 14416 // Note that per both C89 and C99, indirection is always legal, even if Result 14417 // is an incomplete type or void. It would be possible to warn about 14418 // dereferencing a void pointer, but it's completely well-defined, and such a 14419 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 14420 // for pointers to 'void' but is fine for any other pointer type: 14421 // 14422 // C++ [expr.unary.op]p1: 14423 // [...] the expression to which [the unary * operator] is applied shall 14424 // be a pointer to an object type, or a pointer to a function type 14425 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 14426 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 14427 << OpTy << Op->getSourceRange(); 14428 14429 // Dereferences are usually l-values... 14430 VK = VK_LValue; 14431 14432 // ...except that certain expressions are never l-values in C. 14433 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 14434 VK = VK_PRValue; 14435 14436 return Result; 14437 } 14438 14439 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 14440 BinaryOperatorKind Opc; 14441 switch (Kind) { 14442 default: llvm_unreachable("Unknown binop!"); 14443 case tok::periodstar: Opc = BO_PtrMemD; break; 14444 case tok::arrowstar: Opc = BO_PtrMemI; break; 14445 case tok::star: Opc = BO_Mul; break; 14446 case tok::slash: Opc = BO_Div; break; 14447 case tok::percent: Opc = BO_Rem; break; 14448 case tok::plus: Opc = BO_Add; break; 14449 case tok::minus: Opc = BO_Sub; break; 14450 case tok::lessless: Opc = BO_Shl; break; 14451 case tok::greatergreater: Opc = BO_Shr; break; 14452 case tok::lessequal: Opc = BO_LE; break; 14453 case tok::less: Opc = BO_LT; break; 14454 case tok::greaterequal: Opc = BO_GE; break; 14455 case tok::greater: Opc = BO_GT; break; 14456 case tok::exclaimequal: Opc = BO_NE; break; 14457 case tok::equalequal: Opc = BO_EQ; break; 14458 case tok::spaceship: Opc = BO_Cmp; break; 14459 case tok::amp: Opc = BO_And; break; 14460 case tok::caret: Opc = BO_Xor; break; 14461 case tok::pipe: Opc = BO_Or; break; 14462 case tok::ampamp: Opc = BO_LAnd; break; 14463 case tok::pipepipe: Opc = BO_LOr; break; 14464 case tok::equal: Opc = BO_Assign; break; 14465 case tok::starequal: Opc = BO_MulAssign; break; 14466 case tok::slashequal: Opc = BO_DivAssign; break; 14467 case tok::percentequal: Opc = BO_RemAssign; break; 14468 case tok::plusequal: Opc = BO_AddAssign; break; 14469 case tok::minusequal: Opc = BO_SubAssign; break; 14470 case tok::lesslessequal: Opc = BO_ShlAssign; break; 14471 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 14472 case tok::ampequal: Opc = BO_AndAssign; break; 14473 case tok::caretequal: Opc = BO_XorAssign; break; 14474 case tok::pipeequal: Opc = BO_OrAssign; break; 14475 case tok::comma: Opc = BO_Comma; break; 14476 } 14477 return Opc; 14478 } 14479 14480 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 14481 tok::TokenKind Kind) { 14482 UnaryOperatorKind Opc; 14483 switch (Kind) { 14484 default: llvm_unreachable("Unknown unary op!"); 14485 case tok::plusplus: Opc = UO_PreInc; break; 14486 case tok::minusminus: Opc = UO_PreDec; break; 14487 case tok::amp: Opc = UO_AddrOf; break; 14488 case tok::star: Opc = UO_Deref; break; 14489 case tok::plus: Opc = UO_Plus; break; 14490 case tok::minus: Opc = UO_Minus; break; 14491 case tok::tilde: Opc = UO_Not; break; 14492 case tok::exclaim: Opc = UO_LNot; break; 14493 case tok::kw___real: Opc = UO_Real; break; 14494 case tok::kw___imag: Opc = UO_Imag; break; 14495 case tok::kw___extension__: Opc = UO_Extension; break; 14496 } 14497 return Opc; 14498 } 14499 14500 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 14501 /// This warning suppressed in the event of macro expansions. 14502 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 14503 SourceLocation OpLoc, bool IsBuiltin) { 14504 if (S.inTemplateInstantiation()) 14505 return; 14506 if (S.isUnevaluatedContext()) 14507 return; 14508 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 14509 return; 14510 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14511 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14512 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14513 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14514 if (!LHSDeclRef || !RHSDeclRef || 14515 LHSDeclRef->getLocation().isMacroID() || 14516 RHSDeclRef->getLocation().isMacroID()) 14517 return; 14518 const ValueDecl *LHSDecl = 14519 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 14520 const ValueDecl *RHSDecl = 14521 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 14522 if (LHSDecl != RHSDecl) 14523 return; 14524 if (LHSDecl->getType().isVolatileQualified()) 14525 return; 14526 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 14527 if (RefTy->getPointeeType().isVolatileQualified()) 14528 return; 14529 14530 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 14531 : diag::warn_self_assignment_overloaded) 14532 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 14533 << RHSExpr->getSourceRange(); 14534 } 14535 14536 /// Check if a bitwise-& is performed on an Objective-C pointer. This 14537 /// is usually indicative of introspection within the Objective-C pointer. 14538 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 14539 SourceLocation OpLoc) { 14540 if (!S.getLangOpts().ObjC) 14541 return; 14542 14543 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 14544 const Expr *LHS = L.get(); 14545 const Expr *RHS = R.get(); 14546 14547 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14548 ObjCPointerExpr = LHS; 14549 OtherExpr = RHS; 14550 } 14551 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14552 ObjCPointerExpr = RHS; 14553 OtherExpr = LHS; 14554 } 14555 14556 // This warning is deliberately made very specific to reduce false 14557 // positives with logic that uses '&' for hashing. This logic mainly 14558 // looks for code trying to introspect into tagged pointers, which 14559 // code should generally never do. 14560 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 14561 unsigned Diag = diag::warn_objc_pointer_masking; 14562 // Determine if we are introspecting the result of performSelectorXXX. 14563 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 14564 // Special case messages to -performSelector and friends, which 14565 // can return non-pointer values boxed in a pointer value. 14566 // Some clients may wish to silence warnings in this subcase. 14567 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14568 Selector S = ME->getSelector(); 14569 StringRef SelArg0 = S.getNameForSlot(0); 14570 if (SelArg0.startswith("performSelector")) 14571 Diag = diag::warn_objc_pointer_masking_performSelector; 14572 } 14573 14574 S.Diag(OpLoc, Diag) 14575 << ObjCPointerExpr->getSourceRange(); 14576 } 14577 } 14578 14579 static NamedDecl *getDeclFromExpr(Expr *E) { 14580 if (!E) 14581 return nullptr; 14582 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14583 return DRE->getDecl(); 14584 if (auto *ME = dyn_cast<MemberExpr>(E)) 14585 return ME->getMemberDecl(); 14586 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14587 return IRE->getDecl(); 14588 return nullptr; 14589 } 14590 14591 // This helper function promotes a binary operator's operands (which are of a 14592 // half vector type) to a vector of floats and then truncates the result to 14593 // a vector of either half or short. 14594 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14595 BinaryOperatorKind Opc, QualType ResultTy, 14596 ExprValueKind VK, ExprObjectKind OK, 14597 bool IsCompAssign, SourceLocation OpLoc, 14598 FPOptionsOverride FPFeatures) { 14599 auto &Context = S.getASTContext(); 14600 assert((isVector(ResultTy, Context.HalfTy) || 14601 isVector(ResultTy, Context.ShortTy)) && 14602 "Result must be a vector of half or short"); 14603 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14604 isVector(RHS.get()->getType(), Context.HalfTy) && 14605 "both operands expected to be a half vector"); 14606 14607 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14608 QualType BinOpResTy = RHS.get()->getType(); 14609 14610 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14611 // change BinOpResTy to a vector of ints. 14612 if (isVector(ResultTy, Context.ShortTy)) 14613 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14614 14615 if (IsCompAssign) 14616 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14617 ResultTy, VK, OK, OpLoc, FPFeatures, 14618 BinOpResTy, BinOpResTy); 14619 14620 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14621 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14622 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14623 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14624 } 14625 14626 static std::pair<ExprResult, ExprResult> 14627 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14628 Expr *RHSExpr) { 14629 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14630 if (!S.Context.isDependenceAllowed()) { 14631 // C cannot handle TypoExpr nodes on either side of a binop because it 14632 // doesn't handle dependent types properly, so make sure any TypoExprs have 14633 // been dealt with before checking the operands. 14634 LHS = S.CorrectDelayedTyposInExpr(LHS); 14635 RHS = S.CorrectDelayedTyposInExpr( 14636 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14637 [Opc, LHS](Expr *E) { 14638 if (Opc != BO_Assign) 14639 return ExprResult(E); 14640 // Avoid correcting the RHS to the same Expr as the LHS. 14641 Decl *D = getDeclFromExpr(E); 14642 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14643 }); 14644 } 14645 return std::make_pair(LHS, RHS); 14646 } 14647 14648 /// Returns true if conversion between vectors of halfs and vectors of floats 14649 /// is needed. 14650 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14651 Expr *E0, Expr *E1 = nullptr) { 14652 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14653 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14654 return false; 14655 14656 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14657 QualType Ty = E->IgnoreImplicit()->getType(); 14658 14659 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14660 // to vectors of floats. Although the element type of the vectors is __fp16, 14661 // the vectors shouldn't be treated as storage-only types. See the 14662 // discussion here: https://reviews.llvm.org/rG825235c140e7 14663 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14664 if (VT->getVectorKind() == VectorType::NeonVector) 14665 return false; 14666 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14667 } 14668 return false; 14669 }; 14670 14671 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14672 } 14673 14674 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14675 /// operator @p Opc at location @c TokLoc. This routine only supports 14676 /// built-in operations; ActOnBinOp handles overloaded operators. 14677 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14678 BinaryOperatorKind Opc, 14679 Expr *LHSExpr, Expr *RHSExpr) { 14680 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14681 // The syntax only allows initializer lists on the RHS of assignment, 14682 // so we don't need to worry about accepting invalid code for 14683 // non-assignment operators. 14684 // C++11 5.17p9: 14685 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14686 // of x = {} is x = T(). 14687 InitializationKind Kind = InitializationKind::CreateDirectList( 14688 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14689 InitializedEntity Entity = 14690 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14691 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14692 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14693 if (Init.isInvalid()) 14694 return Init; 14695 RHSExpr = Init.get(); 14696 } 14697 14698 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14699 QualType ResultTy; // Result type of the binary operator. 14700 // The following two variables are used for compound assignment operators 14701 QualType CompLHSTy; // Type of LHS after promotions for computation 14702 QualType CompResultTy; // Type of computation result 14703 ExprValueKind VK = VK_PRValue; 14704 ExprObjectKind OK = OK_Ordinary; 14705 bool ConvertHalfVec = false; 14706 14707 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14708 if (!LHS.isUsable() || !RHS.isUsable()) 14709 return ExprError(); 14710 14711 if (getLangOpts().OpenCL) { 14712 QualType LHSTy = LHSExpr->getType(); 14713 QualType RHSTy = RHSExpr->getType(); 14714 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14715 // the ATOMIC_VAR_INIT macro. 14716 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14717 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14718 if (BO_Assign == Opc) 14719 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14720 else 14721 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14722 return ExprError(); 14723 } 14724 14725 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14726 // only with a builtin functions and therefore should be disallowed here. 14727 if (LHSTy->isImageType() || RHSTy->isImageType() || 14728 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14729 LHSTy->isPipeType() || RHSTy->isPipeType() || 14730 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14731 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14732 return ExprError(); 14733 } 14734 } 14735 14736 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14737 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14738 14739 switch (Opc) { 14740 case BO_Assign: 14741 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14742 if (getLangOpts().CPlusPlus && 14743 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14744 VK = LHS.get()->getValueKind(); 14745 OK = LHS.get()->getObjectKind(); 14746 } 14747 if (!ResultTy.isNull()) { 14748 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14749 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14750 14751 // Avoid copying a block to the heap if the block is assigned to a local 14752 // auto variable that is declared in the same scope as the block. This 14753 // optimization is unsafe if the local variable is declared in an outer 14754 // scope. For example: 14755 // 14756 // BlockTy b; 14757 // { 14758 // b = ^{...}; 14759 // } 14760 // // It is unsafe to invoke the block here if it wasn't copied to the 14761 // // heap. 14762 // b(); 14763 14764 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14765 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14766 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14767 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14768 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14769 14770 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14771 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14772 NTCUC_Assignment, NTCUK_Copy); 14773 } 14774 RecordModifiableNonNullParam(*this, LHS.get()); 14775 break; 14776 case BO_PtrMemD: 14777 case BO_PtrMemI: 14778 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14779 Opc == BO_PtrMemI); 14780 break; 14781 case BO_Mul: 14782 case BO_Div: 14783 ConvertHalfVec = true; 14784 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14785 Opc == BO_Div); 14786 break; 14787 case BO_Rem: 14788 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14789 break; 14790 case BO_Add: 14791 ConvertHalfVec = true; 14792 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14793 break; 14794 case BO_Sub: 14795 ConvertHalfVec = true; 14796 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14797 break; 14798 case BO_Shl: 14799 case BO_Shr: 14800 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14801 break; 14802 case BO_LE: 14803 case BO_LT: 14804 case BO_GE: 14805 case BO_GT: 14806 ConvertHalfVec = true; 14807 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14808 break; 14809 case BO_EQ: 14810 case BO_NE: 14811 ConvertHalfVec = true; 14812 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14813 break; 14814 case BO_Cmp: 14815 ConvertHalfVec = true; 14816 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14817 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14818 break; 14819 case BO_And: 14820 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14821 LLVM_FALLTHROUGH; 14822 case BO_Xor: 14823 case BO_Or: 14824 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14825 break; 14826 case BO_LAnd: 14827 case BO_LOr: 14828 ConvertHalfVec = true; 14829 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14830 break; 14831 case BO_MulAssign: 14832 case BO_DivAssign: 14833 ConvertHalfVec = true; 14834 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14835 Opc == BO_DivAssign); 14836 CompLHSTy = CompResultTy; 14837 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14838 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14839 break; 14840 case BO_RemAssign: 14841 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14842 CompLHSTy = CompResultTy; 14843 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14844 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14845 break; 14846 case BO_AddAssign: 14847 ConvertHalfVec = true; 14848 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14849 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14850 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14851 break; 14852 case BO_SubAssign: 14853 ConvertHalfVec = true; 14854 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14855 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14856 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14857 break; 14858 case BO_ShlAssign: 14859 case BO_ShrAssign: 14860 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14861 CompLHSTy = CompResultTy; 14862 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14863 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14864 break; 14865 case BO_AndAssign: 14866 case BO_OrAssign: // fallthrough 14867 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14868 LLVM_FALLTHROUGH; 14869 case BO_XorAssign: 14870 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14871 CompLHSTy = CompResultTy; 14872 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14873 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14874 break; 14875 case BO_Comma: 14876 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14877 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14878 VK = RHS.get()->getValueKind(); 14879 OK = RHS.get()->getObjectKind(); 14880 } 14881 break; 14882 } 14883 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14884 return ExprError(); 14885 14886 // Some of the binary operations require promoting operands of half vector to 14887 // float vectors and truncating the result back to half vector. For now, we do 14888 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14889 // arm64). 14890 assert( 14891 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14892 isVector(LHS.get()->getType(), Context.HalfTy)) && 14893 "both sides are half vectors or neither sides are"); 14894 ConvertHalfVec = 14895 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14896 14897 // Check for array bounds violations for both sides of the BinaryOperator 14898 CheckArrayAccess(LHS.get()); 14899 CheckArrayAccess(RHS.get()); 14900 14901 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14902 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14903 &Context.Idents.get("object_setClass"), 14904 SourceLocation(), LookupOrdinaryName); 14905 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14906 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14907 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14908 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14909 "object_setClass(") 14910 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14911 ",") 14912 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14913 } 14914 else 14915 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14916 } 14917 else if (const ObjCIvarRefExpr *OIRE = 14918 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14919 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14920 14921 // Opc is not a compound assignment if CompResultTy is null. 14922 if (CompResultTy.isNull()) { 14923 if (ConvertHalfVec) 14924 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14925 OpLoc, CurFPFeatureOverrides()); 14926 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14927 VK, OK, OpLoc, CurFPFeatureOverrides()); 14928 } 14929 14930 // Handle compound assignments. 14931 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14932 OK_ObjCProperty) { 14933 VK = VK_LValue; 14934 OK = LHS.get()->getObjectKind(); 14935 } 14936 14937 // The LHS is not converted to the result type for fixed-point compound 14938 // assignment as the common type is computed on demand. Reset the CompLHSTy 14939 // to the LHS type we would have gotten after unary conversions. 14940 if (CompResultTy->isFixedPointType()) 14941 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14942 14943 if (ConvertHalfVec) 14944 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14945 OpLoc, CurFPFeatureOverrides()); 14946 14947 return CompoundAssignOperator::Create( 14948 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14949 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14950 } 14951 14952 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14953 /// operators are mixed in a way that suggests that the programmer forgot that 14954 /// comparison operators have higher precedence. The most typical example of 14955 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14956 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14957 SourceLocation OpLoc, Expr *LHSExpr, 14958 Expr *RHSExpr) { 14959 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14960 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14961 14962 // Check that one of the sides is a comparison operator and the other isn't. 14963 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14964 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14965 if (isLeftComp == isRightComp) 14966 return; 14967 14968 // Bitwise operations are sometimes used as eager logical ops. 14969 // Don't diagnose this. 14970 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14971 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14972 if (isLeftBitwise || isRightBitwise) 14973 return; 14974 14975 SourceRange DiagRange = isLeftComp 14976 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14977 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14978 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14979 SourceRange ParensRange = 14980 isLeftComp 14981 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14982 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14983 14984 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14985 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14986 SuggestParentheses(Self, OpLoc, 14987 Self.PDiag(diag::note_precedence_silence) << OpStr, 14988 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14989 SuggestParentheses(Self, OpLoc, 14990 Self.PDiag(diag::note_precedence_bitwise_first) 14991 << BinaryOperator::getOpcodeStr(Opc), 14992 ParensRange); 14993 } 14994 14995 /// It accepts a '&&' expr that is inside a '||' one. 14996 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14997 /// in parentheses. 14998 static void 14999 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 15000 BinaryOperator *Bop) { 15001 assert(Bop->getOpcode() == BO_LAnd); 15002 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 15003 << Bop->getSourceRange() << OpLoc; 15004 SuggestParentheses(Self, Bop->getOperatorLoc(), 15005 Self.PDiag(diag::note_precedence_silence) 15006 << Bop->getOpcodeStr(), 15007 Bop->getSourceRange()); 15008 } 15009 15010 /// Returns true if the given expression can be evaluated as a constant 15011 /// 'true'. 15012 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 15013 bool Res; 15014 return !E->isValueDependent() && 15015 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 15016 } 15017 15018 /// Returns true if the given expression can be evaluated as a constant 15019 /// 'false'. 15020 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 15021 bool Res; 15022 return !E->isValueDependent() && 15023 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 15024 } 15025 15026 /// Look for '&&' in the left hand of a '||' expr. 15027 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 15028 Expr *LHSExpr, Expr *RHSExpr) { 15029 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 15030 if (Bop->getOpcode() == BO_LAnd) { 15031 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 15032 if (EvaluatesAsFalse(S, RHSExpr)) 15033 return; 15034 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 15035 if (!EvaluatesAsTrue(S, Bop->getLHS())) 15036 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15037 } else if (Bop->getOpcode() == BO_LOr) { 15038 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 15039 // If it's "a || b && 1 || c" we didn't warn earlier for 15040 // "a || b && 1", but warn now. 15041 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 15042 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 15043 } 15044 } 15045 } 15046 } 15047 15048 /// Look for '&&' in the right hand of a '||' expr. 15049 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 15050 Expr *LHSExpr, Expr *RHSExpr) { 15051 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 15052 if (Bop->getOpcode() == BO_LAnd) { 15053 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 15054 if (EvaluatesAsFalse(S, LHSExpr)) 15055 return; 15056 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 15057 if (!EvaluatesAsTrue(S, Bop->getRHS())) 15058 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15059 } 15060 } 15061 } 15062 15063 /// Look for bitwise op in the left or right hand of a bitwise op with 15064 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 15065 /// the '&' expression in parentheses. 15066 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 15067 SourceLocation OpLoc, Expr *SubExpr) { 15068 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15069 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 15070 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 15071 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 15072 << Bop->getSourceRange() << OpLoc; 15073 SuggestParentheses(S, Bop->getOperatorLoc(), 15074 S.PDiag(diag::note_precedence_silence) 15075 << Bop->getOpcodeStr(), 15076 Bop->getSourceRange()); 15077 } 15078 } 15079 } 15080 15081 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 15082 Expr *SubExpr, StringRef Shift) { 15083 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15084 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 15085 StringRef Op = Bop->getOpcodeStr(); 15086 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 15087 << Bop->getSourceRange() << OpLoc << Shift << Op; 15088 SuggestParentheses(S, Bop->getOperatorLoc(), 15089 S.PDiag(diag::note_precedence_silence) << Op, 15090 Bop->getSourceRange()); 15091 } 15092 } 15093 } 15094 15095 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 15096 Expr *LHSExpr, Expr *RHSExpr) { 15097 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 15098 if (!OCE) 15099 return; 15100 15101 FunctionDecl *FD = OCE->getDirectCallee(); 15102 if (!FD || !FD->isOverloadedOperator()) 15103 return; 15104 15105 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 15106 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 15107 return; 15108 15109 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 15110 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 15111 << (Kind == OO_LessLess); 15112 SuggestParentheses(S, OCE->getOperatorLoc(), 15113 S.PDiag(diag::note_precedence_silence) 15114 << (Kind == OO_LessLess ? "<<" : ">>"), 15115 OCE->getSourceRange()); 15116 SuggestParentheses( 15117 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 15118 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 15119 } 15120 15121 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 15122 /// precedence. 15123 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 15124 SourceLocation OpLoc, Expr *LHSExpr, 15125 Expr *RHSExpr){ 15126 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 15127 if (BinaryOperator::isBitwiseOp(Opc)) 15128 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 15129 15130 // Diagnose "arg1 & arg2 | arg3" 15131 if ((Opc == BO_Or || Opc == BO_Xor) && 15132 !OpLoc.isMacroID()/* Don't warn in macros. */) { 15133 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 15134 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 15135 } 15136 15137 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 15138 // We don't warn for 'assert(a || b && "bad")' since this is safe. 15139 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 15140 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 15141 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 15142 } 15143 15144 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 15145 || Opc == BO_Shr) { 15146 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 15147 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 15148 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 15149 } 15150 15151 // Warn on overloaded shift operators and comparisons, such as: 15152 // cout << 5 == 4; 15153 if (BinaryOperator::isComparisonOp(Opc)) 15154 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 15155 } 15156 15157 // Binary Operators. 'Tok' is the token for the operator. 15158 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 15159 tok::TokenKind Kind, 15160 Expr *LHSExpr, Expr *RHSExpr) { 15161 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 15162 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 15163 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 15164 15165 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 15166 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 15167 15168 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 15169 } 15170 15171 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 15172 UnresolvedSetImpl &Functions) { 15173 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 15174 if (OverOp != OO_None && OverOp != OO_Equal) 15175 LookupOverloadedOperatorName(OverOp, S, Functions); 15176 15177 // In C++20 onwards, we may have a second operator to look up. 15178 if (getLangOpts().CPlusPlus20) { 15179 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 15180 LookupOverloadedOperatorName(ExtraOp, S, Functions); 15181 } 15182 } 15183 15184 /// Build an overloaded binary operator expression in the given scope. 15185 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 15186 BinaryOperatorKind Opc, 15187 Expr *LHS, Expr *RHS) { 15188 switch (Opc) { 15189 case BO_Assign: 15190 case BO_DivAssign: 15191 case BO_RemAssign: 15192 case BO_SubAssign: 15193 case BO_AndAssign: 15194 case BO_OrAssign: 15195 case BO_XorAssign: 15196 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 15197 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 15198 break; 15199 default: 15200 break; 15201 } 15202 15203 // Find all of the overloaded operators visible from this point. 15204 UnresolvedSet<16> Functions; 15205 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 15206 15207 // Build the (potentially-overloaded, potentially-dependent) 15208 // binary operation. 15209 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 15210 } 15211 15212 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 15213 BinaryOperatorKind Opc, 15214 Expr *LHSExpr, Expr *RHSExpr) { 15215 ExprResult LHS, RHS; 15216 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 15217 if (!LHS.isUsable() || !RHS.isUsable()) 15218 return ExprError(); 15219 LHSExpr = LHS.get(); 15220 RHSExpr = RHS.get(); 15221 15222 // We want to end up calling one of checkPseudoObjectAssignment 15223 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 15224 // both expressions are overloadable or either is type-dependent), 15225 // or CreateBuiltinBinOp (in any other case). We also want to get 15226 // any placeholder types out of the way. 15227 15228 // Handle pseudo-objects in the LHS. 15229 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 15230 // Assignments with a pseudo-object l-value need special analysis. 15231 if (pty->getKind() == BuiltinType::PseudoObject && 15232 BinaryOperator::isAssignmentOp(Opc)) 15233 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 15234 15235 // Don't resolve overloads if the other type is overloadable. 15236 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 15237 // We can't actually test that if we still have a placeholder, 15238 // though. Fortunately, none of the exceptions we see in that 15239 // code below are valid when the LHS is an overload set. Note 15240 // that an overload set can be dependently-typed, but it never 15241 // instantiates to having an overloadable type. 15242 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15243 if (resolvedRHS.isInvalid()) return ExprError(); 15244 RHSExpr = resolvedRHS.get(); 15245 15246 if (RHSExpr->isTypeDependent() || 15247 RHSExpr->getType()->isOverloadableType()) 15248 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15249 } 15250 15251 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 15252 // template, diagnose the missing 'template' keyword instead of diagnosing 15253 // an invalid use of a bound member function. 15254 // 15255 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 15256 // to C++1z [over.over]/1.4, but we already checked for that case above. 15257 if (Opc == BO_LT && inTemplateInstantiation() && 15258 (pty->getKind() == BuiltinType::BoundMember || 15259 pty->getKind() == BuiltinType::Overload)) { 15260 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 15261 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 15262 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 15263 return isa<FunctionTemplateDecl>(ND); 15264 })) { 15265 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 15266 : OE->getNameLoc(), 15267 diag::err_template_kw_missing) 15268 << OE->getName().getAsString() << ""; 15269 return ExprError(); 15270 } 15271 } 15272 15273 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 15274 if (LHS.isInvalid()) return ExprError(); 15275 LHSExpr = LHS.get(); 15276 } 15277 15278 // Handle pseudo-objects in the RHS. 15279 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 15280 // An overload in the RHS can potentially be resolved by the type 15281 // being assigned to. 15282 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 15283 if (getLangOpts().CPlusPlus && 15284 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 15285 LHSExpr->getType()->isOverloadableType())) 15286 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15287 15288 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15289 } 15290 15291 // Don't resolve overloads if the other type is overloadable. 15292 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 15293 LHSExpr->getType()->isOverloadableType()) 15294 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15295 15296 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15297 if (!resolvedRHS.isUsable()) return ExprError(); 15298 RHSExpr = resolvedRHS.get(); 15299 } 15300 15301 if (getLangOpts().CPlusPlus) { 15302 // If either expression is type-dependent, always build an 15303 // overloaded op. 15304 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 15305 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15306 15307 // Otherwise, build an overloaded op if either expression has an 15308 // overloadable type. 15309 if (LHSExpr->getType()->isOverloadableType() || 15310 RHSExpr->getType()->isOverloadableType()) 15311 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15312 } 15313 15314 if (getLangOpts().RecoveryAST && 15315 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 15316 assert(!getLangOpts().CPlusPlus); 15317 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 15318 "Should only occur in error-recovery path."); 15319 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 15320 // C [6.15.16] p3: 15321 // An assignment expression has the value of the left operand after the 15322 // assignment, but is not an lvalue. 15323 return CompoundAssignOperator::Create( 15324 Context, LHSExpr, RHSExpr, Opc, 15325 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 15326 OpLoc, CurFPFeatureOverrides()); 15327 QualType ResultType; 15328 switch (Opc) { 15329 case BO_Assign: 15330 ResultType = LHSExpr->getType().getUnqualifiedType(); 15331 break; 15332 case BO_LT: 15333 case BO_GT: 15334 case BO_LE: 15335 case BO_GE: 15336 case BO_EQ: 15337 case BO_NE: 15338 case BO_LAnd: 15339 case BO_LOr: 15340 // These operators have a fixed result type regardless of operands. 15341 ResultType = Context.IntTy; 15342 break; 15343 case BO_Comma: 15344 ResultType = RHSExpr->getType(); 15345 break; 15346 default: 15347 ResultType = Context.DependentTy; 15348 break; 15349 } 15350 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 15351 VK_PRValue, OK_Ordinary, OpLoc, 15352 CurFPFeatureOverrides()); 15353 } 15354 15355 // Build a built-in binary operation. 15356 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15357 } 15358 15359 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 15360 if (T.isNull() || T->isDependentType()) 15361 return false; 15362 15363 if (!T->isPromotableIntegerType()) 15364 return true; 15365 15366 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 15367 } 15368 15369 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 15370 UnaryOperatorKind Opc, 15371 Expr *InputExpr) { 15372 ExprResult Input = InputExpr; 15373 ExprValueKind VK = VK_PRValue; 15374 ExprObjectKind OK = OK_Ordinary; 15375 QualType resultType; 15376 bool CanOverflow = false; 15377 15378 bool ConvertHalfVec = false; 15379 if (getLangOpts().OpenCL) { 15380 QualType Ty = InputExpr->getType(); 15381 // The only legal unary operation for atomics is '&'. 15382 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 15383 // OpenCL special types - image, sampler, pipe, and blocks are to be used 15384 // only with a builtin functions and therefore should be disallowed here. 15385 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 15386 || Ty->isBlockPointerType())) { 15387 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15388 << InputExpr->getType() 15389 << Input.get()->getSourceRange()); 15390 } 15391 } 15392 15393 if (getLangOpts().HLSL) { 15394 if (Opc == UO_AddrOf) 15395 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0); 15396 if (Opc == UO_Deref) 15397 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1); 15398 } 15399 15400 switch (Opc) { 15401 case UO_PreInc: 15402 case UO_PreDec: 15403 case UO_PostInc: 15404 case UO_PostDec: 15405 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 15406 OpLoc, 15407 Opc == UO_PreInc || 15408 Opc == UO_PostInc, 15409 Opc == UO_PreInc || 15410 Opc == UO_PreDec); 15411 CanOverflow = isOverflowingIntegerType(Context, resultType); 15412 break; 15413 case UO_AddrOf: 15414 resultType = CheckAddressOfOperand(Input, OpLoc); 15415 CheckAddressOfNoDeref(InputExpr); 15416 RecordModifiableNonNullParam(*this, InputExpr); 15417 break; 15418 case UO_Deref: { 15419 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15420 if (Input.isInvalid()) return ExprError(); 15421 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 15422 break; 15423 } 15424 case UO_Plus: 15425 case UO_Minus: 15426 CanOverflow = Opc == UO_Minus && 15427 isOverflowingIntegerType(Context, Input.get()->getType()); 15428 Input = UsualUnaryConversions(Input.get()); 15429 if (Input.isInvalid()) return ExprError(); 15430 // Unary plus and minus require promoting an operand of half vector to a 15431 // float vector and truncating the result back to a half vector. For now, we 15432 // do this only when HalfArgsAndReturns is set (that is, when the target is 15433 // arm or arm64). 15434 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 15435 15436 // If the operand is a half vector, promote it to a float vector. 15437 if (ConvertHalfVec) 15438 Input = convertVector(Input.get(), Context.FloatTy, *this); 15439 resultType = Input.get()->getType(); 15440 if (resultType->isDependentType()) 15441 break; 15442 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 15443 break; 15444 else if (resultType->isVectorType() && 15445 // The z vector extensions don't allow + or - with bool vectors. 15446 (!Context.getLangOpts().ZVector || 15447 resultType->castAs<VectorType>()->getVectorKind() != 15448 VectorType::AltiVecBool)) 15449 break; 15450 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 15451 Opc == UO_Plus && 15452 resultType->isPointerType()) 15453 break; 15454 15455 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15456 << resultType << Input.get()->getSourceRange()); 15457 15458 case UO_Not: // bitwise complement 15459 Input = UsualUnaryConversions(Input.get()); 15460 if (Input.isInvalid()) 15461 return ExprError(); 15462 resultType = Input.get()->getType(); 15463 if (resultType->isDependentType()) 15464 break; 15465 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 15466 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 15467 // C99 does not support '~' for complex conjugation. 15468 Diag(OpLoc, diag::ext_integer_complement_complex) 15469 << resultType << Input.get()->getSourceRange(); 15470 else if (resultType->hasIntegerRepresentation()) 15471 break; 15472 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 15473 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 15474 // on vector float types. 15475 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15476 if (!T->isIntegerType()) 15477 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15478 << resultType << Input.get()->getSourceRange()); 15479 } else { 15480 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15481 << resultType << Input.get()->getSourceRange()); 15482 } 15483 break; 15484 15485 case UO_LNot: // logical negation 15486 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 15487 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15488 if (Input.isInvalid()) return ExprError(); 15489 resultType = Input.get()->getType(); 15490 15491 // Though we still have to promote half FP to float... 15492 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 15493 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 15494 resultType = Context.FloatTy; 15495 } 15496 15497 if (resultType->isDependentType()) 15498 break; 15499 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 15500 // C99 6.5.3.3p1: ok, fallthrough; 15501 if (Context.getLangOpts().CPlusPlus) { 15502 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 15503 // operand contextually converted to bool. 15504 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 15505 ScalarTypeToBooleanCastKind(resultType)); 15506 } else if (Context.getLangOpts().OpenCL && 15507 Context.getLangOpts().OpenCLVersion < 120) { 15508 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15509 // operate on scalar float types. 15510 if (!resultType->isIntegerType() && !resultType->isPointerType()) 15511 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15512 << resultType << Input.get()->getSourceRange()); 15513 } 15514 } else if (resultType->isExtVectorType()) { 15515 if (Context.getLangOpts().OpenCL && 15516 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 15517 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15518 // operate on vector float types. 15519 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15520 if (!T->isIntegerType()) 15521 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15522 << resultType << Input.get()->getSourceRange()); 15523 } 15524 // Vector logical not returns the signed variant of the operand type. 15525 resultType = GetSignedVectorType(resultType); 15526 break; 15527 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 15528 const VectorType *VTy = resultType->castAs<VectorType>(); 15529 if (VTy->getVectorKind() != VectorType::GenericVector) 15530 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15531 << resultType << Input.get()->getSourceRange()); 15532 15533 // Vector logical not returns the signed variant of the operand type. 15534 resultType = GetSignedVectorType(resultType); 15535 break; 15536 } else { 15537 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15538 << resultType << Input.get()->getSourceRange()); 15539 } 15540 15541 // LNot always has type int. C99 6.5.3.3p5. 15542 // In C++, it's bool. C++ 5.3.1p8 15543 resultType = Context.getLogicalOperationType(); 15544 break; 15545 case UO_Real: 15546 case UO_Imag: 15547 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 15548 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 15549 // complex l-values to ordinary l-values and all other values to r-values. 15550 if (Input.isInvalid()) return ExprError(); 15551 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 15552 if (Input.get()->isGLValue() && 15553 Input.get()->getObjectKind() == OK_Ordinary) 15554 VK = Input.get()->getValueKind(); 15555 } else if (!getLangOpts().CPlusPlus) { 15556 // In C, a volatile scalar is read by __imag. In C++, it is not. 15557 Input = DefaultLvalueConversion(Input.get()); 15558 } 15559 break; 15560 case UO_Extension: 15561 resultType = Input.get()->getType(); 15562 VK = Input.get()->getValueKind(); 15563 OK = Input.get()->getObjectKind(); 15564 break; 15565 case UO_Coawait: 15566 // It's unnecessary to represent the pass-through operator co_await in the 15567 // AST; just return the input expression instead. 15568 assert(!Input.get()->getType()->isDependentType() && 15569 "the co_await expression must be non-dependant before " 15570 "building operator co_await"); 15571 return Input; 15572 } 15573 if (resultType.isNull() || Input.isInvalid()) 15574 return ExprError(); 15575 15576 // Check for array bounds violations in the operand of the UnaryOperator, 15577 // except for the '*' and '&' operators that have to be handled specially 15578 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15579 // that are explicitly defined as valid by the standard). 15580 if (Opc != UO_AddrOf && Opc != UO_Deref) 15581 CheckArrayAccess(Input.get()); 15582 15583 auto *UO = 15584 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15585 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15586 15587 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15588 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15589 !isUnevaluatedContext()) 15590 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15591 15592 // Convert the result back to a half vector. 15593 if (ConvertHalfVec) 15594 return convertVector(UO, Context.HalfTy, *this); 15595 return UO; 15596 } 15597 15598 /// Determine whether the given expression is a qualified member 15599 /// access expression, of a form that could be turned into a pointer to member 15600 /// with the address-of operator. 15601 bool Sema::isQualifiedMemberAccess(Expr *E) { 15602 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15603 if (!DRE->getQualifier()) 15604 return false; 15605 15606 ValueDecl *VD = DRE->getDecl(); 15607 if (!VD->isCXXClassMember()) 15608 return false; 15609 15610 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15611 return true; 15612 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15613 return Method->isInstance(); 15614 15615 return false; 15616 } 15617 15618 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15619 if (!ULE->getQualifier()) 15620 return false; 15621 15622 for (NamedDecl *D : ULE->decls()) { 15623 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15624 if (Method->isInstance()) 15625 return true; 15626 } else { 15627 // Overload set does not contain methods. 15628 break; 15629 } 15630 } 15631 15632 return false; 15633 } 15634 15635 return false; 15636 } 15637 15638 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15639 UnaryOperatorKind Opc, Expr *Input) { 15640 // First things first: handle placeholders so that the 15641 // overloaded-operator check considers the right type. 15642 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15643 // Increment and decrement of pseudo-object references. 15644 if (pty->getKind() == BuiltinType::PseudoObject && 15645 UnaryOperator::isIncrementDecrementOp(Opc)) 15646 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15647 15648 // extension is always a builtin operator. 15649 if (Opc == UO_Extension) 15650 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15651 15652 // & gets special logic for several kinds of placeholder. 15653 // The builtin code knows what to do. 15654 if (Opc == UO_AddrOf && 15655 (pty->getKind() == BuiltinType::Overload || 15656 pty->getKind() == BuiltinType::UnknownAny || 15657 pty->getKind() == BuiltinType::BoundMember)) 15658 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15659 15660 // Anything else needs to be handled now. 15661 ExprResult Result = CheckPlaceholderExpr(Input); 15662 if (Result.isInvalid()) return ExprError(); 15663 Input = Result.get(); 15664 } 15665 15666 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15667 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15668 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15669 // Find all of the overloaded operators visible from this point. 15670 UnresolvedSet<16> Functions; 15671 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15672 if (S && OverOp != OO_None) 15673 LookupOverloadedOperatorName(OverOp, S, Functions); 15674 15675 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15676 } 15677 15678 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15679 } 15680 15681 // Unary Operators. 'Tok' is the token for the operator. 15682 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15683 tok::TokenKind Op, Expr *Input) { 15684 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15685 } 15686 15687 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15688 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15689 LabelDecl *TheDecl) { 15690 TheDecl->markUsed(Context); 15691 // Create the AST node. The address of a label always has type 'void*'. 15692 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15693 Context.getPointerType(Context.VoidTy)); 15694 } 15695 15696 void Sema::ActOnStartStmtExpr() { 15697 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15698 } 15699 15700 void Sema::ActOnStmtExprError() { 15701 // Note that function is also called by TreeTransform when leaving a 15702 // StmtExpr scope without rebuilding anything. 15703 15704 DiscardCleanupsInEvaluationContext(); 15705 PopExpressionEvaluationContext(); 15706 } 15707 15708 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15709 SourceLocation RPLoc) { 15710 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15711 } 15712 15713 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15714 SourceLocation RPLoc, unsigned TemplateDepth) { 15715 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15716 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15717 15718 if (hasAnyUnrecoverableErrorsInThisFunction()) 15719 DiscardCleanupsInEvaluationContext(); 15720 assert(!Cleanup.exprNeedsCleanups() && 15721 "cleanups within StmtExpr not correctly bound!"); 15722 PopExpressionEvaluationContext(); 15723 15724 // FIXME: there are a variety of strange constraints to enforce here, for 15725 // example, it is not possible to goto into a stmt expression apparently. 15726 // More semantic analysis is needed. 15727 15728 // If there are sub-stmts in the compound stmt, take the type of the last one 15729 // as the type of the stmtexpr. 15730 QualType Ty = Context.VoidTy; 15731 bool StmtExprMayBindToTemp = false; 15732 if (!Compound->body_empty()) { 15733 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15734 if (const auto *LastStmt = 15735 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15736 if (const Expr *Value = LastStmt->getExprStmt()) { 15737 StmtExprMayBindToTemp = true; 15738 Ty = Value->getType(); 15739 } 15740 } 15741 } 15742 15743 // FIXME: Check that expression type is complete/non-abstract; statement 15744 // expressions are not lvalues. 15745 Expr *ResStmtExpr = 15746 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15747 if (StmtExprMayBindToTemp) 15748 return MaybeBindToTemporary(ResStmtExpr); 15749 return ResStmtExpr; 15750 } 15751 15752 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15753 if (ER.isInvalid()) 15754 return ExprError(); 15755 15756 // Do function/array conversion on the last expression, but not 15757 // lvalue-to-rvalue. However, initialize an unqualified type. 15758 ER = DefaultFunctionArrayConversion(ER.get()); 15759 if (ER.isInvalid()) 15760 return ExprError(); 15761 Expr *E = ER.get(); 15762 15763 if (E->isTypeDependent()) 15764 return E; 15765 15766 // In ARC, if the final expression ends in a consume, splice 15767 // the consume out and bind it later. In the alternate case 15768 // (when dealing with a retainable type), the result 15769 // initialization will create a produce. In both cases the 15770 // result will be +1, and we'll need to balance that out with 15771 // a bind. 15772 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15773 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15774 return Cast->getSubExpr(); 15775 15776 // FIXME: Provide a better location for the initialization. 15777 return PerformCopyInitialization( 15778 InitializedEntity::InitializeStmtExprResult( 15779 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15780 SourceLocation(), E); 15781 } 15782 15783 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15784 TypeSourceInfo *TInfo, 15785 ArrayRef<OffsetOfComponent> Components, 15786 SourceLocation RParenLoc) { 15787 QualType ArgTy = TInfo->getType(); 15788 bool Dependent = ArgTy->isDependentType(); 15789 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15790 15791 // We must have at least one component that refers to the type, and the first 15792 // one is known to be a field designator. Verify that the ArgTy represents 15793 // a struct/union/class. 15794 if (!Dependent && !ArgTy->isRecordType()) 15795 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15796 << ArgTy << TypeRange); 15797 15798 // Type must be complete per C99 7.17p3 because a declaring a variable 15799 // with an incomplete type would be ill-formed. 15800 if (!Dependent 15801 && RequireCompleteType(BuiltinLoc, ArgTy, 15802 diag::err_offsetof_incomplete_type, TypeRange)) 15803 return ExprError(); 15804 15805 bool DidWarnAboutNonPOD = false; 15806 QualType CurrentType = ArgTy; 15807 SmallVector<OffsetOfNode, 4> Comps; 15808 SmallVector<Expr*, 4> Exprs; 15809 for (const OffsetOfComponent &OC : Components) { 15810 if (OC.isBrackets) { 15811 // Offset of an array sub-field. TODO: Should we allow vector elements? 15812 if (!CurrentType->isDependentType()) { 15813 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15814 if(!AT) 15815 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15816 << CurrentType); 15817 CurrentType = AT->getElementType(); 15818 } else 15819 CurrentType = Context.DependentTy; 15820 15821 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15822 if (IdxRval.isInvalid()) 15823 return ExprError(); 15824 Expr *Idx = IdxRval.get(); 15825 15826 // The expression must be an integral expression. 15827 // FIXME: An integral constant expression? 15828 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15829 !Idx->getType()->isIntegerType()) 15830 return ExprError( 15831 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15832 << Idx->getSourceRange()); 15833 15834 // Record this array index. 15835 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15836 Exprs.push_back(Idx); 15837 continue; 15838 } 15839 15840 // Offset of a field. 15841 if (CurrentType->isDependentType()) { 15842 // We have the offset of a field, but we can't look into the dependent 15843 // type. Just record the identifier of the field. 15844 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15845 CurrentType = Context.DependentTy; 15846 continue; 15847 } 15848 15849 // We need to have a complete type to look into. 15850 if (RequireCompleteType(OC.LocStart, CurrentType, 15851 diag::err_offsetof_incomplete_type)) 15852 return ExprError(); 15853 15854 // Look for the designated field. 15855 const RecordType *RC = CurrentType->getAs<RecordType>(); 15856 if (!RC) 15857 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15858 << CurrentType); 15859 RecordDecl *RD = RC->getDecl(); 15860 15861 // C++ [lib.support.types]p5: 15862 // The macro offsetof accepts a restricted set of type arguments in this 15863 // International Standard. type shall be a POD structure or a POD union 15864 // (clause 9). 15865 // C++11 [support.types]p4: 15866 // If type is not a standard-layout class (Clause 9), the results are 15867 // undefined. 15868 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15869 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15870 unsigned DiagID = 15871 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15872 : diag::ext_offsetof_non_pod_type; 15873 15874 if (!IsSafe && !DidWarnAboutNonPOD && 15875 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15876 PDiag(DiagID) 15877 << SourceRange(Components[0].LocStart, OC.LocEnd) 15878 << CurrentType)) 15879 DidWarnAboutNonPOD = true; 15880 } 15881 15882 // Look for the field. 15883 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15884 LookupQualifiedName(R, RD); 15885 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15886 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15887 if (!MemberDecl) { 15888 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15889 MemberDecl = IndirectMemberDecl->getAnonField(); 15890 } 15891 15892 if (!MemberDecl) 15893 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15894 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15895 OC.LocEnd)); 15896 15897 // C99 7.17p3: 15898 // (If the specified member is a bit-field, the behavior is undefined.) 15899 // 15900 // We diagnose this as an error. 15901 if (MemberDecl->isBitField()) { 15902 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15903 << MemberDecl->getDeclName() 15904 << SourceRange(BuiltinLoc, RParenLoc); 15905 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15906 return ExprError(); 15907 } 15908 15909 RecordDecl *Parent = MemberDecl->getParent(); 15910 if (IndirectMemberDecl) 15911 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15912 15913 // If the member was found in a base class, introduce OffsetOfNodes for 15914 // the base class indirections. 15915 CXXBasePaths Paths; 15916 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15917 Paths)) { 15918 if (Paths.getDetectedVirtual()) { 15919 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15920 << MemberDecl->getDeclName() 15921 << SourceRange(BuiltinLoc, RParenLoc); 15922 return ExprError(); 15923 } 15924 15925 CXXBasePath &Path = Paths.front(); 15926 for (const CXXBasePathElement &B : Path) 15927 Comps.push_back(OffsetOfNode(B.Base)); 15928 } 15929 15930 if (IndirectMemberDecl) { 15931 for (auto *FI : IndirectMemberDecl->chain()) { 15932 assert(isa<FieldDecl>(FI)); 15933 Comps.push_back(OffsetOfNode(OC.LocStart, 15934 cast<FieldDecl>(FI), OC.LocEnd)); 15935 } 15936 } else 15937 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15938 15939 CurrentType = MemberDecl->getType().getNonReferenceType(); 15940 } 15941 15942 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15943 Comps, Exprs, RParenLoc); 15944 } 15945 15946 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15947 SourceLocation BuiltinLoc, 15948 SourceLocation TypeLoc, 15949 ParsedType ParsedArgTy, 15950 ArrayRef<OffsetOfComponent> Components, 15951 SourceLocation RParenLoc) { 15952 15953 TypeSourceInfo *ArgTInfo; 15954 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15955 if (ArgTy.isNull()) 15956 return ExprError(); 15957 15958 if (!ArgTInfo) 15959 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15960 15961 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15962 } 15963 15964 15965 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15966 Expr *CondExpr, 15967 Expr *LHSExpr, Expr *RHSExpr, 15968 SourceLocation RPLoc) { 15969 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15970 15971 ExprValueKind VK = VK_PRValue; 15972 ExprObjectKind OK = OK_Ordinary; 15973 QualType resType; 15974 bool CondIsTrue = false; 15975 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15976 resType = Context.DependentTy; 15977 } else { 15978 // The conditional expression is required to be a constant expression. 15979 llvm::APSInt condEval(32); 15980 ExprResult CondICE = VerifyIntegerConstantExpression( 15981 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15982 if (CondICE.isInvalid()) 15983 return ExprError(); 15984 CondExpr = CondICE.get(); 15985 CondIsTrue = condEval.getZExtValue(); 15986 15987 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15988 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15989 15990 resType = ActiveExpr->getType(); 15991 VK = ActiveExpr->getValueKind(); 15992 OK = ActiveExpr->getObjectKind(); 15993 } 15994 15995 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15996 resType, VK, OK, RPLoc, CondIsTrue); 15997 } 15998 15999 //===----------------------------------------------------------------------===// 16000 // Clang Extensions. 16001 //===----------------------------------------------------------------------===// 16002 16003 /// ActOnBlockStart - This callback is invoked when a block literal is started. 16004 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 16005 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 16006 16007 if (LangOpts.CPlusPlus) { 16008 MangleNumberingContext *MCtx; 16009 Decl *ManglingContextDecl; 16010 std::tie(MCtx, ManglingContextDecl) = 16011 getCurrentMangleNumberContext(Block->getDeclContext()); 16012 if (MCtx) { 16013 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 16014 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 16015 } 16016 } 16017 16018 PushBlockScope(CurScope, Block); 16019 CurContext->addDecl(Block); 16020 if (CurScope) 16021 PushDeclContext(CurScope, Block); 16022 else 16023 CurContext = Block; 16024 16025 getCurBlock()->HasImplicitReturnType = true; 16026 16027 // Enter a new evaluation context to insulate the block from any 16028 // cleanups from the enclosing full-expression. 16029 PushExpressionEvaluationContext( 16030 ExpressionEvaluationContext::PotentiallyEvaluated); 16031 } 16032 16033 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 16034 Scope *CurScope) { 16035 assert(ParamInfo.getIdentifier() == nullptr && 16036 "block-id should have no identifier!"); 16037 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 16038 BlockScopeInfo *CurBlock = getCurBlock(); 16039 16040 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 16041 QualType T = Sig->getType(); 16042 16043 // FIXME: We should allow unexpanded parameter packs here, but that would, 16044 // in turn, make the block expression contain unexpanded parameter packs. 16045 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 16046 // Drop the parameters. 16047 FunctionProtoType::ExtProtoInfo EPI; 16048 EPI.HasTrailingReturn = false; 16049 EPI.TypeQuals.addConst(); 16050 T = Context.getFunctionType(Context.DependentTy, None, EPI); 16051 Sig = Context.getTrivialTypeSourceInfo(T); 16052 } 16053 16054 // GetTypeForDeclarator always produces a function type for a block 16055 // literal signature. Furthermore, it is always a FunctionProtoType 16056 // unless the function was written with a typedef. 16057 assert(T->isFunctionType() && 16058 "GetTypeForDeclarator made a non-function block signature"); 16059 16060 // Look for an explicit signature in that function type. 16061 FunctionProtoTypeLoc ExplicitSignature; 16062 16063 if ((ExplicitSignature = Sig->getTypeLoc() 16064 .getAsAdjusted<FunctionProtoTypeLoc>())) { 16065 16066 // Check whether that explicit signature was synthesized by 16067 // GetTypeForDeclarator. If so, don't save that as part of the 16068 // written signature. 16069 if (ExplicitSignature.getLocalRangeBegin() == 16070 ExplicitSignature.getLocalRangeEnd()) { 16071 // This would be much cheaper if we stored TypeLocs instead of 16072 // TypeSourceInfos. 16073 TypeLoc Result = ExplicitSignature.getReturnLoc(); 16074 unsigned Size = Result.getFullDataSize(); 16075 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 16076 Sig->getTypeLoc().initializeFullCopy(Result, Size); 16077 16078 ExplicitSignature = FunctionProtoTypeLoc(); 16079 } 16080 } 16081 16082 CurBlock->TheDecl->setSignatureAsWritten(Sig); 16083 CurBlock->FunctionType = T; 16084 16085 const auto *Fn = T->castAs<FunctionType>(); 16086 QualType RetTy = Fn->getReturnType(); 16087 bool isVariadic = 16088 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 16089 16090 CurBlock->TheDecl->setIsVariadic(isVariadic); 16091 16092 // Context.DependentTy is used as a placeholder for a missing block 16093 // return type. TODO: what should we do with declarators like: 16094 // ^ * { ... } 16095 // If the answer is "apply template argument deduction".... 16096 if (RetTy != Context.DependentTy) { 16097 CurBlock->ReturnType = RetTy; 16098 CurBlock->TheDecl->setBlockMissingReturnType(false); 16099 CurBlock->HasImplicitReturnType = false; 16100 } 16101 16102 // Push block parameters from the declarator if we had them. 16103 SmallVector<ParmVarDecl*, 8> Params; 16104 if (ExplicitSignature) { 16105 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 16106 ParmVarDecl *Param = ExplicitSignature.getParam(I); 16107 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 16108 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 16109 // Diagnose this as an extension in C17 and earlier. 16110 if (!getLangOpts().C2x) 16111 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 16112 } 16113 Params.push_back(Param); 16114 } 16115 16116 // Fake up parameter variables if we have a typedef, like 16117 // ^ fntype { ... } 16118 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 16119 for (const auto &I : Fn->param_types()) { 16120 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 16121 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 16122 Params.push_back(Param); 16123 } 16124 } 16125 16126 // Set the parameters on the block decl. 16127 if (!Params.empty()) { 16128 CurBlock->TheDecl->setParams(Params); 16129 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 16130 /*CheckParameterNames=*/false); 16131 } 16132 16133 // Finally we can process decl attributes. 16134 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 16135 16136 // Put the parameter variables in scope. 16137 for (auto AI : CurBlock->TheDecl->parameters()) { 16138 AI->setOwningFunction(CurBlock->TheDecl); 16139 16140 // If this has an identifier, add it to the scope stack. 16141 if (AI->getIdentifier()) { 16142 CheckShadow(CurBlock->TheScope, AI); 16143 16144 PushOnScopeChains(AI, CurBlock->TheScope); 16145 } 16146 } 16147 } 16148 16149 /// ActOnBlockError - If there is an error parsing a block, this callback 16150 /// is invoked to pop the information about the block from the action impl. 16151 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 16152 // Leave the expression-evaluation context. 16153 DiscardCleanupsInEvaluationContext(); 16154 PopExpressionEvaluationContext(); 16155 16156 // Pop off CurBlock, handle nested blocks. 16157 PopDeclContext(); 16158 PopFunctionScopeInfo(); 16159 } 16160 16161 /// ActOnBlockStmtExpr - This is called when the body of a block statement 16162 /// literal was successfully completed. ^(int x){...} 16163 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 16164 Stmt *Body, Scope *CurScope) { 16165 // If blocks are disabled, emit an error. 16166 if (!LangOpts.Blocks) 16167 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 16168 16169 // Leave the expression-evaluation context. 16170 if (hasAnyUnrecoverableErrorsInThisFunction()) 16171 DiscardCleanupsInEvaluationContext(); 16172 assert(!Cleanup.exprNeedsCleanups() && 16173 "cleanups within block not correctly bound!"); 16174 PopExpressionEvaluationContext(); 16175 16176 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 16177 BlockDecl *BD = BSI->TheDecl; 16178 16179 if (BSI->HasImplicitReturnType) 16180 deduceClosureReturnType(*BSI); 16181 16182 QualType RetTy = Context.VoidTy; 16183 if (!BSI->ReturnType.isNull()) 16184 RetTy = BSI->ReturnType; 16185 16186 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 16187 QualType BlockTy; 16188 16189 // If the user wrote a function type in some form, try to use that. 16190 if (!BSI->FunctionType.isNull()) { 16191 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 16192 16193 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 16194 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 16195 16196 // Turn protoless block types into nullary block types. 16197 if (isa<FunctionNoProtoType>(FTy)) { 16198 FunctionProtoType::ExtProtoInfo EPI; 16199 EPI.ExtInfo = Ext; 16200 BlockTy = Context.getFunctionType(RetTy, None, EPI); 16201 16202 // Otherwise, if we don't need to change anything about the function type, 16203 // preserve its sugar structure. 16204 } else if (FTy->getReturnType() == RetTy && 16205 (!NoReturn || FTy->getNoReturnAttr())) { 16206 BlockTy = BSI->FunctionType; 16207 16208 // Otherwise, make the minimal modifications to the function type. 16209 } else { 16210 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 16211 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 16212 EPI.TypeQuals = Qualifiers(); 16213 EPI.ExtInfo = Ext; 16214 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 16215 } 16216 16217 // If we don't have a function type, just build one from nothing. 16218 } else { 16219 FunctionProtoType::ExtProtoInfo EPI; 16220 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 16221 BlockTy = Context.getFunctionType(RetTy, None, EPI); 16222 } 16223 16224 DiagnoseUnusedParameters(BD->parameters()); 16225 BlockTy = Context.getBlockPointerType(BlockTy); 16226 16227 // If needed, diagnose invalid gotos and switches in the block. 16228 if (getCurFunction()->NeedsScopeChecking() && 16229 !PP.isCodeCompletionEnabled()) 16230 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 16231 16232 BD->setBody(cast<CompoundStmt>(Body)); 16233 16234 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 16235 DiagnoseUnguardedAvailabilityViolations(BD); 16236 16237 // Try to apply the named return value optimization. We have to check again 16238 // if we can do this, though, because blocks keep return statements around 16239 // to deduce an implicit return type. 16240 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 16241 !BD->isDependentContext()) 16242 computeNRVO(Body, BSI); 16243 16244 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 16245 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 16246 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 16247 NTCUK_Destruct|NTCUK_Copy); 16248 16249 PopDeclContext(); 16250 16251 // Set the captured variables on the block. 16252 SmallVector<BlockDecl::Capture, 4> Captures; 16253 for (Capture &Cap : BSI->Captures) { 16254 if (Cap.isInvalid() || Cap.isThisCapture()) 16255 continue; 16256 16257 VarDecl *Var = Cap.getVariable(); 16258 Expr *CopyExpr = nullptr; 16259 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 16260 if (const RecordType *Record = 16261 Cap.getCaptureType()->getAs<RecordType>()) { 16262 // The capture logic needs the destructor, so make sure we mark it. 16263 // Usually this is unnecessary because most local variables have 16264 // their destructors marked at declaration time, but parameters are 16265 // an exception because it's technically only the call site that 16266 // actually requires the destructor. 16267 if (isa<ParmVarDecl>(Var)) 16268 FinalizeVarWithDestructor(Var, Record); 16269 16270 // Enter a separate potentially-evaluated context while building block 16271 // initializers to isolate their cleanups from those of the block 16272 // itself. 16273 // FIXME: Is this appropriate even when the block itself occurs in an 16274 // unevaluated operand? 16275 EnterExpressionEvaluationContext EvalContext( 16276 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16277 16278 SourceLocation Loc = Cap.getLocation(); 16279 16280 ExprResult Result = BuildDeclarationNameExpr( 16281 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 16282 16283 // According to the blocks spec, the capture of a variable from 16284 // the stack requires a const copy constructor. This is not true 16285 // of the copy/move done to move a __block variable to the heap. 16286 if (!Result.isInvalid() && 16287 !Result.get()->getType().isConstQualified()) { 16288 Result = ImpCastExprToType(Result.get(), 16289 Result.get()->getType().withConst(), 16290 CK_NoOp, VK_LValue); 16291 } 16292 16293 if (!Result.isInvalid()) { 16294 Result = PerformCopyInitialization( 16295 InitializedEntity::InitializeBlock(Var->getLocation(), 16296 Cap.getCaptureType()), 16297 Loc, Result.get()); 16298 } 16299 16300 // Build a full-expression copy expression if initialization 16301 // succeeded and used a non-trivial constructor. Recover from 16302 // errors by pretending that the copy isn't necessary. 16303 if (!Result.isInvalid() && 16304 !cast<CXXConstructExpr>(Result.get())->getConstructor() 16305 ->isTrivial()) { 16306 Result = MaybeCreateExprWithCleanups(Result); 16307 CopyExpr = Result.get(); 16308 } 16309 } 16310 } 16311 16312 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 16313 CopyExpr); 16314 Captures.push_back(NewCap); 16315 } 16316 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 16317 16318 // Pop the block scope now but keep it alive to the end of this function. 16319 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 16320 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 16321 16322 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 16323 16324 // If the block isn't obviously global, i.e. it captures anything at 16325 // all, then we need to do a few things in the surrounding context: 16326 if (Result->getBlockDecl()->hasCaptures()) { 16327 // First, this expression has a new cleanup object. 16328 ExprCleanupObjects.push_back(Result->getBlockDecl()); 16329 Cleanup.setExprNeedsCleanups(true); 16330 16331 // It also gets a branch-protected scope if any of the captured 16332 // variables needs destruction. 16333 for (const auto &CI : Result->getBlockDecl()->captures()) { 16334 const VarDecl *var = CI.getVariable(); 16335 if (var->getType().isDestructedType() != QualType::DK_none) { 16336 setFunctionHasBranchProtectedScope(); 16337 break; 16338 } 16339 } 16340 } 16341 16342 if (getCurFunction()) 16343 getCurFunction()->addBlock(BD); 16344 16345 return Result; 16346 } 16347 16348 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 16349 SourceLocation RPLoc) { 16350 TypeSourceInfo *TInfo; 16351 GetTypeFromParser(Ty, &TInfo); 16352 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 16353 } 16354 16355 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 16356 Expr *E, TypeSourceInfo *TInfo, 16357 SourceLocation RPLoc) { 16358 Expr *OrigExpr = E; 16359 bool IsMS = false; 16360 16361 // CUDA device code does not support varargs. 16362 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 16363 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 16364 CUDAFunctionTarget T = IdentifyCUDATarget(F); 16365 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 16366 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 16367 } 16368 } 16369 16370 // NVPTX does not support va_arg expression. 16371 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 16372 Context.getTargetInfo().getTriple().isNVPTX()) 16373 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 16374 16375 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 16376 // as Microsoft ABI on an actual Microsoft platform, where 16377 // __builtin_ms_va_list and __builtin_va_list are the same.) 16378 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 16379 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 16380 QualType MSVaListType = Context.getBuiltinMSVaListType(); 16381 if (Context.hasSameType(MSVaListType, E->getType())) { 16382 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16383 return ExprError(); 16384 IsMS = true; 16385 } 16386 } 16387 16388 // Get the va_list type 16389 QualType VaListType = Context.getBuiltinVaListType(); 16390 if (!IsMS) { 16391 if (VaListType->isArrayType()) { 16392 // Deal with implicit array decay; for example, on x86-64, 16393 // va_list is an array, but it's supposed to decay to 16394 // a pointer for va_arg. 16395 VaListType = Context.getArrayDecayedType(VaListType); 16396 // Make sure the input expression also decays appropriately. 16397 ExprResult Result = UsualUnaryConversions(E); 16398 if (Result.isInvalid()) 16399 return ExprError(); 16400 E = Result.get(); 16401 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 16402 // If va_list is a record type and we are compiling in C++ mode, 16403 // check the argument using reference binding. 16404 InitializedEntity Entity = InitializedEntity::InitializeParameter( 16405 Context, Context.getLValueReferenceType(VaListType), false); 16406 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 16407 if (Init.isInvalid()) 16408 return ExprError(); 16409 E = Init.getAs<Expr>(); 16410 } else { 16411 // Otherwise, the va_list argument must be an l-value because 16412 // it is modified by va_arg. 16413 if (!E->isTypeDependent() && 16414 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16415 return ExprError(); 16416 } 16417 } 16418 16419 if (!IsMS && !E->isTypeDependent() && 16420 !Context.hasSameType(VaListType, E->getType())) 16421 return ExprError( 16422 Diag(E->getBeginLoc(), 16423 diag::err_first_argument_to_va_arg_not_of_type_va_list) 16424 << OrigExpr->getType() << E->getSourceRange()); 16425 16426 if (!TInfo->getType()->isDependentType()) { 16427 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 16428 diag::err_second_parameter_to_va_arg_incomplete, 16429 TInfo->getTypeLoc())) 16430 return ExprError(); 16431 16432 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 16433 TInfo->getType(), 16434 diag::err_second_parameter_to_va_arg_abstract, 16435 TInfo->getTypeLoc())) 16436 return ExprError(); 16437 16438 if (!TInfo->getType().isPODType(Context)) { 16439 Diag(TInfo->getTypeLoc().getBeginLoc(), 16440 TInfo->getType()->isObjCLifetimeType() 16441 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 16442 : diag::warn_second_parameter_to_va_arg_not_pod) 16443 << TInfo->getType() 16444 << TInfo->getTypeLoc().getSourceRange(); 16445 } 16446 16447 // Check for va_arg where arguments of the given type will be promoted 16448 // (i.e. this va_arg is guaranteed to have undefined behavior). 16449 QualType PromoteType; 16450 if (TInfo->getType()->isPromotableIntegerType()) { 16451 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 16452 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 16453 // and C2x 7.16.1.1p2 says, in part: 16454 // If type is not compatible with the type of the actual next argument 16455 // (as promoted according to the default argument promotions), the 16456 // behavior is undefined, except for the following cases: 16457 // - both types are pointers to qualified or unqualified versions of 16458 // compatible types; 16459 // - one type is a signed integer type, the other type is the 16460 // corresponding unsigned integer type, and the value is 16461 // representable in both types; 16462 // - one type is pointer to qualified or unqualified void and the 16463 // other is a pointer to a qualified or unqualified character type. 16464 // Given that type compatibility is the primary requirement (ignoring 16465 // qualifications), you would think we could call typesAreCompatible() 16466 // directly to test this. However, in C++, that checks for *same type*, 16467 // which causes false positives when passing an enumeration type to 16468 // va_arg. Instead, get the underlying type of the enumeration and pass 16469 // that. 16470 QualType UnderlyingType = TInfo->getType(); 16471 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 16472 UnderlyingType = ET->getDecl()->getIntegerType(); 16473 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16474 /*CompareUnqualified*/ true)) 16475 PromoteType = QualType(); 16476 16477 // If the types are still not compatible, we need to test whether the 16478 // promoted type and the underlying type are the same except for 16479 // signedness. Ask the AST for the correctly corresponding type and see 16480 // if that's compatible. 16481 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && 16482 PromoteType->isUnsignedIntegerType() != 16483 UnderlyingType->isUnsignedIntegerType()) { 16484 UnderlyingType = 16485 UnderlyingType->isUnsignedIntegerType() 16486 ? Context.getCorrespondingSignedType(UnderlyingType) 16487 : Context.getCorrespondingUnsignedType(UnderlyingType); 16488 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16489 /*CompareUnqualified*/ true)) 16490 PromoteType = QualType(); 16491 } 16492 } 16493 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 16494 PromoteType = Context.DoubleTy; 16495 if (!PromoteType.isNull()) 16496 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 16497 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 16498 << TInfo->getType() 16499 << PromoteType 16500 << TInfo->getTypeLoc().getSourceRange()); 16501 } 16502 16503 QualType T = TInfo->getType().getNonLValueExprType(Context); 16504 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 16505 } 16506 16507 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 16508 // The type of __null will be int or long, depending on the size of 16509 // pointers on the target. 16510 QualType Ty; 16511 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 16512 if (pw == Context.getTargetInfo().getIntWidth()) 16513 Ty = Context.IntTy; 16514 else if (pw == Context.getTargetInfo().getLongWidth()) 16515 Ty = Context.LongTy; 16516 else if (pw == Context.getTargetInfo().getLongLongWidth()) 16517 Ty = Context.LongLongTy; 16518 else { 16519 llvm_unreachable("I don't know size of pointer!"); 16520 } 16521 16522 return new (Context) GNUNullExpr(Ty, TokenLoc); 16523 } 16524 16525 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { 16526 CXXRecordDecl *ImplDecl = nullptr; 16527 16528 // Fetch the std::source_location::__impl decl. 16529 if (NamespaceDecl *Std = S.getStdNamespace()) { 16530 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"), 16531 Loc, Sema::LookupOrdinaryName); 16532 if (S.LookupQualifiedName(ResultSL, Std)) { 16533 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { 16534 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"), 16535 Loc, Sema::LookupOrdinaryName); 16536 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && 16537 S.LookupQualifiedName(ResultImpl, SLDecl)) { 16538 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); 16539 } 16540 } 16541 } 16542 } 16543 16544 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { 16545 S.Diag(Loc, diag::err_std_source_location_impl_not_found); 16546 return nullptr; 16547 } 16548 16549 // Verify that __impl is a trivial struct type, with no base classes, and with 16550 // only the four expected fields. 16551 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || 16552 ImplDecl->getNumBases() != 0) { 16553 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 16554 return nullptr; 16555 } 16556 16557 unsigned Count = 0; 16558 for (FieldDecl *F : ImplDecl->fields()) { 16559 StringRef Name = F->getName(); 16560 16561 if (Name == "_M_file_name") { 16562 if (F->getType() != 16563 S.Context.getPointerType(S.Context.CharTy.withConst())) 16564 break; 16565 Count++; 16566 } else if (Name == "_M_function_name") { 16567 if (F->getType() != 16568 S.Context.getPointerType(S.Context.CharTy.withConst())) 16569 break; 16570 Count++; 16571 } else if (Name == "_M_line") { 16572 if (!F->getType()->isIntegerType()) 16573 break; 16574 Count++; 16575 } else if (Name == "_M_column") { 16576 if (!F->getType()->isIntegerType()) 16577 break; 16578 Count++; 16579 } else { 16580 Count = 100; // invalid 16581 break; 16582 } 16583 } 16584 if (Count != 4) { 16585 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 16586 return nullptr; 16587 } 16588 16589 return ImplDecl; 16590 } 16591 16592 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 16593 SourceLocation BuiltinLoc, 16594 SourceLocation RPLoc) { 16595 QualType ResultTy; 16596 switch (Kind) { 16597 case SourceLocExpr::File: 16598 case SourceLocExpr::Function: { 16599 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0); 16600 ResultTy = 16601 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType()); 16602 break; 16603 } 16604 case SourceLocExpr::Line: 16605 case SourceLocExpr::Column: 16606 ResultTy = Context.UnsignedIntTy; 16607 break; 16608 case SourceLocExpr::SourceLocStruct: 16609 if (!StdSourceLocationImplDecl) { 16610 StdSourceLocationImplDecl = 16611 LookupStdSourceLocationImpl(*this, BuiltinLoc); 16612 if (!StdSourceLocationImplDecl) 16613 return ExprError(); 16614 } 16615 ResultTy = Context.getPointerType( 16616 Context.getRecordType(StdSourceLocationImplDecl).withConst()); 16617 break; 16618 } 16619 16620 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext); 16621 } 16622 16623 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 16624 QualType ResultTy, 16625 SourceLocation BuiltinLoc, 16626 SourceLocation RPLoc, 16627 DeclContext *ParentContext) { 16628 return new (Context) 16629 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); 16630 } 16631 16632 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 16633 bool Diagnose) { 16634 if (!getLangOpts().ObjC) 16635 return false; 16636 16637 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 16638 if (!PT) 16639 return false; 16640 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 16641 16642 // Ignore any parens, implicit casts (should only be 16643 // array-to-pointer decays), and not-so-opaque values. The last is 16644 // important for making this trigger for property assignments. 16645 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 16646 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 16647 if (OV->getSourceExpr()) 16648 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 16649 16650 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 16651 if (!PT->isObjCIdType() && 16652 !(ID && ID->getIdentifier()->isStr("NSString"))) 16653 return false; 16654 if (!SL->isAscii()) 16655 return false; 16656 16657 if (Diagnose) { 16658 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 16659 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 16660 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 16661 } 16662 return true; 16663 } 16664 16665 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16666 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16667 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16668 !SrcExpr->isNullPointerConstant( 16669 getASTContext(), Expr::NPC_NeverValueDependent)) { 16670 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16671 return false; 16672 if (Diagnose) { 16673 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16674 << /*number*/1 16675 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16676 Expr *NumLit = 16677 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16678 if (NumLit) 16679 Exp = NumLit; 16680 } 16681 return true; 16682 } 16683 16684 return false; 16685 } 16686 16687 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16688 const Expr *SrcExpr) { 16689 if (!DstType->isFunctionPointerType() || 16690 !SrcExpr->getType()->isFunctionType()) 16691 return false; 16692 16693 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16694 if (!DRE) 16695 return false; 16696 16697 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16698 if (!FD) 16699 return false; 16700 16701 return !S.checkAddressOfFunctionIsAvailable(FD, 16702 /*Complain=*/true, 16703 SrcExpr->getBeginLoc()); 16704 } 16705 16706 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16707 SourceLocation Loc, 16708 QualType DstType, QualType SrcType, 16709 Expr *SrcExpr, AssignmentAction Action, 16710 bool *Complained) { 16711 if (Complained) 16712 *Complained = false; 16713 16714 // Decode the result (notice that AST's are still created for extensions). 16715 bool CheckInferredResultType = false; 16716 bool isInvalid = false; 16717 unsigned DiagKind = 0; 16718 ConversionFixItGenerator ConvHints; 16719 bool MayHaveConvFixit = false; 16720 bool MayHaveFunctionDiff = false; 16721 const ObjCInterfaceDecl *IFace = nullptr; 16722 const ObjCProtocolDecl *PDecl = nullptr; 16723 16724 switch (ConvTy) { 16725 case Compatible: 16726 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16727 return false; 16728 16729 case PointerToInt: 16730 if (getLangOpts().CPlusPlus) { 16731 DiagKind = diag::err_typecheck_convert_pointer_int; 16732 isInvalid = true; 16733 } else { 16734 DiagKind = diag::ext_typecheck_convert_pointer_int; 16735 } 16736 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16737 MayHaveConvFixit = true; 16738 break; 16739 case IntToPointer: 16740 if (getLangOpts().CPlusPlus) { 16741 DiagKind = diag::err_typecheck_convert_int_pointer; 16742 isInvalid = true; 16743 } else { 16744 DiagKind = diag::ext_typecheck_convert_int_pointer; 16745 } 16746 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16747 MayHaveConvFixit = true; 16748 break; 16749 case IncompatibleFunctionPointer: 16750 if (getLangOpts().CPlusPlus) { 16751 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16752 isInvalid = true; 16753 } else { 16754 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16755 } 16756 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16757 MayHaveConvFixit = true; 16758 break; 16759 case IncompatiblePointer: 16760 if (Action == AA_Passing_CFAudited) { 16761 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16762 } else if (getLangOpts().CPlusPlus) { 16763 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16764 isInvalid = true; 16765 } else { 16766 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16767 } 16768 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16769 SrcType->isObjCObjectPointerType(); 16770 if (!CheckInferredResultType) { 16771 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16772 } else if (CheckInferredResultType) { 16773 SrcType = SrcType.getUnqualifiedType(); 16774 DstType = DstType.getUnqualifiedType(); 16775 } 16776 MayHaveConvFixit = true; 16777 break; 16778 case IncompatiblePointerSign: 16779 if (getLangOpts().CPlusPlus) { 16780 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16781 isInvalid = true; 16782 } else { 16783 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16784 } 16785 break; 16786 case FunctionVoidPointer: 16787 if (getLangOpts().CPlusPlus) { 16788 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16789 isInvalid = true; 16790 } else { 16791 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16792 } 16793 break; 16794 case IncompatiblePointerDiscardsQualifiers: { 16795 // Perform array-to-pointer decay if necessary. 16796 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16797 16798 isInvalid = true; 16799 16800 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16801 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16802 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16803 DiagKind = diag::err_typecheck_incompatible_address_space; 16804 break; 16805 16806 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16807 DiagKind = diag::err_typecheck_incompatible_ownership; 16808 break; 16809 } 16810 16811 llvm_unreachable("unknown error case for discarding qualifiers!"); 16812 // fallthrough 16813 } 16814 case CompatiblePointerDiscardsQualifiers: 16815 // If the qualifiers lost were because we were applying the 16816 // (deprecated) C++ conversion from a string literal to a char* 16817 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16818 // Ideally, this check would be performed in 16819 // checkPointerTypesForAssignment. However, that would require a 16820 // bit of refactoring (so that the second argument is an 16821 // expression, rather than a type), which should be done as part 16822 // of a larger effort to fix checkPointerTypesForAssignment for 16823 // C++ semantics. 16824 if (getLangOpts().CPlusPlus && 16825 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16826 return false; 16827 if (getLangOpts().CPlusPlus) { 16828 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16829 isInvalid = true; 16830 } else { 16831 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16832 } 16833 16834 break; 16835 case IncompatibleNestedPointerQualifiers: 16836 if (getLangOpts().CPlusPlus) { 16837 isInvalid = true; 16838 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16839 } else { 16840 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16841 } 16842 break; 16843 case IncompatibleNestedPointerAddressSpaceMismatch: 16844 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16845 isInvalid = true; 16846 break; 16847 case IntToBlockPointer: 16848 DiagKind = diag::err_int_to_block_pointer; 16849 isInvalid = true; 16850 break; 16851 case IncompatibleBlockPointer: 16852 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16853 isInvalid = true; 16854 break; 16855 case IncompatibleObjCQualifiedId: { 16856 if (SrcType->isObjCQualifiedIdType()) { 16857 const ObjCObjectPointerType *srcOPT = 16858 SrcType->castAs<ObjCObjectPointerType>(); 16859 for (auto *srcProto : srcOPT->quals()) { 16860 PDecl = srcProto; 16861 break; 16862 } 16863 if (const ObjCInterfaceType *IFaceT = 16864 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16865 IFace = IFaceT->getDecl(); 16866 } 16867 else if (DstType->isObjCQualifiedIdType()) { 16868 const ObjCObjectPointerType *dstOPT = 16869 DstType->castAs<ObjCObjectPointerType>(); 16870 for (auto *dstProto : dstOPT->quals()) { 16871 PDecl = dstProto; 16872 break; 16873 } 16874 if (const ObjCInterfaceType *IFaceT = 16875 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16876 IFace = IFaceT->getDecl(); 16877 } 16878 if (getLangOpts().CPlusPlus) { 16879 DiagKind = diag::err_incompatible_qualified_id; 16880 isInvalid = true; 16881 } else { 16882 DiagKind = diag::warn_incompatible_qualified_id; 16883 } 16884 break; 16885 } 16886 case IncompatibleVectors: 16887 if (getLangOpts().CPlusPlus) { 16888 DiagKind = diag::err_incompatible_vectors; 16889 isInvalid = true; 16890 } else { 16891 DiagKind = diag::warn_incompatible_vectors; 16892 } 16893 break; 16894 case IncompatibleObjCWeakRef: 16895 DiagKind = diag::err_arc_weak_unavailable_assign; 16896 isInvalid = true; 16897 break; 16898 case Incompatible: 16899 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16900 if (Complained) 16901 *Complained = true; 16902 return true; 16903 } 16904 16905 DiagKind = diag::err_typecheck_convert_incompatible; 16906 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16907 MayHaveConvFixit = true; 16908 isInvalid = true; 16909 MayHaveFunctionDiff = true; 16910 break; 16911 } 16912 16913 QualType FirstType, SecondType; 16914 switch (Action) { 16915 case AA_Assigning: 16916 case AA_Initializing: 16917 // The destination type comes first. 16918 FirstType = DstType; 16919 SecondType = SrcType; 16920 break; 16921 16922 case AA_Returning: 16923 case AA_Passing: 16924 case AA_Passing_CFAudited: 16925 case AA_Converting: 16926 case AA_Sending: 16927 case AA_Casting: 16928 // The source type comes first. 16929 FirstType = SrcType; 16930 SecondType = DstType; 16931 break; 16932 } 16933 16934 PartialDiagnostic FDiag = PDiag(DiagKind); 16935 AssignmentAction ActionForDiag = Action; 16936 if (Action == AA_Passing_CFAudited) 16937 ActionForDiag = AA_Passing; 16938 16939 FDiag << FirstType << SecondType << ActionForDiag 16940 << SrcExpr->getSourceRange(); 16941 16942 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16943 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16944 auto isPlainChar = [](const clang::Type *Type) { 16945 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16946 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16947 }; 16948 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16949 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16950 } 16951 16952 // If we can fix the conversion, suggest the FixIts. 16953 if (!ConvHints.isNull()) { 16954 for (FixItHint &H : ConvHints.Hints) 16955 FDiag << H; 16956 } 16957 16958 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16959 16960 if (MayHaveFunctionDiff) 16961 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16962 16963 Diag(Loc, FDiag); 16964 if ((DiagKind == diag::warn_incompatible_qualified_id || 16965 DiagKind == diag::err_incompatible_qualified_id) && 16966 PDecl && IFace && !IFace->hasDefinition()) 16967 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16968 << IFace << PDecl; 16969 16970 if (SecondType == Context.OverloadTy) 16971 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16972 FirstType, /*TakingAddress=*/true); 16973 16974 if (CheckInferredResultType) 16975 EmitRelatedResultTypeNote(SrcExpr); 16976 16977 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16978 EmitRelatedResultTypeNoteForReturn(DstType); 16979 16980 if (Complained) 16981 *Complained = true; 16982 return isInvalid; 16983 } 16984 16985 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16986 llvm::APSInt *Result, 16987 AllowFoldKind CanFold) { 16988 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16989 public: 16990 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16991 QualType T) override { 16992 return S.Diag(Loc, diag::err_ice_not_integral) 16993 << T << S.LangOpts.CPlusPlus; 16994 } 16995 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16996 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16997 } 16998 } Diagnoser; 16999 17000 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 17001 } 17002 17003 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 17004 llvm::APSInt *Result, 17005 unsigned DiagID, 17006 AllowFoldKind CanFold) { 17007 class IDDiagnoser : public VerifyICEDiagnoser { 17008 unsigned DiagID; 17009 17010 public: 17011 IDDiagnoser(unsigned DiagID) 17012 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 17013 17014 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 17015 return S.Diag(Loc, DiagID); 17016 } 17017 } Diagnoser(DiagID); 17018 17019 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 17020 } 17021 17022 Sema::SemaDiagnosticBuilder 17023 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 17024 QualType T) { 17025 return diagnoseNotICE(S, Loc); 17026 } 17027 17028 Sema::SemaDiagnosticBuilder 17029 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 17030 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 17031 } 17032 17033 ExprResult 17034 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 17035 VerifyICEDiagnoser &Diagnoser, 17036 AllowFoldKind CanFold) { 17037 SourceLocation DiagLoc = E->getBeginLoc(); 17038 17039 if (getLangOpts().CPlusPlus11) { 17040 // C++11 [expr.const]p5: 17041 // If an expression of literal class type is used in a context where an 17042 // integral constant expression is required, then that class type shall 17043 // have a single non-explicit conversion function to an integral or 17044 // unscoped enumeration type 17045 ExprResult Converted; 17046 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 17047 VerifyICEDiagnoser &BaseDiagnoser; 17048 public: 17049 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 17050 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 17051 BaseDiagnoser.Suppress, true), 17052 BaseDiagnoser(BaseDiagnoser) {} 17053 17054 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 17055 QualType T) override { 17056 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 17057 } 17058 17059 SemaDiagnosticBuilder diagnoseIncomplete( 17060 Sema &S, SourceLocation Loc, QualType T) override { 17061 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 17062 } 17063 17064 SemaDiagnosticBuilder diagnoseExplicitConv( 17065 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 17066 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 17067 } 17068 17069 SemaDiagnosticBuilder noteExplicitConv( 17070 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 17071 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 17072 << ConvTy->isEnumeralType() << ConvTy; 17073 } 17074 17075 SemaDiagnosticBuilder diagnoseAmbiguous( 17076 Sema &S, SourceLocation Loc, QualType T) override { 17077 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 17078 } 17079 17080 SemaDiagnosticBuilder noteAmbiguous( 17081 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 17082 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 17083 << ConvTy->isEnumeralType() << ConvTy; 17084 } 17085 17086 SemaDiagnosticBuilder diagnoseConversion( 17087 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 17088 llvm_unreachable("conversion functions are permitted"); 17089 } 17090 } ConvertDiagnoser(Diagnoser); 17091 17092 Converted = PerformContextualImplicitConversion(DiagLoc, E, 17093 ConvertDiagnoser); 17094 if (Converted.isInvalid()) 17095 return Converted; 17096 E = Converted.get(); 17097 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 17098 return ExprError(); 17099 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 17100 // An ICE must be of integral or unscoped enumeration type. 17101 if (!Diagnoser.Suppress) 17102 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 17103 << E->getSourceRange(); 17104 return ExprError(); 17105 } 17106 17107 ExprResult RValueExpr = DefaultLvalueConversion(E); 17108 if (RValueExpr.isInvalid()) 17109 return ExprError(); 17110 17111 E = RValueExpr.get(); 17112 17113 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 17114 // in the non-ICE case. 17115 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 17116 if (Result) 17117 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 17118 if (!isa<ConstantExpr>(E)) 17119 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 17120 : ConstantExpr::Create(Context, E); 17121 return E; 17122 } 17123 17124 Expr::EvalResult EvalResult; 17125 SmallVector<PartialDiagnosticAt, 8> Notes; 17126 EvalResult.Diag = &Notes; 17127 17128 // Try to evaluate the expression, and produce diagnostics explaining why it's 17129 // not a constant expression as a side-effect. 17130 bool Folded = 17131 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 17132 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 17133 17134 if (!isa<ConstantExpr>(E)) 17135 E = ConstantExpr::Create(Context, E, EvalResult.Val); 17136 17137 // In C++11, we can rely on diagnostics being produced for any expression 17138 // which is not a constant expression. If no diagnostics were produced, then 17139 // this is a constant expression. 17140 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 17141 if (Result) 17142 *Result = EvalResult.Val.getInt(); 17143 return E; 17144 } 17145 17146 // If our only note is the usual "invalid subexpression" note, just point 17147 // the caret at its location rather than producing an essentially 17148 // redundant note. 17149 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 17150 diag::note_invalid_subexpr_in_const_expr) { 17151 DiagLoc = Notes[0].first; 17152 Notes.clear(); 17153 } 17154 17155 if (!Folded || !CanFold) { 17156 if (!Diagnoser.Suppress) { 17157 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 17158 for (const PartialDiagnosticAt &Note : Notes) 17159 Diag(Note.first, Note.second); 17160 } 17161 17162 return ExprError(); 17163 } 17164 17165 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 17166 for (const PartialDiagnosticAt &Note : Notes) 17167 Diag(Note.first, Note.second); 17168 17169 if (Result) 17170 *Result = EvalResult.Val.getInt(); 17171 return E; 17172 } 17173 17174 namespace { 17175 // Handle the case where we conclude a expression which we speculatively 17176 // considered to be unevaluated is actually evaluated. 17177 class TransformToPE : public TreeTransform<TransformToPE> { 17178 typedef TreeTransform<TransformToPE> BaseTransform; 17179 17180 public: 17181 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 17182 17183 // Make sure we redo semantic analysis 17184 bool AlwaysRebuild() { return true; } 17185 bool ReplacingOriginal() { return true; } 17186 17187 // We need to special-case DeclRefExprs referring to FieldDecls which 17188 // are not part of a member pointer formation; normal TreeTransforming 17189 // doesn't catch this case because of the way we represent them in the AST. 17190 // FIXME: This is a bit ugly; is it really the best way to handle this 17191 // case? 17192 // 17193 // Error on DeclRefExprs referring to FieldDecls. 17194 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 17195 if (isa<FieldDecl>(E->getDecl()) && 17196 !SemaRef.isUnevaluatedContext()) 17197 return SemaRef.Diag(E->getLocation(), 17198 diag::err_invalid_non_static_member_use) 17199 << E->getDecl() << E->getSourceRange(); 17200 17201 return BaseTransform::TransformDeclRefExpr(E); 17202 } 17203 17204 // Exception: filter out member pointer formation 17205 ExprResult TransformUnaryOperator(UnaryOperator *E) { 17206 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 17207 return E; 17208 17209 return BaseTransform::TransformUnaryOperator(E); 17210 } 17211 17212 // The body of a lambda-expression is in a separate expression evaluation 17213 // context so never needs to be transformed. 17214 // FIXME: Ideally we wouldn't transform the closure type either, and would 17215 // just recreate the capture expressions and lambda expression. 17216 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 17217 return SkipLambdaBody(E, Body); 17218 } 17219 }; 17220 } 17221 17222 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 17223 assert(isUnevaluatedContext() && 17224 "Should only transform unevaluated expressions"); 17225 ExprEvalContexts.back().Context = 17226 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 17227 if (isUnevaluatedContext()) 17228 return E; 17229 return TransformToPE(*this).TransformExpr(E); 17230 } 17231 17232 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { 17233 assert(isUnevaluatedContext() && 17234 "Should only transform unevaluated expressions"); 17235 ExprEvalContexts.back().Context = 17236 ExprEvalContexts[ExprEvalContexts.size() - 2].Context; 17237 if (isUnevaluatedContext()) 17238 return TInfo; 17239 return TransformToPE(*this).TransformType(TInfo); 17240 } 17241 17242 void 17243 Sema::PushExpressionEvaluationContext( 17244 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 17245 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17246 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 17247 LambdaContextDecl, ExprContext); 17248 17249 // Discarded statements and immediate contexts nested in other 17250 // discarded statements or immediate context are themselves 17251 // a discarded statement or an immediate context, respectively. 17252 ExprEvalContexts.back().InDiscardedStatement = 17253 ExprEvalContexts[ExprEvalContexts.size() - 2] 17254 .isDiscardedStatementContext(); 17255 ExprEvalContexts.back().InImmediateFunctionContext = 17256 ExprEvalContexts[ExprEvalContexts.size() - 2] 17257 .isImmediateFunctionContext(); 17258 17259 Cleanup.reset(); 17260 if (!MaybeODRUseExprs.empty()) 17261 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 17262 } 17263 17264 void 17265 Sema::PushExpressionEvaluationContext( 17266 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 17267 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17268 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 17269 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 17270 } 17271 17272 namespace { 17273 17274 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 17275 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 17276 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 17277 if (E->getOpcode() == UO_Deref) 17278 return CheckPossibleDeref(S, E->getSubExpr()); 17279 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 17280 return CheckPossibleDeref(S, E->getBase()); 17281 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 17282 return CheckPossibleDeref(S, E->getBase()); 17283 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 17284 QualType Inner; 17285 QualType Ty = E->getType(); 17286 if (const auto *Ptr = Ty->getAs<PointerType>()) 17287 Inner = Ptr->getPointeeType(); 17288 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 17289 Inner = Arr->getElementType(); 17290 else 17291 return nullptr; 17292 17293 if (Inner->hasAttr(attr::NoDeref)) 17294 return E; 17295 } 17296 return nullptr; 17297 } 17298 17299 } // namespace 17300 17301 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 17302 for (const Expr *E : Rec.PossibleDerefs) { 17303 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 17304 if (DeclRef) { 17305 const ValueDecl *Decl = DeclRef->getDecl(); 17306 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 17307 << Decl->getName() << E->getSourceRange(); 17308 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 17309 } else { 17310 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 17311 << E->getSourceRange(); 17312 } 17313 } 17314 Rec.PossibleDerefs.clear(); 17315 } 17316 17317 /// Check whether E, which is either a discarded-value expression or an 17318 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 17319 /// and if so, remove it from the list of volatile-qualified assignments that 17320 /// we are going to warn are deprecated. 17321 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 17322 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 17323 return; 17324 17325 // Note: ignoring parens here is not justified by the standard rules, but 17326 // ignoring parentheses seems like a more reasonable approach, and this only 17327 // drives a deprecation warning so doesn't affect conformance. 17328 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 17329 if (BO->getOpcode() == BO_Assign) { 17330 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 17331 llvm::erase_value(LHSs, BO->getLHS()); 17332 } 17333 } 17334 } 17335 17336 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 17337 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 17338 !Decl->isConsteval() || isConstantEvaluated() || 17339 RebuildingImmediateInvocation || isImmediateFunctionContext()) 17340 return E; 17341 17342 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 17343 /// It's OK if this fails; we'll also remove this in 17344 /// HandleImmediateInvocations, but catching it here allows us to avoid 17345 /// walking the AST looking for it in simple cases. 17346 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 17347 if (auto *DeclRef = 17348 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 17349 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 17350 17351 E = MaybeCreateExprWithCleanups(E); 17352 17353 ConstantExpr *Res = ConstantExpr::Create( 17354 getASTContext(), E.get(), 17355 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 17356 getASTContext()), 17357 /*IsImmediateInvocation*/ true); 17358 /// Value-dependent constant expressions should not be immediately 17359 /// evaluated until they are instantiated. 17360 if (!Res->isValueDependent()) 17361 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 17362 return Res; 17363 } 17364 17365 static void EvaluateAndDiagnoseImmediateInvocation( 17366 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 17367 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 17368 Expr::EvalResult Eval; 17369 Eval.Diag = &Notes; 17370 ConstantExpr *CE = Candidate.getPointer(); 17371 bool Result = CE->EvaluateAsConstantExpr( 17372 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 17373 if (!Result || !Notes.empty()) { 17374 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 17375 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 17376 InnerExpr = FunctionalCast->getSubExpr(); 17377 FunctionDecl *FD = nullptr; 17378 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 17379 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 17380 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 17381 FD = Call->getConstructor(); 17382 else 17383 llvm_unreachable("unhandled decl kind"); 17384 assert(FD->isConsteval()); 17385 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 17386 for (auto &Note : Notes) 17387 SemaRef.Diag(Note.first, Note.second); 17388 return; 17389 } 17390 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 17391 } 17392 17393 static void RemoveNestedImmediateInvocation( 17394 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 17395 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 17396 struct ComplexRemove : TreeTransform<ComplexRemove> { 17397 using Base = TreeTransform<ComplexRemove>; 17398 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17399 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 17400 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 17401 CurrentII; 17402 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 17403 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 17404 SmallVector<Sema::ImmediateInvocationCandidate, 17405 4>::reverse_iterator Current) 17406 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 17407 void RemoveImmediateInvocation(ConstantExpr* E) { 17408 auto It = std::find_if(CurrentII, IISet.rend(), 17409 [E](Sema::ImmediateInvocationCandidate Elem) { 17410 return Elem.getPointer() == E; 17411 }); 17412 assert(It != IISet.rend() && 17413 "ConstantExpr marked IsImmediateInvocation should " 17414 "be present"); 17415 It->setInt(1); // Mark as deleted 17416 } 17417 ExprResult TransformConstantExpr(ConstantExpr *E) { 17418 if (!E->isImmediateInvocation()) 17419 return Base::TransformConstantExpr(E); 17420 RemoveImmediateInvocation(E); 17421 return Base::TransformExpr(E->getSubExpr()); 17422 } 17423 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 17424 /// we need to remove its DeclRefExpr from the DRSet. 17425 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 17426 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 17427 return Base::TransformCXXOperatorCallExpr(E); 17428 } 17429 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 17430 /// here. 17431 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 17432 if (!Init) 17433 return Init; 17434 /// ConstantExpr are the first layer of implicit node to be removed so if 17435 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 17436 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 17437 if (CE->isImmediateInvocation()) 17438 RemoveImmediateInvocation(CE); 17439 return Base::TransformInitializer(Init, NotCopyInit); 17440 } 17441 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 17442 DRSet.erase(E); 17443 return E; 17444 } 17445 bool AlwaysRebuild() { return false; } 17446 bool ReplacingOriginal() { return true; } 17447 bool AllowSkippingCXXConstructExpr() { 17448 bool Res = AllowSkippingFirstCXXConstructExpr; 17449 AllowSkippingFirstCXXConstructExpr = true; 17450 return Res; 17451 } 17452 bool AllowSkippingFirstCXXConstructExpr = true; 17453 } Transformer(SemaRef, Rec.ReferenceToConsteval, 17454 Rec.ImmediateInvocationCandidates, It); 17455 17456 /// CXXConstructExpr with a single argument are getting skipped by 17457 /// TreeTransform in some situtation because they could be implicit. This 17458 /// can only occur for the top-level CXXConstructExpr because it is used 17459 /// nowhere in the expression being transformed therefore will not be rebuilt. 17460 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 17461 /// skipping the first CXXConstructExpr. 17462 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 17463 Transformer.AllowSkippingFirstCXXConstructExpr = false; 17464 17465 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 17466 assert(Res.isUsable()); 17467 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 17468 It->getPointer()->setSubExpr(Res.get()); 17469 } 17470 17471 static void 17472 HandleImmediateInvocations(Sema &SemaRef, 17473 Sema::ExpressionEvaluationContextRecord &Rec) { 17474 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 17475 Rec.ReferenceToConsteval.size() == 0) || 17476 SemaRef.RebuildingImmediateInvocation) 17477 return; 17478 17479 /// When we have more then 1 ImmediateInvocationCandidates we need to check 17480 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 17481 /// need to remove ReferenceToConsteval in the immediate invocation. 17482 if (Rec.ImmediateInvocationCandidates.size() > 1) { 17483 17484 /// Prevent sema calls during the tree transform from adding pointers that 17485 /// are already in the sets. 17486 llvm::SaveAndRestore<bool> DisableIITracking( 17487 SemaRef.RebuildingImmediateInvocation, true); 17488 17489 /// Prevent diagnostic during tree transfrom as they are duplicates 17490 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 17491 17492 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 17493 It != Rec.ImmediateInvocationCandidates.rend(); It++) 17494 if (!It->getInt()) 17495 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 17496 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 17497 Rec.ReferenceToConsteval.size()) { 17498 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 17499 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17500 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 17501 bool VisitDeclRefExpr(DeclRefExpr *E) { 17502 DRSet.erase(E); 17503 return DRSet.size(); 17504 } 17505 } Visitor(Rec.ReferenceToConsteval); 17506 Visitor.TraverseStmt( 17507 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 17508 } 17509 for (auto CE : Rec.ImmediateInvocationCandidates) 17510 if (!CE.getInt()) 17511 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 17512 for (auto DR : Rec.ReferenceToConsteval) { 17513 auto *FD = cast<FunctionDecl>(DR->getDecl()); 17514 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 17515 << FD; 17516 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 17517 } 17518 } 17519 17520 void Sema::PopExpressionEvaluationContext() { 17521 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 17522 unsigned NumTypos = Rec.NumTypos; 17523 17524 if (!Rec.Lambdas.empty()) { 17525 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 17526 if (!getLangOpts().CPlusPlus20 && 17527 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 17528 Rec.isUnevaluated() || 17529 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 17530 unsigned D; 17531 if (Rec.isUnevaluated()) { 17532 // C++11 [expr.prim.lambda]p2: 17533 // A lambda-expression shall not appear in an unevaluated operand 17534 // (Clause 5). 17535 D = diag::err_lambda_unevaluated_operand; 17536 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 17537 // C++1y [expr.const]p2: 17538 // A conditional-expression e is a core constant expression unless the 17539 // evaluation of e, following the rules of the abstract machine, would 17540 // evaluate [...] a lambda-expression. 17541 D = diag::err_lambda_in_constant_expression; 17542 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 17543 // C++17 [expr.prim.lamda]p2: 17544 // A lambda-expression shall not appear [...] in a template-argument. 17545 D = diag::err_lambda_in_invalid_context; 17546 } else 17547 llvm_unreachable("Couldn't infer lambda error message."); 17548 17549 for (const auto *L : Rec.Lambdas) 17550 Diag(L->getBeginLoc(), D); 17551 } 17552 } 17553 17554 WarnOnPendingNoDerefs(Rec); 17555 HandleImmediateInvocations(*this, Rec); 17556 17557 // Warn on any volatile-qualified simple-assignments that are not discarded- 17558 // value expressions nor unevaluated operands (those cases get removed from 17559 // this list by CheckUnusedVolatileAssignment). 17560 for (auto *BO : Rec.VolatileAssignmentLHSs) 17561 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 17562 << BO->getType(); 17563 17564 // When are coming out of an unevaluated context, clear out any 17565 // temporaries that we may have created as part of the evaluation of 17566 // the expression in that context: they aren't relevant because they 17567 // will never be constructed. 17568 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 17569 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 17570 ExprCleanupObjects.end()); 17571 Cleanup = Rec.ParentCleanup; 17572 CleanupVarDeclMarking(); 17573 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 17574 // Otherwise, merge the contexts together. 17575 } else { 17576 Cleanup.mergeFrom(Rec.ParentCleanup); 17577 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 17578 Rec.SavedMaybeODRUseExprs.end()); 17579 } 17580 17581 // Pop the current expression evaluation context off the stack. 17582 ExprEvalContexts.pop_back(); 17583 17584 // The global expression evaluation context record is never popped. 17585 ExprEvalContexts.back().NumTypos += NumTypos; 17586 } 17587 17588 void Sema::DiscardCleanupsInEvaluationContext() { 17589 ExprCleanupObjects.erase( 17590 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 17591 ExprCleanupObjects.end()); 17592 Cleanup.reset(); 17593 MaybeODRUseExprs.clear(); 17594 } 17595 17596 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 17597 ExprResult Result = CheckPlaceholderExpr(E); 17598 if (Result.isInvalid()) 17599 return ExprError(); 17600 E = Result.get(); 17601 if (!E->getType()->isVariablyModifiedType()) 17602 return E; 17603 return TransformToPotentiallyEvaluated(E); 17604 } 17605 17606 /// Are we in a context that is potentially constant evaluated per C++20 17607 /// [expr.const]p12? 17608 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 17609 /// C++2a [expr.const]p12: 17610 // An expression or conversion is potentially constant evaluated if it is 17611 switch (SemaRef.ExprEvalContexts.back().Context) { 17612 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17613 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17614 17615 // -- a manifestly constant-evaluated expression, 17616 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17617 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17618 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17619 // -- a potentially-evaluated expression, 17620 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17621 // -- an immediate subexpression of a braced-init-list, 17622 17623 // -- [FIXME] an expression of the form & cast-expression that occurs 17624 // within a templated entity 17625 // -- a subexpression of one of the above that is not a subexpression of 17626 // a nested unevaluated operand. 17627 return true; 17628 17629 case Sema::ExpressionEvaluationContext::Unevaluated: 17630 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17631 // Expressions in this context are never evaluated. 17632 return false; 17633 } 17634 llvm_unreachable("Invalid context"); 17635 } 17636 17637 /// Return true if this function has a calling convention that requires mangling 17638 /// in the size of the parameter pack. 17639 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 17640 // These manglings don't do anything on non-Windows or non-x86 platforms, so 17641 // we don't need parameter type sizes. 17642 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 17643 if (!TT.isOSWindows() || !TT.isX86()) 17644 return false; 17645 17646 // If this is C++ and this isn't an extern "C" function, parameters do not 17647 // need to be complete. In this case, C++ mangling will apply, which doesn't 17648 // use the size of the parameters. 17649 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 17650 return false; 17651 17652 // Stdcall, fastcall, and vectorcall need this special treatment. 17653 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17654 switch (CC) { 17655 case CC_X86StdCall: 17656 case CC_X86FastCall: 17657 case CC_X86VectorCall: 17658 return true; 17659 default: 17660 break; 17661 } 17662 return false; 17663 } 17664 17665 /// Require that all of the parameter types of function be complete. Normally, 17666 /// parameter types are only required to be complete when a function is called 17667 /// or defined, but to mangle functions with certain calling conventions, the 17668 /// mangler needs to know the size of the parameter list. In this situation, 17669 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 17670 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 17671 /// result in a linker error. Clang doesn't implement this behavior, and instead 17672 /// attempts to error at compile time. 17673 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 17674 SourceLocation Loc) { 17675 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 17676 FunctionDecl *FD; 17677 ParmVarDecl *Param; 17678 17679 public: 17680 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 17681 : FD(FD), Param(Param) {} 17682 17683 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17684 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17685 StringRef CCName; 17686 switch (CC) { 17687 case CC_X86StdCall: 17688 CCName = "stdcall"; 17689 break; 17690 case CC_X86FastCall: 17691 CCName = "fastcall"; 17692 break; 17693 case CC_X86VectorCall: 17694 CCName = "vectorcall"; 17695 break; 17696 default: 17697 llvm_unreachable("CC does not need mangling"); 17698 } 17699 17700 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17701 << Param->getDeclName() << FD->getDeclName() << CCName; 17702 } 17703 }; 17704 17705 for (ParmVarDecl *Param : FD->parameters()) { 17706 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17707 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17708 } 17709 } 17710 17711 namespace { 17712 enum class OdrUseContext { 17713 /// Declarations in this context are not odr-used. 17714 None, 17715 /// Declarations in this context are formally odr-used, but this is a 17716 /// dependent context. 17717 Dependent, 17718 /// Declarations in this context are odr-used but not actually used (yet). 17719 FormallyOdrUsed, 17720 /// Declarations in this context are used. 17721 Used 17722 }; 17723 } 17724 17725 /// Are we within a context in which references to resolved functions or to 17726 /// variables result in odr-use? 17727 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17728 OdrUseContext Result; 17729 17730 switch (SemaRef.ExprEvalContexts.back().Context) { 17731 case Sema::ExpressionEvaluationContext::Unevaluated: 17732 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17733 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17734 return OdrUseContext::None; 17735 17736 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17737 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17738 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17739 Result = OdrUseContext::Used; 17740 break; 17741 17742 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17743 Result = OdrUseContext::FormallyOdrUsed; 17744 break; 17745 17746 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17747 // A default argument formally results in odr-use, but doesn't actually 17748 // result in a use in any real sense until it itself is used. 17749 Result = OdrUseContext::FormallyOdrUsed; 17750 break; 17751 } 17752 17753 if (SemaRef.CurContext->isDependentContext()) 17754 return OdrUseContext::Dependent; 17755 17756 return Result; 17757 } 17758 17759 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17760 if (!Func->isConstexpr()) 17761 return false; 17762 17763 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17764 return true; 17765 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17766 return CCD && CCD->getInheritedConstructor(); 17767 } 17768 17769 /// Mark a function referenced, and check whether it is odr-used 17770 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17771 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17772 bool MightBeOdrUse) { 17773 assert(Func && "No function?"); 17774 17775 Func->setReferenced(); 17776 17777 // Recursive functions aren't really used until they're used from some other 17778 // context. 17779 bool IsRecursiveCall = CurContext == Func; 17780 17781 // C++11 [basic.def.odr]p3: 17782 // A function whose name appears as a potentially-evaluated expression is 17783 // odr-used if it is the unique lookup result or the selected member of a 17784 // set of overloaded functions [...]. 17785 // 17786 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17787 // can just check that here. 17788 OdrUseContext OdrUse = 17789 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17790 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17791 OdrUse = OdrUseContext::FormallyOdrUsed; 17792 17793 // Trivial default constructors and destructors are never actually used. 17794 // FIXME: What about other special members? 17795 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17796 OdrUse == OdrUseContext::Used) { 17797 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17798 if (Constructor->isDefaultConstructor()) 17799 OdrUse = OdrUseContext::FormallyOdrUsed; 17800 if (isa<CXXDestructorDecl>(Func)) 17801 OdrUse = OdrUseContext::FormallyOdrUsed; 17802 } 17803 17804 // C++20 [expr.const]p12: 17805 // A function [...] is needed for constant evaluation if it is [...] a 17806 // constexpr function that is named by an expression that is potentially 17807 // constant evaluated 17808 bool NeededForConstantEvaluation = 17809 isPotentiallyConstantEvaluatedContext(*this) && 17810 isImplicitlyDefinableConstexprFunction(Func); 17811 17812 // Determine whether we require a function definition to exist, per 17813 // C++11 [temp.inst]p3: 17814 // Unless a function template specialization has been explicitly 17815 // instantiated or explicitly specialized, the function template 17816 // specialization is implicitly instantiated when the specialization is 17817 // referenced in a context that requires a function definition to exist. 17818 // C++20 [temp.inst]p7: 17819 // The existence of a definition of a [...] function is considered to 17820 // affect the semantics of the program if the [...] function is needed for 17821 // constant evaluation by an expression 17822 // C++20 [basic.def.odr]p10: 17823 // Every program shall contain exactly one definition of every non-inline 17824 // function or variable that is odr-used in that program outside of a 17825 // discarded statement 17826 // C++20 [special]p1: 17827 // The implementation will implicitly define [defaulted special members] 17828 // if they are odr-used or needed for constant evaluation. 17829 // 17830 // Note that we skip the implicit instantiation of templates that are only 17831 // used in unused default arguments or by recursive calls to themselves. 17832 // This is formally non-conforming, but seems reasonable in practice. 17833 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17834 NeededForConstantEvaluation); 17835 17836 // C++14 [temp.expl.spec]p6: 17837 // If a template [...] is explicitly specialized then that specialization 17838 // shall be declared before the first use of that specialization that would 17839 // cause an implicit instantiation to take place, in every translation unit 17840 // in which such a use occurs 17841 if (NeedDefinition && 17842 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17843 Func->getMemberSpecializationInfo())) 17844 checkSpecializationVisibility(Loc, Func); 17845 17846 if (getLangOpts().CUDA) 17847 CheckCUDACall(Loc, Func); 17848 17849 if (getLangOpts().SYCLIsDevice) 17850 checkSYCLDeviceFunction(Loc, Func); 17851 17852 // If we need a definition, try to create one. 17853 if (NeedDefinition && !Func->getBody()) { 17854 runWithSufficientStackSpace(Loc, [&] { 17855 if (CXXConstructorDecl *Constructor = 17856 dyn_cast<CXXConstructorDecl>(Func)) { 17857 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17858 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17859 if (Constructor->isDefaultConstructor()) { 17860 if (Constructor->isTrivial() && 17861 !Constructor->hasAttr<DLLExportAttr>()) 17862 return; 17863 DefineImplicitDefaultConstructor(Loc, Constructor); 17864 } else if (Constructor->isCopyConstructor()) { 17865 DefineImplicitCopyConstructor(Loc, Constructor); 17866 } else if (Constructor->isMoveConstructor()) { 17867 DefineImplicitMoveConstructor(Loc, Constructor); 17868 } 17869 } else if (Constructor->getInheritedConstructor()) { 17870 DefineInheritingConstructor(Loc, Constructor); 17871 } 17872 } else if (CXXDestructorDecl *Destructor = 17873 dyn_cast<CXXDestructorDecl>(Func)) { 17874 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17875 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17876 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17877 return; 17878 DefineImplicitDestructor(Loc, Destructor); 17879 } 17880 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17881 MarkVTableUsed(Loc, Destructor->getParent()); 17882 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17883 if (MethodDecl->isOverloadedOperator() && 17884 MethodDecl->getOverloadedOperator() == OO_Equal) { 17885 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17886 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17887 if (MethodDecl->isCopyAssignmentOperator()) 17888 DefineImplicitCopyAssignment(Loc, MethodDecl); 17889 else if (MethodDecl->isMoveAssignmentOperator()) 17890 DefineImplicitMoveAssignment(Loc, MethodDecl); 17891 } 17892 } else if (isa<CXXConversionDecl>(MethodDecl) && 17893 MethodDecl->getParent()->isLambda()) { 17894 CXXConversionDecl *Conversion = 17895 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17896 if (Conversion->isLambdaToBlockPointerConversion()) 17897 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17898 else 17899 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17900 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17901 MarkVTableUsed(Loc, MethodDecl->getParent()); 17902 } 17903 17904 if (Func->isDefaulted() && !Func->isDeleted()) { 17905 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17906 if (DCK != DefaultedComparisonKind::None) 17907 DefineDefaultedComparison(Loc, Func, DCK); 17908 } 17909 17910 // Implicit instantiation of function templates and member functions of 17911 // class templates. 17912 if (Func->isImplicitlyInstantiable()) { 17913 TemplateSpecializationKind TSK = 17914 Func->getTemplateSpecializationKindForInstantiation(); 17915 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17916 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17917 if (FirstInstantiation) { 17918 PointOfInstantiation = Loc; 17919 if (auto *MSI = Func->getMemberSpecializationInfo()) 17920 MSI->setPointOfInstantiation(Loc); 17921 // FIXME: Notify listener. 17922 else 17923 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17924 } else if (TSK != TSK_ImplicitInstantiation) { 17925 // Use the point of use as the point of instantiation, instead of the 17926 // point of explicit instantiation (which we track as the actual point 17927 // of instantiation). This gives better backtraces in diagnostics. 17928 PointOfInstantiation = Loc; 17929 } 17930 17931 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17932 Func->isConstexpr()) { 17933 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17934 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17935 CodeSynthesisContexts.size()) 17936 PendingLocalImplicitInstantiations.push_back( 17937 std::make_pair(Func, PointOfInstantiation)); 17938 else if (Func->isConstexpr()) 17939 // Do not defer instantiations of constexpr functions, to avoid the 17940 // expression evaluator needing to call back into Sema if it sees a 17941 // call to such a function. 17942 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17943 else { 17944 Func->setInstantiationIsPending(true); 17945 PendingInstantiations.push_back( 17946 std::make_pair(Func, PointOfInstantiation)); 17947 // Notify the consumer that a function was implicitly instantiated. 17948 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17949 } 17950 } 17951 } else { 17952 // Walk redefinitions, as some of them may be instantiable. 17953 for (auto i : Func->redecls()) { 17954 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17955 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17956 } 17957 } 17958 }); 17959 } 17960 17961 // C++14 [except.spec]p17: 17962 // An exception-specification is considered to be needed when: 17963 // - the function is odr-used or, if it appears in an unevaluated operand, 17964 // would be odr-used if the expression were potentially-evaluated; 17965 // 17966 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17967 // function is a pure virtual function we're calling, and in that case the 17968 // function was selected by overload resolution and we need to resolve its 17969 // exception specification for a different reason. 17970 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17971 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17972 ResolveExceptionSpec(Loc, FPT); 17973 17974 // If this is the first "real" use, act on that. 17975 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17976 // Keep track of used but undefined functions. 17977 if (!Func->isDefined()) { 17978 if (mightHaveNonExternalLinkage(Func)) 17979 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17980 else if (Func->getMostRecentDecl()->isInlined() && 17981 !LangOpts.GNUInline && 17982 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17983 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17984 else if (isExternalWithNoLinkageType(Func)) 17985 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17986 } 17987 17988 // Some x86 Windows calling conventions mangle the size of the parameter 17989 // pack into the name. Computing the size of the parameters requires the 17990 // parameter types to be complete. Check that now. 17991 if (funcHasParameterSizeMangling(*this, Func)) 17992 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17993 17994 // In the MS C++ ABI, the compiler emits destructor variants where they are 17995 // used. If the destructor is used here but defined elsewhere, mark the 17996 // virtual base destructors referenced. If those virtual base destructors 17997 // are inline, this will ensure they are defined when emitting the complete 17998 // destructor variant. This checking may be redundant if the destructor is 17999 // provided later in this TU. 18000 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 18001 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 18002 CXXRecordDecl *Parent = Dtor->getParent(); 18003 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 18004 CheckCompleteDestructorVariant(Loc, Dtor); 18005 } 18006 } 18007 18008 Func->markUsed(Context); 18009 } 18010 } 18011 18012 /// Directly mark a variable odr-used. Given a choice, prefer to use 18013 /// MarkVariableReferenced since it does additional checks and then 18014 /// calls MarkVarDeclODRUsed. 18015 /// If the variable must be captured: 18016 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 18017 /// - else capture it in the DeclContext that maps to the 18018 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 18019 static void 18020 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 18021 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 18022 // Keep track of used but undefined variables. 18023 // FIXME: We shouldn't suppress this warning for static data members. 18024 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 18025 (!Var->isExternallyVisible() || Var->isInline() || 18026 SemaRef.isExternalWithNoLinkageType(Var)) && 18027 !(Var->isStaticDataMember() && Var->hasInit())) { 18028 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 18029 if (old.isInvalid()) 18030 old = Loc; 18031 } 18032 QualType CaptureType, DeclRefType; 18033 if (SemaRef.LangOpts.OpenMP) 18034 SemaRef.tryCaptureOpenMPLambdas(Var); 18035 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 18036 /*EllipsisLoc*/ SourceLocation(), 18037 /*BuildAndDiagnose*/ true, 18038 CaptureType, DeclRefType, 18039 FunctionScopeIndexToStopAt); 18040 18041 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { 18042 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 18043 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 18044 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 18045 if (VarTarget == Sema::CVT_Host && 18046 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 18047 UserTarget == Sema::CFT_Global)) { 18048 // Diagnose ODR-use of host global variables in device functions. 18049 // Reference of device global variables in host functions is allowed 18050 // through shadow variables therefore it is not diagnosed. 18051 if (SemaRef.LangOpts.CUDAIsDevice) { 18052 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 18053 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 18054 SemaRef.targetDiag(Var->getLocation(), 18055 Var->getType().isConstQualified() 18056 ? diag::note_cuda_const_var_unpromoted 18057 : diag::note_cuda_host_var); 18058 } 18059 } else if (VarTarget == Sema::CVT_Device && 18060 (UserTarget == Sema::CFT_Host || 18061 UserTarget == Sema::CFT_HostDevice)) { 18062 // Record a CUDA/HIP device side variable if it is ODR-used 18063 // by host code. This is done conservatively, when the variable is 18064 // referenced in any of the following contexts: 18065 // - a non-function context 18066 // - a host function 18067 // - a host device function 18068 // This makes the ODR-use of the device side variable by host code to 18069 // be visible in the device compilation for the compiler to be able to 18070 // emit template variables instantiated by host code only and to 18071 // externalize the static device side variable ODR-used by host code. 18072 if (!Var->hasExternalStorage()) 18073 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 18074 else if (SemaRef.LangOpts.GPURelocatableDeviceCode) 18075 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var); 18076 } 18077 } 18078 18079 Var->markUsed(SemaRef.Context); 18080 } 18081 18082 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 18083 SourceLocation Loc, 18084 unsigned CapturingScopeIndex) { 18085 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 18086 } 18087 18088 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 18089 ValueDecl *var) { 18090 DeclContext *VarDC = var->getDeclContext(); 18091 18092 // If the parameter still belongs to the translation unit, then 18093 // we're actually just using one parameter in the declaration of 18094 // the next. 18095 if (isa<ParmVarDecl>(var) && 18096 isa<TranslationUnitDecl>(VarDC)) 18097 return; 18098 18099 // For C code, don't diagnose about capture if we're not actually in code 18100 // right now; it's impossible to write a non-constant expression outside of 18101 // function context, so we'll get other (more useful) diagnostics later. 18102 // 18103 // For C++, things get a bit more nasty... it would be nice to suppress this 18104 // diagnostic for certain cases like using a local variable in an array bound 18105 // for a member of a local class, but the correct predicate is not obvious. 18106 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 18107 return; 18108 18109 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 18110 unsigned ContextKind = 3; // unknown 18111 if (isa<CXXMethodDecl>(VarDC) && 18112 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 18113 ContextKind = 2; 18114 } else if (isa<FunctionDecl>(VarDC)) { 18115 ContextKind = 0; 18116 } else if (isa<BlockDecl>(VarDC)) { 18117 ContextKind = 1; 18118 } 18119 18120 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 18121 << var << ValueKind << ContextKind << VarDC; 18122 S.Diag(var->getLocation(), diag::note_entity_declared_at) 18123 << var; 18124 18125 // FIXME: Add additional diagnostic info about class etc. which prevents 18126 // capture. 18127 } 18128 18129 18130 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 18131 bool &SubCapturesAreNested, 18132 QualType &CaptureType, 18133 QualType &DeclRefType) { 18134 // Check whether we've already captured it. 18135 if (CSI->CaptureMap.count(Var)) { 18136 // If we found a capture, any subcaptures are nested. 18137 SubCapturesAreNested = true; 18138 18139 // Retrieve the capture type for this variable. 18140 CaptureType = CSI->getCapture(Var).getCaptureType(); 18141 18142 // Compute the type of an expression that refers to this variable. 18143 DeclRefType = CaptureType.getNonReferenceType(); 18144 18145 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 18146 // are mutable in the sense that user can change their value - they are 18147 // private instances of the captured declarations. 18148 const Capture &Cap = CSI->getCapture(Var); 18149 if (Cap.isCopyCapture() && 18150 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 18151 !(isa<CapturedRegionScopeInfo>(CSI) && 18152 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 18153 DeclRefType.addConst(); 18154 return true; 18155 } 18156 return false; 18157 } 18158 18159 // Only block literals, captured statements, and lambda expressions can 18160 // capture; other scopes don't work. 18161 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 18162 SourceLocation Loc, 18163 const bool Diagnose, Sema &S) { 18164 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 18165 return getLambdaAwareParentOfDeclContext(DC); 18166 else if (Var->hasLocalStorage()) { 18167 if (Diagnose) 18168 diagnoseUncapturableValueReference(S, Loc, Var); 18169 } 18170 return nullptr; 18171 } 18172 18173 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18174 // certain types of variables (unnamed, variably modified types etc.) 18175 // so check for eligibility. 18176 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 18177 SourceLocation Loc, 18178 const bool Diagnose, Sema &S) { 18179 18180 bool IsBlock = isa<BlockScopeInfo>(CSI); 18181 bool IsLambda = isa<LambdaScopeInfo>(CSI); 18182 18183 // Lambdas are not allowed to capture unnamed variables 18184 // (e.g. anonymous unions). 18185 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 18186 // assuming that's the intent. 18187 if (IsLambda && !Var->getDeclName()) { 18188 if (Diagnose) { 18189 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 18190 S.Diag(Var->getLocation(), diag::note_declared_at); 18191 } 18192 return false; 18193 } 18194 18195 // Prohibit variably-modified types in blocks; they're difficult to deal with. 18196 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 18197 if (Diagnose) { 18198 S.Diag(Loc, diag::err_ref_vm_type); 18199 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18200 } 18201 return false; 18202 } 18203 // Prohibit structs with flexible array members too. 18204 // We cannot capture what is in the tail end of the struct. 18205 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 18206 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 18207 if (Diagnose) { 18208 if (IsBlock) 18209 S.Diag(Loc, diag::err_ref_flexarray_type); 18210 else 18211 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 18212 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18213 } 18214 return false; 18215 } 18216 } 18217 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18218 // Lambdas and captured statements are not allowed to capture __block 18219 // variables; they don't support the expected semantics. 18220 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 18221 if (Diagnose) { 18222 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 18223 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18224 } 18225 return false; 18226 } 18227 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 18228 if (S.getLangOpts().OpenCL && IsBlock && 18229 Var->getType()->isBlockPointerType()) { 18230 if (Diagnose) 18231 S.Diag(Loc, diag::err_opencl_block_ref_block); 18232 return false; 18233 } 18234 18235 return true; 18236 } 18237 18238 // Returns true if the capture by block was successful. 18239 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 18240 SourceLocation Loc, 18241 const bool BuildAndDiagnose, 18242 QualType &CaptureType, 18243 QualType &DeclRefType, 18244 const bool Nested, 18245 Sema &S, bool Invalid) { 18246 bool ByRef = false; 18247 18248 // Blocks are not allowed to capture arrays, excepting OpenCL. 18249 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 18250 // (decayed to pointers). 18251 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 18252 if (BuildAndDiagnose) { 18253 S.Diag(Loc, diag::err_ref_array_type); 18254 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18255 Invalid = true; 18256 } else { 18257 return false; 18258 } 18259 } 18260 18261 // Forbid the block-capture of autoreleasing variables. 18262 if (!Invalid && 18263 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18264 if (BuildAndDiagnose) { 18265 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 18266 << /*block*/ 0; 18267 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18268 Invalid = true; 18269 } else { 18270 return false; 18271 } 18272 } 18273 18274 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 18275 if (const auto *PT = CaptureType->getAs<PointerType>()) { 18276 QualType PointeeTy = PT->getPointeeType(); 18277 18278 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 18279 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 18280 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 18281 if (BuildAndDiagnose) { 18282 SourceLocation VarLoc = Var->getLocation(); 18283 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 18284 S.Diag(VarLoc, diag::note_declare_parameter_strong); 18285 } 18286 } 18287 } 18288 18289 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18290 if (HasBlocksAttr || CaptureType->isReferenceType() || 18291 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 18292 // Block capture by reference does not change the capture or 18293 // declaration reference types. 18294 ByRef = true; 18295 } else { 18296 // Block capture by copy introduces 'const'. 18297 CaptureType = CaptureType.getNonReferenceType().withConst(); 18298 DeclRefType = CaptureType; 18299 } 18300 18301 // Actually capture the variable. 18302 if (BuildAndDiagnose) 18303 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 18304 CaptureType, Invalid); 18305 18306 return !Invalid; 18307 } 18308 18309 18310 /// Capture the given variable in the captured region. 18311 static bool captureInCapturedRegion( 18312 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 18313 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 18314 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 18315 bool IsTopScope, Sema &S, bool Invalid) { 18316 // By default, capture variables by reference. 18317 bool ByRef = true; 18318 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18319 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18320 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 18321 // Using an LValue reference type is consistent with Lambdas (see below). 18322 if (S.isOpenMPCapturedDecl(Var)) { 18323 bool HasConst = DeclRefType.isConstQualified(); 18324 DeclRefType = DeclRefType.getUnqualifiedType(); 18325 // Don't lose diagnostics about assignments to const. 18326 if (HasConst) 18327 DeclRefType.addConst(); 18328 } 18329 // Do not capture firstprivates in tasks. 18330 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 18331 OMPC_unknown) 18332 return true; 18333 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 18334 RSI->OpenMPCaptureLevel); 18335 } 18336 18337 if (ByRef) 18338 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18339 else 18340 CaptureType = DeclRefType; 18341 18342 // Actually capture the variable. 18343 if (BuildAndDiagnose) 18344 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 18345 Loc, SourceLocation(), CaptureType, Invalid); 18346 18347 return !Invalid; 18348 } 18349 18350 /// Capture the given variable in the lambda. 18351 static bool captureInLambda(LambdaScopeInfo *LSI, 18352 VarDecl *Var, 18353 SourceLocation Loc, 18354 const bool BuildAndDiagnose, 18355 QualType &CaptureType, 18356 QualType &DeclRefType, 18357 const bool RefersToCapturedVariable, 18358 const Sema::TryCaptureKind Kind, 18359 SourceLocation EllipsisLoc, 18360 const bool IsTopScope, 18361 Sema &S, bool Invalid) { 18362 // Determine whether we are capturing by reference or by value. 18363 bool ByRef = false; 18364 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18365 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18366 } else { 18367 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 18368 } 18369 18370 // Compute the type of the field that will capture this variable. 18371 if (ByRef) { 18372 // C++11 [expr.prim.lambda]p15: 18373 // An entity is captured by reference if it is implicitly or 18374 // explicitly captured but not captured by copy. It is 18375 // unspecified whether additional unnamed non-static data 18376 // members are declared in the closure type for entities 18377 // captured by reference. 18378 // 18379 // FIXME: It is not clear whether we want to build an lvalue reference 18380 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 18381 // to do the former, while EDG does the latter. Core issue 1249 will 18382 // clarify, but for now we follow GCC because it's a more permissive and 18383 // easily defensible position. 18384 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18385 } else { 18386 // C++11 [expr.prim.lambda]p14: 18387 // For each entity captured by copy, an unnamed non-static 18388 // data member is declared in the closure type. The 18389 // declaration order of these members is unspecified. The type 18390 // of such a data member is the type of the corresponding 18391 // captured entity if the entity is not a reference to an 18392 // object, or the referenced type otherwise. [Note: If the 18393 // captured entity is a reference to a function, the 18394 // corresponding data member is also a reference to a 18395 // function. - end note ] 18396 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 18397 if (!RefType->getPointeeType()->isFunctionType()) 18398 CaptureType = RefType->getPointeeType(); 18399 } 18400 18401 // Forbid the lambda copy-capture of autoreleasing variables. 18402 if (!Invalid && 18403 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18404 if (BuildAndDiagnose) { 18405 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 18406 S.Diag(Var->getLocation(), diag::note_previous_decl) 18407 << Var->getDeclName(); 18408 Invalid = true; 18409 } else { 18410 return false; 18411 } 18412 } 18413 18414 // Make sure that by-copy captures are of a complete and non-abstract type. 18415 if (!Invalid && BuildAndDiagnose) { 18416 if (!CaptureType->isDependentType() && 18417 S.RequireCompleteSizedType( 18418 Loc, CaptureType, 18419 diag::err_capture_of_incomplete_or_sizeless_type, 18420 Var->getDeclName())) 18421 Invalid = true; 18422 else if (S.RequireNonAbstractType(Loc, CaptureType, 18423 diag::err_capture_of_abstract_type)) 18424 Invalid = true; 18425 } 18426 } 18427 18428 // Compute the type of a reference to this captured variable. 18429 if (ByRef) 18430 DeclRefType = CaptureType.getNonReferenceType(); 18431 else { 18432 // C++ [expr.prim.lambda]p5: 18433 // The closure type for a lambda-expression has a public inline 18434 // function call operator [...]. This function call operator is 18435 // declared const (9.3.1) if and only if the lambda-expression's 18436 // parameter-declaration-clause is not followed by mutable. 18437 DeclRefType = CaptureType.getNonReferenceType(); 18438 if (!LSI->Mutable && !CaptureType->isReferenceType()) 18439 DeclRefType.addConst(); 18440 } 18441 18442 // Add the capture. 18443 if (BuildAndDiagnose) 18444 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 18445 Loc, EllipsisLoc, CaptureType, Invalid); 18446 18447 return !Invalid; 18448 } 18449 18450 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 18451 // Offer a Copy fix even if the type is dependent. 18452 if (Var->getType()->isDependentType()) 18453 return true; 18454 QualType T = Var->getType().getNonReferenceType(); 18455 if (T.isTriviallyCopyableType(Context)) 18456 return true; 18457 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 18458 18459 if (!(RD = RD->getDefinition())) 18460 return false; 18461 if (RD->hasSimpleCopyConstructor()) 18462 return true; 18463 if (RD->hasUserDeclaredCopyConstructor()) 18464 for (CXXConstructorDecl *Ctor : RD->ctors()) 18465 if (Ctor->isCopyConstructor()) 18466 return !Ctor->isDeleted(); 18467 } 18468 return false; 18469 } 18470 18471 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 18472 /// default capture. Fixes may be omitted if they aren't allowed by the 18473 /// standard, for example we can't emit a default copy capture fix-it if we 18474 /// already explicitly copy capture capture another variable. 18475 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 18476 VarDecl *Var) { 18477 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 18478 // Don't offer Capture by copy of default capture by copy fixes if Var is 18479 // known not to be copy constructible. 18480 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 18481 18482 SmallString<32> FixBuffer; 18483 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 18484 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 18485 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 18486 if (ShouldOfferCopyFix) { 18487 // Offer fixes to insert an explicit capture for the variable. 18488 // [] -> [VarName] 18489 // [OtherCapture] -> [OtherCapture, VarName] 18490 FixBuffer.assign({Separator, Var->getName()}); 18491 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18492 << Var << /*value*/ 0 18493 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18494 } 18495 // As above but capture by reference. 18496 FixBuffer.assign({Separator, "&", Var->getName()}); 18497 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18498 << Var << /*reference*/ 1 18499 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18500 } 18501 18502 // Only try to offer default capture if there are no captures excluding this 18503 // and init captures. 18504 // [this]: OK. 18505 // [X = Y]: OK. 18506 // [&A, &B]: Don't offer. 18507 // [A, B]: Don't offer. 18508 if (llvm::any_of(LSI->Captures, [](Capture &C) { 18509 return !C.isThisCapture() && !C.isInitCapture(); 18510 })) 18511 return; 18512 18513 // The default capture specifiers, '=' or '&', must appear first in the 18514 // capture body. 18515 SourceLocation DefaultInsertLoc = 18516 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 18517 18518 if (ShouldOfferCopyFix) { 18519 bool CanDefaultCopyCapture = true; 18520 // [=, *this] OK since c++17 18521 // [=, this] OK since c++20 18522 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 18523 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 18524 ? LSI->getCXXThisCapture().isCopyCapture() 18525 : false; 18526 // We can't use default capture by copy if any captures already specified 18527 // capture by copy. 18528 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 18529 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 18530 })) { 18531 FixBuffer.assign({"=", Separator}); 18532 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 18533 << /*value*/ 0 18534 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 18535 } 18536 } 18537 18538 // We can't use default capture by reference if any captures already specified 18539 // capture by reference. 18540 if (llvm::none_of(LSI->Captures, [](Capture &C) { 18541 return !C.isInitCapture() && C.isReferenceCapture() && 18542 !C.isThisCapture(); 18543 })) { 18544 FixBuffer.assign({"&", Separator}); 18545 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 18546 << /*reference*/ 1 18547 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 18548 } 18549 } 18550 18551 bool Sema::tryCaptureVariable( 18552 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 18553 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 18554 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 18555 // An init-capture is notionally from the context surrounding its 18556 // declaration, but its parent DC is the lambda class. 18557 DeclContext *VarDC = Var->getDeclContext(); 18558 if (Var->isInitCapture()) 18559 VarDC = VarDC->getParent(); 18560 18561 DeclContext *DC = CurContext; 18562 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 18563 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 18564 // We need to sync up the Declaration Context with the 18565 // FunctionScopeIndexToStopAt 18566 if (FunctionScopeIndexToStopAt) { 18567 unsigned FSIndex = FunctionScopes.size() - 1; 18568 while (FSIndex != MaxFunctionScopesIndex) { 18569 DC = getLambdaAwareParentOfDeclContext(DC); 18570 --FSIndex; 18571 } 18572 } 18573 18574 18575 // If the variable is declared in the current context, there is no need to 18576 // capture it. 18577 if (VarDC == DC) return true; 18578 18579 // Capture global variables if it is required to use private copy of this 18580 // variable. 18581 bool IsGlobal = !Var->hasLocalStorage(); 18582 if (IsGlobal && 18583 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 18584 MaxFunctionScopesIndex))) 18585 return true; 18586 Var = Var->getCanonicalDecl(); 18587 18588 // Walk up the stack to determine whether we can capture the variable, 18589 // performing the "simple" checks that don't depend on type. We stop when 18590 // we've either hit the declared scope of the variable or find an existing 18591 // capture of that variable. We start from the innermost capturing-entity 18592 // (the DC) and ensure that all intervening capturing-entities 18593 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 18594 // declcontext can either capture the variable or have already captured 18595 // the variable. 18596 CaptureType = Var->getType(); 18597 DeclRefType = CaptureType.getNonReferenceType(); 18598 bool Nested = false; 18599 bool Explicit = (Kind != TryCapture_Implicit); 18600 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 18601 do { 18602 // Only block literals, captured statements, and lambda expressions can 18603 // capture; other scopes don't work. 18604 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 18605 ExprLoc, 18606 BuildAndDiagnose, 18607 *this); 18608 // We need to check for the parent *first* because, if we *have* 18609 // private-captured a global variable, we need to recursively capture it in 18610 // intermediate blocks, lambdas, etc. 18611 if (!ParentDC) { 18612 if (IsGlobal) { 18613 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 18614 break; 18615 } 18616 return true; 18617 } 18618 18619 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 18620 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 18621 18622 18623 // Check whether we've already captured it. 18624 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 18625 DeclRefType)) { 18626 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 18627 break; 18628 } 18629 // If we are instantiating a generic lambda call operator body, 18630 // we do not want to capture new variables. What was captured 18631 // during either a lambdas transformation or initial parsing 18632 // should be used. 18633 if (isGenericLambdaCallOperatorSpecialization(DC)) { 18634 if (BuildAndDiagnose) { 18635 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18636 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 18637 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18638 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18639 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18640 buildLambdaCaptureFixit(*this, LSI, Var); 18641 } else 18642 diagnoseUncapturableValueReference(*this, ExprLoc, Var); 18643 } 18644 return true; 18645 } 18646 18647 // Try to capture variable-length arrays types. 18648 if (Var->getType()->isVariablyModifiedType()) { 18649 // We're going to walk down into the type and look for VLA 18650 // expressions. 18651 QualType QTy = Var->getType(); 18652 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18653 QTy = PVD->getOriginalType(); 18654 captureVariablyModifiedType(Context, QTy, CSI); 18655 } 18656 18657 if (getLangOpts().OpenMP) { 18658 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18659 // OpenMP private variables should not be captured in outer scope, so 18660 // just break here. Similarly, global variables that are captured in a 18661 // target region should not be captured outside the scope of the region. 18662 if (RSI->CapRegionKind == CR_OpenMP) { 18663 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 18664 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 18665 // If the variable is private (i.e. not captured) and has variably 18666 // modified type, we still need to capture the type for correct 18667 // codegen in all regions, associated with the construct. Currently, 18668 // it is captured in the innermost captured region only. 18669 if (IsOpenMPPrivateDecl != OMPC_unknown && 18670 Var->getType()->isVariablyModifiedType()) { 18671 QualType QTy = Var->getType(); 18672 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18673 QTy = PVD->getOriginalType(); 18674 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 18675 I < E; ++I) { 18676 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 18677 FunctionScopes[FunctionScopesIndex - I]); 18678 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 18679 "Wrong number of captured regions associated with the " 18680 "OpenMP construct."); 18681 captureVariablyModifiedType(Context, QTy, OuterRSI); 18682 } 18683 } 18684 bool IsTargetCap = 18685 IsOpenMPPrivateDecl != OMPC_private && 18686 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 18687 RSI->OpenMPCaptureLevel); 18688 // Do not capture global if it is not privatized in outer regions. 18689 bool IsGlobalCap = 18690 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 18691 RSI->OpenMPCaptureLevel); 18692 18693 // When we detect target captures we are looking from inside the 18694 // target region, therefore we need to propagate the capture from the 18695 // enclosing region. Therefore, the capture is not initially nested. 18696 if (IsTargetCap) 18697 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18698 18699 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18700 (IsGlobal && !IsGlobalCap)) { 18701 Nested = !IsTargetCap; 18702 bool HasConst = DeclRefType.isConstQualified(); 18703 DeclRefType = DeclRefType.getUnqualifiedType(); 18704 // Don't lose diagnostics about assignments to const. 18705 if (HasConst) 18706 DeclRefType.addConst(); 18707 CaptureType = Context.getLValueReferenceType(DeclRefType); 18708 break; 18709 } 18710 } 18711 } 18712 } 18713 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18714 // No capture-default, and this is not an explicit capture 18715 // so cannot capture this variable. 18716 if (BuildAndDiagnose) { 18717 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18718 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18719 auto *LSI = cast<LambdaScopeInfo>(CSI); 18720 if (LSI->Lambda) { 18721 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18722 buildLambdaCaptureFixit(*this, LSI, Var); 18723 } 18724 // FIXME: If we error out because an outer lambda can not implicitly 18725 // capture a variable that an inner lambda explicitly captures, we 18726 // should have the inner lambda do the explicit capture - because 18727 // it makes for cleaner diagnostics later. This would purely be done 18728 // so that the diagnostic does not misleadingly claim that a variable 18729 // can not be captured by a lambda implicitly even though it is captured 18730 // explicitly. Suggestion: 18731 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18732 // at the function head 18733 // - cache the StartingDeclContext - this must be a lambda 18734 // - captureInLambda in the innermost lambda the variable. 18735 } 18736 return true; 18737 } 18738 18739 FunctionScopesIndex--; 18740 DC = ParentDC; 18741 Explicit = false; 18742 } while (!VarDC->Equals(DC)); 18743 18744 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18745 // computing the type of the capture at each step, checking type-specific 18746 // requirements, and adding captures if requested. 18747 // If the variable had already been captured previously, we start capturing 18748 // at the lambda nested within that one. 18749 bool Invalid = false; 18750 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18751 ++I) { 18752 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18753 18754 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18755 // certain types of variables (unnamed, variably modified types etc.) 18756 // so check for eligibility. 18757 if (!Invalid) 18758 Invalid = 18759 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18760 18761 // After encountering an error, if we're actually supposed to capture, keep 18762 // capturing in nested contexts to suppress any follow-on diagnostics. 18763 if (Invalid && !BuildAndDiagnose) 18764 return true; 18765 18766 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18767 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18768 DeclRefType, Nested, *this, Invalid); 18769 Nested = true; 18770 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18771 Invalid = !captureInCapturedRegion( 18772 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18773 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18774 Nested = true; 18775 } else { 18776 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18777 Invalid = 18778 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18779 DeclRefType, Nested, Kind, EllipsisLoc, 18780 /*IsTopScope*/ I == N - 1, *this, Invalid); 18781 Nested = true; 18782 } 18783 18784 if (Invalid && !BuildAndDiagnose) 18785 return true; 18786 } 18787 return Invalid; 18788 } 18789 18790 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18791 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18792 QualType CaptureType; 18793 QualType DeclRefType; 18794 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18795 /*BuildAndDiagnose=*/true, CaptureType, 18796 DeclRefType, nullptr); 18797 } 18798 18799 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18800 QualType CaptureType; 18801 QualType DeclRefType; 18802 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18803 /*BuildAndDiagnose=*/false, CaptureType, 18804 DeclRefType, nullptr); 18805 } 18806 18807 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18808 QualType CaptureType; 18809 QualType DeclRefType; 18810 18811 // Determine whether we can capture this variable. 18812 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18813 /*BuildAndDiagnose=*/false, CaptureType, 18814 DeclRefType, nullptr)) 18815 return QualType(); 18816 18817 return DeclRefType; 18818 } 18819 18820 namespace { 18821 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18822 // The produced TemplateArgumentListInfo* points to data stored within this 18823 // object, so should only be used in contexts where the pointer will not be 18824 // used after the CopiedTemplateArgs object is destroyed. 18825 class CopiedTemplateArgs { 18826 bool HasArgs; 18827 TemplateArgumentListInfo TemplateArgStorage; 18828 public: 18829 template<typename RefExpr> 18830 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18831 if (HasArgs) 18832 E->copyTemplateArgumentsInto(TemplateArgStorage); 18833 } 18834 operator TemplateArgumentListInfo*() 18835 #ifdef __has_cpp_attribute 18836 #if __has_cpp_attribute(clang::lifetimebound) 18837 [[clang::lifetimebound]] 18838 #endif 18839 #endif 18840 { 18841 return HasArgs ? &TemplateArgStorage : nullptr; 18842 } 18843 }; 18844 } 18845 18846 /// Walk the set of potential results of an expression and mark them all as 18847 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18848 /// 18849 /// \return A new expression if we found any potential results, ExprEmpty() if 18850 /// not, and ExprError() if we diagnosed an error. 18851 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18852 NonOdrUseReason NOUR) { 18853 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18854 // an object that satisfies the requirements for appearing in a 18855 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18856 // is immediately applied." This function handles the lvalue-to-rvalue 18857 // conversion part. 18858 // 18859 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18860 // transform it into the relevant kind of non-odr-use node and rebuild the 18861 // tree of nodes leading to it. 18862 // 18863 // This is a mini-TreeTransform that only transforms a restricted subset of 18864 // nodes (and only certain operands of them). 18865 18866 // Rebuild a subexpression. 18867 auto Rebuild = [&](Expr *Sub) { 18868 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18869 }; 18870 18871 // Check whether a potential result satisfies the requirements of NOUR. 18872 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18873 // Any entity other than a VarDecl is always odr-used whenever it's named 18874 // in a potentially-evaluated expression. 18875 auto *VD = dyn_cast<VarDecl>(D); 18876 if (!VD) 18877 return true; 18878 18879 // C++2a [basic.def.odr]p4: 18880 // A variable x whose name appears as a potentially-evalauted expression 18881 // e is odr-used by e unless 18882 // -- x is a reference that is usable in constant expressions, or 18883 // -- x is a variable of non-reference type that is usable in constant 18884 // expressions and has no mutable subobjects, and e is an element of 18885 // the set of potential results of an expression of 18886 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18887 // conversion is applied, or 18888 // -- x is a variable of non-reference type, and e is an element of the 18889 // set of potential results of a discarded-value expression to which 18890 // the lvalue-to-rvalue conversion is not applied 18891 // 18892 // We check the first bullet and the "potentially-evaluated" condition in 18893 // BuildDeclRefExpr. We check the type requirements in the second bullet 18894 // in CheckLValueToRValueConversionOperand below. 18895 switch (NOUR) { 18896 case NOUR_None: 18897 case NOUR_Unevaluated: 18898 llvm_unreachable("unexpected non-odr-use-reason"); 18899 18900 case NOUR_Constant: 18901 // Constant references were handled when they were built. 18902 if (VD->getType()->isReferenceType()) 18903 return true; 18904 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18905 if (RD->hasMutableFields()) 18906 return true; 18907 if (!VD->isUsableInConstantExpressions(S.Context)) 18908 return true; 18909 break; 18910 18911 case NOUR_Discarded: 18912 if (VD->getType()->isReferenceType()) 18913 return true; 18914 break; 18915 } 18916 return false; 18917 }; 18918 18919 // Mark that this expression does not constitute an odr-use. 18920 auto MarkNotOdrUsed = [&] { 18921 S.MaybeODRUseExprs.remove(E); 18922 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18923 LSI->markVariableExprAsNonODRUsed(E); 18924 }; 18925 18926 // C++2a [basic.def.odr]p2: 18927 // The set of potential results of an expression e is defined as follows: 18928 switch (E->getStmtClass()) { 18929 // -- If e is an id-expression, ... 18930 case Expr::DeclRefExprClass: { 18931 auto *DRE = cast<DeclRefExpr>(E); 18932 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18933 break; 18934 18935 // Rebuild as a non-odr-use DeclRefExpr. 18936 MarkNotOdrUsed(); 18937 return DeclRefExpr::Create( 18938 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18939 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18940 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18941 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18942 } 18943 18944 case Expr::FunctionParmPackExprClass: { 18945 auto *FPPE = cast<FunctionParmPackExpr>(E); 18946 // If any of the declarations in the pack is odr-used, then the expression 18947 // as a whole constitutes an odr-use. 18948 for (VarDecl *D : *FPPE) 18949 if (IsPotentialResultOdrUsed(D)) 18950 return ExprEmpty(); 18951 18952 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18953 // nothing cares about whether we marked this as an odr-use, but it might 18954 // be useful for non-compiler tools. 18955 MarkNotOdrUsed(); 18956 break; 18957 } 18958 18959 // -- If e is a subscripting operation with an array operand... 18960 case Expr::ArraySubscriptExprClass: { 18961 auto *ASE = cast<ArraySubscriptExpr>(E); 18962 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18963 if (!OldBase->getType()->isArrayType()) 18964 break; 18965 ExprResult Base = Rebuild(OldBase); 18966 if (!Base.isUsable()) 18967 return Base; 18968 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18969 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18970 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18971 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18972 ASE->getRBracketLoc()); 18973 } 18974 18975 case Expr::MemberExprClass: { 18976 auto *ME = cast<MemberExpr>(E); 18977 // -- If e is a class member access expression [...] naming a non-static 18978 // data member... 18979 if (isa<FieldDecl>(ME->getMemberDecl())) { 18980 ExprResult Base = Rebuild(ME->getBase()); 18981 if (!Base.isUsable()) 18982 return Base; 18983 return MemberExpr::Create( 18984 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18985 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18986 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18987 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18988 ME->getObjectKind(), ME->isNonOdrUse()); 18989 } 18990 18991 if (ME->getMemberDecl()->isCXXInstanceMember()) 18992 break; 18993 18994 // -- If e is a class member access expression naming a static data member, 18995 // ... 18996 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18997 break; 18998 18999 // Rebuild as a non-odr-use MemberExpr. 19000 MarkNotOdrUsed(); 19001 return MemberExpr::Create( 19002 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 19003 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 19004 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 19005 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 19006 } 19007 19008 case Expr::BinaryOperatorClass: { 19009 auto *BO = cast<BinaryOperator>(E); 19010 Expr *LHS = BO->getLHS(); 19011 Expr *RHS = BO->getRHS(); 19012 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 19013 if (BO->getOpcode() == BO_PtrMemD) { 19014 ExprResult Sub = Rebuild(LHS); 19015 if (!Sub.isUsable()) 19016 return Sub; 19017 LHS = Sub.get(); 19018 // -- If e is a comma expression, ... 19019 } else if (BO->getOpcode() == BO_Comma) { 19020 ExprResult Sub = Rebuild(RHS); 19021 if (!Sub.isUsable()) 19022 return Sub; 19023 RHS = Sub.get(); 19024 } else { 19025 break; 19026 } 19027 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 19028 LHS, RHS); 19029 } 19030 19031 // -- If e has the form (e1)... 19032 case Expr::ParenExprClass: { 19033 auto *PE = cast<ParenExpr>(E); 19034 ExprResult Sub = Rebuild(PE->getSubExpr()); 19035 if (!Sub.isUsable()) 19036 return Sub; 19037 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 19038 } 19039 19040 // -- If e is a glvalue conditional expression, ... 19041 // We don't apply this to a binary conditional operator. FIXME: Should we? 19042 case Expr::ConditionalOperatorClass: { 19043 auto *CO = cast<ConditionalOperator>(E); 19044 ExprResult LHS = Rebuild(CO->getLHS()); 19045 if (LHS.isInvalid()) 19046 return ExprError(); 19047 ExprResult RHS = Rebuild(CO->getRHS()); 19048 if (RHS.isInvalid()) 19049 return ExprError(); 19050 if (!LHS.isUsable() && !RHS.isUsable()) 19051 return ExprEmpty(); 19052 if (!LHS.isUsable()) 19053 LHS = CO->getLHS(); 19054 if (!RHS.isUsable()) 19055 RHS = CO->getRHS(); 19056 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 19057 CO->getCond(), LHS.get(), RHS.get()); 19058 } 19059 19060 // [Clang extension] 19061 // -- If e has the form __extension__ e1... 19062 case Expr::UnaryOperatorClass: { 19063 auto *UO = cast<UnaryOperator>(E); 19064 if (UO->getOpcode() != UO_Extension) 19065 break; 19066 ExprResult Sub = Rebuild(UO->getSubExpr()); 19067 if (!Sub.isUsable()) 19068 return Sub; 19069 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 19070 Sub.get()); 19071 } 19072 19073 // [Clang extension] 19074 // -- If e has the form _Generic(...), the set of potential results is the 19075 // union of the sets of potential results of the associated expressions. 19076 case Expr::GenericSelectionExprClass: { 19077 auto *GSE = cast<GenericSelectionExpr>(E); 19078 19079 SmallVector<Expr *, 4> AssocExprs; 19080 bool AnyChanged = false; 19081 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 19082 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 19083 if (AssocExpr.isInvalid()) 19084 return ExprError(); 19085 if (AssocExpr.isUsable()) { 19086 AssocExprs.push_back(AssocExpr.get()); 19087 AnyChanged = true; 19088 } else { 19089 AssocExprs.push_back(OrigAssocExpr); 19090 } 19091 } 19092 19093 return AnyChanged ? S.CreateGenericSelectionExpr( 19094 GSE->getGenericLoc(), GSE->getDefaultLoc(), 19095 GSE->getRParenLoc(), GSE->getControllingExpr(), 19096 GSE->getAssocTypeSourceInfos(), AssocExprs) 19097 : ExprEmpty(); 19098 } 19099 19100 // [Clang extension] 19101 // -- If e has the form __builtin_choose_expr(...), the set of potential 19102 // results is the union of the sets of potential results of the 19103 // second and third subexpressions. 19104 case Expr::ChooseExprClass: { 19105 auto *CE = cast<ChooseExpr>(E); 19106 19107 ExprResult LHS = Rebuild(CE->getLHS()); 19108 if (LHS.isInvalid()) 19109 return ExprError(); 19110 19111 ExprResult RHS = Rebuild(CE->getLHS()); 19112 if (RHS.isInvalid()) 19113 return ExprError(); 19114 19115 if (!LHS.get() && !RHS.get()) 19116 return ExprEmpty(); 19117 if (!LHS.isUsable()) 19118 LHS = CE->getLHS(); 19119 if (!RHS.isUsable()) 19120 RHS = CE->getRHS(); 19121 19122 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 19123 RHS.get(), CE->getRParenLoc()); 19124 } 19125 19126 // Step through non-syntactic nodes. 19127 case Expr::ConstantExprClass: { 19128 auto *CE = cast<ConstantExpr>(E); 19129 ExprResult Sub = Rebuild(CE->getSubExpr()); 19130 if (!Sub.isUsable()) 19131 return Sub; 19132 return ConstantExpr::Create(S.Context, Sub.get()); 19133 } 19134 19135 // We could mostly rely on the recursive rebuilding to rebuild implicit 19136 // casts, but not at the top level, so rebuild them here. 19137 case Expr::ImplicitCastExprClass: { 19138 auto *ICE = cast<ImplicitCastExpr>(E); 19139 // Only step through the narrow set of cast kinds we expect to encounter. 19140 // Anything else suggests we've left the region in which potential results 19141 // can be found. 19142 switch (ICE->getCastKind()) { 19143 case CK_NoOp: 19144 case CK_DerivedToBase: 19145 case CK_UncheckedDerivedToBase: { 19146 ExprResult Sub = Rebuild(ICE->getSubExpr()); 19147 if (!Sub.isUsable()) 19148 return Sub; 19149 CXXCastPath Path(ICE->path()); 19150 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 19151 ICE->getValueKind(), &Path); 19152 } 19153 19154 default: 19155 break; 19156 } 19157 break; 19158 } 19159 19160 default: 19161 break; 19162 } 19163 19164 // Can't traverse through this node. Nothing to do. 19165 return ExprEmpty(); 19166 } 19167 19168 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 19169 // Check whether the operand is or contains an object of non-trivial C union 19170 // type. 19171 if (E->getType().isVolatileQualified() && 19172 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 19173 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 19174 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 19175 Sema::NTCUC_LValueToRValueVolatile, 19176 NTCUK_Destruct|NTCUK_Copy); 19177 19178 // C++2a [basic.def.odr]p4: 19179 // [...] an expression of non-volatile-qualified non-class type to which 19180 // the lvalue-to-rvalue conversion is applied [...] 19181 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 19182 return E; 19183 19184 ExprResult Result = 19185 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 19186 if (Result.isInvalid()) 19187 return ExprError(); 19188 return Result.get() ? Result : E; 19189 } 19190 19191 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 19192 Res = CorrectDelayedTyposInExpr(Res); 19193 19194 if (!Res.isUsable()) 19195 return Res; 19196 19197 // If a constant-expression is a reference to a variable where we delay 19198 // deciding whether it is an odr-use, just assume we will apply the 19199 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 19200 // (a non-type template argument), we have special handling anyway. 19201 return CheckLValueToRValueConversionOperand(Res.get()); 19202 } 19203 19204 void Sema::CleanupVarDeclMarking() { 19205 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 19206 // call. 19207 MaybeODRUseExprSet LocalMaybeODRUseExprs; 19208 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 19209 19210 for (Expr *E : LocalMaybeODRUseExprs) { 19211 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 19212 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 19213 DRE->getLocation(), *this); 19214 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 19215 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 19216 *this); 19217 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 19218 for (VarDecl *VD : *FP) 19219 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 19220 } else { 19221 llvm_unreachable("Unexpected expression"); 19222 } 19223 } 19224 19225 assert(MaybeODRUseExprs.empty() && 19226 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 19227 } 19228 19229 static void DoMarkVarDeclReferenced( 19230 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 19231 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19232 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 19233 isa<FunctionParmPackExpr>(E)) && 19234 "Invalid Expr argument to DoMarkVarDeclReferenced"); 19235 Var->setReferenced(); 19236 19237 if (Var->isInvalidDecl()) 19238 return; 19239 19240 auto *MSI = Var->getMemberSpecializationInfo(); 19241 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 19242 : Var->getTemplateSpecializationKind(); 19243 19244 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 19245 bool UsableInConstantExpr = 19246 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 19247 19248 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 19249 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 19250 } 19251 19252 // C++20 [expr.const]p12: 19253 // A variable [...] is needed for constant evaluation if it is [...] a 19254 // variable whose name appears as a potentially constant evaluated 19255 // expression that is either a contexpr variable or is of non-volatile 19256 // const-qualified integral type or of reference type 19257 bool NeededForConstantEvaluation = 19258 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 19259 19260 bool NeedDefinition = 19261 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 19262 19263 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 19264 "Can't instantiate a partial template specialization."); 19265 19266 // If this might be a member specialization of a static data member, check 19267 // the specialization is visible. We already did the checks for variable 19268 // template specializations when we created them. 19269 if (NeedDefinition && TSK != TSK_Undeclared && 19270 !isa<VarTemplateSpecializationDecl>(Var)) 19271 SemaRef.checkSpecializationVisibility(Loc, Var); 19272 19273 // Perform implicit instantiation of static data members, static data member 19274 // templates of class templates, and variable template specializations. Delay 19275 // instantiations of variable templates, except for those that could be used 19276 // in a constant expression. 19277 if (NeedDefinition && isTemplateInstantiation(TSK)) { 19278 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 19279 // instantiation declaration if a variable is usable in a constant 19280 // expression (among other cases). 19281 bool TryInstantiating = 19282 TSK == TSK_ImplicitInstantiation || 19283 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 19284 19285 if (TryInstantiating) { 19286 SourceLocation PointOfInstantiation = 19287 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 19288 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 19289 if (FirstInstantiation) { 19290 PointOfInstantiation = Loc; 19291 if (MSI) 19292 MSI->setPointOfInstantiation(PointOfInstantiation); 19293 // FIXME: Notify listener. 19294 else 19295 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 19296 } 19297 19298 if (UsableInConstantExpr) { 19299 // Do not defer instantiations of variables that could be used in a 19300 // constant expression. 19301 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 19302 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 19303 }); 19304 19305 // Re-set the member to trigger a recomputation of the dependence bits 19306 // for the expression. 19307 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19308 DRE->setDecl(DRE->getDecl()); 19309 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 19310 ME->setMemberDecl(ME->getMemberDecl()); 19311 } else if (FirstInstantiation || 19312 isa<VarTemplateSpecializationDecl>(Var)) { 19313 // FIXME: For a specialization of a variable template, we don't 19314 // distinguish between "declaration and type implicitly instantiated" 19315 // and "implicit instantiation of definition requested", so we have 19316 // no direct way to avoid enqueueing the pending instantiation 19317 // multiple times. 19318 SemaRef.PendingInstantiations 19319 .push_back(std::make_pair(Var, PointOfInstantiation)); 19320 } 19321 } 19322 } 19323 19324 // C++2a [basic.def.odr]p4: 19325 // A variable x whose name appears as a potentially-evaluated expression e 19326 // is odr-used by e unless 19327 // -- x is a reference that is usable in constant expressions 19328 // -- x is a variable of non-reference type that is usable in constant 19329 // expressions and has no mutable subobjects [FIXME], and e is an 19330 // element of the set of potential results of an expression of 19331 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 19332 // conversion is applied 19333 // -- x is a variable of non-reference type, and e is an element of the set 19334 // of potential results of a discarded-value expression to which the 19335 // lvalue-to-rvalue conversion is not applied [FIXME] 19336 // 19337 // We check the first part of the second bullet here, and 19338 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 19339 // FIXME: To get the third bullet right, we need to delay this even for 19340 // variables that are not usable in constant expressions. 19341 19342 // If we already know this isn't an odr-use, there's nothing more to do. 19343 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19344 if (DRE->isNonOdrUse()) 19345 return; 19346 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 19347 if (ME->isNonOdrUse()) 19348 return; 19349 19350 switch (OdrUse) { 19351 case OdrUseContext::None: 19352 assert((!E || isa<FunctionParmPackExpr>(E)) && 19353 "missing non-odr-use marking for unevaluated decl ref"); 19354 break; 19355 19356 case OdrUseContext::FormallyOdrUsed: 19357 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 19358 // behavior. 19359 break; 19360 19361 case OdrUseContext::Used: 19362 // If we might later find that this expression isn't actually an odr-use, 19363 // delay the marking. 19364 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 19365 SemaRef.MaybeODRUseExprs.insert(E); 19366 else 19367 MarkVarDeclODRUsed(Var, Loc, SemaRef); 19368 break; 19369 19370 case OdrUseContext::Dependent: 19371 // If this is a dependent context, we don't need to mark variables as 19372 // odr-used, but we may still need to track them for lambda capture. 19373 // FIXME: Do we also need to do this inside dependent typeid expressions 19374 // (which are modeled as unevaluated at this point)? 19375 const bool RefersToEnclosingScope = 19376 (SemaRef.CurContext != Var->getDeclContext() && 19377 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 19378 if (RefersToEnclosingScope) { 19379 LambdaScopeInfo *const LSI = 19380 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 19381 if (LSI && (!LSI->CallOperator || 19382 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 19383 // If a variable could potentially be odr-used, defer marking it so 19384 // until we finish analyzing the full expression for any 19385 // lvalue-to-rvalue 19386 // or discarded value conversions that would obviate odr-use. 19387 // Add it to the list of potential captures that will be analyzed 19388 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 19389 // unless the variable is a reference that was initialized by a constant 19390 // expression (this will never need to be captured or odr-used). 19391 // 19392 // FIXME: We can simplify this a lot after implementing P0588R1. 19393 assert(E && "Capture variable should be used in an expression."); 19394 if (!Var->getType()->isReferenceType() || 19395 !Var->isUsableInConstantExpressions(SemaRef.Context)) 19396 LSI->addPotentialCapture(E->IgnoreParens()); 19397 } 19398 } 19399 break; 19400 } 19401 } 19402 19403 /// Mark a variable referenced, and check whether it is odr-used 19404 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 19405 /// used directly for normal expressions referring to VarDecl. 19406 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 19407 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 19408 } 19409 19410 static void 19411 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 19412 bool MightBeOdrUse, 19413 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19414 if (SemaRef.isInOpenMPDeclareTargetContext()) 19415 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 19416 19417 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 19418 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 19419 return; 19420 } 19421 19422 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 19423 19424 // If this is a call to a method via a cast, also mark the method in the 19425 // derived class used in case codegen can devirtualize the call. 19426 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 19427 if (!ME) 19428 return; 19429 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 19430 if (!MD) 19431 return; 19432 // Only attempt to devirtualize if this is truly a virtual call. 19433 bool IsVirtualCall = MD->isVirtual() && 19434 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 19435 if (!IsVirtualCall) 19436 return; 19437 19438 // If it's possible to devirtualize the call, mark the called function 19439 // referenced. 19440 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 19441 ME->getBase(), SemaRef.getLangOpts().AppleKext); 19442 if (DM) 19443 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 19444 } 19445 19446 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 19447 /// 19448 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 19449 /// handled with care if the DeclRefExpr is not newly-created. 19450 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 19451 // TODO: update this with DR# once a defect report is filed. 19452 // C++11 defect. The address of a pure member should not be an ODR use, even 19453 // if it's a qualified reference. 19454 bool OdrUse = true; 19455 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 19456 if (Method->isVirtual() && 19457 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 19458 OdrUse = false; 19459 19460 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 19461 if (!isUnevaluatedContext() && !isConstantEvaluated() && 19462 FD->isConsteval() && !RebuildingImmediateInvocation) 19463 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 19464 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 19465 RefsMinusAssignments); 19466 } 19467 19468 /// Perform reference-marking and odr-use handling for a MemberExpr. 19469 void Sema::MarkMemberReferenced(MemberExpr *E) { 19470 // C++11 [basic.def.odr]p2: 19471 // A non-overloaded function whose name appears as a potentially-evaluated 19472 // expression or a member of a set of candidate functions, if selected by 19473 // overload resolution when referred to from a potentially-evaluated 19474 // expression, is odr-used, unless it is a pure virtual function and its 19475 // name is not explicitly qualified. 19476 bool MightBeOdrUse = true; 19477 if (E->performsVirtualDispatch(getLangOpts())) { 19478 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 19479 if (Method->isPure()) 19480 MightBeOdrUse = false; 19481 } 19482 SourceLocation Loc = 19483 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 19484 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 19485 RefsMinusAssignments); 19486 } 19487 19488 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 19489 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 19490 for (VarDecl *VD : *E) 19491 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 19492 RefsMinusAssignments); 19493 } 19494 19495 /// Perform marking for a reference to an arbitrary declaration. It 19496 /// marks the declaration referenced, and performs odr-use checking for 19497 /// functions and variables. This method should not be used when building a 19498 /// normal expression which refers to a variable. 19499 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 19500 bool MightBeOdrUse) { 19501 if (MightBeOdrUse) { 19502 if (auto *VD = dyn_cast<VarDecl>(D)) { 19503 MarkVariableReferenced(Loc, VD); 19504 return; 19505 } 19506 } 19507 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 19508 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 19509 return; 19510 } 19511 D->setReferenced(); 19512 } 19513 19514 namespace { 19515 // Mark all of the declarations used by a type as referenced. 19516 // FIXME: Not fully implemented yet! We need to have a better understanding 19517 // of when we're entering a context we should not recurse into. 19518 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 19519 // TreeTransforms rebuilding the type in a new context. Rather than 19520 // duplicating the TreeTransform logic, we should consider reusing it here. 19521 // Currently that causes problems when rebuilding LambdaExprs. 19522 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 19523 Sema &S; 19524 SourceLocation Loc; 19525 19526 public: 19527 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 19528 19529 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 19530 19531 bool TraverseTemplateArgument(const TemplateArgument &Arg); 19532 }; 19533 } 19534 19535 bool MarkReferencedDecls::TraverseTemplateArgument( 19536 const TemplateArgument &Arg) { 19537 { 19538 // A non-type template argument is a constant-evaluated context. 19539 EnterExpressionEvaluationContext Evaluated( 19540 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 19541 if (Arg.getKind() == TemplateArgument::Declaration) { 19542 if (Decl *D = Arg.getAsDecl()) 19543 S.MarkAnyDeclReferenced(Loc, D, true); 19544 } else if (Arg.getKind() == TemplateArgument::Expression) { 19545 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 19546 } 19547 } 19548 19549 return Inherited::TraverseTemplateArgument(Arg); 19550 } 19551 19552 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 19553 MarkReferencedDecls Marker(*this, Loc); 19554 Marker.TraverseType(T); 19555 } 19556 19557 namespace { 19558 /// Helper class that marks all of the declarations referenced by 19559 /// potentially-evaluated subexpressions as "referenced". 19560 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 19561 public: 19562 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 19563 bool SkipLocalVariables; 19564 ArrayRef<const Expr *> StopAt; 19565 19566 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 19567 ArrayRef<const Expr *> StopAt) 19568 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 19569 19570 void visitUsedDecl(SourceLocation Loc, Decl *D) { 19571 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 19572 } 19573 19574 void Visit(Expr *E) { 19575 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end()) 19576 return; 19577 Inherited::Visit(E); 19578 } 19579 19580 void VisitDeclRefExpr(DeclRefExpr *E) { 19581 // If we were asked not to visit local variables, don't. 19582 if (SkipLocalVariables) { 19583 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 19584 if (VD->hasLocalStorage()) 19585 return; 19586 } 19587 19588 // FIXME: This can trigger the instantiation of the initializer of a 19589 // variable, which can cause the expression to become value-dependent 19590 // or error-dependent. Do we need to propagate the new dependence bits? 19591 S.MarkDeclRefReferenced(E); 19592 } 19593 19594 void VisitMemberExpr(MemberExpr *E) { 19595 S.MarkMemberReferenced(E); 19596 Visit(E->getBase()); 19597 } 19598 }; 19599 } // namespace 19600 19601 /// Mark any declarations that appear within this expression or any 19602 /// potentially-evaluated subexpressions as "referenced". 19603 /// 19604 /// \param SkipLocalVariables If true, don't mark local variables as 19605 /// 'referenced'. 19606 /// \param StopAt Subexpressions that we shouldn't recurse into. 19607 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 19608 bool SkipLocalVariables, 19609 ArrayRef<const Expr*> StopAt) { 19610 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 19611 } 19612 19613 /// Emit a diagnostic when statements are reachable. 19614 /// FIXME: check for reachability even in expressions for which we don't build a 19615 /// CFG (eg, in the initializer of a global or in a constant expression). 19616 /// For example, 19617 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 19618 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 19619 const PartialDiagnostic &PD) { 19620 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 19621 if (!FunctionScopes.empty()) 19622 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 19623 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 19624 return true; 19625 } 19626 19627 // The initializer of a constexpr variable or of the first declaration of a 19628 // static data member is not syntactically a constant evaluated constant, 19629 // but nonetheless is always required to be a constant expression, so we 19630 // can skip diagnosing. 19631 // FIXME: Using the mangling context here is a hack. 19632 if (auto *VD = dyn_cast_or_null<VarDecl>( 19633 ExprEvalContexts.back().ManglingContextDecl)) { 19634 if (VD->isConstexpr() || 19635 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 19636 return false; 19637 // FIXME: For any other kind of variable, we should build a CFG for its 19638 // initializer and check whether the context in question is reachable. 19639 } 19640 19641 Diag(Loc, PD); 19642 return true; 19643 } 19644 19645 /// Emit a diagnostic that describes an effect on the run-time behavior 19646 /// of the program being compiled. 19647 /// 19648 /// This routine emits the given diagnostic when the code currently being 19649 /// type-checked is "potentially evaluated", meaning that there is a 19650 /// possibility that the code will actually be executable. Code in sizeof() 19651 /// expressions, code used only during overload resolution, etc., are not 19652 /// potentially evaluated. This routine will suppress such diagnostics or, 19653 /// in the absolutely nutty case of potentially potentially evaluated 19654 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 19655 /// later. 19656 /// 19657 /// This routine should be used for all diagnostics that describe the run-time 19658 /// behavior of a program, such as passing a non-POD value through an ellipsis. 19659 /// Failure to do so will likely result in spurious diagnostics or failures 19660 /// during overload resolution or within sizeof/alignof/typeof/typeid. 19661 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 19662 const PartialDiagnostic &PD) { 19663 19664 if (ExprEvalContexts.back().isDiscardedStatementContext()) 19665 return false; 19666 19667 switch (ExprEvalContexts.back().Context) { 19668 case ExpressionEvaluationContext::Unevaluated: 19669 case ExpressionEvaluationContext::UnevaluatedList: 19670 case ExpressionEvaluationContext::UnevaluatedAbstract: 19671 case ExpressionEvaluationContext::DiscardedStatement: 19672 // The argument will never be evaluated, so don't complain. 19673 break; 19674 19675 case ExpressionEvaluationContext::ConstantEvaluated: 19676 case ExpressionEvaluationContext::ImmediateFunctionContext: 19677 // Relevant diagnostics should be produced by constant evaluation. 19678 break; 19679 19680 case ExpressionEvaluationContext::PotentiallyEvaluated: 19681 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 19682 return DiagIfReachable(Loc, Stmts, PD); 19683 } 19684 19685 return false; 19686 } 19687 19688 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 19689 const PartialDiagnostic &PD) { 19690 return DiagRuntimeBehavior( 19691 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 19692 } 19693 19694 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 19695 CallExpr *CE, FunctionDecl *FD) { 19696 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 19697 return false; 19698 19699 // If we're inside a decltype's expression, don't check for a valid return 19700 // type or construct temporaries until we know whether this is the last call. 19701 if (ExprEvalContexts.back().ExprContext == 19702 ExpressionEvaluationContextRecord::EK_Decltype) { 19703 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 19704 return false; 19705 } 19706 19707 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19708 FunctionDecl *FD; 19709 CallExpr *CE; 19710 19711 public: 19712 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19713 : FD(FD), CE(CE) { } 19714 19715 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19716 if (!FD) { 19717 S.Diag(Loc, diag::err_call_incomplete_return) 19718 << T << CE->getSourceRange(); 19719 return; 19720 } 19721 19722 S.Diag(Loc, diag::err_call_function_incomplete_return) 19723 << CE->getSourceRange() << FD << T; 19724 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19725 << FD->getDeclName(); 19726 } 19727 } Diagnoser(FD, CE); 19728 19729 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19730 return true; 19731 19732 return false; 19733 } 19734 19735 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19736 // will prevent this condition from triggering, which is what we want. 19737 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19738 SourceLocation Loc; 19739 19740 unsigned diagnostic = diag::warn_condition_is_assignment; 19741 bool IsOrAssign = false; 19742 19743 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19744 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19745 return; 19746 19747 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19748 19749 // Greylist some idioms by putting them into a warning subcategory. 19750 if (ObjCMessageExpr *ME 19751 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19752 Selector Sel = ME->getSelector(); 19753 19754 // self = [<foo> init...] 19755 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19756 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19757 19758 // <foo> = [<bar> nextObject] 19759 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19760 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19761 } 19762 19763 Loc = Op->getOperatorLoc(); 19764 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19765 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19766 return; 19767 19768 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19769 Loc = Op->getOperatorLoc(); 19770 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19771 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19772 else { 19773 // Not an assignment. 19774 return; 19775 } 19776 19777 Diag(Loc, diagnostic) << E->getSourceRange(); 19778 19779 SourceLocation Open = E->getBeginLoc(); 19780 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19781 Diag(Loc, diag::note_condition_assign_silence) 19782 << FixItHint::CreateInsertion(Open, "(") 19783 << FixItHint::CreateInsertion(Close, ")"); 19784 19785 if (IsOrAssign) 19786 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19787 << FixItHint::CreateReplacement(Loc, "!="); 19788 else 19789 Diag(Loc, diag::note_condition_assign_to_comparison) 19790 << FixItHint::CreateReplacement(Loc, "=="); 19791 } 19792 19793 /// Redundant parentheses over an equality comparison can indicate 19794 /// that the user intended an assignment used as condition. 19795 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19796 // Don't warn if the parens came from a macro. 19797 SourceLocation parenLoc = ParenE->getBeginLoc(); 19798 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19799 return; 19800 // Don't warn for dependent expressions. 19801 if (ParenE->isTypeDependent()) 19802 return; 19803 19804 Expr *E = ParenE->IgnoreParens(); 19805 19806 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19807 if (opE->getOpcode() == BO_EQ && 19808 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19809 == Expr::MLV_Valid) { 19810 SourceLocation Loc = opE->getOperatorLoc(); 19811 19812 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19813 SourceRange ParenERange = ParenE->getSourceRange(); 19814 Diag(Loc, diag::note_equality_comparison_silence) 19815 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19816 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19817 Diag(Loc, diag::note_equality_comparison_to_assign) 19818 << FixItHint::CreateReplacement(Loc, "="); 19819 } 19820 } 19821 19822 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19823 bool IsConstexpr) { 19824 DiagnoseAssignmentAsCondition(E); 19825 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19826 DiagnoseEqualityWithExtraParens(parenE); 19827 19828 ExprResult result = CheckPlaceholderExpr(E); 19829 if (result.isInvalid()) return ExprError(); 19830 E = result.get(); 19831 19832 if (!E->isTypeDependent()) { 19833 if (getLangOpts().CPlusPlus) 19834 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19835 19836 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19837 if (ERes.isInvalid()) 19838 return ExprError(); 19839 E = ERes.get(); 19840 19841 QualType T = E->getType(); 19842 if (!T->isScalarType()) { // C99 6.8.4.1p1 19843 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19844 << T << E->getSourceRange(); 19845 return ExprError(); 19846 } 19847 CheckBoolLikeConversion(E, Loc); 19848 } 19849 19850 return E; 19851 } 19852 19853 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19854 Expr *SubExpr, ConditionKind CK, 19855 bool MissingOK) { 19856 // MissingOK indicates whether having no condition expression is valid 19857 // (for loop) or invalid (e.g. while loop). 19858 if (!SubExpr) 19859 return MissingOK ? ConditionResult() : ConditionError(); 19860 19861 ExprResult Cond; 19862 switch (CK) { 19863 case ConditionKind::Boolean: 19864 Cond = CheckBooleanCondition(Loc, SubExpr); 19865 break; 19866 19867 case ConditionKind::ConstexprIf: 19868 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19869 break; 19870 19871 case ConditionKind::Switch: 19872 Cond = CheckSwitchCondition(Loc, SubExpr); 19873 break; 19874 } 19875 if (Cond.isInvalid()) { 19876 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19877 {SubExpr}, PreferredConditionType(CK)); 19878 if (!Cond.get()) 19879 return ConditionError(); 19880 } 19881 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19882 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19883 if (!FullExpr.get()) 19884 return ConditionError(); 19885 19886 return ConditionResult(*this, nullptr, FullExpr, 19887 CK == ConditionKind::ConstexprIf); 19888 } 19889 19890 namespace { 19891 /// A visitor for rebuilding a call to an __unknown_any expression 19892 /// to have an appropriate type. 19893 struct RebuildUnknownAnyFunction 19894 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19895 19896 Sema &S; 19897 19898 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19899 19900 ExprResult VisitStmt(Stmt *S) { 19901 llvm_unreachable("unexpected statement!"); 19902 } 19903 19904 ExprResult VisitExpr(Expr *E) { 19905 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19906 << E->getSourceRange(); 19907 return ExprError(); 19908 } 19909 19910 /// Rebuild an expression which simply semantically wraps another 19911 /// expression which it shares the type and value kind of. 19912 template <class T> ExprResult rebuildSugarExpr(T *E) { 19913 ExprResult SubResult = Visit(E->getSubExpr()); 19914 if (SubResult.isInvalid()) return ExprError(); 19915 19916 Expr *SubExpr = SubResult.get(); 19917 E->setSubExpr(SubExpr); 19918 E->setType(SubExpr->getType()); 19919 E->setValueKind(SubExpr->getValueKind()); 19920 assert(E->getObjectKind() == OK_Ordinary); 19921 return E; 19922 } 19923 19924 ExprResult VisitParenExpr(ParenExpr *E) { 19925 return rebuildSugarExpr(E); 19926 } 19927 19928 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19929 return rebuildSugarExpr(E); 19930 } 19931 19932 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19933 ExprResult SubResult = Visit(E->getSubExpr()); 19934 if (SubResult.isInvalid()) return ExprError(); 19935 19936 Expr *SubExpr = SubResult.get(); 19937 E->setSubExpr(SubExpr); 19938 E->setType(S.Context.getPointerType(SubExpr->getType())); 19939 assert(E->isPRValue()); 19940 assert(E->getObjectKind() == OK_Ordinary); 19941 return E; 19942 } 19943 19944 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19945 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19946 19947 E->setType(VD->getType()); 19948 19949 assert(E->isPRValue()); 19950 if (S.getLangOpts().CPlusPlus && 19951 !(isa<CXXMethodDecl>(VD) && 19952 cast<CXXMethodDecl>(VD)->isInstance())) 19953 E->setValueKind(VK_LValue); 19954 19955 return E; 19956 } 19957 19958 ExprResult VisitMemberExpr(MemberExpr *E) { 19959 return resolveDecl(E, E->getMemberDecl()); 19960 } 19961 19962 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19963 return resolveDecl(E, E->getDecl()); 19964 } 19965 }; 19966 } 19967 19968 /// Given a function expression of unknown-any type, try to rebuild it 19969 /// to have a function type. 19970 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19971 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19972 if (Result.isInvalid()) return ExprError(); 19973 return S.DefaultFunctionArrayConversion(Result.get()); 19974 } 19975 19976 namespace { 19977 /// A visitor for rebuilding an expression of type __unknown_anytype 19978 /// into one which resolves the type directly on the referring 19979 /// expression. Strict preservation of the original source 19980 /// structure is not a goal. 19981 struct RebuildUnknownAnyExpr 19982 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19983 19984 Sema &S; 19985 19986 /// The current destination type. 19987 QualType DestType; 19988 19989 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19990 : S(S), DestType(CastType) {} 19991 19992 ExprResult VisitStmt(Stmt *S) { 19993 llvm_unreachable("unexpected statement!"); 19994 } 19995 19996 ExprResult VisitExpr(Expr *E) { 19997 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19998 << E->getSourceRange(); 19999 return ExprError(); 20000 } 20001 20002 ExprResult VisitCallExpr(CallExpr *E); 20003 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 20004 20005 /// Rebuild an expression which simply semantically wraps another 20006 /// expression which it shares the type and value kind of. 20007 template <class T> ExprResult rebuildSugarExpr(T *E) { 20008 ExprResult SubResult = Visit(E->getSubExpr()); 20009 if (SubResult.isInvalid()) return ExprError(); 20010 Expr *SubExpr = SubResult.get(); 20011 E->setSubExpr(SubExpr); 20012 E->setType(SubExpr->getType()); 20013 E->setValueKind(SubExpr->getValueKind()); 20014 assert(E->getObjectKind() == OK_Ordinary); 20015 return E; 20016 } 20017 20018 ExprResult VisitParenExpr(ParenExpr *E) { 20019 return rebuildSugarExpr(E); 20020 } 20021 20022 ExprResult VisitUnaryExtension(UnaryOperator *E) { 20023 return rebuildSugarExpr(E); 20024 } 20025 20026 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 20027 const PointerType *Ptr = DestType->getAs<PointerType>(); 20028 if (!Ptr) { 20029 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 20030 << E->getSourceRange(); 20031 return ExprError(); 20032 } 20033 20034 if (isa<CallExpr>(E->getSubExpr())) { 20035 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 20036 << E->getSourceRange(); 20037 return ExprError(); 20038 } 20039 20040 assert(E->isPRValue()); 20041 assert(E->getObjectKind() == OK_Ordinary); 20042 E->setType(DestType); 20043 20044 // Build the sub-expression as if it were an object of the pointee type. 20045 DestType = Ptr->getPointeeType(); 20046 ExprResult SubResult = Visit(E->getSubExpr()); 20047 if (SubResult.isInvalid()) return ExprError(); 20048 E->setSubExpr(SubResult.get()); 20049 return E; 20050 } 20051 20052 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 20053 20054 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 20055 20056 ExprResult VisitMemberExpr(MemberExpr *E) { 20057 return resolveDecl(E, E->getMemberDecl()); 20058 } 20059 20060 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 20061 return resolveDecl(E, E->getDecl()); 20062 } 20063 }; 20064 } 20065 20066 /// Rebuilds a call expression which yielded __unknown_anytype. 20067 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 20068 Expr *CalleeExpr = E->getCallee(); 20069 20070 enum FnKind { 20071 FK_MemberFunction, 20072 FK_FunctionPointer, 20073 FK_BlockPointer 20074 }; 20075 20076 FnKind Kind; 20077 QualType CalleeType = CalleeExpr->getType(); 20078 if (CalleeType == S.Context.BoundMemberTy) { 20079 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 20080 Kind = FK_MemberFunction; 20081 CalleeType = Expr::findBoundMemberType(CalleeExpr); 20082 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 20083 CalleeType = Ptr->getPointeeType(); 20084 Kind = FK_FunctionPointer; 20085 } else { 20086 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 20087 Kind = FK_BlockPointer; 20088 } 20089 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 20090 20091 // Verify that this is a legal result type of a function. 20092 if (DestType->isArrayType() || DestType->isFunctionType()) { 20093 unsigned diagID = diag::err_func_returning_array_function; 20094 if (Kind == FK_BlockPointer) 20095 diagID = diag::err_block_returning_array_function; 20096 20097 S.Diag(E->getExprLoc(), diagID) 20098 << DestType->isFunctionType() << DestType; 20099 return ExprError(); 20100 } 20101 20102 // Otherwise, go ahead and set DestType as the call's result. 20103 E->setType(DestType.getNonLValueExprType(S.Context)); 20104 E->setValueKind(Expr::getValueKindForType(DestType)); 20105 assert(E->getObjectKind() == OK_Ordinary); 20106 20107 // Rebuild the function type, replacing the result type with DestType. 20108 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 20109 if (Proto) { 20110 // __unknown_anytype(...) is a special case used by the debugger when 20111 // it has no idea what a function's signature is. 20112 // 20113 // We want to build this call essentially under the K&R 20114 // unprototyped rules, but making a FunctionNoProtoType in C++ 20115 // would foul up all sorts of assumptions. However, we cannot 20116 // simply pass all arguments as variadic arguments, nor can we 20117 // portably just call the function under a non-variadic type; see 20118 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 20119 // However, it turns out that in practice it is generally safe to 20120 // call a function declared as "A foo(B,C,D);" under the prototype 20121 // "A foo(B,C,D,...);". The only known exception is with the 20122 // Windows ABI, where any variadic function is implicitly cdecl 20123 // regardless of its normal CC. Therefore we change the parameter 20124 // types to match the types of the arguments. 20125 // 20126 // This is a hack, but it is far superior to moving the 20127 // corresponding target-specific code from IR-gen to Sema/AST. 20128 20129 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 20130 SmallVector<QualType, 8> ArgTypes; 20131 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 20132 ArgTypes.reserve(E->getNumArgs()); 20133 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 20134 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 20135 } 20136 ParamTypes = ArgTypes; 20137 } 20138 DestType = S.Context.getFunctionType(DestType, ParamTypes, 20139 Proto->getExtProtoInfo()); 20140 } else { 20141 DestType = S.Context.getFunctionNoProtoType(DestType, 20142 FnType->getExtInfo()); 20143 } 20144 20145 // Rebuild the appropriate pointer-to-function type. 20146 switch (Kind) { 20147 case FK_MemberFunction: 20148 // Nothing to do. 20149 break; 20150 20151 case FK_FunctionPointer: 20152 DestType = S.Context.getPointerType(DestType); 20153 break; 20154 20155 case FK_BlockPointer: 20156 DestType = S.Context.getBlockPointerType(DestType); 20157 break; 20158 } 20159 20160 // Finally, we can recurse. 20161 ExprResult CalleeResult = Visit(CalleeExpr); 20162 if (!CalleeResult.isUsable()) return ExprError(); 20163 E->setCallee(CalleeResult.get()); 20164 20165 // Bind a temporary if necessary. 20166 return S.MaybeBindToTemporary(E); 20167 } 20168 20169 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 20170 // Verify that this is a legal result type of a call. 20171 if (DestType->isArrayType() || DestType->isFunctionType()) { 20172 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 20173 << DestType->isFunctionType() << DestType; 20174 return ExprError(); 20175 } 20176 20177 // Rewrite the method result type if available. 20178 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 20179 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 20180 Method->setReturnType(DestType); 20181 } 20182 20183 // Change the type of the message. 20184 E->setType(DestType.getNonReferenceType()); 20185 E->setValueKind(Expr::getValueKindForType(DestType)); 20186 20187 return S.MaybeBindToTemporary(E); 20188 } 20189 20190 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 20191 // The only case we should ever see here is a function-to-pointer decay. 20192 if (E->getCastKind() == CK_FunctionToPointerDecay) { 20193 assert(E->isPRValue()); 20194 assert(E->getObjectKind() == OK_Ordinary); 20195 20196 E->setType(DestType); 20197 20198 // Rebuild the sub-expression as the pointee (function) type. 20199 DestType = DestType->castAs<PointerType>()->getPointeeType(); 20200 20201 ExprResult Result = Visit(E->getSubExpr()); 20202 if (!Result.isUsable()) return ExprError(); 20203 20204 E->setSubExpr(Result.get()); 20205 return E; 20206 } else if (E->getCastKind() == CK_LValueToRValue) { 20207 assert(E->isPRValue()); 20208 assert(E->getObjectKind() == OK_Ordinary); 20209 20210 assert(isa<BlockPointerType>(E->getType())); 20211 20212 E->setType(DestType); 20213 20214 // The sub-expression has to be a lvalue reference, so rebuild it as such. 20215 DestType = S.Context.getLValueReferenceType(DestType); 20216 20217 ExprResult Result = Visit(E->getSubExpr()); 20218 if (!Result.isUsable()) return ExprError(); 20219 20220 E->setSubExpr(Result.get()); 20221 return E; 20222 } else { 20223 llvm_unreachable("Unhandled cast type!"); 20224 } 20225 } 20226 20227 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 20228 ExprValueKind ValueKind = VK_LValue; 20229 QualType Type = DestType; 20230 20231 // We know how to make this work for certain kinds of decls: 20232 20233 // - functions 20234 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 20235 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 20236 DestType = Ptr->getPointeeType(); 20237 ExprResult Result = resolveDecl(E, VD); 20238 if (Result.isInvalid()) return ExprError(); 20239 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 20240 VK_PRValue); 20241 } 20242 20243 if (!Type->isFunctionType()) { 20244 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 20245 << VD << E->getSourceRange(); 20246 return ExprError(); 20247 } 20248 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 20249 // We must match the FunctionDecl's type to the hack introduced in 20250 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 20251 // type. See the lengthy commentary in that routine. 20252 QualType FDT = FD->getType(); 20253 const FunctionType *FnType = FDT->castAs<FunctionType>(); 20254 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 20255 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 20256 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 20257 SourceLocation Loc = FD->getLocation(); 20258 FunctionDecl *NewFD = FunctionDecl::Create( 20259 S.Context, FD->getDeclContext(), Loc, Loc, 20260 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 20261 SC_None, S.getCurFPFeatures().isFPConstrained(), 20262 false /*isInlineSpecified*/, FD->hasPrototype(), 20263 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 20264 20265 if (FD->getQualifier()) 20266 NewFD->setQualifierInfo(FD->getQualifierLoc()); 20267 20268 SmallVector<ParmVarDecl*, 16> Params; 20269 for (const auto &AI : FT->param_types()) { 20270 ParmVarDecl *Param = 20271 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 20272 Param->setScopeInfo(0, Params.size()); 20273 Params.push_back(Param); 20274 } 20275 NewFD->setParams(Params); 20276 DRE->setDecl(NewFD); 20277 VD = DRE->getDecl(); 20278 } 20279 } 20280 20281 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 20282 if (MD->isInstance()) { 20283 ValueKind = VK_PRValue; 20284 Type = S.Context.BoundMemberTy; 20285 } 20286 20287 // Function references aren't l-values in C. 20288 if (!S.getLangOpts().CPlusPlus) 20289 ValueKind = VK_PRValue; 20290 20291 // - variables 20292 } else if (isa<VarDecl>(VD)) { 20293 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 20294 Type = RefTy->getPointeeType(); 20295 } else if (Type->isFunctionType()) { 20296 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 20297 << VD << E->getSourceRange(); 20298 return ExprError(); 20299 } 20300 20301 // - nothing else 20302 } else { 20303 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 20304 << VD << E->getSourceRange(); 20305 return ExprError(); 20306 } 20307 20308 // Modifying the declaration like this is friendly to IR-gen but 20309 // also really dangerous. 20310 VD->setType(DestType); 20311 E->setType(Type); 20312 E->setValueKind(ValueKind); 20313 return E; 20314 } 20315 20316 /// Check a cast of an unknown-any type. We intentionally only 20317 /// trigger this for C-style casts. 20318 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 20319 Expr *CastExpr, CastKind &CastKind, 20320 ExprValueKind &VK, CXXCastPath &Path) { 20321 // The type we're casting to must be either void or complete. 20322 if (!CastType->isVoidType() && 20323 RequireCompleteType(TypeRange.getBegin(), CastType, 20324 diag::err_typecheck_cast_to_incomplete)) 20325 return ExprError(); 20326 20327 // Rewrite the casted expression from scratch. 20328 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 20329 if (!result.isUsable()) return ExprError(); 20330 20331 CastExpr = result.get(); 20332 VK = CastExpr->getValueKind(); 20333 CastKind = CK_NoOp; 20334 20335 return CastExpr; 20336 } 20337 20338 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 20339 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 20340 } 20341 20342 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 20343 Expr *arg, QualType ¶mType) { 20344 // If the syntactic form of the argument is not an explicit cast of 20345 // any sort, just do default argument promotion. 20346 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 20347 if (!castArg) { 20348 ExprResult result = DefaultArgumentPromotion(arg); 20349 if (result.isInvalid()) return ExprError(); 20350 paramType = result.get()->getType(); 20351 return result; 20352 } 20353 20354 // Otherwise, use the type that was written in the explicit cast. 20355 assert(!arg->hasPlaceholderType()); 20356 paramType = castArg->getTypeAsWritten(); 20357 20358 // Copy-initialize a parameter of that type. 20359 InitializedEntity entity = 20360 InitializedEntity::InitializeParameter(Context, paramType, 20361 /*consumed*/ false); 20362 return PerformCopyInitialization(entity, callLoc, arg); 20363 } 20364 20365 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 20366 Expr *orig = E; 20367 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 20368 while (true) { 20369 E = E->IgnoreParenImpCasts(); 20370 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 20371 E = call->getCallee(); 20372 diagID = diag::err_uncasted_call_of_unknown_any; 20373 } else { 20374 break; 20375 } 20376 } 20377 20378 SourceLocation loc; 20379 NamedDecl *d; 20380 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 20381 loc = ref->getLocation(); 20382 d = ref->getDecl(); 20383 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 20384 loc = mem->getMemberLoc(); 20385 d = mem->getMemberDecl(); 20386 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 20387 diagID = diag::err_uncasted_call_of_unknown_any; 20388 loc = msg->getSelectorStartLoc(); 20389 d = msg->getMethodDecl(); 20390 if (!d) { 20391 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 20392 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 20393 << orig->getSourceRange(); 20394 return ExprError(); 20395 } 20396 } else { 20397 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 20398 << E->getSourceRange(); 20399 return ExprError(); 20400 } 20401 20402 S.Diag(loc, diagID) << d << orig->getSourceRange(); 20403 20404 // Never recoverable. 20405 return ExprError(); 20406 } 20407 20408 /// Check for operands with placeholder types and complain if found. 20409 /// Returns ExprError() if there was an error and no recovery was possible. 20410 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 20411 if (!Context.isDependenceAllowed()) { 20412 // C cannot handle TypoExpr nodes on either side of a binop because it 20413 // doesn't handle dependent types properly, so make sure any TypoExprs have 20414 // been dealt with before checking the operands. 20415 ExprResult Result = CorrectDelayedTyposInExpr(E); 20416 if (!Result.isUsable()) return ExprError(); 20417 E = Result.get(); 20418 } 20419 20420 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 20421 if (!placeholderType) return E; 20422 20423 switch (placeholderType->getKind()) { 20424 20425 // Overloaded expressions. 20426 case BuiltinType::Overload: { 20427 // Try to resolve a single function template specialization. 20428 // This is obligatory. 20429 ExprResult Result = E; 20430 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 20431 return Result; 20432 20433 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 20434 // leaves Result unchanged on failure. 20435 Result = E; 20436 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 20437 return Result; 20438 20439 // If that failed, try to recover with a call. 20440 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 20441 /*complain*/ true); 20442 return Result; 20443 } 20444 20445 // Bound member functions. 20446 case BuiltinType::BoundMember: { 20447 ExprResult result = E; 20448 const Expr *BME = E->IgnoreParens(); 20449 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 20450 // Try to give a nicer diagnostic if it is a bound member that we recognize. 20451 if (isa<CXXPseudoDestructorExpr>(BME)) { 20452 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 20453 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 20454 if (ME->getMemberNameInfo().getName().getNameKind() == 20455 DeclarationName::CXXDestructorName) 20456 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 20457 } 20458 tryToRecoverWithCall(result, PD, 20459 /*complain*/ true); 20460 return result; 20461 } 20462 20463 // ARC unbridged casts. 20464 case BuiltinType::ARCUnbridgedCast: { 20465 Expr *realCast = stripARCUnbridgedCast(E); 20466 diagnoseARCUnbridgedCast(realCast); 20467 return realCast; 20468 } 20469 20470 // Expressions of unknown type. 20471 case BuiltinType::UnknownAny: 20472 return diagnoseUnknownAnyExpr(*this, E); 20473 20474 // Pseudo-objects. 20475 case BuiltinType::PseudoObject: 20476 return checkPseudoObjectRValue(E); 20477 20478 case BuiltinType::BuiltinFn: { 20479 // Accept __noop without parens by implicitly converting it to a call expr. 20480 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 20481 if (DRE) { 20482 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 20483 unsigned BuiltinID = FD->getBuiltinID(); 20484 if (BuiltinID == Builtin::BI__noop) { 20485 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 20486 CK_BuiltinFnToFnPtr) 20487 .get(); 20488 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 20489 VK_PRValue, SourceLocation(), 20490 FPOptionsOverride()); 20491 } 20492 20493 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) { 20494 // Any use of these other than a direct call is ill-formed as of C++20, 20495 // because they are not addressable functions. In earlier language 20496 // modes, warn and force an instantiation of the real body. 20497 Diag(E->getBeginLoc(), 20498 getLangOpts().CPlusPlus20 20499 ? diag::err_use_of_unaddressable_function 20500 : diag::warn_cxx20_compat_use_of_unaddressable_function); 20501 if (FD->isImplicitlyInstantiable()) { 20502 // Require a definition here because a normal attempt at 20503 // instantiation for a builtin will be ignored, and we won't try 20504 // again later. We assume that the definition of the template 20505 // precedes this use. 20506 InstantiateFunctionDefinition(E->getBeginLoc(), FD, 20507 /*Recursive=*/false, 20508 /*DefinitionRequired=*/true, 20509 /*AtEndOfTU=*/false); 20510 } 20511 // Produce a properly-typed reference to the function. 20512 CXXScopeSpec SS; 20513 SS.Adopt(DRE->getQualifierLoc()); 20514 TemplateArgumentListInfo TemplateArgs; 20515 DRE->copyTemplateArgumentsInto(TemplateArgs); 20516 return BuildDeclRefExpr( 20517 FD, FD->getType(), VK_LValue, DRE->getNameInfo(), 20518 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(), 20519 DRE->getTemplateKeywordLoc(), 20520 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr); 20521 } 20522 } 20523 20524 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 20525 return ExprError(); 20526 } 20527 20528 case BuiltinType::IncompleteMatrixIdx: 20529 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 20530 ->getRowIdx() 20531 ->getBeginLoc(), 20532 diag::err_matrix_incomplete_index); 20533 return ExprError(); 20534 20535 // Expressions of unknown type. 20536 case BuiltinType::OMPArraySection: 20537 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 20538 return ExprError(); 20539 20540 // Expressions of unknown type. 20541 case BuiltinType::OMPArrayShaping: 20542 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 20543 20544 case BuiltinType::OMPIterator: 20545 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 20546 20547 // Everything else should be impossible. 20548 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 20549 case BuiltinType::Id: 20550 #include "clang/Basic/OpenCLImageTypes.def" 20551 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 20552 case BuiltinType::Id: 20553 #include "clang/Basic/OpenCLExtensionTypes.def" 20554 #define SVE_TYPE(Name, Id, SingletonId) \ 20555 case BuiltinType::Id: 20556 #include "clang/Basic/AArch64SVEACLETypes.def" 20557 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 20558 case BuiltinType::Id: 20559 #include "clang/Basic/PPCTypes.def" 20560 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 20561 #include "clang/Basic/RISCVVTypes.def" 20562 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 20563 #define PLACEHOLDER_TYPE(Id, SingletonId) 20564 #include "clang/AST/BuiltinTypes.def" 20565 break; 20566 } 20567 20568 llvm_unreachable("invalid placeholder type!"); 20569 } 20570 20571 bool Sema::CheckCaseExpression(Expr *E) { 20572 if (E->isTypeDependent()) 20573 return true; 20574 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 20575 return E->getType()->isIntegralOrEnumerationType(); 20576 return false; 20577 } 20578 20579 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 20580 ExprResult 20581 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 20582 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 20583 "Unknown Objective-C Boolean value!"); 20584 QualType BoolT = Context.ObjCBuiltinBoolTy; 20585 if (!Context.getBOOLDecl()) { 20586 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 20587 Sema::LookupOrdinaryName); 20588 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 20589 NamedDecl *ND = Result.getFoundDecl(); 20590 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 20591 Context.setBOOLDecl(TD); 20592 } 20593 } 20594 if (Context.getBOOLDecl()) 20595 BoolT = Context.getBOOLType(); 20596 return new (Context) 20597 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 20598 } 20599 20600 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 20601 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 20602 SourceLocation RParen) { 20603 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 20604 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20605 return Spec.getPlatform() == Platform; 20606 }); 20607 // Transcribe the "ios" availability check to "maccatalyst" when compiling 20608 // for "maccatalyst" if "maccatalyst" is not specified. 20609 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 20610 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20611 return Spec.getPlatform() == "ios"; 20612 }); 20613 } 20614 if (Spec == AvailSpecs.end()) 20615 return None; 20616 return Spec->getVersion(); 20617 }; 20618 20619 VersionTuple Version; 20620 if (auto MaybeVersion = 20621 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 20622 Version = *MaybeVersion; 20623 20624 // The use of `@available` in the enclosing context should be analyzed to 20625 // warn when it's used inappropriately (i.e. not if(@available)). 20626 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 20627 Context->HasPotentialAvailabilityViolations = true; 20628 20629 return new (Context) 20630 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 20631 } 20632 20633 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 20634 ArrayRef<Expr *> SubExprs, QualType T) { 20635 if (!Context.getLangOpts().RecoveryAST) 20636 return ExprError(); 20637 20638 if (isSFINAEContext()) 20639 return ExprError(); 20640 20641 if (T.isNull() || T->isUndeducedType() || 20642 !Context.getLangOpts().RecoveryASTType) 20643 // We don't know the concrete type, fallback to dependent type. 20644 T = Context.DependentTy; 20645 20646 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 20647 } 20648