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/TypeLoc.h" 31 #include "clang/Basic/Builtins.h" 32 #include "clang/Basic/DiagnosticSema.h" 33 #include "clang/Basic/PartialDiagnostic.h" 34 #include "clang/Basic/SourceManager.h" 35 #include "clang/Basic/TargetInfo.h" 36 #include "clang/Lex/LiteralSupport.h" 37 #include "clang/Lex/Preprocessor.h" 38 #include "clang/Sema/AnalysisBasedWarnings.h" 39 #include "clang/Sema/DeclSpec.h" 40 #include "clang/Sema/DelayedDiagnostic.h" 41 #include "clang/Sema/Designator.h" 42 #include "clang/Sema/Initialization.h" 43 #include "clang/Sema/Lookup.h" 44 #include "clang/Sema/Overload.h" 45 #include "clang/Sema/ParsedTemplate.h" 46 #include "clang/Sema/Scope.h" 47 #include "clang/Sema/ScopeInfo.h" 48 #include "clang/Sema/SemaFixItUtils.h" 49 #include "clang/Sema/SemaInternal.h" 50 #include "clang/Sema/Template.h" 51 #include "llvm/ADT/STLExtras.h" 52 #include "llvm/ADT/StringExtras.h" 53 #include "llvm/Support/ConvertUTF.h" 54 #include "llvm/Support/SaveAndRestore.h" 55 56 using namespace clang; 57 using namespace sema; 58 59 /// Determine whether the use of this declaration is valid, without 60 /// emitting diagnostics. 61 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 62 // See if this is an auto-typed variable whose initializer we are parsing. 63 if (ParsingInitForAutoVars.count(D)) 64 return false; 65 66 // See if this is a deleted function. 67 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 68 if (FD->isDeleted()) 69 return false; 70 71 // If the function has a deduced return type, and we can't deduce it, 72 // then we can't use it either. 73 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 74 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 75 return false; 76 77 // See if this is an aligned allocation/deallocation function that is 78 // unavailable. 79 if (TreatUnavailableAsInvalid && 80 isUnavailableAlignedAllocationFunction(*FD)) 81 return false; 82 } 83 84 // See if this function is unavailable. 85 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 86 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 87 return false; 88 89 if (isa<UnresolvedUsingIfExistsDecl>(D)) 90 return false; 91 92 return true; 93 } 94 95 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 96 // Warn if this is used but marked unused. 97 if (const auto *A = D->getAttr<UnusedAttr>()) { 98 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 99 // should diagnose them. 100 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 101 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 102 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 103 if (DC && !DC->hasAttr<UnusedAttr>()) 104 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 105 } 106 } 107 } 108 109 /// Emit a note explaining that this function is deleted. 110 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 111 assert(Decl && Decl->isDeleted()); 112 113 if (Decl->isDefaulted()) { 114 // If the method was explicitly defaulted, point at that declaration. 115 if (!Decl->isImplicit()) 116 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 117 118 // Try to diagnose why this special member function was implicitly 119 // deleted. This might fail, if that reason no longer applies. 120 DiagnoseDeletedDefaultedFunction(Decl); 121 return; 122 } 123 124 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 125 if (Ctor && Ctor->isInheritingConstructor()) 126 return NoteDeletedInheritingConstructor(Ctor); 127 128 Diag(Decl->getLocation(), diag::note_availability_specified_here) 129 << Decl << 1; 130 } 131 132 /// Determine whether a FunctionDecl was ever declared with an 133 /// explicit storage class. 134 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 135 for (auto I : D->redecls()) { 136 if (I->getStorageClass() != SC_None) 137 return true; 138 } 139 return false; 140 } 141 142 /// Check whether we're in an extern inline function and referring to a 143 /// variable or function with internal linkage (C11 6.7.4p3). 144 /// 145 /// This is only a warning because we used to silently accept this code, but 146 /// in many cases it will not behave correctly. This is not enabled in C++ mode 147 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 148 /// and so while there may still be user mistakes, most of the time we can't 149 /// prove that there are errors. 150 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 151 const NamedDecl *D, 152 SourceLocation Loc) { 153 // This is disabled under C++; there are too many ways for this to fire in 154 // contexts where the warning is a false positive, or where it is technically 155 // correct but benign. 156 if (S.getLangOpts().CPlusPlus) 157 return; 158 159 // Check if this is an inlined function or method. 160 FunctionDecl *Current = S.getCurFunctionDecl(); 161 if (!Current) 162 return; 163 if (!Current->isInlined()) 164 return; 165 if (!Current->isExternallyVisible()) 166 return; 167 168 // Check if the decl has internal linkage. 169 if (D->getFormalLinkage() != InternalLinkage) 170 return; 171 172 // Downgrade from ExtWarn to Extension if 173 // (1) the supposedly external inline function is in the main file, 174 // and probably won't be included anywhere else. 175 // (2) the thing we're referencing is a pure function. 176 // (3) the thing we're referencing is another inline function. 177 // This last can give us false negatives, but it's better than warning on 178 // wrappers for simple C library functions. 179 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 180 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 181 if (!DowngradeWarning && UsedFn) 182 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 183 184 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 185 : diag::ext_internal_in_extern_inline) 186 << /*IsVar=*/!UsedFn << D; 187 188 S.MaybeSuggestAddingStaticToDecl(Current); 189 190 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 191 << D; 192 } 193 194 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 195 const FunctionDecl *First = Cur->getFirstDecl(); 196 197 // Suggest "static" on the function, if possible. 198 if (!hasAnyExplicitStorageClass(First)) { 199 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 200 Diag(DeclBegin, diag::note_convert_inline_to_static) 201 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 202 } 203 } 204 205 /// Determine whether the use of this declaration is valid, and 206 /// emit any corresponding diagnostics. 207 /// 208 /// This routine diagnoses various problems with referencing 209 /// declarations that can occur when using a declaration. For example, 210 /// it might warn if a deprecated or unavailable declaration is being 211 /// used, or produce an error (and return true) if a C++0x deleted 212 /// function is being used. 213 /// 214 /// \returns true if there was an error (this declaration cannot be 215 /// referenced), false otherwise. 216 /// 217 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 218 const ObjCInterfaceDecl *UnknownObjCClass, 219 bool ObjCPropertyAccess, 220 bool AvoidPartialAvailabilityChecks, 221 ObjCInterfaceDecl *ClassReceiver) { 222 SourceLocation Loc = Locs.front(); 223 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 224 // If there were any diagnostics suppressed by template argument deduction, 225 // emit them now. 226 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 227 if (Pos != SuppressedDiagnostics.end()) { 228 for (const PartialDiagnosticAt &Suppressed : Pos->second) 229 Diag(Suppressed.first, Suppressed.second); 230 231 // Clear out the list of suppressed diagnostics, so that we don't emit 232 // them again for this specialization. However, we don't obsolete this 233 // entry from the table, because we want to avoid ever emitting these 234 // diagnostics again. 235 Pos->second.clear(); 236 } 237 238 // C++ [basic.start.main]p3: 239 // The function 'main' shall not be used within a program. 240 if (cast<FunctionDecl>(D)->isMain()) 241 Diag(Loc, diag::ext_main_used); 242 243 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 244 } 245 246 // See if this is an auto-typed variable whose initializer we are parsing. 247 if (ParsingInitForAutoVars.count(D)) { 248 if (isa<BindingDecl>(D)) { 249 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 250 << D->getDeclName(); 251 } else { 252 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 253 << D->getDeclName() << cast<VarDecl>(D)->getType(); 254 } 255 return true; 256 } 257 258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 259 // See if this is a deleted function. 260 if (FD->isDeleted()) { 261 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 262 if (Ctor && Ctor->isInheritingConstructor()) 263 Diag(Loc, diag::err_deleted_inherited_ctor_use) 264 << Ctor->getParent() 265 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 266 else 267 Diag(Loc, diag::err_deleted_function_use); 268 NoteDeletedFunction(FD); 269 return true; 270 } 271 272 // [expr.prim.id]p4 273 // A program that refers explicitly or implicitly to a function with a 274 // trailing requires-clause whose constraint-expression is not satisfied, 275 // other than to declare it, is ill-formed. [...] 276 // 277 // See if this is a function with constraints that need to be satisfied. 278 // Check this before deducing the return type, as it might instantiate the 279 // definition. 280 if (FD->getTrailingRequiresClause()) { 281 ConstraintSatisfaction Satisfaction; 282 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 283 // A diagnostic will have already been generated (non-constant 284 // constraint expression, for example) 285 return true; 286 if (!Satisfaction.IsSatisfied) { 287 Diag(Loc, 288 diag::err_reference_to_function_with_unsatisfied_constraints) 289 << D; 290 DiagnoseUnsatisfiedConstraint(Satisfaction); 291 return true; 292 } 293 } 294 295 // If the function has a deduced return type, and we can't deduce it, 296 // then we can't use it either. 297 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 298 DeduceReturnType(FD, Loc)) 299 return true; 300 301 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 302 return true; 303 304 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 305 return true; 306 } 307 308 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 309 // Lambdas are only default-constructible or assignable in C++2a onwards. 310 if (MD->getParent()->isLambda() && 311 ((isa<CXXConstructorDecl>(MD) && 312 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 313 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 314 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 315 << !isa<CXXConstructorDecl>(MD); 316 } 317 } 318 319 auto getReferencedObjCProp = [](const NamedDecl *D) -> 320 const ObjCPropertyDecl * { 321 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 322 return MD->findPropertyDecl(); 323 return nullptr; 324 }; 325 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 326 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 327 return true; 328 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 329 return true; 330 } 331 332 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 333 // Only the variables omp_in and omp_out are allowed in the combiner. 334 // Only the variables omp_priv and omp_orig are allowed in the 335 // initializer-clause. 336 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 337 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 338 isa<VarDecl>(D)) { 339 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 340 << getCurFunction()->HasOMPDeclareReductionCombiner; 341 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 342 return true; 343 } 344 345 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 346 // List-items in map clauses on this construct may only refer to the declared 347 // variable var and entities that could be referenced by a procedure defined 348 // at the same location 349 if (LangOpts.OpenMP && isa<VarDecl>(D) && 350 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 351 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 352 << getOpenMPDeclareMapperVarName(); 353 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 354 return true; 355 } 356 357 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 358 Diag(Loc, diag::err_use_of_empty_using_if_exists); 359 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 360 return true; 361 } 362 363 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 364 AvoidPartialAvailabilityChecks, ClassReceiver); 365 366 DiagnoseUnusedOfDecl(*this, D, Loc); 367 368 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 369 370 if (auto *VD = dyn_cast<ValueDecl>(D)) 371 checkTypeSupport(VD->getType(), Loc, VD); 372 373 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 374 if (!Context.getTargetInfo().isTLSSupported()) 375 if (const auto *VD = dyn_cast<VarDecl>(D)) 376 if (VD->getTLSKind() != VarDecl::TLS_None) 377 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 378 } 379 380 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 381 !isUnevaluatedContext()) { 382 // C++ [expr.prim.req.nested] p3 383 // A local parameter shall only appear as an unevaluated operand 384 // (Clause 8) within the constraint-expression. 385 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 386 << D; 387 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 388 return true; 389 } 390 391 return false; 392 } 393 394 /// DiagnoseSentinelCalls - This routine checks whether a call or 395 /// message-send is to a declaration with the sentinel attribute, and 396 /// if so, it checks that the requirements of the sentinel are 397 /// satisfied. 398 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 399 ArrayRef<Expr *> Args) { 400 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 401 if (!attr) 402 return; 403 404 // The number of formal parameters of the declaration. 405 unsigned numFormalParams; 406 407 // The kind of declaration. This is also an index into a %select in 408 // the diagnostic. 409 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 410 411 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 412 numFormalParams = MD->param_size(); 413 calleeType = CT_Method; 414 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 415 numFormalParams = FD->param_size(); 416 calleeType = CT_Function; 417 } else if (isa<VarDecl>(D)) { 418 QualType type = cast<ValueDecl>(D)->getType(); 419 const FunctionType *fn = nullptr; 420 if (const PointerType *ptr = type->getAs<PointerType>()) { 421 fn = ptr->getPointeeType()->getAs<FunctionType>(); 422 if (!fn) return; 423 calleeType = CT_Function; 424 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 425 fn = ptr->getPointeeType()->castAs<FunctionType>(); 426 calleeType = CT_Block; 427 } else { 428 return; 429 } 430 431 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 432 numFormalParams = proto->getNumParams(); 433 } else { 434 numFormalParams = 0; 435 } 436 } else { 437 return; 438 } 439 440 // "nullPos" is the number of formal parameters at the end which 441 // effectively count as part of the variadic arguments. This is 442 // useful if you would prefer to not have *any* formal parameters, 443 // but the language forces you to have at least one. 444 unsigned nullPos = attr->getNullPos(); 445 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 446 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 447 448 // The number of arguments which should follow the sentinel. 449 unsigned numArgsAfterSentinel = attr->getSentinel(); 450 451 // If there aren't enough arguments for all the formal parameters, 452 // the sentinel, and the args after the sentinel, complain. 453 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 454 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 455 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 456 return; 457 } 458 459 // Otherwise, find the sentinel expression. 460 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 461 if (!sentinelExpr) return; 462 if (sentinelExpr->isValueDependent()) return; 463 if (Context.isSentinelNullExpr(sentinelExpr)) return; 464 465 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 466 // or 'NULL' if those are actually defined in the context. Only use 467 // 'nil' for ObjC methods, where it's much more likely that the 468 // variadic arguments form a list of object pointers. 469 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 470 std::string NullValue; 471 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 472 NullValue = "nil"; 473 else if (getLangOpts().CPlusPlus11) 474 NullValue = "nullptr"; 475 else if (PP.isMacroDefined("NULL")) 476 NullValue = "NULL"; 477 else 478 NullValue = "(void*) 0"; 479 480 if (MissingNilLoc.isInvalid()) 481 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 482 else 483 Diag(MissingNilLoc, diag::warn_missing_sentinel) 484 << int(calleeType) 485 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 486 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 487 } 488 489 SourceRange Sema::getExprRange(Expr *E) const { 490 return E ? E->getSourceRange() : SourceRange(); 491 } 492 493 //===----------------------------------------------------------------------===// 494 // Standard Promotions and Conversions 495 //===----------------------------------------------------------------------===// 496 497 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 498 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 499 // Handle any placeholder expressions which made it here. 500 if (E->hasPlaceholderType()) { 501 ExprResult result = CheckPlaceholderExpr(E); 502 if (result.isInvalid()) return ExprError(); 503 E = result.get(); 504 } 505 506 QualType Ty = E->getType(); 507 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 508 509 if (Ty->isFunctionType()) { 510 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 511 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 512 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 513 return ExprError(); 514 515 E = ImpCastExprToType(E, Context.getPointerType(Ty), 516 CK_FunctionToPointerDecay).get(); 517 } else if (Ty->isArrayType()) { 518 // In C90 mode, arrays only promote to pointers if the array expression is 519 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 520 // type 'array of type' is converted to an expression that has type 'pointer 521 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 522 // that has type 'array of type' ...". The relevant change is "an lvalue" 523 // (C90) to "an expression" (C99). 524 // 525 // C++ 4.2p1: 526 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 527 // T" can be converted to an rvalue of type "pointer to T". 528 // 529 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 530 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 531 CK_ArrayToPointerDecay); 532 if (Res.isInvalid()) 533 return ExprError(); 534 E = Res.get(); 535 } 536 } 537 return E; 538 } 539 540 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 541 // Check to see if we are dereferencing a null pointer. If so, 542 // and if not volatile-qualified, this is undefined behavior that the 543 // optimizer will delete, so warn about it. People sometimes try to use this 544 // to get a deterministic trap and are surprised by clang's behavior. This 545 // only handles the pattern "*null", which is a very syntactic check. 546 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 547 if (UO && UO->getOpcode() == UO_Deref && 548 UO->getSubExpr()->getType()->isPointerType()) { 549 const LangAS AS = 550 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 551 if ((!isTargetAddressSpace(AS) || 552 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 553 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 554 S.Context, Expr::NPC_ValueDependentIsNotNull) && 555 !UO->getType().isVolatileQualified()) { 556 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 557 S.PDiag(diag::warn_indirection_through_null) 558 << UO->getSubExpr()->getSourceRange()); 559 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 560 S.PDiag(diag::note_indirection_through_null)); 561 } 562 } 563 } 564 565 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 566 SourceLocation AssignLoc, 567 const Expr* RHS) { 568 const ObjCIvarDecl *IV = OIRE->getDecl(); 569 if (!IV) 570 return; 571 572 DeclarationName MemberName = IV->getDeclName(); 573 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 574 if (!Member || !Member->isStr("isa")) 575 return; 576 577 const Expr *Base = OIRE->getBase(); 578 QualType BaseType = Base->getType(); 579 if (OIRE->isArrow()) 580 BaseType = BaseType->getPointeeType(); 581 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 582 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 583 ObjCInterfaceDecl *ClassDeclared = nullptr; 584 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 585 if (!ClassDeclared->getSuperClass() 586 && (*ClassDeclared->ivar_begin()) == IV) { 587 if (RHS) { 588 NamedDecl *ObjectSetClass = 589 S.LookupSingleName(S.TUScope, 590 &S.Context.Idents.get("object_setClass"), 591 SourceLocation(), S.LookupOrdinaryName); 592 if (ObjectSetClass) { 593 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 594 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 595 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 596 "object_setClass(") 597 << FixItHint::CreateReplacement( 598 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 599 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 600 } 601 else 602 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 603 } else { 604 NamedDecl *ObjectGetClass = 605 S.LookupSingleName(S.TUScope, 606 &S.Context.Idents.get("object_getClass"), 607 SourceLocation(), S.LookupOrdinaryName); 608 if (ObjectGetClass) 609 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 610 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 611 "object_getClass(") 612 << FixItHint::CreateReplacement( 613 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 614 else 615 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 616 } 617 S.Diag(IV->getLocation(), diag::note_ivar_decl); 618 } 619 } 620 } 621 622 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 623 // Handle any placeholder expressions which made it here. 624 if (E->hasPlaceholderType()) { 625 ExprResult result = CheckPlaceholderExpr(E); 626 if (result.isInvalid()) return ExprError(); 627 E = result.get(); 628 } 629 630 // C++ [conv.lval]p1: 631 // A glvalue of a non-function, non-array type T can be 632 // converted to a prvalue. 633 if (!E->isGLValue()) return E; 634 635 QualType T = E->getType(); 636 assert(!T.isNull() && "r-value conversion on typeless expression?"); 637 638 // lvalue-to-rvalue conversion cannot be applied to function or array types. 639 if (T->isFunctionType() || T->isArrayType()) 640 return E; 641 642 // We don't want to throw lvalue-to-rvalue casts on top of 643 // expressions of certain types in C++. 644 if (getLangOpts().CPlusPlus && 645 (E->getType() == Context.OverloadTy || 646 T->isDependentType() || 647 T->isRecordType())) 648 return E; 649 650 // The C standard is actually really unclear on this point, and 651 // DR106 tells us what the result should be but not why. It's 652 // generally best to say that void types just doesn't undergo 653 // lvalue-to-rvalue at all. Note that expressions of unqualified 654 // 'void' type are never l-values, but qualified void can be. 655 if (T->isVoidType()) 656 return E; 657 658 // OpenCL usually rejects direct accesses to values of 'half' type. 659 if (getLangOpts().OpenCL && 660 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 661 T->isHalfType()) { 662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 663 << 0 << T; 664 return ExprError(); 665 } 666 667 CheckForNullPointerDereference(*this, E); 668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 670 &Context.Idents.get("object_getClass"), 671 SourceLocation(), LookupOrdinaryName); 672 if (ObjectGetClass) 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 674 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 675 << FixItHint::CreateReplacement( 676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 677 else 678 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 679 } 680 else if (const ObjCIvarRefExpr *OIRE = 681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 683 684 // C++ [conv.lval]p1: 685 // [...] If T is a non-class type, the type of the prvalue is the 686 // cv-unqualified version of T. Otherwise, the type of the 687 // rvalue is T. 688 // 689 // C99 6.3.2.1p2: 690 // If the lvalue has qualified type, the value has the unqualified 691 // version of the type of the lvalue; otherwise, the value has the 692 // type of the lvalue. 693 if (T.hasQualifiers()) 694 T = T.getUnqualifiedType(); 695 696 // Under the MS ABI, lock down the inheritance model now. 697 if (T->isMemberPointerType() && 698 Context.getTargetInfo().getCXXABI().isMicrosoft()) 699 (void)isCompleteType(E->getExprLoc(), T); 700 701 ExprResult Res = CheckLValueToRValueConversionOperand(E); 702 if (Res.isInvalid()) 703 return Res; 704 E = Res.get(); 705 706 // Loading a __weak object implicitly retains the value, so we need a cleanup to 707 // balance that. 708 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 709 Cleanup.setExprNeedsCleanups(true); 710 711 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 712 Cleanup.setExprNeedsCleanups(true); 713 714 // C++ [conv.lval]p3: 715 // If T is cv std::nullptr_t, the result is a null pointer constant. 716 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 717 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 718 CurFPFeatureOverrides()); 719 720 // C11 6.3.2.1p2: 721 // ... if the lvalue has atomic type, the value has the non-atomic version 722 // of the type of the lvalue ... 723 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 724 T = Atomic->getValueType().getUnqualifiedType(); 725 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 726 nullptr, VK_PRValue, FPOptionsOverride()); 727 } 728 729 return Res; 730 } 731 732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 733 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 734 if (Res.isInvalid()) 735 return ExprError(); 736 Res = DefaultLvalueConversion(Res.get()); 737 if (Res.isInvalid()) 738 return ExprError(); 739 return Res; 740 } 741 742 /// CallExprUnaryConversions - a special case of an unary conversion 743 /// performed on a function designator of a call expression. 744 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 745 QualType Ty = E->getType(); 746 ExprResult Res = E; 747 // Only do implicit cast for a function type, but not for a pointer 748 // to function type. 749 if (Ty->isFunctionType()) { 750 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 751 CK_FunctionToPointerDecay); 752 if (Res.isInvalid()) 753 return ExprError(); 754 } 755 Res = DefaultLvalueConversion(Res.get()); 756 if (Res.isInvalid()) 757 return ExprError(); 758 return Res.get(); 759 } 760 761 /// UsualUnaryConversions - Performs various conversions that are common to most 762 /// operators (C99 6.3). The conversions of array and function types are 763 /// sometimes suppressed. For example, the array->pointer conversion doesn't 764 /// apply if the array is an argument to the sizeof or address (&) operators. 765 /// In these instances, this routine should *not* be called. 766 ExprResult Sema::UsualUnaryConversions(Expr *E) { 767 // First, convert to an r-value. 768 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 769 if (Res.isInvalid()) 770 return ExprError(); 771 E = Res.get(); 772 773 QualType Ty = E->getType(); 774 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 775 776 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); 777 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() && 778 (getLangOpts().getFPEvalMethod() != 779 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine || 780 PP.getLastFPEvalPragmaLocation().isValid())) { 781 switch (EvalMethod) { 782 default: 783 llvm_unreachable("Unrecognized float evaluation method"); 784 break; 785 case LangOptions::FEM_UnsetOnCommandLine: 786 llvm_unreachable("Float evaluation method should be set by now"); 787 break; 788 case LangOptions::FEM_Double: 789 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0) 790 // Widen the expression to double. 791 return Ty->isComplexType() 792 ? ImpCastExprToType(E, 793 Context.getComplexType(Context.DoubleTy), 794 CK_FloatingComplexCast) 795 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast); 796 break; 797 case LangOptions::FEM_Extended: 798 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0) 799 // Widen the expression to long double. 800 return Ty->isComplexType() 801 ? ImpCastExprToType( 802 E, Context.getComplexType(Context.LongDoubleTy), 803 CK_FloatingComplexCast) 804 : ImpCastExprToType(E, Context.LongDoubleTy, 805 CK_FloatingCast); 806 break; 807 } 808 } 809 810 // Half FP have to be promoted to float unless it is natively supported 811 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 812 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 813 814 // Try to perform integral promotions if the object has a theoretically 815 // promotable type. 816 if (Ty->isIntegralOrUnscopedEnumerationType()) { 817 // C99 6.3.1.1p2: 818 // 819 // The following may be used in an expression wherever an int or 820 // unsigned int may be used: 821 // - an object or expression with an integer type whose integer 822 // conversion rank is less than or equal to the rank of int 823 // and unsigned int. 824 // - A bit-field of type _Bool, int, signed int, or unsigned int. 825 // 826 // If an int can represent all values of the original type, the 827 // value is converted to an int; otherwise, it is converted to an 828 // unsigned int. These are called the integer promotions. All 829 // other types are unchanged by the integer promotions. 830 831 QualType PTy = Context.isPromotableBitField(E); 832 if (!PTy.isNull()) { 833 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 834 return E; 835 } 836 if (Ty->isPromotableIntegerType()) { 837 QualType PT = Context.getPromotedIntegerType(Ty); 838 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 839 return E; 840 } 841 } 842 return E; 843 } 844 845 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 846 /// do not have a prototype. Arguments that have type float or __fp16 847 /// are promoted to double. All other argument types are converted by 848 /// UsualUnaryConversions(). 849 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 850 QualType Ty = E->getType(); 851 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 852 853 ExprResult Res = UsualUnaryConversions(E); 854 if (Res.isInvalid()) 855 return ExprError(); 856 E = Res.get(); 857 858 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 859 // promote to double. 860 // Note that default argument promotion applies only to float (and 861 // half/fp16); it does not apply to _Float16. 862 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 863 if (BTy && (BTy->getKind() == BuiltinType::Half || 864 BTy->getKind() == BuiltinType::Float)) { 865 if (getLangOpts().OpenCL && 866 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 867 if (BTy->getKind() == BuiltinType::Half) { 868 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 869 } 870 } else { 871 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 872 } 873 } 874 if (BTy && 875 getLangOpts().getExtendIntArgs() == 876 LangOptions::ExtendArgsKind::ExtendTo64 && 877 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 878 Context.getTypeSizeInChars(BTy) < 879 Context.getTypeSizeInChars(Context.LongLongTy)) { 880 E = (Ty->isUnsignedIntegerType()) 881 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 882 .get() 883 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 884 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 885 "Unexpected typesize for LongLongTy"); 886 } 887 888 // C++ performs lvalue-to-rvalue conversion as a default argument 889 // promotion, even on class types, but note: 890 // C++11 [conv.lval]p2: 891 // When an lvalue-to-rvalue conversion occurs in an unevaluated 892 // operand or a subexpression thereof the value contained in the 893 // referenced object is not accessed. Otherwise, if the glvalue 894 // has a class type, the conversion copy-initializes a temporary 895 // of type T from the glvalue and the result of the conversion 896 // is a prvalue for the temporary. 897 // FIXME: add some way to gate this entire thing for correctness in 898 // potentially potentially evaluated contexts. 899 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 900 ExprResult Temp = PerformCopyInitialization( 901 InitializedEntity::InitializeTemporary(E->getType()), 902 E->getExprLoc(), E); 903 if (Temp.isInvalid()) 904 return ExprError(); 905 E = Temp.get(); 906 } 907 908 return E; 909 } 910 911 /// Determine the degree of POD-ness for an expression. 912 /// Incomplete types are considered POD, since this check can be performed 913 /// when we're in an unevaluated context. 914 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 915 if (Ty->isIncompleteType()) { 916 // C++11 [expr.call]p7: 917 // After these conversions, if the argument does not have arithmetic, 918 // enumeration, pointer, pointer to member, or class type, the program 919 // is ill-formed. 920 // 921 // Since we've already performed array-to-pointer and function-to-pointer 922 // decay, the only such type in C++ is cv void. This also handles 923 // initializer lists as variadic arguments. 924 if (Ty->isVoidType()) 925 return VAK_Invalid; 926 927 if (Ty->isObjCObjectType()) 928 return VAK_Invalid; 929 return VAK_Valid; 930 } 931 932 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 933 return VAK_Invalid; 934 935 if (Ty.isCXX98PODType(Context)) 936 return VAK_Valid; 937 938 // C++11 [expr.call]p7: 939 // Passing a potentially-evaluated argument of class type (Clause 9) 940 // having a non-trivial copy constructor, a non-trivial move constructor, 941 // or a non-trivial destructor, with no corresponding parameter, 942 // is conditionally-supported with implementation-defined semantics. 943 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 944 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 945 if (!Record->hasNonTrivialCopyConstructor() && 946 !Record->hasNonTrivialMoveConstructor() && 947 !Record->hasNonTrivialDestructor()) 948 return VAK_ValidInCXX11; 949 950 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 951 return VAK_Valid; 952 953 if (Ty->isObjCObjectType()) 954 return VAK_Invalid; 955 956 if (getLangOpts().MSVCCompat) 957 return VAK_MSVCUndefined; 958 959 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 960 // permitted to reject them. We should consider doing so. 961 return VAK_Undefined; 962 } 963 964 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 965 // Don't allow one to pass an Objective-C interface to a vararg. 966 const QualType &Ty = E->getType(); 967 VarArgKind VAK = isValidVarArgType(Ty); 968 969 // Complain about passing non-POD types through varargs. 970 switch (VAK) { 971 case VAK_ValidInCXX11: 972 DiagRuntimeBehavior( 973 E->getBeginLoc(), nullptr, 974 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 975 LLVM_FALLTHROUGH; 976 case VAK_Valid: 977 if (Ty->isRecordType()) { 978 // This is unlikely to be what the user intended. If the class has a 979 // 'c_str' member function, the user probably meant to call that. 980 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 981 PDiag(diag::warn_pass_class_arg_to_vararg) 982 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 983 } 984 break; 985 986 case VAK_Undefined: 987 case VAK_MSVCUndefined: 988 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 989 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 990 << getLangOpts().CPlusPlus11 << Ty << CT); 991 break; 992 993 case VAK_Invalid: 994 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 995 Diag(E->getBeginLoc(), 996 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 997 << Ty << CT; 998 else if (Ty->isObjCObjectType()) 999 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 1000 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 1001 << Ty << CT); 1002 else 1003 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 1004 << isa<InitListExpr>(E) << Ty << CT; 1005 break; 1006 } 1007 } 1008 1009 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 1010 /// will create a trap if the resulting type is not a POD type. 1011 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 1012 FunctionDecl *FDecl) { 1013 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 1014 // Strip the unbridged-cast placeholder expression off, if applicable. 1015 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 1016 (CT == VariadicMethod || 1017 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 1018 E = stripARCUnbridgedCast(E); 1019 1020 // Otherwise, do normal placeholder checking. 1021 } else { 1022 ExprResult ExprRes = CheckPlaceholderExpr(E); 1023 if (ExprRes.isInvalid()) 1024 return ExprError(); 1025 E = ExprRes.get(); 1026 } 1027 } 1028 1029 ExprResult ExprRes = DefaultArgumentPromotion(E); 1030 if (ExprRes.isInvalid()) 1031 return ExprError(); 1032 1033 // Copy blocks to the heap. 1034 if (ExprRes.get()->getType()->isBlockPointerType()) 1035 maybeExtendBlockObject(ExprRes); 1036 1037 E = ExprRes.get(); 1038 1039 // Diagnostics regarding non-POD argument types are 1040 // emitted along with format string checking in Sema::CheckFunctionCall(). 1041 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1042 // Turn this into a trap. 1043 CXXScopeSpec SS; 1044 SourceLocation TemplateKWLoc; 1045 UnqualifiedId Name; 1046 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1047 E->getBeginLoc()); 1048 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1049 /*HasTrailingLParen=*/true, 1050 /*IsAddressOfOperand=*/false); 1051 if (TrapFn.isInvalid()) 1052 return ExprError(); 1053 1054 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1055 None, E->getEndLoc()); 1056 if (Call.isInvalid()) 1057 return ExprError(); 1058 1059 ExprResult Comma = 1060 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1061 if (Comma.isInvalid()) 1062 return ExprError(); 1063 return Comma.get(); 1064 } 1065 1066 if (!getLangOpts().CPlusPlus && 1067 RequireCompleteType(E->getExprLoc(), E->getType(), 1068 diag::err_call_incomplete_argument)) 1069 return ExprError(); 1070 1071 return E; 1072 } 1073 1074 /// Converts an integer to complex float type. Helper function of 1075 /// UsualArithmeticConversions() 1076 /// 1077 /// \return false if the integer expression is an integer type and is 1078 /// successfully converted to the complex type. 1079 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1080 ExprResult &ComplexExpr, 1081 QualType IntTy, 1082 QualType ComplexTy, 1083 bool SkipCast) { 1084 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1085 if (SkipCast) return false; 1086 if (IntTy->isIntegerType()) { 1087 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1088 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1089 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1090 CK_FloatingRealToComplex); 1091 } else { 1092 assert(IntTy->isComplexIntegerType()); 1093 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1094 CK_IntegralComplexToFloatingComplex); 1095 } 1096 return false; 1097 } 1098 1099 /// Handle arithmetic conversion with complex types. Helper function of 1100 /// UsualArithmeticConversions() 1101 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1102 ExprResult &RHS, QualType LHSType, 1103 QualType RHSType, 1104 bool IsCompAssign) { 1105 // if we have an integer operand, the result is the complex type. 1106 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1107 /*skipCast*/false)) 1108 return LHSType; 1109 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1110 /*skipCast*/IsCompAssign)) 1111 return RHSType; 1112 1113 // This handles complex/complex, complex/float, or float/complex. 1114 // When both operands are complex, the shorter operand is converted to the 1115 // type of the longer, and that is the type of the result. This corresponds 1116 // to what is done when combining two real floating-point operands. 1117 // The fun begins when size promotion occur across type domains. 1118 // From H&S 6.3.4: When one operand is complex and the other is a real 1119 // floating-point type, the less precise type is converted, within it's 1120 // real or complex domain, to the precision of the other type. For example, 1121 // when combining a "long double" with a "double _Complex", the 1122 // "double _Complex" is promoted to "long double _Complex". 1123 1124 // Compute the rank of the two types, regardless of whether they are complex. 1125 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1126 1127 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1128 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1129 QualType LHSElementType = 1130 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1131 QualType RHSElementType = 1132 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1133 1134 QualType ResultType = S.Context.getComplexType(LHSElementType); 1135 if (Order < 0) { 1136 // Promote the precision of the LHS if not an assignment. 1137 ResultType = S.Context.getComplexType(RHSElementType); 1138 if (!IsCompAssign) { 1139 if (LHSComplexType) 1140 LHS = 1141 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1142 else 1143 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1144 } 1145 } else if (Order > 0) { 1146 // Promote the precision of the RHS. 1147 if (RHSComplexType) 1148 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1149 else 1150 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1151 } 1152 return ResultType; 1153 } 1154 1155 /// Handle arithmetic conversion from integer to float. Helper function 1156 /// of UsualArithmeticConversions() 1157 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1158 ExprResult &IntExpr, 1159 QualType FloatTy, QualType IntTy, 1160 bool ConvertFloat, bool ConvertInt) { 1161 if (IntTy->isIntegerType()) { 1162 if (ConvertInt) 1163 // Convert intExpr to the lhs floating point type. 1164 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1165 CK_IntegralToFloating); 1166 return FloatTy; 1167 } 1168 1169 // Convert both sides to the appropriate complex float. 1170 assert(IntTy->isComplexIntegerType()); 1171 QualType result = S.Context.getComplexType(FloatTy); 1172 1173 // _Complex int -> _Complex float 1174 if (ConvertInt) 1175 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1176 CK_IntegralComplexToFloatingComplex); 1177 1178 // float -> _Complex float 1179 if (ConvertFloat) 1180 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1181 CK_FloatingRealToComplex); 1182 1183 return result; 1184 } 1185 1186 /// Handle arithmethic conversion with floating point types. Helper 1187 /// function of UsualArithmeticConversions() 1188 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1189 ExprResult &RHS, QualType LHSType, 1190 QualType RHSType, bool IsCompAssign) { 1191 bool LHSFloat = LHSType->isRealFloatingType(); 1192 bool RHSFloat = RHSType->isRealFloatingType(); 1193 1194 // N1169 4.1.4: If one of the operands has a floating type and the other 1195 // operand has a fixed-point type, the fixed-point operand 1196 // is converted to the floating type [...] 1197 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1198 if (LHSFloat) 1199 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1200 else if (!IsCompAssign) 1201 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1202 return LHSFloat ? LHSType : RHSType; 1203 } 1204 1205 // If we have two real floating types, convert the smaller operand 1206 // to the bigger result. 1207 if (LHSFloat && RHSFloat) { 1208 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1209 if (order > 0) { 1210 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1211 return LHSType; 1212 } 1213 1214 assert(order < 0 && "illegal float comparison"); 1215 if (!IsCompAssign) 1216 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1217 return RHSType; 1218 } 1219 1220 if (LHSFloat) { 1221 // Half FP has to be promoted to float unless it is natively supported 1222 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1223 LHSType = S.Context.FloatTy; 1224 1225 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1226 /*ConvertFloat=*/!IsCompAssign, 1227 /*ConvertInt=*/ true); 1228 } 1229 assert(RHSFloat); 1230 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1231 /*ConvertFloat=*/ true, 1232 /*ConvertInt=*/!IsCompAssign); 1233 } 1234 1235 /// Diagnose attempts to convert between __float128, __ibm128 and 1236 /// long double if there is no support for such conversion. 1237 /// Helper function of UsualArithmeticConversions(). 1238 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1239 QualType RHSType) { 1240 // No issue if either is not a floating point type. 1241 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1242 return false; 1243 1244 // No issue if both have the same 128-bit float semantics. 1245 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1246 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1247 1248 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1249 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1250 1251 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1252 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1253 1254 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1255 &RHSSem != &llvm::APFloat::IEEEquad()) && 1256 (&LHSSem != &llvm::APFloat::IEEEquad() || 1257 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1258 return false; 1259 1260 return true; 1261 } 1262 1263 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1264 1265 namespace { 1266 /// These helper callbacks are placed in an anonymous namespace to 1267 /// permit their use as function template parameters. 1268 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1269 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1270 } 1271 1272 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1273 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1274 CK_IntegralComplexCast); 1275 } 1276 } 1277 1278 /// Handle integer arithmetic conversions. Helper function of 1279 /// UsualArithmeticConversions() 1280 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1281 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1282 ExprResult &RHS, QualType LHSType, 1283 QualType RHSType, bool IsCompAssign) { 1284 // The rules for this case are in C99 6.3.1.8 1285 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1286 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1287 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1288 if (LHSSigned == RHSSigned) { 1289 // Same signedness; use the higher-ranked type 1290 if (order >= 0) { 1291 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1292 return LHSType; 1293 } else if (!IsCompAssign) 1294 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1295 return RHSType; 1296 } else if (order != (LHSSigned ? 1 : -1)) { 1297 // The unsigned type has greater than or equal rank to the 1298 // signed type, so use the unsigned type 1299 if (RHSSigned) { 1300 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1301 return LHSType; 1302 } else if (!IsCompAssign) 1303 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1304 return RHSType; 1305 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1306 // The two types are different widths; if we are here, that 1307 // means the signed type is larger than the unsigned type, so 1308 // use the signed type. 1309 if (LHSSigned) { 1310 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1311 return LHSType; 1312 } else if (!IsCompAssign) 1313 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1314 return RHSType; 1315 } else { 1316 // The signed type is higher-ranked than the unsigned type, 1317 // but isn't actually any bigger (like unsigned int and long 1318 // on most 32-bit systems). Use the unsigned type corresponding 1319 // to the signed type. 1320 QualType result = 1321 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1322 RHS = (*doRHSCast)(S, RHS.get(), result); 1323 if (!IsCompAssign) 1324 LHS = (*doLHSCast)(S, LHS.get(), result); 1325 return result; 1326 } 1327 } 1328 1329 /// Handle conversions with GCC complex int extension. Helper function 1330 /// of UsualArithmeticConversions() 1331 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1332 ExprResult &RHS, QualType LHSType, 1333 QualType RHSType, 1334 bool IsCompAssign) { 1335 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1336 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1337 1338 if (LHSComplexInt && RHSComplexInt) { 1339 QualType LHSEltType = LHSComplexInt->getElementType(); 1340 QualType RHSEltType = RHSComplexInt->getElementType(); 1341 QualType ScalarType = 1342 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1343 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1344 1345 return S.Context.getComplexType(ScalarType); 1346 } 1347 1348 if (LHSComplexInt) { 1349 QualType LHSEltType = LHSComplexInt->getElementType(); 1350 QualType ScalarType = 1351 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1352 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1353 QualType ComplexType = S.Context.getComplexType(ScalarType); 1354 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1355 CK_IntegralRealToComplex); 1356 1357 return ComplexType; 1358 } 1359 1360 assert(RHSComplexInt); 1361 1362 QualType RHSEltType = RHSComplexInt->getElementType(); 1363 QualType ScalarType = 1364 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1365 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1366 QualType ComplexType = S.Context.getComplexType(ScalarType); 1367 1368 if (!IsCompAssign) 1369 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1370 CK_IntegralRealToComplex); 1371 return ComplexType; 1372 } 1373 1374 /// Return the rank of a given fixed point or integer type. The value itself 1375 /// doesn't matter, but the values must be increasing with proper increasing 1376 /// rank as described in N1169 4.1.1. 1377 static unsigned GetFixedPointRank(QualType Ty) { 1378 const auto *BTy = Ty->getAs<BuiltinType>(); 1379 assert(BTy && "Expected a builtin type."); 1380 1381 switch (BTy->getKind()) { 1382 case BuiltinType::ShortFract: 1383 case BuiltinType::UShortFract: 1384 case BuiltinType::SatShortFract: 1385 case BuiltinType::SatUShortFract: 1386 return 1; 1387 case BuiltinType::Fract: 1388 case BuiltinType::UFract: 1389 case BuiltinType::SatFract: 1390 case BuiltinType::SatUFract: 1391 return 2; 1392 case BuiltinType::LongFract: 1393 case BuiltinType::ULongFract: 1394 case BuiltinType::SatLongFract: 1395 case BuiltinType::SatULongFract: 1396 return 3; 1397 case BuiltinType::ShortAccum: 1398 case BuiltinType::UShortAccum: 1399 case BuiltinType::SatShortAccum: 1400 case BuiltinType::SatUShortAccum: 1401 return 4; 1402 case BuiltinType::Accum: 1403 case BuiltinType::UAccum: 1404 case BuiltinType::SatAccum: 1405 case BuiltinType::SatUAccum: 1406 return 5; 1407 case BuiltinType::LongAccum: 1408 case BuiltinType::ULongAccum: 1409 case BuiltinType::SatLongAccum: 1410 case BuiltinType::SatULongAccum: 1411 return 6; 1412 default: 1413 if (BTy->isInteger()) 1414 return 0; 1415 llvm_unreachable("Unexpected fixed point or integer type"); 1416 } 1417 } 1418 1419 /// handleFixedPointConversion - Fixed point operations between fixed 1420 /// point types and integers or other fixed point types do not fall under 1421 /// usual arithmetic conversion since these conversions could result in loss 1422 /// of precsision (N1169 4.1.4). These operations should be calculated with 1423 /// the full precision of their result type (N1169 4.1.6.2.1). 1424 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1425 QualType RHSTy) { 1426 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1427 "Expected at least one of the operands to be a fixed point type"); 1428 assert((LHSTy->isFixedPointOrIntegerType() || 1429 RHSTy->isFixedPointOrIntegerType()) && 1430 "Special fixed point arithmetic operation conversions are only " 1431 "applied to ints or other fixed point types"); 1432 1433 // If one operand has signed fixed-point type and the other operand has 1434 // unsigned fixed-point type, then the unsigned fixed-point operand is 1435 // converted to its corresponding signed fixed-point type and the resulting 1436 // type is the type of the converted operand. 1437 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1438 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1439 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1440 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1441 1442 // The result type is the type with the highest rank, whereby a fixed-point 1443 // conversion rank is always greater than an integer conversion rank; if the 1444 // type of either of the operands is a saturating fixedpoint type, the result 1445 // type shall be the saturating fixed-point type corresponding to the type 1446 // with the highest rank; the resulting value is converted (taking into 1447 // account rounding and overflow) to the precision of the resulting type. 1448 // Same ranks between signed and unsigned types are resolved earlier, so both 1449 // types are either signed or both unsigned at this point. 1450 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1451 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1452 1453 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1454 1455 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1456 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1457 1458 return ResultTy; 1459 } 1460 1461 /// Check that the usual arithmetic conversions can be performed on this pair of 1462 /// expressions that might be of enumeration type. 1463 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1464 SourceLocation Loc, 1465 Sema::ArithConvKind ACK) { 1466 // C++2a [expr.arith.conv]p1: 1467 // If one operand is of enumeration type and the other operand is of a 1468 // different enumeration type or a floating-point type, this behavior is 1469 // deprecated ([depr.arith.conv.enum]). 1470 // 1471 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1472 // Eventually we will presumably reject these cases (in C++23 onwards?). 1473 QualType L = LHS->getType(), R = RHS->getType(); 1474 bool LEnum = L->isUnscopedEnumerationType(), 1475 REnum = R->isUnscopedEnumerationType(); 1476 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1477 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1478 (REnum && L->isFloatingType())) { 1479 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1480 ? diag::warn_arith_conv_enum_float_cxx20 1481 : diag::warn_arith_conv_enum_float) 1482 << LHS->getSourceRange() << RHS->getSourceRange() 1483 << (int)ACK << LEnum << L << R; 1484 } else if (!IsCompAssign && LEnum && REnum && 1485 !S.Context.hasSameUnqualifiedType(L, R)) { 1486 unsigned DiagID; 1487 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1488 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1489 // If either enumeration type is unnamed, it's less likely that the 1490 // user cares about this, but this situation is still deprecated in 1491 // C++2a. Use a different warning group. 1492 DiagID = S.getLangOpts().CPlusPlus20 1493 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1494 : diag::warn_arith_conv_mixed_anon_enum_types; 1495 } else if (ACK == Sema::ACK_Conditional) { 1496 // Conditional expressions are separated out because they have 1497 // historically had a different warning flag. 1498 DiagID = S.getLangOpts().CPlusPlus20 1499 ? diag::warn_conditional_mixed_enum_types_cxx20 1500 : diag::warn_conditional_mixed_enum_types; 1501 } else if (ACK == Sema::ACK_Comparison) { 1502 // Comparison expressions are separated out because they have 1503 // historically had a different warning flag. 1504 DiagID = S.getLangOpts().CPlusPlus20 1505 ? diag::warn_comparison_mixed_enum_types_cxx20 1506 : diag::warn_comparison_mixed_enum_types; 1507 } else { 1508 DiagID = S.getLangOpts().CPlusPlus20 1509 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1510 : diag::warn_arith_conv_mixed_enum_types; 1511 } 1512 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1513 << (int)ACK << L << R; 1514 } 1515 } 1516 1517 /// UsualArithmeticConversions - Performs various conversions that are common to 1518 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1519 /// routine returns the first non-arithmetic type found. The client is 1520 /// responsible for emitting appropriate error diagnostics. 1521 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1522 SourceLocation Loc, 1523 ArithConvKind ACK) { 1524 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1525 1526 if (ACK != ACK_CompAssign) { 1527 LHS = UsualUnaryConversions(LHS.get()); 1528 if (LHS.isInvalid()) 1529 return QualType(); 1530 } 1531 1532 RHS = UsualUnaryConversions(RHS.get()); 1533 if (RHS.isInvalid()) 1534 return QualType(); 1535 1536 // For conversion purposes, we ignore any qualifiers. 1537 // For example, "const float" and "float" are equivalent. 1538 QualType LHSType = 1539 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1540 QualType RHSType = 1541 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1542 1543 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1544 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1545 LHSType = AtomicLHS->getValueType(); 1546 1547 // If both types are identical, no conversion is needed. 1548 if (LHSType == RHSType) 1549 return LHSType; 1550 1551 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1552 // The caller can deal with this (e.g. pointer + int). 1553 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1554 return QualType(); 1555 1556 // Apply unary and bitfield promotions to the LHS's type. 1557 QualType LHSUnpromotedType = LHSType; 1558 if (LHSType->isPromotableIntegerType()) 1559 LHSType = Context.getPromotedIntegerType(LHSType); 1560 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1561 if (!LHSBitfieldPromoteTy.isNull()) 1562 LHSType = LHSBitfieldPromoteTy; 1563 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1564 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1565 1566 // If both types are identical, no conversion is needed. 1567 if (LHSType == RHSType) 1568 return LHSType; 1569 1570 // At this point, we have two different arithmetic types. 1571 1572 // Diagnose attempts to convert between __ibm128, __float128 and long double 1573 // where such conversions currently can't be handled. 1574 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1575 return QualType(); 1576 1577 // Handle complex types first (C99 6.3.1.8p1). 1578 if (LHSType->isComplexType() || RHSType->isComplexType()) 1579 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1580 ACK == ACK_CompAssign); 1581 1582 // Now handle "real" floating types (i.e. float, double, long double). 1583 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1584 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1585 ACK == ACK_CompAssign); 1586 1587 // Handle GCC complex int extension. 1588 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1589 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1590 ACK == ACK_CompAssign); 1591 1592 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1593 return handleFixedPointConversion(*this, LHSType, RHSType); 1594 1595 // Finally, we have two differing integer types. 1596 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1597 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1598 } 1599 1600 //===----------------------------------------------------------------------===// 1601 // Semantic Analysis for various Expression Types 1602 //===----------------------------------------------------------------------===// 1603 1604 1605 ExprResult 1606 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1607 SourceLocation DefaultLoc, 1608 SourceLocation RParenLoc, 1609 Expr *ControllingExpr, 1610 ArrayRef<ParsedType> ArgTypes, 1611 ArrayRef<Expr *> ArgExprs) { 1612 unsigned NumAssocs = ArgTypes.size(); 1613 assert(NumAssocs == ArgExprs.size()); 1614 1615 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1616 for (unsigned i = 0; i < NumAssocs; ++i) { 1617 if (ArgTypes[i]) 1618 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1619 else 1620 Types[i] = nullptr; 1621 } 1622 1623 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1624 ControllingExpr, 1625 llvm::makeArrayRef(Types, NumAssocs), 1626 ArgExprs); 1627 delete [] Types; 1628 return ER; 1629 } 1630 1631 ExprResult 1632 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1633 SourceLocation DefaultLoc, 1634 SourceLocation RParenLoc, 1635 Expr *ControllingExpr, 1636 ArrayRef<TypeSourceInfo *> Types, 1637 ArrayRef<Expr *> Exprs) { 1638 unsigned NumAssocs = Types.size(); 1639 assert(NumAssocs == Exprs.size()); 1640 1641 // Decay and strip qualifiers for the controlling expression type, and handle 1642 // placeholder type replacement. See committee discussion from WG14 DR423. 1643 { 1644 EnterExpressionEvaluationContext Unevaluated( 1645 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1646 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1647 if (R.isInvalid()) 1648 return ExprError(); 1649 ControllingExpr = R.get(); 1650 } 1651 1652 // The controlling expression is an unevaluated operand, so side effects are 1653 // likely unintended. 1654 if (!inTemplateInstantiation() && 1655 ControllingExpr->HasSideEffects(Context, false)) 1656 Diag(ControllingExpr->getExprLoc(), 1657 diag::warn_side_effects_unevaluated_context); 1658 1659 bool TypeErrorFound = false, 1660 IsResultDependent = ControllingExpr->isTypeDependent(), 1661 ContainsUnexpandedParameterPack 1662 = ControllingExpr->containsUnexpandedParameterPack(); 1663 1664 for (unsigned i = 0; i < NumAssocs; ++i) { 1665 if (Exprs[i]->containsUnexpandedParameterPack()) 1666 ContainsUnexpandedParameterPack = true; 1667 1668 if (Types[i]) { 1669 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1670 ContainsUnexpandedParameterPack = true; 1671 1672 if (Types[i]->getType()->isDependentType()) { 1673 IsResultDependent = true; 1674 } else { 1675 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1676 // complete object type other than a variably modified type." 1677 unsigned D = 0; 1678 if (Types[i]->getType()->isIncompleteType()) 1679 D = diag::err_assoc_type_incomplete; 1680 else if (!Types[i]->getType()->isObjectType()) 1681 D = diag::err_assoc_type_nonobject; 1682 else if (Types[i]->getType()->isVariablyModifiedType()) 1683 D = diag::err_assoc_type_variably_modified; 1684 1685 if (D != 0) { 1686 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1687 << Types[i]->getTypeLoc().getSourceRange() 1688 << Types[i]->getType(); 1689 TypeErrorFound = true; 1690 } 1691 1692 // C11 6.5.1.1p2 "No two generic associations in the same generic 1693 // selection shall specify compatible types." 1694 for (unsigned j = i+1; j < NumAssocs; ++j) 1695 if (Types[j] && !Types[j]->getType()->isDependentType() && 1696 Context.typesAreCompatible(Types[i]->getType(), 1697 Types[j]->getType())) { 1698 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1699 diag::err_assoc_compatible_types) 1700 << Types[j]->getTypeLoc().getSourceRange() 1701 << Types[j]->getType() 1702 << Types[i]->getType(); 1703 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1704 diag::note_compat_assoc) 1705 << Types[i]->getTypeLoc().getSourceRange() 1706 << Types[i]->getType(); 1707 TypeErrorFound = true; 1708 } 1709 } 1710 } 1711 } 1712 if (TypeErrorFound) 1713 return ExprError(); 1714 1715 // If we determined that the generic selection is result-dependent, don't 1716 // try to compute the result expression. 1717 if (IsResultDependent) 1718 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1719 Exprs, DefaultLoc, RParenLoc, 1720 ContainsUnexpandedParameterPack); 1721 1722 SmallVector<unsigned, 1> CompatIndices; 1723 unsigned DefaultIndex = -1U; 1724 for (unsigned i = 0; i < NumAssocs; ++i) { 1725 if (!Types[i]) 1726 DefaultIndex = i; 1727 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1728 Types[i]->getType())) 1729 CompatIndices.push_back(i); 1730 } 1731 1732 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1733 // type compatible with at most one of the types named in its generic 1734 // association list." 1735 if (CompatIndices.size() > 1) { 1736 // We strip parens here because the controlling expression is typically 1737 // parenthesized in macro definitions. 1738 ControllingExpr = ControllingExpr->IgnoreParens(); 1739 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1740 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1741 << (unsigned)CompatIndices.size(); 1742 for (unsigned I : CompatIndices) { 1743 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1744 diag::note_compat_assoc) 1745 << Types[I]->getTypeLoc().getSourceRange() 1746 << Types[I]->getType(); 1747 } 1748 return ExprError(); 1749 } 1750 1751 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1752 // its controlling expression shall have type compatible with exactly one of 1753 // the types named in its generic association list." 1754 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1755 // We strip parens here because the controlling expression is typically 1756 // parenthesized in macro definitions. 1757 ControllingExpr = ControllingExpr->IgnoreParens(); 1758 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1759 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1760 return ExprError(); 1761 } 1762 1763 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1764 // type name that is compatible with the type of the controlling expression, 1765 // then the result expression of the generic selection is the expression 1766 // in that generic association. Otherwise, the result expression of the 1767 // generic selection is the expression in the default generic association." 1768 unsigned ResultIndex = 1769 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1770 1771 return GenericSelectionExpr::Create( 1772 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1773 ContainsUnexpandedParameterPack, ResultIndex); 1774 } 1775 1776 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1777 /// location of the token and the offset of the ud-suffix within it. 1778 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1779 unsigned Offset) { 1780 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1781 S.getLangOpts()); 1782 } 1783 1784 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1785 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1786 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1787 IdentifierInfo *UDSuffix, 1788 SourceLocation UDSuffixLoc, 1789 ArrayRef<Expr*> Args, 1790 SourceLocation LitEndLoc) { 1791 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1792 1793 QualType ArgTy[2]; 1794 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1795 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1796 if (ArgTy[ArgIdx]->isArrayType()) 1797 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1798 } 1799 1800 DeclarationName OpName = 1801 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1802 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1803 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1804 1805 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1806 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1807 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1808 /*AllowStringTemplatePack*/ false, 1809 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1810 return ExprError(); 1811 1812 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1813 } 1814 1815 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1816 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1817 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1818 /// multiple tokens. However, the common case is that StringToks points to one 1819 /// string. 1820 /// 1821 ExprResult 1822 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1823 assert(!StringToks.empty() && "Must have at least one string!"); 1824 1825 StringLiteralParser Literal(StringToks, PP); 1826 if (Literal.hadError) 1827 return ExprError(); 1828 1829 SmallVector<SourceLocation, 4> StringTokLocs; 1830 for (const Token &Tok : StringToks) 1831 StringTokLocs.push_back(Tok.getLocation()); 1832 1833 QualType CharTy = Context.CharTy; 1834 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1835 if (Literal.isWide()) { 1836 CharTy = Context.getWideCharType(); 1837 Kind = StringLiteral::Wide; 1838 } else if (Literal.isUTF8()) { 1839 if (getLangOpts().Char8) 1840 CharTy = Context.Char8Ty; 1841 Kind = StringLiteral::UTF8; 1842 } else if (Literal.isUTF16()) { 1843 CharTy = Context.Char16Ty; 1844 Kind = StringLiteral::UTF16; 1845 } else if (Literal.isUTF32()) { 1846 CharTy = Context.Char32Ty; 1847 Kind = StringLiteral::UTF32; 1848 } else if (Literal.isPascal()) { 1849 CharTy = Context.UnsignedCharTy; 1850 } 1851 1852 // Warn on initializing an array of char from a u8 string literal; this 1853 // becomes ill-formed in C++2a. 1854 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1855 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1856 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1857 1858 // Create removals for all 'u8' prefixes in the string literal(s). This 1859 // ensures C++2a compatibility (but may change the program behavior when 1860 // built by non-Clang compilers for which the execution character set is 1861 // not always UTF-8). 1862 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1863 SourceLocation RemovalDiagLoc; 1864 for (const Token &Tok : StringToks) { 1865 if (Tok.getKind() == tok::utf8_string_literal) { 1866 if (RemovalDiagLoc.isInvalid()) 1867 RemovalDiagLoc = Tok.getLocation(); 1868 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1869 Tok.getLocation(), 1870 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1871 getSourceManager(), getLangOpts()))); 1872 } 1873 } 1874 Diag(RemovalDiagLoc, RemovalDiag); 1875 } 1876 1877 QualType StrTy = 1878 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1879 1880 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1881 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1882 Kind, Literal.Pascal, StrTy, 1883 &StringTokLocs[0], 1884 StringTokLocs.size()); 1885 if (Literal.getUDSuffix().empty()) 1886 return Lit; 1887 1888 // We're building a user-defined literal. 1889 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1890 SourceLocation UDSuffixLoc = 1891 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1892 Literal.getUDSuffixOffset()); 1893 1894 // Make sure we're allowed user-defined literals here. 1895 if (!UDLScope) 1896 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1897 1898 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1899 // operator "" X (str, len) 1900 QualType SizeType = Context.getSizeType(); 1901 1902 DeclarationName OpName = 1903 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1904 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1905 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1906 1907 QualType ArgTy[] = { 1908 Context.getArrayDecayedType(StrTy), SizeType 1909 }; 1910 1911 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1912 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1913 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1914 /*AllowStringTemplatePack*/ true, 1915 /*DiagnoseMissing*/ true, Lit)) { 1916 1917 case LOLR_Cooked: { 1918 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1919 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1920 StringTokLocs[0]); 1921 Expr *Args[] = { Lit, LenArg }; 1922 1923 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1924 } 1925 1926 case LOLR_Template: { 1927 TemplateArgumentListInfo ExplicitArgs; 1928 TemplateArgument Arg(Lit); 1929 TemplateArgumentLocInfo ArgInfo(Lit); 1930 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1931 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1932 &ExplicitArgs); 1933 } 1934 1935 case LOLR_StringTemplatePack: { 1936 TemplateArgumentListInfo ExplicitArgs; 1937 1938 unsigned CharBits = Context.getIntWidth(CharTy); 1939 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1940 llvm::APSInt Value(CharBits, CharIsUnsigned); 1941 1942 TemplateArgument TypeArg(CharTy); 1943 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1944 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1945 1946 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1947 Value = Lit->getCodeUnit(I); 1948 TemplateArgument Arg(Context, Value, CharTy); 1949 TemplateArgumentLocInfo ArgInfo; 1950 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1951 } 1952 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1953 &ExplicitArgs); 1954 } 1955 case LOLR_Raw: 1956 case LOLR_ErrorNoDiagnostic: 1957 llvm_unreachable("unexpected literal operator lookup result"); 1958 case LOLR_Error: 1959 return ExprError(); 1960 } 1961 llvm_unreachable("unexpected literal operator lookup result"); 1962 } 1963 1964 DeclRefExpr * 1965 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1966 SourceLocation Loc, 1967 const CXXScopeSpec *SS) { 1968 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1969 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1970 } 1971 1972 DeclRefExpr * 1973 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1974 const DeclarationNameInfo &NameInfo, 1975 const CXXScopeSpec *SS, NamedDecl *FoundD, 1976 SourceLocation TemplateKWLoc, 1977 const TemplateArgumentListInfo *TemplateArgs) { 1978 NestedNameSpecifierLoc NNS = 1979 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1980 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1981 TemplateArgs); 1982 } 1983 1984 // CUDA/HIP: Check whether a captured reference variable is referencing a 1985 // host variable in a device or host device lambda. 1986 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1987 VarDecl *VD) { 1988 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1989 return false; 1990 assert(VD->getType()->isReferenceType()); 1991 1992 // Check whether the reference variable is referencing a host variable. 1993 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1994 if (!DRE) 1995 return false; 1996 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1997 if (!Referee || !Referee->hasGlobalStorage() || 1998 Referee->hasAttr<CUDADeviceAttr>()) 1999 return false; 2000 2001 // Check whether the current function is a device or host device lambda. 2002 // Check whether the reference variable is a capture by getDeclContext() 2003 // since refersToEnclosingVariableOrCapture() is not ready at this point. 2004 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 2005 if (MD && MD->getParent()->isLambda() && 2006 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 2007 VD->getDeclContext() != MD) 2008 return true; 2009 2010 return false; 2011 } 2012 2013 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 2014 // A declaration named in an unevaluated operand never constitutes an odr-use. 2015 if (isUnevaluatedContext()) 2016 return NOUR_Unevaluated; 2017 2018 // C++2a [basic.def.odr]p4: 2019 // A variable x whose name appears as a potentially-evaluated expression e 2020 // is odr-used by e unless [...] x is a reference that is usable in 2021 // constant expressions. 2022 // CUDA/HIP: 2023 // If a reference variable referencing a host variable is captured in a 2024 // device or host device lambda, the value of the referee must be copied 2025 // to the capture and the reference variable must be treated as odr-use 2026 // since the value of the referee is not known at compile time and must 2027 // be loaded from the captured. 2028 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2029 if (VD->getType()->isReferenceType() && 2030 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2031 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2032 VD->isUsableInConstantExpressions(Context)) 2033 return NOUR_Constant; 2034 } 2035 2036 // All remaining non-variable cases constitute an odr-use. For variables, we 2037 // need to wait and see how the expression is used. 2038 return NOUR_None; 2039 } 2040 2041 /// BuildDeclRefExpr - Build an expression that references a 2042 /// declaration that does not require a closure capture. 2043 DeclRefExpr * 2044 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2045 const DeclarationNameInfo &NameInfo, 2046 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2047 SourceLocation TemplateKWLoc, 2048 const TemplateArgumentListInfo *TemplateArgs) { 2049 bool RefersToCapturedVariable = 2050 isa<VarDecl>(D) && 2051 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2052 2053 DeclRefExpr *E = DeclRefExpr::Create( 2054 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2055 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2056 MarkDeclRefReferenced(E); 2057 2058 // C++ [except.spec]p17: 2059 // An exception-specification is considered to be needed when: 2060 // - in an expression, the function is the unique lookup result or 2061 // the selected member of a set of overloaded functions. 2062 // 2063 // We delay doing this until after we've built the function reference and 2064 // marked it as used so that: 2065 // a) if the function is defaulted, we get errors from defining it before / 2066 // instead of errors from computing its exception specification, and 2067 // b) if the function is a defaulted comparison, we can use the body we 2068 // build when defining it as input to the exception specification 2069 // computation rather than computing a new body. 2070 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2071 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2072 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2073 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2074 } 2075 } 2076 2077 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2078 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2079 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2080 getCurFunction()->recordUseOfWeak(E); 2081 2082 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2083 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2084 FD = IFD->getAnonField(); 2085 if (FD) { 2086 UnusedPrivateFields.remove(FD); 2087 // Just in case we're building an illegal pointer-to-member. 2088 if (FD->isBitField()) 2089 E->setObjectKind(OK_BitField); 2090 } 2091 2092 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2093 // designates a bit-field. 2094 if (auto *BD = dyn_cast<BindingDecl>(D)) 2095 if (auto *BE = BD->getBinding()) 2096 E->setObjectKind(BE->getObjectKind()); 2097 2098 return E; 2099 } 2100 2101 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2102 /// possibly a list of template arguments. 2103 /// 2104 /// If this produces template arguments, it is permitted to call 2105 /// DecomposeTemplateName. 2106 /// 2107 /// This actually loses a lot of source location information for 2108 /// non-standard name kinds; we should consider preserving that in 2109 /// some way. 2110 void 2111 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2112 TemplateArgumentListInfo &Buffer, 2113 DeclarationNameInfo &NameInfo, 2114 const TemplateArgumentListInfo *&TemplateArgs) { 2115 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2116 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2117 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2118 2119 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2120 Id.TemplateId->NumArgs); 2121 translateTemplateArguments(TemplateArgsPtr, Buffer); 2122 2123 TemplateName TName = Id.TemplateId->Template.get(); 2124 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2125 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2126 TemplateArgs = &Buffer; 2127 } else { 2128 NameInfo = GetNameFromUnqualifiedId(Id); 2129 TemplateArgs = nullptr; 2130 } 2131 } 2132 2133 static void emitEmptyLookupTypoDiagnostic( 2134 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2135 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2136 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2137 DeclContext *Ctx = 2138 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2139 if (!TC) { 2140 // Emit a special diagnostic for failed member lookups. 2141 // FIXME: computing the declaration context might fail here (?) 2142 if (Ctx) 2143 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2144 << SS.getRange(); 2145 else 2146 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2147 return; 2148 } 2149 2150 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2151 bool DroppedSpecifier = 2152 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2153 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2154 ? diag::note_implicit_param_decl 2155 : diag::note_previous_decl; 2156 if (!Ctx) 2157 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2158 SemaRef.PDiag(NoteID)); 2159 else 2160 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2161 << Typo << Ctx << DroppedSpecifier 2162 << SS.getRange(), 2163 SemaRef.PDiag(NoteID)); 2164 } 2165 2166 /// Diagnose a lookup that found results in an enclosing class during error 2167 /// recovery. This usually indicates that the results were found in a dependent 2168 /// base class that could not be searched as part of a template definition. 2169 /// Always issues a diagnostic (though this may be only a warning in MS 2170 /// compatibility mode). 2171 /// 2172 /// Return \c true if the error is unrecoverable, or \c false if the caller 2173 /// should attempt to recover using these lookup results. 2174 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2175 // During a default argument instantiation the CurContext points 2176 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2177 // function parameter list, hence add an explicit check. 2178 bool isDefaultArgument = 2179 !CodeSynthesisContexts.empty() && 2180 CodeSynthesisContexts.back().Kind == 2181 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2182 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2183 bool isInstance = CurMethod && CurMethod->isInstance() && 2184 R.getNamingClass() == CurMethod->getParent() && 2185 !isDefaultArgument; 2186 2187 // There are two ways we can find a class-scope declaration during template 2188 // instantiation that we did not find in the template definition: if it is a 2189 // member of a dependent base class, or if it is declared after the point of 2190 // use in the same class. Distinguish these by comparing the class in which 2191 // the member was found to the naming class of the lookup. 2192 unsigned DiagID = diag::err_found_in_dependent_base; 2193 unsigned NoteID = diag::note_member_declared_at; 2194 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2195 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2196 : diag::err_found_later_in_class; 2197 } else if (getLangOpts().MSVCCompat) { 2198 DiagID = diag::ext_found_in_dependent_base; 2199 NoteID = diag::note_dependent_member_use; 2200 } 2201 2202 if (isInstance) { 2203 // Give a code modification hint to insert 'this->'. 2204 Diag(R.getNameLoc(), DiagID) 2205 << R.getLookupName() 2206 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2207 CheckCXXThisCapture(R.getNameLoc()); 2208 } else { 2209 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2210 // they're not shadowed). 2211 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2212 } 2213 2214 for (NamedDecl *D : R) 2215 Diag(D->getLocation(), NoteID); 2216 2217 // Return true if we are inside a default argument instantiation 2218 // and the found name refers to an instance member function, otherwise 2219 // the caller will try to create an implicit member call and this is wrong 2220 // for default arguments. 2221 // 2222 // FIXME: Is this special case necessary? We could allow the caller to 2223 // diagnose this. 2224 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2225 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2226 return true; 2227 } 2228 2229 // Tell the callee to try to recover. 2230 return false; 2231 } 2232 2233 /// Diagnose an empty lookup. 2234 /// 2235 /// \return false if new lookup candidates were found 2236 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2237 CorrectionCandidateCallback &CCC, 2238 TemplateArgumentListInfo *ExplicitTemplateArgs, 2239 ArrayRef<Expr *> Args, TypoExpr **Out) { 2240 DeclarationName Name = R.getLookupName(); 2241 2242 unsigned diagnostic = diag::err_undeclared_var_use; 2243 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2244 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2245 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2246 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2247 diagnostic = diag::err_undeclared_use; 2248 diagnostic_suggest = diag::err_undeclared_use_suggest; 2249 } 2250 2251 // If the original lookup was an unqualified lookup, fake an 2252 // unqualified lookup. This is useful when (for example) the 2253 // original lookup would not have found something because it was a 2254 // dependent name. 2255 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2256 while (DC) { 2257 if (isa<CXXRecordDecl>(DC)) { 2258 LookupQualifiedName(R, DC); 2259 2260 if (!R.empty()) { 2261 // Don't give errors about ambiguities in this lookup. 2262 R.suppressDiagnostics(); 2263 2264 // If there's a best viable function among the results, only mention 2265 // that one in the notes. 2266 OverloadCandidateSet Candidates(R.getNameLoc(), 2267 OverloadCandidateSet::CSK_Normal); 2268 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2269 OverloadCandidateSet::iterator Best; 2270 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2271 OR_Success) { 2272 R.clear(); 2273 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2274 R.resolveKind(); 2275 } 2276 2277 return DiagnoseDependentMemberLookup(R); 2278 } 2279 2280 R.clear(); 2281 } 2282 2283 DC = DC->getLookupParent(); 2284 } 2285 2286 // We didn't find anything, so try to correct for a typo. 2287 TypoCorrection Corrected; 2288 if (S && Out) { 2289 SourceLocation TypoLoc = R.getNameLoc(); 2290 assert(!ExplicitTemplateArgs && 2291 "Diagnosing an empty lookup with explicit template args!"); 2292 *Out = CorrectTypoDelayed( 2293 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2294 [=](const TypoCorrection &TC) { 2295 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2296 diagnostic, diagnostic_suggest); 2297 }, 2298 nullptr, CTK_ErrorRecovery); 2299 if (*Out) 2300 return true; 2301 } else if (S && 2302 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2303 S, &SS, CCC, CTK_ErrorRecovery))) { 2304 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2305 bool DroppedSpecifier = 2306 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2307 R.setLookupName(Corrected.getCorrection()); 2308 2309 bool AcceptableWithRecovery = false; 2310 bool AcceptableWithoutRecovery = false; 2311 NamedDecl *ND = Corrected.getFoundDecl(); 2312 if (ND) { 2313 if (Corrected.isOverloaded()) { 2314 OverloadCandidateSet OCS(R.getNameLoc(), 2315 OverloadCandidateSet::CSK_Normal); 2316 OverloadCandidateSet::iterator Best; 2317 for (NamedDecl *CD : Corrected) { 2318 if (FunctionTemplateDecl *FTD = 2319 dyn_cast<FunctionTemplateDecl>(CD)) 2320 AddTemplateOverloadCandidate( 2321 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2322 Args, OCS); 2323 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2324 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2325 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2326 Args, OCS); 2327 } 2328 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2329 case OR_Success: 2330 ND = Best->FoundDecl; 2331 Corrected.setCorrectionDecl(ND); 2332 break; 2333 default: 2334 // FIXME: Arbitrarily pick the first declaration for the note. 2335 Corrected.setCorrectionDecl(ND); 2336 break; 2337 } 2338 } 2339 R.addDecl(ND); 2340 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2341 CXXRecordDecl *Record = nullptr; 2342 if (Corrected.getCorrectionSpecifier()) { 2343 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2344 Record = Ty->getAsCXXRecordDecl(); 2345 } 2346 if (!Record) 2347 Record = cast<CXXRecordDecl>( 2348 ND->getDeclContext()->getRedeclContext()); 2349 R.setNamingClass(Record); 2350 } 2351 2352 auto *UnderlyingND = ND->getUnderlyingDecl(); 2353 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2354 isa<FunctionTemplateDecl>(UnderlyingND); 2355 // FIXME: If we ended up with a typo for a type name or 2356 // Objective-C class name, we're in trouble because the parser 2357 // is in the wrong place to recover. Suggest the typo 2358 // correction, but don't make it a fix-it since we're not going 2359 // to recover well anyway. 2360 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2361 getAsTypeTemplateDecl(UnderlyingND) || 2362 isa<ObjCInterfaceDecl>(UnderlyingND); 2363 } else { 2364 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2365 // because we aren't able to recover. 2366 AcceptableWithoutRecovery = true; 2367 } 2368 2369 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2370 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2371 ? diag::note_implicit_param_decl 2372 : diag::note_previous_decl; 2373 if (SS.isEmpty()) 2374 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2375 PDiag(NoteID), AcceptableWithRecovery); 2376 else 2377 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2378 << Name << computeDeclContext(SS, false) 2379 << DroppedSpecifier << SS.getRange(), 2380 PDiag(NoteID), AcceptableWithRecovery); 2381 2382 // Tell the callee whether to try to recover. 2383 return !AcceptableWithRecovery; 2384 } 2385 } 2386 R.clear(); 2387 2388 // Emit a special diagnostic for failed member lookups. 2389 // FIXME: computing the declaration context might fail here (?) 2390 if (!SS.isEmpty()) { 2391 Diag(R.getNameLoc(), diag::err_no_member) 2392 << Name << computeDeclContext(SS, false) 2393 << SS.getRange(); 2394 return true; 2395 } 2396 2397 // Give up, we can't recover. 2398 Diag(R.getNameLoc(), diagnostic) << Name; 2399 return true; 2400 } 2401 2402 /// In Microsoft mode, if we are inside a template class whose parent class has 2403 /// dependent base classes, and we can't resolve an unqualified identifier, then 2404 /// assume the identifier is a member of a dependent base class. We can only 2405 /// recover successfully in static methods, instance methods, and other contexts 2406 /// where 'this' is available. This doesn't precisely match MSVC's 2407 /// instantiation model, but it's close enough. 2408 static Expr * 2409 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2410 DeclarationNameInfo &NameInfo, 2411 SourceLocation TemplateKWLoc, 2412 const TemplateArgumentListInfo *TemplateArgs) { 2413 // Only try to recover from lookup into dependent bases in static methods or 2414 // contexts where 'this' is available. 2415 QualType ThisType = S.getCurrentThisType(); 2416 const CXXRecordDecl *RD = nullptr; 2417 if (!ThisType.isNull()) 2418 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2419 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2420 RD = MD->getParent(); 2421 if (!RD || !RD->hasAnyDependentBases()) 2422 return nullptr; 2423 2424 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2425 // is available, suggest inserting 'this->' as a fixit. 2426 SourceLocation Loc = NameInfo.getLoc(); 2427 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2428 DB << NameInfo.getName() << RD; 2429 2430 if (!ThisType.isNull()) { 2431 DB << FixItHint::CreateInsertion(Loc, "this->"); 2432 return CXXDependentScopeMemberExpr::Create( 2433 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2434 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2435 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2436 } 2437 2438 // Synthesize a fake NNS that points to the derived class. This will 2439 // perform name lookup during template instantiation. 2440 CXXScopeSpec SS; 2441 auto *NNS = 2442 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2443 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2444 return DependentScopeDeclRefExpr::Create( 2445 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2446 TemplateArgs); 2447 } 2448 2449 ExprResult 2450 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2451 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2452 bool HasTrailingLParen, bool IsAddressOfOperand, 2453 CorrectionCandidateCallback *CCC, 2454 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2455 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2456 "cannot be direct & operand and have a trailing lparen"); 2457 if (SS.isInvalid()) 2458 return ExprError(); 2459 2460 TemplateArgumentListInfo TemplateArgsBuffer; 2461 2462 // Decompose the UnqualifiedId into the following data. 2463 DeclarationNameInfo NameInfo; 2464 const TemplateArgumentListInfo *TemplateArgs; 2465 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2466 2467 DeclarationName Name = NameInfo.getName(); 2468 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2469 SourceLocation NameLoc = NameInfo.getLoc(); 2470 2471 if (II && II->isEditorPlaceholder()) { 2472 // FIXME: When typed placeholders are supported we can create a typed 2473 // placeholder expression node. 2474 return ExprError(); 2475 } 2476 2477 // C++ [temp.dep.expr]p3: 2478 // An id-expression is type-dependent if it contains: 2479 // -- an identifier that was declared with a dependent type, 2480 // (note: handled after lookup) 2481 // -- a template-id that is dependent, 2482 // (note: handled in BuildTemplateIdExpr) 2483 // -- a conversion-function-id that specifies a dependent type, 2484 // -- a nested-name-specifier that contains a class-name that 2485 // names a dependent type. 2486 // Determine whether this is a member of an unknown specialization; 2487 // we need to handle these differently. 2488 bool DependentID = false; 2489 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2490 Name.getCXXNameType()->isDependentType()) { 2491 DependentID = true; 2492 } else if (SS.isSet()) { 2493 if (DeclContext *DC = computeDeclContext(SS, false)) { 2494 if (RequireCompleteDeclContext(SS, DC)) 2495 return ExprError(); 2496 } else { 2497 DependentID = true; 2498 } 2499 } 2500 2501 if (DependentID) 2502 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2503 IsAddressOfOperand, TemplateArgs); 2504 2505 // Perform the required lookup. 2506 LookupResult R(*this, NameInfo, 2507 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2508 ? LookupObjCImplicitSelfParam 2509 : LookupOrdinaryName); 2510 if (TemplateKWLoc.isValid() || TemplateArgs) { 2511 // Lookup the template name again to correctly establish the context in 2512 // which it was found. This is really unfortunate as we already did the 2513 // lookup to determine that it was a template name in the first place. If 2514 // this becomes a performance hit, we can work harder to preserve those 2515 // results until we get here but it's likely not worth it. 2516 bool MemberOfUnknownSpecialization; 2517 AssumedTemplateKind AssumedTemplate; 2518 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2519 MemberOfUnknownSpecialization, TemplateKWLoc, 2520 &AssumedTemplate)) 2521 return ExprError(); 2522 2523 if (MemberOfUnknownSpecialization || 2524 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2525 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2526 IsAddressOfOperand, TemplateArgs); 2527 } else { 2528 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2529 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2530 2531 // If the result might be in a dependent base class, this is a dependent 2532 // id-expression. 2533 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2534 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2535 IsAddressOfOperand, TemplateArgs); 2536 2537 // If this reference is in an Objective-C method, then we need to do 2538 // some special Objective-C lookup, too. 2539 if (IvarLookupFollowUp) { 2540 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2541 if (E.isInvalid()) 2542 return ExprError(); 2543 2544 if (Expr *Ex = E.getAs<Expr>()) 2545 return Ex; 2546 } 2547 } 2548 2549 if (R.isAmbiguous()) 2550 return ExprError(); 2551 2552 // This could be an implicitly declared function reference (legal in C90, 2553 // extension in C99, forbidden in C++). 2554 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2555 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2556 if (D) R.addDecl(D); 2557 } 2558 2559 // Determine whether this name might be a candidate for 2560 // argument-dependent lookup. 2561 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2562 2563 if (R.empty() && !ADL) { 2564 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2565 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2566 TemplateKWLoc, TemplateArgs)) 2567 return E; 2568 } 2569 2570 // Don't diagnose an empty lookup for inline assembly. 2571 if (IsInlineAsmIdentifier) 2572 return ExprError(); 2573 2574 // If this name wasn't predeclared and if this is not a function 2575 // call, diagnose the problem. 2576 TypoExpr *TE = nullptr; 2577 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2578 : nullptr); 2579 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2580 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2581 "Typo correction callback misconfigured"); 2582 if (CCC) { 2583 // Make sure the callback knows what the typo being diagnosed is. 2584 CCC->setTypoName(II); 2585 if (SS.isValid()) 2586 CCC->setTypoNNS(SS.getScopeRep()); 2587 } 2588 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2589 // a template name, but we happen to have always already looked up the name 2590 // before we get here if it must be a template name. 2591 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2592 None, &TE)) { 2593 if (TE && KeywordReplacement) { 2594 auto &State = getTypoExprState(TE); 2595 auto BestTC = State.Consumer->getNextCorrection(); 2596 if (BestTC.isKeyword()) { 2597 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2598 if (State.DiagHandler) 2599 State.DiagHandler(BestTC); 2600 KeywordReplacement->startToken(); 2601 KeywordReplacement->setKind(II->getTokenID()); 2602 KeywordReplacement->setIdentifierInfo(II); 2603 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2604 // Clean up the state associated with the TypoExpr, since it has 2605 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2606 clearDelayedTypo(TE); 2607 // Signal that a correction to a keyword was performed by returning a 2608 // valid-but-null ExprResult. 2609 return (Expr*)nullptr; 2610 } 2611 State.Consumer->resetCorrectionStream(); 2612 } 2613 return TE ? TE : ExprError(); 2614 } 2615 2616 assert(!R.empty() && 2617 "DiagnoseEmptyLookup returned false but added no results"); 2618 2619 // If we found an Objective-C instance variable, let 2620 // LookupInObjCMethod build the appropriate expression to 2621 // reference the ivar. 2622 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2623 R.clear(); 2624 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2625 // In a hopelessly buggy code, Objective-C instance variable 2626 // lookup fails and no expression will be built to reference it. 2627 if (!E.isInvalid() && !E.get()) 2628 return ExprError(); 2629 return E; 2630 } 2631 } 2632 2633 // This is guaranteed from this point on. 2634 assert(!R.empty() || ADL); 2635 2636 // Check whether this might be a C++ implicit instance member access. 2637 // C++ [class.mfct.non-static]p3: 2638 // When an id-expression that is not part of a class member access 2639 // syntax and not used to form a pointer to member is used in the 2640 // body of a non-static member function of class X, if name lookup 2641 // resolves the name in the id-expression to a non-static non-type 2642 // member of some class C, the id-expression is transformed into a 2643 // class member access expression using (*this) as the 2644 // postfix-expression to the left of the . operator. 2645 // 2646 // But we don't actually need to do this for '&' operands if R 2647 // resolved to a function or overloaded function set, because the 2648 // expression is ill-formed if it actually works out to be a 2649 // non-static member function: 2650 // 2651 // C++ [expr.ref]p4: 2652 // Otherwise, if E1.E2 refers to a non-static member function. . . 2653 // [t]he expression can be used only as the left-hand operand of a 2654 // member function call. 2655 // 2656 // There are other safeguards against such uses, but it's important 2657 // to get this right here so that we don't end up making a 2658 // spuriously dependent expression if we're inside a dependent 2659 // instance method. 2660 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2661 bool MightBeImplicitMember; 2662 if (!IsAddressOfOperand) 2663 MightBeImplicitMember = true; 2664 else if (!SS.isEmpty()) 2665 MightBeImplicitMember = false; 2666 else if (R.isOverloadedResult()) 2667 MightBeImplicitMember = false; 2668 else if (R.isUnresolvableResult()) 2669 MightBeImplicitMember = true; 2670 else 2671 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2672 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2673 isa<MSPropertyDecl>(R.getFoundDecl()); 2674 2675 if (MightBeImplicitMember) 2676 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2677 R, TemplateArgs, S); 2678 } 2679 2680 if (TemplateArgs || TemplateKWLoc.isValid()) { 2681 2682 // In C++1y, if this is a variable template id, then check it 2683 // in BuildTemplateIdExpr(). 2684 // The single lookup result must be a variable template declaration. 2685 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2686 Id.TemplateId->Kind == TNK_Var_template) { 2687 assert(R.getAsSingle<VarTemplateDecl>() && 2688 "There should only be one declaration found."); 2689 } 2690 2691 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2692 } 2693 2694 return BuildDeclarationNameExpr(SS, R, ADL); 2695 } 2696 2697 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2698 /// declaration name, generally during template instantiation. 2699 /// There's a large number of things which don't need to be done along 2700 /// this path. 2701 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2702 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2703 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2704 DeclContext *DC = computeDeclContext(SS, false); 2705 if (!DC) 2706 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2707 NameInfo, /*TemplateArgs=*/nullptr); 2708 2709 if (RequireCompleteDeclContext(SS, DC)) 2710 return ExprError(); 2711 2712 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2713 LookupQualifiedName(R, DC); 2714 2715 if (R.isAmbiguous()) 2716 return ExprError(); 2717 2718 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2719 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2720 NameInfo, /*TemplateArgs=*/nullptr); 2721 2722 if (R.empty()) { 2723 // Don't diagnose problems with invalid record decl, the secondary no_member 2724 // diagnostic during template instantiation is likely bogus, e.g. if a class 2725 // is invalid because it's derived from an invalid base class, then missing 2726 // members were likely supposed to be inherited. 2727 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2728 if (CD->isInvalidDecl()) 2729 return ExprError(); 2730 Diag(NameInfo.getLoc(), diag::err_no_member) 2731 << NameInfo.getName() << DC << SS.getRange(); 2732 return ExprError(); 2733 } 2734 2735 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2736 // Diagnose a missing typename if this resolved unambiguously to a type in 2737 // a dependent context. If we can recover with a type, downgrade this to 2738 // a warning in Microsoft compatibility mode. 2739 unsigned DiagID = diag::err_typename_missing; 2740 if (RecoveryTSI && getLangOpts().MSVCCompat) 2741 DiagID = diag::ext_typename_missing; 2742 SourceLocation Loc = SS.getBeginLoc(); 2743 auto D = Diag(Loc, DiagID); 2744 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2745 << SourceRange(Loc, NameInfo.getEndLoc()); 2746 2747 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2748 // context. 2749 if (!RecoveryTSI) 2750 return ExprError(); 2751 2752 // Only issue the fixit if we're prepared to recover. 2753 D << FixItHint::CreateInsertion(Loc, "typename "); 2754 2755 // Recover by pretending this was an elaborated type. 2756 QualType Ty = Context.getTypeDeclType(TD); 2757 TypeLocBuilder TLB; 2758 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2759 2760 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2761 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2762 QTL.setElaboratedKeywordLoc(SourceLocation()); 2763 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2764 2765 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2766 2767 return ExprEmpty(); 2768 } 2769 2770 // Defend against this resolving to an implicit member access. We usually 2771 // won't get here if this might be a legitimate a class member (we end up in 2772 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2773 // a pointer-to-member or in an unevaluated context in C++11. 2774 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2775 return BuildPossibleImplicitMemberExpr(SS, 2776 /*TemplateKWLoc=*/SourceLocation(), 2777 R, /*TemplateArgs=*/nullptr, S); 2778 2779 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2780 } 2781 2782 /// The parser has read a name in, and Sema has detected that we're currently 2783 /// inside an ObjC method. Perform some additional checks and determine if we 2784 /// should form a reference to an ivar. 2785 /// 2786 /// Ideally, most of this would be done by lookup, but there's 2787 /// actually quite a lot of extra work involved. 2788 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2789 IdentifierInfo *II) { 2790 SourceLocation Loc = Lookup.getNameLoc(); 2791 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2792 2793 // Check for error condition which is already reported. 2794 if (!CurMethod) 2795 return DeclResult(true); 2796 2797 // There are two cases to handle here. 1) scoped lookup could have failed, 2798 // in which case we should look for an ivar. 2) scoped lookup could have 2799 // found a decl, but that decl is outside the current instance method (i.e. 2800 // a global variable). In these two cases, we do a lookup for an ivar with 2801 // this name, if the lookup sucedes, we replace it our current decl. 2802 2803 // If we're in a class method, we don't normally want to look for 2804 // ivars. But if we don't find anything else, and there's an 2805 // ivar, that's an error. 2806 bool IsClassMethod = CurMethod->isClassMethod(); 2807 2808 bool LookForIvars; 2809 if (Lookup.empty()) 2810 LookForIvars = true; 2811 else if (IsClassMethod) 2812 LookForIvars = false; 2813 else 2814 LookForIvars = (Lookup.isSingleResult() && 2815 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2816 ObjCInterfaceDecl *IFace = nullptr; 2817 if (LookForIvars) { 2818 IFace = CurMethod->getClassInterface(); 2819 ObjCInterfaceDecl *ClassDeclared; 2820 ObjCIvarDecl *IV = nullptr; 2821 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2822 // Diagnose using an ivar in a class method. 2823 if (IsClassMethod) { 2824 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2825 return DeclResult(true); 2826 } 2827 2828 // Diagnose the use of an ivar outside of the declaring class. 2829 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2830 !declaresSameEntity(ClassDeclared, IFace) && 2831 !getLangOpts().DebuggerSupport) 2832 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2833 2834 // Success. 2835 return IV; 2836 } 2837 } else if (CurMethod->isInstanceMethod()) { 2838 // We should warn if a local variable hides an ivar. 2839 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2840 ObjCInterfaceDecl *ClassDeclared; 2841 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2842 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2843 declaresSameEntity(IFace, ClassDeclared)) 2844 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2845 } 2846 } 2847 } else if (Lookup.isSingleResult() && 2848 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2849 // If accessing a stand-alone ivar in a class method, this is an error. 2850 if (const ObjCIvarDecl *IV = 2851 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2852 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2853 return DeclResult(true); 2854 } 2855 } 2856 2857 // Didn't encounter an error, didn't find an ivar. 2858 return DeclResult(false); 2859 } 2860 2861 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2862 ObjCIvarDecl *IV) { 2863 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2864 assert(CurMethod && CurMethod->isInstanceMethod() && 2865 "should not reference ivar from this context"); 2866 2867 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2868 assert(IFace && "should not reference ivar from this context"); 2869 2870 // If we're referencing an invalid decl, just return this as a silent 2871 // error node. The error diagnostic was already emitted on the decl. 2872 if (IV->isInvalidDecl()) 2873 return ExprError(); 2874 2875 // Check if referencing a field with __attribute__((deprecated)). 2876 if (DiagnoseUseOfDecl(IV, Loc)) 2877 return ExprError(); 2878 2879 // FIXME: This should use a new expr for a direct reference, don't 2880 // turn this into Self->ivar, just return a BareIVarExpr or something. 2881 IdentifierInfo &II = Context.Idents.get("self"); 2882 UnqualifiedId SelfName; 2883 SelfName.setImplicitSelfParam(&II); 2884 CXXScopeSpec SelfScopeSpec; 2885 SourceLocation TemplateKWLoc; 2886 ExprResult SelfExpr = 2887 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2888 /*HasTrailingLParen=*/false, 2889 /*IsAddressOfOperand=*/false); 2890 if (SelfExpr.isInvalid()) 2891 return ExprError(); 2892 2893 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2894 if (SelfExpr.isInvalid()) 2895 return ExprError(); 2896 2897 MarkAnyDeclReferenced(Loc, IV, true); 2898 2899 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2900 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2901 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2902 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2903 2904 ObjCIvarRefExpr *Result = new (Context) 2905 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2906 IV->getLocation(), SelfExpr.get(), true, true); 2907 2908 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2909 if (!isUnevaluatedContext() && 2910 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2911 getCurFunction()->recordUseOfWeak(Result); 2912 } 2913 if (getLangOpts().ObjCAutoRefCount) 2914 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2915 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2916 2917 return Result; 2918 } 2919 2920 /// The parser has read a name in, and Sema has detected that we're currently 2921 /// inside an ObjC method. Perform some additional checks and determine if we 2922 /// should form a reference to an ivar. If so, build an expression referencing 2923 /// that ivar. 2924 ExprResult 2925 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2926 IdentifierInfo *II, bool AllowBuiltinCreation) { 2927 // FIXME: Integrate this lookup step into LookupParsedName. 2928 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2929 if (Ivar.isInvalid()) 2930 return ExprError(); 2931 if (Ivar.isUsable()) 2932 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2933 cast<ObjCIvarDecl>(Ivar.get())); 2934 2935 if (Lookup.empty() && II && AllowBuiltinCreation) 2936 LookupBuiltin(Lookup); 2937 2938 // Sentinel value saying that we didn't do anything special. 2939 return ExprResult(false); 2940 } 2941 2942 /// Cast a base object to a member's actual type. 2943 /// 2944 /// There are two relevant checks: 2945 /// 2946 /// C++ [class.access.base]p7: 2947 /// 2948 /// If a class member access operator [...] is used to access a non-static 2949 /// data member or non-static member function, the reference is ill-formed if 2950 /// the left operand [...] cannot be implicitly converted to a pointer to the 2951 /// naming class of the right operand. 2952 /// 2953 /// C++ [expr.ref]p7: 2954 /// 2955 /// If E2 is a non-static data member or a non-static member function, the 2956 /// program is ill-formed if the class of which E2 is directly a member is an 2957 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2958 /// 2959 /// Note that the latter check does not consider access; the access of the 2960 /// "real" base class is checked as appropriate when checking the access of the 2961 /// member name. 2962 ExprResult 2963 Sema::PerformObjectMemberConversion(Expr *From, 2964 NestedNameSpecifier *Qualifier, 2965 NamedDecl *FoundDecl, 2966 NamedDecl *Member) { 2967 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2968 if (!RD) 2969 return From; 2970 2971 QualType DestRecordType; 2972 QualType DestType; 2973 QualType FromRecordType; 2974 QualType FromType = From->getType(); 2975 bool PointerConversions = false; 2976 if (isa<FieldDecl>(Member)) { 2977 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2978 auto FromPtrType = FromType->getAs<PointerType>(); 2979 DestRecordType = Context.getAddrSpaceQualType( 2980 DestRecordType, FromPtrType 2981 ? FromType->getPointeeType().getAddressSpace() 2982 : FromType.getAddressSpace()); 2983 2984 if (FromPtrType) { 2985 DestType = Context.getPointerType(DestRecordType); 2986 FromRecordType = FromPtrType->getPointeeType(); 2987 PointerConversions = true; 2988 } else { 2989 DestType = DestRecordType; 2990 FromRecordType = FromType; 2991 } 2992 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2993 if (Method->isStatic()) 2994 return From; 2995 2996 DestType = Method->getThisType(); 2997 DestRecordType = DestType->getPointeeType(); 2998 2999 if (FromType->getAs<PointerType>()) { 3000 FromRecordType = FromType->getPointeeType(); 3001 PointerConversions = true; 3002 } else { 3003 FromRecordType = FromType; 3004 DestType = DestRecordType; 3005 } 3006 3007 LangAS FromAS = FromRecordType.getAddressSpace(); 3008 LangAS DestAS = DestRecordType.getAddressSpace(); 3009 if (FromAS != DestAS) { 3010 QualType FromRecordTypeWithoutAS = 3011 Context.removeAddrSpaceQualType(FromRecordType); 3012 QualType FromTypeWithDestAS = 3013 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 3014 if (PointerConversions) 3015 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 3016 From = ImpCastExprToType(From, FromTypeWithDestAS, 3017 CK_AddressSpaceConversion, From->getValueKind()) 3018 .get(); 3019 } 3020 } else { 3021 // No conversion necessary. 3022 return From; 3023 } 3024 3025 if (DestType->isDependentType() || FromType->isDependentType()) 3026 return From; 3027 3028 // If the unqualified types are the same, no conversion is necessary. 3029 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3030 return From; 3031 3032 SourceRange FromRange = From->getSourceRange(); 3033 SourceLocation FromLoc = FromRange.getBegin(); 3034 3035 ExprValueKind VK = From->getValueKind(); 3036 3037 // C++ [class.member.lookup]p8: 3038 // [...] Ambiguities can often be resolved by qualifying a name with its 3039 // class name. 3040 // 3041 // If the member was a qualified name and the qualified referred to a 3042 // specific base subobject type, we'll cast to that intermediate type 3043 // first and then to the object in which the member is declared. That allows 3044 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3045 // 3046 // class Base { public: int x; }; 3047 // class Derived1 : public Base { }; 3048 // class Derived2 : public Base { }; 3049 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3050 // 3051 // void VeryDerived::f() { 3052 // x = 17; // error: ambiguous base subobjects 3053 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3054 // } 3055 if (Qualifier && Qualifier->getAsType()) { 3056 QualType QType = QualType(Qualifier->getAsType(), 0); 3057 assert(QType->isRecordType() && "lookup done with non-record type"); 3058 3059 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); 3060 3061 // In C++98, the qualifier type doesn't actually have to be a base 3062 // type of the object type, in which case we just ignore it. 3063 // Otherwise build the appropriate casts. 3064 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3065 CXXCastPath BasePath; 3066 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3067 FromLoc, FromRange, &BasePath)) 3068 return ExprError(); 3069 3070 if (PointerConversions) 3071 QType = Context.getPointerType(QType); 3072 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3073 VK, &BasePath).get(); 3074 3075 FromType = QType; 3076 FromRecordType = QRecordType; 3077 3078 // If the qualifier type was the same as the destination type, 3079 // we're done. 3080 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3081 return From; 3082 } 3083 } 3084 3085 CXXCastPath BasePath; 3086 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3087 FromLoc, FromRange, &BasePath, 3088 /*IgnoreAccess=*/true)) 3089 return ExprError(); 3090 3091 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3092 VK, &BasePath); 3093 } 3094 3095 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3096 const LookupResult &R, 3097 bool HasTrailingLParen) { 3098 // Only when used directly as the postfix-expression of a call. 3099 if (!HasTrailingLParen) 3100 return false; 3101 3102 // Never if a scope specifier was provided. 3103 if (SS.isSet()) 3104 return false; 3105 3106 // Only in C++ or ObjC++. 3107 if (!getLangOpts().CPlusPlus) 3108 return false; 3109 3110 // Turn off ADL when we find certain kinds of declarations during 3111 // normal lookup: 3112 for (NamedDecl *D : R) { 3113 // C++0x [basic.lookup.argdep]p3: 3114 // -- a declaration of a class member 3115 // Since using decls preserve this property, we check this on the 3116 // original decl. 3117 if (D->isCXXClassMember()) 3118 return false; 3119 3120 // C++0x [basic.lookup.argdep]p3: 3121 // -- a block-scope function declaration that is not a 3122 // using-declaration 3123 // NOTE: we also trigger this for function templates (in fact, we 3124 // don't check the decl type at all, since all other decl types 3125 // turn off ADL anyway). 3126 if (isa<UsingShadowDecl>(D)) 3127 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3128 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3129 return false; 3130 3131 // C++0x [basic.lookup.argdep]p3: 3132 // -- a declaration that is neither a function or a function 3133 // template 3134 // And also for builtin functions. 3135 if (isa<FunctionDecl>(D)) { 3136 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3137 3138 // But also builtin functions. 3139 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3140 return false; 3141 } else if (!isa<FunctionTemplateDecl>(D)) 3142 return false; 3143 } 3144 3145 return true; 3146 } 3147 3148 3149 /// Diagnoses obvious problems with the use of the given declaration 3150 /// as an expression. This is only actually called for lookups that 3151 /// were not overloaded, and it doesn't promise that the declaration 3152 /// will in fact be used. 3153 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3154 if (D->isInvalidDecl()) 3155 return true; 3156 3157 if (isa<TypedefNameDecl>(D)) { 3158 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3159 return true; 3160 } 3161 3162 if (isa<ObjCInterfaceDecl>(D)) { 3163 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3164 return true; 3165 } 3166 3167 if (isa<NamespaceDecl>(D)) { 3168 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3169 return true; 3170 } 3171 3172 return false; 3173 } 3174 3175 // Certain multiversion types should be treated as overloaded even when there is 3176 // only one result. 3177 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3178 assert(R.isSingleResult() && "Expected only a single result"); 3179 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3180 return FD && 3181 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3182 } 3183 3184 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3185 LookupResult &R, bool NeedsADL, 3186 bool AcceptInvalidDecl) { 3187 // If this is a single, fully-resolved result and we don't need ADL, 3188 // just build an ordinary singleton decl ref. 3189 if (!NeedsADL && R.isSingleResult() && 3190 !R.getAsSingle<FunctionTemplateDecl>() && 3191 !ShouldLookupResultBeMultiVersionOverload(R)) 3192 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3193 R.getRepresentativeDecl(), nullptr, 3194 AcceptInvalidDecl); 3195 3196 // We only need to check the declaration if there's exactly one 3197 // result, because in the overloaded case the results can only be 3198 // functions and function templates. 3199 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3200 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3201 return ExprError(); 3202 3203 // Otherwise, just build an unresolved lookup expression. Suppress 3204 // any lookup-related diagnostics; we'll hash these out later, when 3205 // we've picked a target. 3206 R.suppressDiagnostics(); 3207 3208 UnresolvedLookupExpr *ULE 3209 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3210 SS.getWithLocInContext(Context), 3211 R.getLookupNameInfo(), 3212 NeedsADL, R.isOverloadedResult(), 3213 R.begin(), R.end()); 3214 3215 return ULE; 3216 } 3217 3218 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3219 ValueDecl *var); 3220 3221 /// Complete semantic analysis for a reference to the given declaration. 3222 ExprResult Sema::BuildDeclarationNameExpr( 3223 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3224 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3225 bool AcceptInvalidDecl) { 3226 assert(D && "Cannot refer to a NULL declaration"); 3227 assert(!isa<FunctionTemplateDecl>(D) && 3228 "Cannot refer unambiguously to a function template"); 3229 3230 SourceLocation Loc = NameInfo.getLoc(); 3231 if (CheckDeclInExpr(*this, Loc, D)) 3232 return ExprError(); 3233 3234 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3235 // Specifically diagnose references to class templates that are missing 3236 // a template argument list. 3237 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3238 return ExprError(); 3239 } 3240 3241 // Make sure that we're referring to a value. 3242 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3243 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3244 Diag(D->getLocation(), diag::note_declared_at); 3245 return ExprError(); 3246 } 3247 3248 // Check whether this declaration can be used. Note that we suppress 3249 // this check when we're going to perform argument-dependent lookup 3250 // on this function name, because this might not be the function 3251 // that overload resolution actually selects. 3252 if (DiagnoseUseOfDecl(D, Loc)) 3253 return ExprError(); 3254 3255 auto *VD = cast<ValueDecl>(D); 3256 3257 // Only create DeclRefExpr's for valid Decl's. 3258 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3259 return ExprError(); 3260 3261 // Handle members of anonymous structs and unions. If we got here, 3262 // and the reference is to a class member indirect field, then this 3263 // must be the subject of a pointer-to-member expression. 3264 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3265 if (!indirectField->isCXXClassMember()) 3266 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3267 indirectField); 3268 3269 QualType type = VD->getType(); 3270 if (type.isNull()) 3271 return ExprError(); 3272 ExprValueKind valueKind = VK_PRValue; 3273 3274 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3275 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3276 // is expanded by some outer '...' in the context of the use. 3277 type = type.getNonPackExpansionType(); 3278 3279 switch (D->getKind()) { 3280 // Ignore all the non-ValueDecl kinds. 3281 #define ABSTRACT_DECL(kind) 3282 #define VALUE(type, base) 3283 #define DECL(type, base) case Decl::type: 3284 #include "clang/AST/DeclNodes.inc" 3285 llvm_unreachable("invalid value decl kind"); 3286 3287 // These shouldn't make it here. 3288 case Decl::ObjCAtDefsField: 3289 llvm_unreachable("forming non-member reference to ivar?"); 3290 3291 // Enum constants are always r-values and never references. 3292 // Unresolved using declarations are dependent. 3293 case Decl::EnumConstant: 3294 case Decl::UnresolvedUsingValue: 3295 case Decl::OMPDeclareReduction: 3296 case Decl::OMPDeclareMapper: 3297 valueKind = VK_PRValue; 3298 break; 3299 3300 // Fields and indirect fields that got here must be for 3301 // pointer-to-member expressions; we just call them l-values for 3302 // internal consistency, because this subexpression doesn't really 3303 // exist in the high-level semantics. 3304 case Decl::Field: 3305 case Decl::IndirectField: 3306 case Decl::ObjCIvar: 3307 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3308 3309 // These can't have reference type in well-formed programs, but 3310 // for internal consistency we do this anyway. 3311 type = type.getNonReferenceType(); 3312 valueKind = VK_LValue; 3313 break; 3314 3315 // Non-type template parameters are either l-values or r-values 3316 // depending on the type. 3317 case Decl::NonTypeTemplateParm: { 3318 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3319 type = reftype->getPointeeType(); 3320 valueKind = VK_LValue; // even if the parameter is an r-value reference 3321 break; 3322 } 3323 3324 // [expr.prim.id.unqual]p2: 3325 // If the entity is a template parameter object for a template 3326 // parameter of type T, the type of the expression is const T. 3327 // [...] The expression is an lvalue if the entity is a [...] template 3328 // parameter object. 3329 if (type->isRecordType()) { 3330 type = type.getUnqualifiedType().withConst(); 3331 valueKind = VK_LValue; 3332 break; 3333 } 3334 3335 // For non-references, we need to strip qualifiers just in case 3336 // the template parameter was declared as 'const int' or whatever. 3337 valueKind = VK_PRValue; 3338 type = type.getUnqualifiedType(); 3339 break; 3340 } 3341 3342 case Decl::Var: 3343 case Decl::VarTemplateSpecialization: 3344 case Decl::VarTemplatePartialSpecialization: 3345 case Decl::Decomposition: 3346 case Decl::OMPCapturedExpr: 3347 // In C, "extern void blah;" is valid and is an r-value. 3348 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3349 type->isVoidType()) { 3350 valueKind = VK_PRValue; 3351 break; 3352 } 3353 LLVM_FALLTHROUGH; 3354 3355 case Decl::ImplicitParam: 3356 case Decl::ParmVar: { 3357 // These are always l-values. 3358 valueKind = VK_LValue; 3359 type = type.getNonReferenceType(); 3360 3361 // FIXME: Does the addition of const really only apply in 3362 // potentially-evaluated contexts? Since the variable isn't actually 3363 // captured in an unevaluated context, it seems that the answer is no. 3364 if (!isUnevaluatedContext()) { 3365 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3366 if (!CapturedType.isNull()) 3367 type = CapturedType; 3368 } 3369 3370 break; 3371 } 3372 3373 case Decl::Binding: { 3374 // These are always lvalues. 3375 valueKind = VK_LValue; 3376 type = type.getNonReferenceType(); 3377 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3378 // decides how that's supposed to work. 3379 auto *BD = cast<BindingDecl>(VD); 3380 if (BD->getDeclContext() != CurContext) { 3381 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3382 if (DD && DD->hasLocalStorage()) 3383 diagnoseUncapturableValueReference(*this, Loc, BD); 3384 } 3385 break; 3386 } 3387 3388 case Decl::Function: { 3389 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3390 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3391 type = Context.BuiltinFnTy; 3392 valueKind = VK_PRValue; 3393 break; 3394 } 3395 } 3396 3397 const FunctionType *fty = type->castAs<FunctionType>(); 3398 3399 // If we're referring to a function with an __unknown_anytype 3400 // result type, make the entire expression __unknown_anytype. 3401 if (fty->getReturnType() == Context.UnknownAnyTy) { 3402 type = Context.UnknownAnyTy; 3403 valueKind = VK_PRValue; 3404 break; 3405 } 3406 3407 // Functions are l-values in C++. 3408 if (getLangOpts().CPlusPlus) { 3409 valueKind = VK_LValue; 3410 break; 3411 } 3412 3413 // C99 DR 316 says that, if a function type comes from a 3414 // function definition (without a prototype), that type is only 3415 // used for checking compatibility. Therefore, when referencing 3416 // the function, we pretend that we don't have the full function 3417 // type. 3418 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3419 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3420 fty->getExtInfo()); 3421 3422 // Functions are r-values in C. 3423 valueKind = VK_PRValue; 3424 break; 3425 } 3426 3427 case Decl::CXXDeductionGuide: 3428 llvm_unreachable("building reference to deduction guide"); 3429 3430 case Decl::MSProperty: 3431 case Decl::MSGuid: 3432 case Decl::TemplateParamObject: 3433 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3434 // capture in OpenMP, or duplicated between host and device? 3435 valueKind = VK_LValue; 3436 break; 3437 3438 case Decl::CXXMethod: 3439 // If we're referring to a method with an __unknown_anytype 3440 // result type, make the entire expression __unknown_anytype. 3441 // This should only be possible with a type written directly. 3442 if (const FunctionProtoType *proto = 3443 dyn_cast<FunctionProtoType>(VD->getType())) 3444 if (proto->getReturnType() == Context.UnknownAnyTy) { 3445 type = Context.UnknownAnyTy; 3446 valueKind = VK_PRValue; 3447 break; 3448 } 3449 3450 // C++ methods are l-values if static, r-values if non-static. 3451 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3452 valueKind = VK_LValue; 3453 break; 3454 } 3455 LLVM_FALLTHROUGH; 3456 3457 case Decl::CXXConversion: 3458 case Decl::CXXDestructor: 3459 case Decl::CXXConstructor: 3460 valueKind = VK_PRValue; 3461 break; 3462 } 3463 3464 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3465 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3466 TemplateArgs); 3467 } 3468 3469 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3470 SmallString<32> &Target) { 3471 Target.resize(CharByteWidth * (Source.size() + 1)); 3472 char *ResultPtr = &Target[0]; 3473 const llvm::UTF8 *ErrorPtr; 3474 bool success = 3475 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3476 (void)success; 3477 assert(success); 3478 Target.resize(ResultPtr - &Target[0]); 3479 } 3480 3481 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3482 PredefinedExpr::IdentKind IK) { 3483 // Pick the current block, lambda, captured statement or function. 3484 Decl *currentDecl = nullptr; 3485 if (const BlockScopeInfo *BSI = getCurBlock()) 3486 currentDecl = BSI->TheDecl; 3487 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3488 currentDecl = LSI->CallOperator; 3489 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3490 currentDecl = CSI->TheCapturedDecl; 3491 else 3492 currentDecl = getCurFunctionOrMethodDecl(); 3493 3494 if (!currentDecl) { 3495 Diag(Loc, diag::ext_predef_outside_function); 3496 currentDecl = Context.getTranslationUnitDecl(); 3497 } 3498 3499 QualType ResTy; 3500 StringLiteral *SL = nullptr; 3501 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3502 ResTy = Context.DependentTy; 3503 else { 3504 // Pre-defined identifiers are of type char[x], where x is the length of 3505 // the string. 3506 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3507 unsigned Length = Str.length(); 3508 3509 llvm::APInt LengthI(32, Length + 1); 3510 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3511 ResTy = 3512 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3513 SmallString<32> RawChars; 3514 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3515 Str, RawChars); 3516 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3517 ArrayType::Normal, 3518 /*IndexTypeQuals*/ 0); 3519 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3520 /*Pascal*/ false, ResTy, Loc); 3521 } else { 3522 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3523 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3524 ArrayType::Normal, 3525 /*IndexTypeQuals*/ 0); 3526 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3527 /*Pascal*/ false, ResTy, Loc); 3528 } 3529 } 3530 3531 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3532 } 3533 3534 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3535 SourceLocation LParen, 3536 SourceLocation RParen, 3537 TypeSourceInfo *TSI) { 3538 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3539 } 3540 3541 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3542 SourceLocation LParen, 3543 SourceLocation RParen, 3544 ParsedType ParsedTy) { 3545 TypeSourceInfo *TSI = nullptr; 3546 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3547 3548 if (Ty.isNull()) 3549 return ExprError(); 3550 if (!TSI) 3551 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3552 3553 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3554 } 3555 3556 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3557 PredefinedExpr::IdentKind IK; 3558 3559 switch (Kind) { 3560 default: llvm_unreachable("Unknown simple primary expr!"); 3561 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3562 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3563 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3564 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3565 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3566 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3567 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3568 } 3569 3570 return BuildPredefinedExpr(Loc, IK); 3571 } 3572 3573 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3574 SmallString<16> CharBuffer; 3575 bool Invalid = false; 3576 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3577 if (Invalid) 3578 return ExprError(); 3579 3580 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3581 PP, Tok.getKind()); 3582 if (Literal.hadError()) 3583 return ExprError(); 3584 3585 QualType Ty; 3586 if (Literal.isWide()) 3587 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3588 else if (Literal.isUTF8() && getLangOpts().Char8) 3589 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3590 else if (Literal.isUTF16()) 3591 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3592 else if (Literal.isUTF32()) 3593 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3594 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3595 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3596 else 3597 Ty = Context.CharTy; // 'x' -> char in C++ 3598 3599 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3600 if (Literal.isWide()) 3601 Kind = CharacterLiteral::Wide; 3602 else if (Literal.isUTF16()) 3603 Kind = CharacterLiteral::UTF16; 3604 else if (Literal.isUTF32()) 3605 Kind = CharacterLiteral::UTF32; 3606 else if (Literal.isUTF8()) 3607 Kind = CharacterLiteral::UTF8; 3608 3609 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3610 Tok.getLocation()); 3611 3612 if (Literal.getUDSuffix().empty()) 3613 return Lit; 3614 3615 // We're building a user-defined literal. 3616 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3617 SourceLocation UDSuffixLoc = 3618 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3619 3620 // Make sure we're allowed user-defined literals here. 3621 if (!UDLScope) 3622 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3623 3624 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3625 // operator "" X (ch) 3626 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3627 Lit, Tok.getLocation()); 3628 } 3629 3630 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3631 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3632 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3633 Context.IntTy, Loc); 3634 } 3635 3636 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3637 QualType Ty, SourceLocation Loc) { 3638 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3639 3640 using llvm::APFloat; 3641 APFloat Val(Format); 3642 3643 APFloat::opStatus result = Literal.GetFloatValue(Val); 3644 3645 // Overflow is always an error, but underflow is only an error if 3646 // we underflowed to zero (APFloat reports denormals as underflow). 3647 if ((result & APFloat::opOverflow) || 3648 ((result & APFloat::opUnderflow) && Val.isZero())) { 3649 unsigned diagnostic; 3650 SmallString<20> buffer; 3651 if (result & APFloat::opOverflow) { 3652 diagnostic = diag::warn_float_overflow; 3653 APFloat::getLargest(Format).toString(buffer); 3654 } else { 3655 diagnostic = diag::warn_float_underflow; 3656 APFloat::getSmallest(Format).toString(buffer); 3657 } 3658 3659 S.Diag(Loc, diagnostic) 3660 << Ty 3661 << StringRef(buffer.data(), buffer.size()); 3662 } 3663 3664 bool isExact = (result == APFloat::opOK); 3665 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3666 } 3667 3668 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3669 assert(E && "Invalid expression"); 3670 3671 if (E->isValueDependent()) 3672 return false; 3673 3674 QualType QT = E->getType(); 3675 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3676 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3677 return true; 3678 } 3679 3680 llvm::APSInt ValueAPS; 3681 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3682 3683 if (R.isInvalid()) 3684 return true; 3685 3686 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3687 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3688 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3689 << toString(ValueAPS, 10) << ValueIsPositive; 3690 return true; 3691 } 3692 3693 return false; 3694 } 3695 3696 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3697 // Fast path for a single digit (which is quite common). A single digit 3698 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3699 if (Tok.getLength() == 1) { 3700 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3701 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3702 } 3703 3704 SmallString<128> SpellingBuffer; 3705 // NumericLiteralParser wants to overread by one character. Add padding to 3706 // the buffer in case the token is copied to the buffer. If getSpelling() 3707 // returns a StringRef to the memory buffer, it should have a null char at 3708 // the EOF, so it is also safe. 3709 SpellingBuffer.resize(Tok.getLength() + 1); 3710 3711 // Get the spelling of the token, which eliminates trigraphs, etc. 3712 bool Invalid = false; 3713 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3714 if (Invalid) 3715 return ExprError(); 3716 3717 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3718 PP.getSourceManager(), PP.getLangOpts(), 3719 PP.getTargetInfo(), PP.getDiagnostics()); 3720 if (Literal.hadError) 3721 return ExprError(); 3722 3723 if (Literal.hasUDSuffix()) { 3724 // We're building a user-defined literal. 3725 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3726 SourceLocation UDSuffixLoc = 3727 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3728 3729 // Make sure we're allowed user-defined literals here. 3730 if (!UDLScope) 3731 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3732 3733 QualType CookedTy; 3734 if (Literal.isFloatingLiteral()) { 3735 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3736 // long double, the literal is treated as a call of the form 3737 // operator "" X (f L) 3738 CookedTy = Context.LongDoubleTy; 3739 } else { 3740 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3741 // unsigned long long, the literal is treated as a call of the form 3742 // operator "" X (n ULL) 3743 CookedTy = Context.UnsignedLongLongTy; 3744 } 3745 3746 DeclarationName OpName = 3747 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3748 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3749 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3750 3751 SourceLocation TokLoc = Tok.getLocation(); 3752 3753 // Perform literal operator lookup to determine if we're building a raw 3754 // literal or a cooked one. 3755 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3756 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3757 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3758 /*AllowStringTemplatePack*/ false, 3759 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3760 case LOLR_ErrorNoDiagnostic: 3761 // Lookup failure for imaginary constants isn't fatal, there's still the 3762 // GNU extension producing _Complex types. 3763 break; 3764 case LOLR_Error: 3765 return ExprError(); 3766 case LOLR_Cooked: { 3767 Expr *Lit; 3768 if (Literal.isFloatingLiteral()) { 3769 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3770 } else { 3771 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3772 if (Literal.GetIntegerValue(ResultVal)) 3773 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3774 << /* Unsigned */ 1; 3775 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3776 Tok.getLocation()); 3777 } 3778 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3779 } 3780 3781 case LOLR_Raw: { 3782 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3783 // literal is treated as a call of the form 3784 // operator "" X ("n") 3785 unsigned Length = Literal.getUDSuffixOffset(); 3786 QualType StrTy = Context.getConstantArrayType( 3787 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3788 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3789 Expr *Lit = StringLiteral::Create( 3790 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3791 /*Pascal*/false, StrTy, &TokLoc, 1); 3792 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3793 } 3794 3795 case LOLR_Template: { 3796 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3797 // template), L is treated as a call fo the form 3798 // operator "" X <'c1', 'c2', ... 'ck'>() 3799 // where n is the source character sequence c1 c2 ... ck. 3800 TemplateArgumentListInfo ExplicitArgs; 3801 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3802 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3803 llvm::APSInt Value(CharBits, CharIsUnsigned); 3804 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3805 Value = TokSpelling[I]; 3806 TemplateArgument Arg(Context, Value, Context.CharTy); 3807 TemplateArgumentLocInfo ArgInfo; 3808 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3809 } 3810 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3811 &ExplicitArgs); 3812 } 3813 case LOLR_StringTemplatePack: 3814 llvm_unreachable("unexpected literal operator lookup result"); 3815 } 3816 } 3817 3818 Expr *Res; 3819 3820 if (Literal.isFixedPointLiteral()) { 3821 QualType Ty; 3822 3823 if (Literal.isAccum) { 3824 if (Literal.isHalf) { 3825 Ty = Context.ShortAccumTy; 3826 } else if (Literal.isLong) { 3827 Ty = Context.LongAccumTy; 3828 } else { 3829 Ty = Context.AccumTy; 3830 } 3831 } else if (Literal.isFract) { 3832 if (Literal.isHalf) { 3833 Ty = Context.ShortFractTy; 3834 } else if (Literal.isLong) { 3835 Ty = Context.LongFractTy; 3836 } else { 3837 Ty = Context.FractTy; 3838 } 3839 } 3840 3841 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3842 3843 bool isSigned = !Literal.isUnsigned; 3844 unsigned scale = Context.getFixedPointScale(Ty); 3845 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3846 3847 llvm::APInt Val(bit_width, 0, isSigned); 3848 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3849 bool ValIsZero = Val.isZero() && !Overflowed; 3850 3851 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3852 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3853 // Clause 6.4.4 - The value of a constant shall be in the range of 3854 // representable values for its type, with exception for constants of a 3855 // fract type with a value of exactly 1; such a constant shall denote 3856 // the maximal value for the type. 3857 --Val; 3858 else if (Val.ugt(MaxVal) || Overflowed) 3859 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3860 3861 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3862 Tok.getLocation(), scale); 3863 } else if (Literal.isFloatingLiteral()) { 3864 QualType Ty; 3865 if (Literal.isHalf){ 3866 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3867 Ty = Context.HalfTy; 3868 else { 3869 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3870 return ExprError(); 3871 } 3872 } else if (Literal.isFloat) 3873 Ty = Context.FloatTy; 3874 else if (Literal.isLong) 3875 Ty = Context.LongDoubleTy; 3876 else if (Literal.isFloat16) 3877 Ty = Context.Float16Ty; 3878 else if (Literal.isFloat128) 3879 Ty = Context.Float128Ty; 3880 else 3881 Ty = Context.DoubleTy; 3882 3883 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3884 3885 if (Ty == Context.DoubleTy) { 3886 if (getLangOpts().SinglePrecisionConstants) { 3887 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3888 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3889 } 3890 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3891 "cl_khr_fp64", getLangOpts())) { 3892 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3893 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3894 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3895 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3896 } 3897 } 3898 } else if (!Literal.isIntegerLiteral()) { 3899 return ExprError(); 3900 } else { 3901 QualType Ty; 3902 3903 // 'long long' is a C99 or C++11 feature. 3904 if (!getLangOpts().C99 && Literal.isLongLong) { 3905 if (getLangOpts().CPlusPlus) 3906 Diag(Tok.getLocation(), 3907 getLangOpts().CPlusPlus11 ? 3908 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3909 else 3910 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3911 } 3912 3913 // 'z/uz' literals are a C++2b feature. 3914 if (Literal.isSizeT) 3915 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3916 ? getLangOpts().CPlusPlus2b 3917 ? diag::warn_cxx20_compat_size_t_suffix 3918 : diag::ext_cxx2b_size_t_suffix 3919 : diag::err_cxx2b_size_t_suffix); 3920 3921 // Get the value in the widest-possible width. 3922 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3923 llvm::APInt ResultVal(MaxWidth, 0); 3924 3925 if (Literal.GetIntegerValue(ResultVal)) { 3926 // If this value didn't fit into uintmax_t, error and force to ull. 3927 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3928 << /* Unsigned */ 1; 3929 Ty = Context.UnsignedLongLongTy; 3930 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3931 "long long is not intmax_t?"); 3932 } else { 3933 // If this value fits into a ULL, try to figure out what else it fits into 3934 // according to the rules of C99 6.4.4.1p5. 3935 3936 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3937 // be an unsigned int. 3938 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3939 3940 // Check from smallest to largest, picking the smallest type we can. 3941 unsigned Width = 0; 3942 3943 // Microsoft specific integer suffixes are explicitly sized. 3944 if (Literal.MicrosoftInteger) { 3945 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3946 Width = 8; 3947 Ty = Context.CharTy; 3948 } else { 3949 Width = Literal.MicrosoftInteger; 3950 Ty = Context.getIntTypeForBitwidth(Width, 3951 /*Signed=*/!Literal.isUnsigned); 3952 } 3953 } 3954 3955 // Check C++2b size_t literals. 3956 if (Literal.isSizeT) { 3957 assert(!Literal.MicrosoftInteger && 3958 "size_t literals can't be Microsoft literals"); 3959 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3960 Context.getTargetInfo().getSizeType()); 3961 3962 // Does it fit in size_t? 3963 if (ResultVal.isIntN(SizeTSize)) { 3964 // Does it fit in ssize_t? 3965 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3966 Ty = Context.getSignedSizeType(); 3967 else if (AllowUnsigned) 3968 Ty = Context.getSizeType(); 3969 Width = SizeTSize; 3970 } 3971 } 3972 3973 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3974 !Literal.isSizeT) { 3975 // Are int/unsigned possibilities? 3976 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3977 3978 // Does it fit in a unsigned int? 3979 if (ResultVal.isIntN(IntSize)) { 3980 // Does it fit in a signed int? 3981 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3982 Ty = Context.IntTy; 3983 else if (AllowUnsigned) 3984 Ty = Context.UnsignedIntTy; 3985 Width = IntSize; 3986 } 3987 } 3988 3989 // Are long/unsigned long possibilities? 3990 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3991 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3992 3993 // Does it fit in a unsigned long? 3994 if (ResultVal.isIntN(LongSize)) { 3995 // Does it fit in a signed long? 3996 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3997 Ty = Context.LongTy; 3998 else if (AllowUnsigned) 3999 Ty = Context.UnsignedLongTy; 4000 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 4001 // is compatible. 4002 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 4003 const unsigned LongLongSize = 4004 Context.getTargetInfo().getLongLongWidth(); 4005 Diag(Tok.getLocation(), 4006 getLangOpts().CPlusPlus 4007 ? Literal.isLong 4008 ? diag::warn_old_implicitly_unsigned_long_cxx 4009 : /*C++98 UB*/ diag:: 4010 ext_old_implicitly_unsigned_long_cxx 4011 : diag::warn_old_implicitly_unsigned_long) 4012 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4013 : /*will be ill-formed*/ 1); 4014 Ty = Context.UnsignedLongTy; 4015 } 4016 Width = LongSize; 4017 } 4018 } 4019 4020 // Check long long if needed. 4021 if (Ty.isNull() && !Literal.isSizeT) { 4022 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4023 4024 // Does it fit in a unsigned long long? 4025 if (ResultVal.isIntN(LongLongSize)) { 4026 // Does it fit in a signed long long? 4027 // To be compatible with MSVC, hex integer literals ending with the 4028 // LL or i64 suffix are always signed in Microsoft mode. 4029 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4030 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4031 Ty = Context.LongLongTy; 4032 else if (AllowUnsigned) 4033 Ty = Context.UnsignedLongLongTy; 4034 Width = LongLongSize; 4035 } 4036 } 4037 4038 // If we still couldn't decide a type, we either have 'size_t' literal 4039 // that is out of range, or a decimal literal that does not fit in a 4040 // signed long long and has no U suffix. 4041 if (Ty.isNull()) { 4042 if (Literal.isSizeT) 4043 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4044 << Literal.isUnsigned; 4045 else 4046 Diag(Tok.getLocation(), 4047 diag::ext_integer_literal_too_large_for_signed); 4048 Ty = Context.UnsignedLongLongTy; 4049 Width = Context.getTargetInfo().getLongLongWidth(); 4050 } 4051 4052 if (ResultVal.getBitWidth() != Width) 4053 ResultVal = ResultVal.trunc(Width); 4054 } 4055 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4056 } 4057 4058 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4059 if (Literal.isImaginary) { 4060 Res = new (Context) ImaginaryLiteral(Res, 4061 Context.getComplexType(Res->getType())); 4062 4063 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4064 } 4065 return Res; 4066 } 4067 4068 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4069 assert(E && "ActOnParenExpr() missing expr"); 4070 QualType ExprTy = E->getType(); 4071 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4072 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4073 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4074 return new (Context) ParenExpr(L, R, E); 4075 } 4076 4077 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4078 SourceLocation Loc, 4079 SourceRange ArgRange) { 4080 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4081 // scalar or vector data type argument..." 4082 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4083 // type (C99 6.2.5p18) or void. 4084 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4085 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4086 << T << ArgRange; 4087 return true; 4088 } 4089 4090 assert((T->isVoidType() || !T->isIncompleteType()) && 4091 "Scalar types should always be complete"); 4092 return false; 4093 } 4094 4095 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4096 SourceLocation Loc, 4097 SourceRange ArgRange, 4098 UnaryExprOrTypeTrait TraitKind) { 4099 // Invalid types must be hard errors for SFINAE in C++. 4100 if (S.LangOpts.CPlusPlus) 4101 return true; 4102 4103 // C99 6.5.3.4p1: 4104 if (T->isFunctionType() && 4105 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4106 TraitKind == UETT_PreferredAlignOf)) { 4107 // sizeof(function)/alignof(function) is allowed as an extension. 4108 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4109 << getTraitSpelling(TraitKind) << ArgRange; 4110 return false; 4111 } 4112 4113 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4114 // this is an error (OpenCL v1.1 s6.3.k) 4115 if (T->isVoidType()) { 4116 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4117 : diag::ext_sizeof_alignof_void_type; 4118 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4119 return false; 4120 } 4121 4122 return true; 4123 } 4124 4125 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4126 SourceLocation Loc, 4127 SourceRange ArgRange, 4128 UnaryExprOrTypeTrait TraitKind) { 4129 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4130 // runtime doesn't allow it. 4131 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4132 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4133 << T << (TraitKind == UETT_SizeOf) 4134 << ArgRange; 4135 return true; 4136 } 4137 4138 return false; 4139 } 4140 4141 /// Check whether E is a pointer from a decayed array type (the decayed 4142 /// pointer type is equal to T) and emit a warning if it is. 4143 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4144 Expr *E) { 4145 // Don't warn if the operation changed the type. 4146 if (T != E->getType()) 4147 return; 4148 4149 // Now look for array decays. 4150 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4151 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4152 return; 4153 4154 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4155 << ICE->getType() 4156 << ICE->getSubExpr()->getType(); 4157 } 4158 4159 /// Check the constraints on expression operands to unary type expression 4160 /// and type traits. 4161 /// 4162 /// Completes any types necessary and validates the constraints on the operand 4163 /// expression. The logic mostly mirrors the type-based overload, but may modify 4164 /// the expression as it completes the type for that expression through template 4165 /// instantiation, etc. 4166 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4167 UnaryExprOrTypeTrait ExprKind) { 4168 QualType ExprTy = E->getType(); 4169 assert(!ExprTy->isReferenceType()); 4170 4171 bool IsUnevaluatedOperand = 4172 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4173 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4174 if (IsUnevaluatedOperand) { 4175 ExprResult Result = CheckUnevaluatedOperand(E); 4176 if (Result.isInvalid()) 4177 return true; 4178 E = Result.get(); 4179 } 4180 4181 // The operand for sizeof and alignof is in an unevaluated expression context, 4182 // so side effects could result in unintended consequences. 4183 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4184 // used to build SFINAE gadgets. 4185 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4186 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4187 !E->isInstantiationDependent() && 4188 E->HasSideEffects(Context, false)) 4189 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4190 4191 if (ExprKind == UETT_VecStep) 4192 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4193 E->getSourceRange()); 4194 4195 // Explicitly list some types as extensions. 4196 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4197 E->getSourceRange(), ExprKind)) 4198 return false; 4199 4200 // 'alignof' applied to an expression only requires the base element type of 4201 // the expression to be complete. 'sizeof' requires the expression's type to 4202 // be complete (and will attempt to complete it if it's an array of unknown 4203 // bound). 4204 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4205 if (RequireCompleteSizedType( 4206 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4207 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4208 getTraitSpelling(ExprKind), E->getSourceRange())) 4209 return true; 4210 } else { 4211 if (RequireCompleteSizedExprType( 4212 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4213 getTraitSpelling(ExprKind), E->getSourceRange())) 4214 return true; 4215 } 4216 4217 // Completing the expression's type may have changed it. 4218 ExprTy = E->getType(); 4219 assert(!ExprTy->isReferenceType()); 4220 4221 if (ExprTy->isFunctionType()) { 4222 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4223 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4224 return true; 4225 } 4226 4227 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4228 E->getSourceRange(), ExprKind)) 4229 return true; 4230 4231 if (ExprKind == UETT_SizeOf) { 4232 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4233 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4234 QualType OType = PVD->getOriginalType(); 4235 QualType Type = PVD->getType(); 4236 if (Type->isPointerType() && OType->isArrayType()) { 4237 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4238 << Type << OType; 4239 Diag(PVD->getLocation(), diag::note_declared_at); 4240 } 4241 } 4242 } 4243 4244 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4245 // decays into a pointer and returns an unintended result. This is most 4246 // likely a typo for "sizeof(array) op x". 4247 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4248 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4249 BO->getLHS()); 4250 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4251 BO->getRHS()); 4252 } 4253 } 4254 4255 return false; 4256 } 4257 4258 /// Check the constraints on operands to unary expression and type 4259 /// traits. 4260 /// 4261 /// This will complete any types necessary, and validate the various constraints 4262 /// on those operands. 4263 /// 4264 /// The UsualUnaryConversions() function is *not* called by this routine. 4265 /// C99 6.3.2.1p[2-4] all state: 4266 /// Except when it is the operand of the sizeof operator ... 4267 /// 4268 /// C++ [expr.sizeof]p4 4269 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4270 /// standard conversions are not applied to the operand of sizeof. 4271 /// 4272 /// This policy is followed for all of the unary trait expressions. 4273 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4274 SourceLocation OpLoc, 4275 SourceRange ExprRange, 4276 UnaryExprOrTypeTrait ExprKind) { 4277 if (ExprType->isDependentType()) 4278 return false; 4279 4280 // C++ [expr.sizeof]p2: 4281 // When applied to a reference or a reference type, the result 4282 // is the size of the referenced type. 4283 // C++11 [expr.alignof]p3: 4284 // When alignof is applied to a reference type, the result 4285 // shall be the alignment of the referenced type. 4286 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4287 ExprType = Ref->getPointeeType(); 4288 4289 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4290 // When alignof or _Alignof is applied to an array type, the result 4291 // is the alignment of the element type. 4292 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4293 ExprKind == UETT_OpenMPRequiredSimdAlign) 4294 ExprType = Context.getBaseElementType(ExprType); 4295 4296 if (ExprKind == UETT_VecStep) 4297 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4298 4299 // Explicitly list some types as extensions. 4300 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4301 ExprKind)) 4302 return false; 4303 4304 if (RequireCompleteSizedType( 4305 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4306 getTraitSpelling(ExprKind), ExprRange)) 4307 return true; 4308 4309 if (ExprType->isFunctionType()) { 4310 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4311 << getTraitSpelling(ExprKind) << ExprRange; 4312 return true; 4313 } 4314 4315 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4316 ExprKind)) 4317 return true; 4318 4319 return false; 4320 } 4321 4322 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4323 // Cannot know anything else if the expression is dependent. 4324 if (E->isTypeDependent()) 4325 return false; 4326 4327 if (E->getObjectKind() == OK_BitField) { 4328 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4329 << 1 << E->getSourceRange(); 4330 return true; 4331 } 4332 4333 ValueDecl *D = nullptr; 4334 Expr *Inner = E->IgnoreParens(); 4335 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4336 D = DRE->getDecl(); 4337 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4338 D = ME->getMemberDecl(); 4339 } 4340 4341 // If it's a field, require the containing struct to have a 4342 // complete definition so that we can compute the layout. 4343 // 4344 // This can happen in C++11 onwards, either by naming the member 4345 // in a way that is not transformed into a member access expression 4346 // (in an unevaluated operand, for instance), or by naming the member 4347 // in a trailing-return-type. 4348 // 4349 // For the record, since __alignof__ on expressions is a GCC 4350 // extension, GCC seems to permit this but always gives the 4351 // nonsensical answer 0. 4352 // 4353 // We don't really need the layout here --- we could instead just 4354 // directly check for all the appropriate alignment-lowing 4355 // attributes --- but that would require duplicating a lot of 4356 // logic that just isn't worth duplicating for such a marginal 4357 // use-case. 4358 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4359 // Fast path this check, since we at least know the record has a 4360 // definition if we can find a member of it. 4361 if (!FD->getParent()->isCompleteDefinition()) { 4362 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4363 << E->getSourceRange(); 4364 return true; 4365 } 4366 4367 // Otherwise, if it's a field, and the field doesn't have 4368 // reference type, then it must have a complete type (or be a 4369 // flexible array member, which we explicitly want to 4370 // white-list anyway), which makes the following checks trivial. 4371 if (!FD->getType()->isReferenceType()) 4372 return false; 4373 } 4374 4375 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4376 } 4377 4378 bool Sema::CheckVecStepExpr(Expr *E) { 4379 E = E->IgnoreParens(); 4380 4381 // Cannot know anything else if the expression is dependent. 4382 if (E->isTypeDependent()) 4383 return false; 4384 4385 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4386 } 4387 4388 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4389 CapturingScopeInfo *CSI) { 4390 assert(T->isVariablyModifiedType()); 4391 assert(CSI != nullptr); 4392 4393 // We're going to walk down into the type and look for VLA expressions. 4394 do { 4395 const Type *Ty = T.getTypePtr(); 4396 switch (Ty->getTypeClass()) { 4397 #define TYPE(Class, Base) 4398 #define ABSTRACT_TYPE(Class, Base) 4399 #define NON_CANONICAL_TYPE(Class, Base) 4400 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4401 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4402 #include "clang/AST/TypeNodes.inc" 4403 T = QualType(); 4404 break; 4405 // These types are never variably-modified. 4406 case Type::Builtin: 4407 case Type::Complex: 4408 case Type::Vector: 4409 case Type::ExtVector: 4410 case Type::ConstantMatrix: 4411 case Type::Record: 4412 case Type::Enum: 4413 case Type::Elaborated: 4414 case Type::TemplateSpecialization: 4415 case Type::ObjCObject: 4416 case Type::ObjCInterface: 4417 case Type::ObjCObjectPointer: 4418 case Type::ObjCTypeParam: 4419 case Type::Pipe: 4420 case Type::BitInt: 4421 llvm_unreachable("type class is never variably-modified!"); 4422 case Type::Adjusted: 4423 T = cast<AdjustedType>(Ty)->getOriginalType(); 4424 break; 4425 case Type::Decayed: 4426 T = cast<DecayedType>(Ty)->getPointeeType(); 4427 break; 4428 case Type::Pointer: 4429 T = cast<PointerType>(Ty)->getPointeeType(); 4430 break; 4431 case Type::BlockPointer: 4432 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4433 break; 4434 case Type::LValueReference: 4435 case Type::RValueReference: 4436 T = cast<ReferenceType>(Ty)->getPointeeType(); 4437 break; 4438 case Type::MemberPointer: 4439 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4440 break; 4441 case Type::ConstantArray: 4442 case Type::IncompleteArray: 4443 // Losing element qualification here is fine. 4444 T = cast<ArrayType>(Ty)->getElementType(); 4445 break; 4446 case Type::VariableArray: { 4447 // Losing element qualification here is fine. 4448 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4449 4450 // Unknown size indication requires no size computation. 4451 // Otherwise, evaluate and record it. 4452 auto Size = VAT->getSizeExpr(); 4453 if (Size && !CSI->isVLATypeCaptured(VAT) && 4454 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4455 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4456 4457 T = VAT->getElementType(); 4458 break; 4459 } 4460 case Type::FunctionProto: 4461 case Type::FunctionNoProto: 4462 T = cast<FunctionType>(Ty)->getReturnType(); 4463 break; 4464 case Type::Paren: 4465 case Type::TypeOf: 4466 case Type::UnaryTransform: 4467 case Type::Attributed: 4468 case Type::SubstTemplateTypeParm: 4469 case Type::MacroQualified: 4470 // Keep walking after single level desugaring. 4471 T = T.getSingleStepDesugaredType(Context); 4472 break; 4473 case Type::Typedef: 4474 T = cast<TypedefType>(Ty)->desugar(); 4475 break; 4476 case Type::Decltype: 4477 T = cast<DecltypeType>(Ty)->desugar(); 4478 break; 4479 case Type::Using: 4480 T = cast<UsingType>(Ty)->desugar(); 4481 break; 4482 case Type::Auto: 4483 case Type::DeducedTemplateSpecialization: 4484 T = cast<DeducedType>(Ty)->getDeducedType(); 4485 break; 4486 case Type::TypeOfExpr: 4487 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4488 break; 4489 case Type::Atomic: 4490 T = cast<AtomicType>(Ty)->getValueType(); 4491 break; 4492 } 4493 } while (!T.isNull() && T->isVariablyModifiedType()); 4494 } 4495 4496 /// Build a sizeof or alignof expression given a type operand. 4497 ExprResult 4498 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4499 SourceLocation OpLoc, 4500 UnaryExprOrTypeTrait ExprKind, 4501 SourceRange R) { 4502 if (!TInfo) 4503 return ExprError(); 4504 4505 QualType T = TInfo->getType(); 4506 4507 if (!T->isDependentType() && 4508 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4509 return ExprError(); 4510 4511 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4512 if (auto *TT = T->getAs<TypedefType>()) { 4513 for (auto I = FunctionScopes.rbegin(), 4514 E = std::prev(FunctionScopes.rend()); 4515 I != E; ++I) { 4516 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4517 if (CSI == nullptr) 4518 break; 4519 DeclContext *DC = nullptr; 4520 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4521 DC = LSI->CallOperator; 4522 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4523 DC = CRSI->TheCapturedDecl; 4524 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4525 DC = BSI->TheDecl; 4526 if (DC) { 4527 if (DC->containsDecl(TT->getDecl())) 4528 break; 4529 captureVariablyModifiedType(Context, T, CSI); 4530 } 4531 } 4532 } 4533 } 4534 4535 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4536 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && 4537 TInfo->getType()->isVariablyModifiedType()) 4538 TInfo = TransformToPotentiallyEvaluated(TInfo); 4539 4540 return new (Context) UnaryExprOrTypeTraitExpr( 4541 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4542 } 4543 4544 /// Build a sizeof or alignof expression given an expression 4545 /// operand. 4546 ExprResult 4547 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4548 UnaryExprOrTypeTrait ExprKind) { 4549 ExprResult PE = CheckPlaceholderExpr(E); 4550 if (PE.isInvalid()) 4551 return ExprError(); 4552 4553 E = PE.get(); 4554 4555 // Verify that the operand is valid. 4556 bool isInvalid = false; 4557 if (E->isTypeDependent()) { 4558 // Delay type-checking for type-dependent expressions. 4559 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4560 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4561 } else if (ExprKind == UETT_VecStep) { 4562 isInvalid = CheckVecStepExpr(E); 4563 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4564 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4565 isInvalid = true; 4566 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4567 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4568 isInvalid = true; 4569 } else { 4570 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4571 } 4572 4573 if (isInvalid) 4574 return ExprError(); 4575 4576 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4577 PE = TransformToPotentiallyEvaluated(E); 4578 if (PE.isInvalid()) return ExprError(); 4579 E = PE.get(); 4580 } 4581 4582 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4583 return new (Context) UnaryExprOrTypeTraitExpr( 4584 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4585 } 4586 4587 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4588 /// expr and the same for @c alignof and @c __alignof 4589 /// Note that the ArgRange is invalid if isType is false. 4590 ExprResult 4591 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4592 UnaryExprOrTypeTrait ExprKind, bool IsType, 4593 void *TyOrEx, SourceRange ArgRange) { 4594 // If error parsing type, ignore. 4595 if (!TyOrEx) return ExprError(); 4596 4597 if (IsType) { 4598 TypeSourceInfo *TInfo; 4599 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4600 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4601 } 4602 4603 Expr *ArgEx = (Expr *)TyOrEx; 4604 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4605 return Result; 4606 } 4607 4608 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4609 bool IsReal) { 4610 if (V.get()->isTypeDependent()) 4611 return S.Context.DependentTy; 4612 4613 // _Real and _Imag are only l-values for normal l-values. 4614 if (V.get()->getObjectKind() != OK_Ordinary) { 4615 V = S.DefaultLvalueConversion(V.get()); 4616 if (V.isInvalid()) 4617 return QualType(); 4618 } 4619 4620 // These operators return the element type of a complex type. 4621 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4622 return CT->getElementType(); 4623 4624 // Otherwise they pass through real integer and floating point types here. 4625 if (V.get()->getType()->isArithmeticType()) 4626 return V.get()->getType(); 4627 4628 // Test for placeholders. 4629 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4630 if (PR.isInvalid()) return QualType(); 4631 if (PR.get() != V.get()) { 4632 V = PR; 4633 return CheckRealImagOperand(S, V, Loc, IsReal); 4634 } 4635 4636 // Reject anything else. 4637 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4638 << (IsReal ? "__real" : "__imag"); 4639 return QualType(); 4640 } 4641 4642 4643 4644 ExprResult 4645 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4646 tok::TokenKind Kind, Expr *Input) { 4647 UnaryOperatorKind Opc; 4648 switch (Kind) { 4649 default: llvm_unreachable("Unknown unary op!"); 4650 case tok::plusplus: Opc = UO_PostInc; break; 4651 case tok::minusminus: Opc = UO_PostDec; break; 4652 } 4653 4654 // Since this might is a postfix expression, get rid of ParenListExprs. 4655 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4656 if (Result.isInvalid()) return ExprError(); 4657 Input = Result.get(); 4658 4659 return BuildUnaryOp(S, OpLoc, Opc, Input); 4660 } 4661 4662 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4663 /// 4664 /// \return true on error 4665 static bool checkArithmeticOnObjCPointer(Sema &S, 4666 SourceLocation opLoc, 4667 Expr *op) { 4668 assert(op->getType()->isObjCObjectPointerType()); 4669 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4670 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4671 return false; 4672 4673 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4674 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4675 << op->getSourceRange(); 4676 return true; 4677 } 4678 4679 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4680 auto *BaseNoParens = Base->IgnoreParens(); 4681 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4682 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4683 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4684 } 4685 4686 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. 4687 // Typically this is DependentTy, but can sometimes be more precise. 4688 // 4689 // There are cases when we could determine a non-dependent type: 4690 // - LHS and RHS may have non-dependent types despite being type-dependent 4691 // (e.g. unbounded array static members of the current instantiation) 4692 // - one may be a dependent-sized array with known element type 4693 // - one may be a dependent-typed valid index (enum in current instantiation) 4694 // 4695 // We *always* return a dependent type, in such cases it is DependentTy. 4696 // This avoids creating type-dependent expressions with non-dependent types. 4697 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 4698 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, 4699 const ASTContext &Ctx) { 4700 assert(LHS->isTypeDependent() || RHS->isTypeDependent()); 4701 QualType LTy = LHS->getType(), RTy = RHS->getType(); 4702 QualType Result = Ctx.DependentTy; 4703 if (RTy->isIntegralOrUnscopedEnumerationType()) { 4704 if (const PointerType *PT = LTy->getAs<PointerType>()) 4705 Result = PT->getPointeeType(); 4706 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) 4707 Result = AT->getElementType(); 4708 } else if (LTy->isIntegralOrUnscopedEnumerationType()) { 4709 if (const PointerType *PT = RTy->getAs<PointerType>()) 4710 Result = PT->getPointeeType(); 4711 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) 4712 Result = AT->getElementType(); 4713 } 4714 // Ensure we return a dependent type. 4715 return Result->isDependentType() ? Result : Ctx.DependentTy; 4716 } 4717 4718 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args); 4719 4720 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, 4721 SourceLocation lbLoc, 4722 MultiExprArg ArgExprs, 4723 SourceLocation rbLoc) { 4724 4725 if (base && !base->getType().isNull() && 4726 base->hasPlaceholderType(BuiltinType::OMPArraySection)) 4727 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(), 4728 SourceLocation(), /*Length*/ nullptr, 4729 /*Stride=*/nullptr, rbLoc); 4730 4731 // Since this might be a postfix expression, get rid of ParenListExprs. 4732 if (isa<ParenListExpr>(base)) { 4733 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4734 if (result.isInvalid()) 4735 return ExprError(); 4736 base = result.get(); 4737 } 4738 4739 // Check if base and idx form a MatrixSubscriptExpr. 4740 // 4741 // Helper to check for comma expressions, which are not allowed as indices for 4742 // matrix subscript expressions. 4743 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4744 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4745 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4746 << SourceRange(base->getBeginLoc(), rbLoc); 4747 return true; 4748 } 4749 return false; 4750 }; 4751 // The matrix subscript operator ([][])is considered a single operator. 4752 // Separating the index expressions by parenthesis is not allowed. 4753 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) && 4754 !isa<MatrixSubscriptExpr>(base)) { 4755 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4756 << SourceRange(base->getBeginLoc(), rbLoc); 4757 return ExprError(); 4758 } 4759 // If the base is a MatrixSubscriptExpr, try to create a new 4760 // MatrixSubscriptExpr. 4761 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4762 if (matSubscriptE) { 4763 assert(ArgExprs.size() == 1); 4764 if (CheckAndReportCommaError(ArgExprs.front())) 4765 return ExprError(); 4766 4767 assert(matSubscriptE->isIncomplete() && 4768 "base has to be an incomplete matrix subscript"); 4769 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(), 4770 matSubscriptE->getRowIdx(), 4771 ArgExprs.front(), rbLoc); 4772 } 4773 4774 // Handle any non-overload placeholder types in the base and index 4775 // expressions. We can't handle overloads here because the other 4776 // operand might be an overloadable type, in which case the overload 4777 // resolution for the operator overload should get the first crack 4778 // at the overload. 4779 bool IsMSPropertySubscript = false; 4780 if (base->getType()->isNonOverloadPlaceholderType()) { 4781 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4782 if (!IsMSPropertySubscript) { 4783 ExprResult result = CheckPlaceholderExpr(base); 4784 if (result.isInvalid()) 4785 return ExprError(); 4786 base = result.get(); 4787 } 4788 } 4789 4790 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4791 if (base->getType()->isMatrixType()) { 4792 assert(ArgExprs.size() == 1); 4793 if (CheckAndReportCommaError(ArgExprs.front())) 4794 return ExprError(); 4795 4796 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr, 4797 rbLoc); 4798 } 4799 4800 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { 4801 Expr *idx = ArgExprs[0]; 4802 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4803 (isa<CXXOperatorCallExpr>(idx) && 4804 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) { 4805 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4806 << SourceRange(base->getBeginLoc(), rbLoc); 4807 } 4808 } 4809 4810 if (ArgExprs.size() == 1 && 4811 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { 4812 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]); 4813 if (result.isInvalid()) 4814 return ExprError(); 4815 ArgExprs[0] = result.get(); 4816 } else { 4817 if (checkArgsForPlaceholders(*this, ArgExprs)) 4818 return ExprError(); 4819 } 4820 4821 // Build an unanalyzed expression if either operand is type-dependent. 4822 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && 4823 (base->isTypeDependent() || 4824 Expr::hasAnyTypeDependentArguments(ArgExprs))) { 4825 return new (Context) ArraySubscriptExpr( 4826 base, ArgExprs.front(), 4827 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()), 4828 VK_LValue, OK_Ordinary, rbLoc); 4829 } 4830 4831 // MSDN, property (C++) 4832 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4833 // This attribute can also be used in the declaration of an empty array in a 4834 // class or structure definition. For example: 4835 // __declspec(property(get=GetX, put=PutX)) int x[]; 4836 // The above statement indicates that x[] can be used with one or more array 4837 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4838 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4839 if (IsMSPropertySubscript) { 4840 assert(ArgExprs.size() == 1); 4841 // Build MS property subscript expression if base is MS property reference 4842 // or MS property subscript. 4843 return new (Context) 4844 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, 4845 VK_LValue, OK_Ordinary, rbLoc); 4846 } 4847 4848 // Use C++ overloaded-operator rules if either operand has record 4849 // type. The spec says to do this if either type is *overloadable*, 4850 // but enum types can't declare subscript operators or conversion 4851 // operators, so there's nothing interesting for overload resolution 4852 // to do if there aren't any record types involved. 4853 // 4854 // ObjC pointers have their own subscripting logic that is not tied 4855 // to overload resolution and so should not take this path. 4856 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && 4857 ((base->getType()->isRecordType() || 4858 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) { 4859 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs); 4860 } 4861 4862 ExprResult Res = 4863 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc); 4864 4865 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4866 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4867 4868 return Res; 4869 } 4870 4871 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4872 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4873 InitializationKind Kind = 4874 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4875 InitializationSequence InitSeq(*this, Entity, Kind, E); 4876 return InitSeq.Perform(*this, Entity, Kind, E); 4877 } 4878 4879 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4880 Expr *ColumnIdx, 4881 SourceLocation RBLoc) { 4882 ExprResult BaseR = CheckPlaceholderExpr(Base); 4883 if (BaseR.isInvalid()) 4884 return BaseR; 4885 Base = BaseR.get(); 4886 4887 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4888 if (RowR.isInvalid()) 4889 return RowR; 4890 RowIdx = RowR.get(); 4891 4892 if (!ColumnIdx) 4893 return new (Context) MatrixSubscriptExpr( 4894 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4895 4896 // Build an unanalyzed expression if any of the operands is type-dependent. 4897 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4898 ColumnIdx->isTypeDependent()) 4899 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4900 Context.DependentTy, RBLoc); 4901 4902 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4903 if (ColumnR.isInvalid()) 4904 return ColumnR; 4905 ColumnIdx = ColumnR.get(); 4906 4907 // Check that IndexExpr is an integer expression. If it is a constant 4908 // expression, check that it is less than Dim (= the number of elements in the 4909 // corresponding dimension). 4910 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4911 bool IsColumnIdx) -> Expr * { 4912 if (!IndexExpr->getType()->isIntegerType() && 4913 !IndexExpr->isTypeDependent()) { 4914 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4915 << IsColumnIdx; 4916 return nullptr; 4917 } 4918 4919 if (Optional<llvm::APSInt> Idx = 4920 IndexExpr->getIntegerConstantExpr(Context)) { 4921 if ((*Idx < 0 || *Idx >= Dim)) { 4922 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4923 << IsColumnIdx << Dim; 4924 return nullptr; 4925 } 4926 } 4927 4928 ExprResult ConvExpr = 4929 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4930 assert(!ConvExpr.isInvalid() && 4931 "should be able to convert any integer type to size type"); 4932 return ConvExpr.get(); 4933 }; 4934 4935 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4936 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4937 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4938 if (!RowIdx || !ColumnIdx) 4939 return ExprError(); 4940 4941 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4942 MTy->getElementType(), RBLoc); 4943 } 4944 4945 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4946 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4947 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4948 4949 // For expressions like `&(*s).b`, the base is recorded and what should be 4950 // checked. 4951 const MemberExpr *Member = nullptr; 4952 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4953 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4954 4955 LastRecord.PossibleDerefs.erase(StrippedExpr); 4956 } 4957 4958 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4959 if (isUnevaluatedContext()) 4960 return; 4961 4962 QualType ResultTy = E->getType(); 4963 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4964 4965 // Bail if the element is an array since it is not memory access. 4966 if (isa<ArrayType>(ResultTy)) 4967 return; 4968 4969 if (ResultTy->hasAttr(attr::NoDeref)) { 4970 LastRecord.PossibleDerefs.insert(E); 4971 return; 4972 } 4973 4974 // Check if the base type is a pointer to a member access of a struct 4975 // marked with noderef. 4976 const Expr *Base = E->getBase(); 4977 QualType BaseTy = Base->getType(); 4978 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4979 // Not a pointer access 4980 return; 4981 4982 const MemberExpr *Member = nullptr; 4983 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4984 Member->isArrow()) 4985 Base = Member->getBase(); 4986 4987 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4988 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4989 LastRecord.PossibleDerefs.insert(E); 4990 } 4991 } 4992 4993 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4994 Expr *LowerBound, 4995 SourceLocation ColonLocFirst, 4996 SourceLocation ColonLocSecond, 4997 Expr *Length, Expr *Stride, 4998 SourceLocation RBLoc) { 4999 if (Base->hasPlaceholderType() && 5000 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5001 ExprResult Result = CheckPlaceholderExpr(Base); 5002 if (Result.isInvalid()) 5003 return ExprError(); 5004 Base = Result.get(); 5005 } 5006 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 5007 ExprResult Result = CheckPlaceholderExpr(LowerBound); 5008 if (Result.isInvalid()) 5009 return ExprError(); 5010 Result = DefaultLvalueConversion(Result.get()); 5011 if (Result.isInvalid()) 5012 return ExprError(); 5013 LowerBound = Result.get(); 5014 } 5015 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 5016 ExprResult Result = CheckPlaceholderExpr(Length); 5017 if (Result.isInvalid()) 5018 return ExprError(); 5019 Result = DefaultLvalueConversion(Result.get()); 5020 if (Result.isInvalid()) 5021 return ExprError(); 5022 Length = Result.get(); 5023 } 5024 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 5025 ExprResult Result = CheckPlaceholderExpr(Stride); 5026 if (Result.isInvalid()) 5027 return ExprError(); 5028 Result = DefaultLvalueConversion(Result.get()); 5029 if (Result.isInvalid()) 5030 return ExprError(); 5031 Stride = Result.get(); 5032 } 5033 5034 // Build an unanalyzed expression if either operand is type-dependent. 5035 if (Base->isTypeDependent() || 5036 (LowerBound && 5037 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 5038 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 5039 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 5040 return new (Context) OMPArraySectionExpr( 5041 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 5042 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5043 } 5044 5045 // Perform default conversions. 5046 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 5047 QualType ResultTy; 5048 if (OriginalTy->isAnyPointerType()) { 5049 ResultTy = OriginalTy->getPointeeType(); 5050 } else if (OriginalTy->isArrayType()) { 5051 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 5052 } else { 5053 return ExprError( 5054 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 5055 << Base->getSourceRange()); 5056 } 5057 // C99 6.5.2.1p1 5058 if (LowerBound) { 5059 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 5060 LowerBound); 5061 if (Res.isInvalid()) 5062 return ExprError(Diag(LowerBound->getExprLoc(), 5063 diag::err_omp_typecheck_section_not_integer) 5064 << 0 << LowerBound->getSourceRange()); 5065 LowerBound = Res.get(); 5066 5067 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5068 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5069 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5070 << 0 << LowerBound->getSourceRange(); 5071 } 5072 if (Length) { 5073 auto Res = 5074 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5075 if (Res.isInvalid()) 5076 return ExprError(Diag(Length->getExprLoc(), 5077 diag::err_omp_typecheck_section_not_integer) 5078 << 1 << Length->getSourceRange()); 5079 Length = Res.get(); 5080 5081 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5082 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5083 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5084 << 1 << Length->getSourceRange(); 5085 } 5086 if (Stride) { 5087 ExprResult Res = 5088 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5089 if (Res.isInvalid()) 5090 return ExprError(Diag(Stride->getExprLoc(), 5091 diag::err_omp_typecheck_section_not_integer) 5092 << 1 << Stride->getSourceRange()); 5093 Stride = Res.get(); 5094 5095 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5096 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5097 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5098 << 1 << Stride->getSourceRange(); 5099 } 5100 5101 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5102 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5103 // type. Note that functions are not objects, and that (in C99 parlance) 5104 // incomplete types are not object types. 5105 if (ResultTy->isFunctionType()) { 5106 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5107 << ResultTy << Base->getSourceRange(); 5108 return ExprError(); 5109 } 5110 5111 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5112 diag::err_omp_section_incomplete_type, Base)) 5113 return ExprError(); 5114 5115 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5116 Expr::EvalResult Result; 5117 if (LowerBound->EvaluateAsInt(Result, Context)) { 5118 // OpenMP 5.0, [2.1.5 Array Sections] 5119 // The array section must be a subset of the original array. 5120 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5121 if (LowerBoundValue.isNegative()) { 5122 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5123 << LowerBound->getSourceRange(); 5124 return ExprError(); 5125 } 5126 } 5127 } 5128 5129 if (Length) { 5130 Expr::EvalResult Result; 5131 if (Length->EvaluateAsInt(Result, Context)) { 5132 // OpenMP 5.0, [2.1.5 Array Sections] 5133 // The length must evaluate to non-negative integers. 5134 llvm::APSInt LengthValue = Result.Val.getInt(); 5135 if (LengthValue.isNegative()) { 5136 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5137 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5138 << Length->getSourceRange(); 5139 return ExprError(); 5140 } 5141 } 5142 } else if (ColonLocFirst.isValid() && 5143 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5144 !OriginalTy->isVariableArrayType()))) { 5145 // OpenMP 5.0, [2.1.5 Array Sections] 5146 // When the size of the array dimension is not known, the length must be 5147 // specified explicitly. 5148 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5149 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5150 return ExprError(); 5151 } 5152 5153 if (Stride) { 5154 Expr::EvalResult Result; 5155 if (Stride->EvaluateAsInt(Result, Context)) { 5156 // OpenMP 5.0, [2.1.5 Array Sections] 5157 // The stride must evaluate to a positive integer. 5158 llvm::APSInt StrideValue = Result.Val.getInt(); 5159 if (!StrideValue.isStrictlyPositive()) { 5160 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5161 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5162 << Stride->getSourceRange(); 5163 return ExprError(); 5164 } 5165 } 5166 } 5167 5168 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5169 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5170 if (Result.isInvalid()) 5171 return ExprError(); 5172 Base = Result.get(); 5173 } 5174 return new (Context) OMPArraySectionExpr( 5175 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5176 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5177 } 5178 5179 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5180 SourceLocation RParenLoc, 5181 ArrayRef<Expr *> Dims, 5182 ArrayRef<SourceRange> Brackets) { 5183 if (Base->hasPlaceholderType()) { 5184 ExprResult Result = CheckPlaceholderExpr(Base); 5185 if (Result.isInvalid()) 5186 return ExprError(); 5187 Result = DefaultLvalueConversion(Result.get()); 5188 if (Result.isInvalid()) 5189 return ExprError(); 5190 Base = Result.get(); 5191 } 5192 QualType BaseTy = Base->getType(); 5193 // Delay analysis of the types/expressions if instantiation/specialization is 5194 // required. 5195 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5196 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5197 LParenLoc, RParenLoc, Dims, Brackets); 5198 if (!BaseTy->isPointerType() || 5199 (!Base->isTypeDependent() && 5200 BaseTy->getPointeeType()->isIncompleteType())) 5201 return ExprError(Diag(Base->getExprLoc(), 5202 diag::err_omp_non_pointer_type_array_shaping_base) 5203 << Base->getSourceRange()); 5204 5205 SmallVector<Expr *, 4> NewDims; 5206 bool ErrorFound = false; 5207 for (Expr *Dim : Dims) { 5208 if (Dim->hasPlaceholderType()) { 5209 ExprResult Result = CheckPlaceholderExpr(Dim); 5210 if (Result.isInvalid()) { 5211 ErrorFound = true; 5212 continue; 5213 } 5214 Result = DefaultLvalueConversion(Result.get()); 5215 if (Result.isInvalid()) { 5216 ErrorFound = true; 5217 continue; 5218 } 5219 Dim = Result.get(); 5220 } 5221 if (!Dim->isTypeDependent()) { 5222 ExprResult Result = 5223 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5224 if (Result.isInvalid()) { 5225 ErrorFound = true; 5226 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5227 << Dim->getSourceRange(); 5228 continue; 5229 } 5230 Dim = Result.get(); 5231 Expr::EvalResult EvResult; 5232 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5233 // OpenMP 5.0, [2.1.4 Array Shaping] 5234 // Each si is an integral type expression that must evaluate to a 5235 // positive integer. 5236 llvm::APSInt Value = EvResult.Val.getInt(); 5237 if (!Value.isStrictlyPositive()) { 5238 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5239 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5240 << Dim->getSourceRange(); 5241 ErrorFound = true; 5242 continue; 5243 } 5244 } 5245 } 5246 NewDims.push_back(Dim); 5247 } 5248 if (ErrorFound) 5249 return ExprError(); 5250 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5251 LParenLoc, RParenLoc, NewDims, Brackets); 5252 } 5253 5254 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5255 SourceLocation LLoc, SourceLocation RLoc, 5256 ArrayRef<OMPIteratorData> Data) { 5257 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5258 bool IsCorrect = true; 5259 for (const OMPIteratorData &D : Data) { 5260 TypeSourceInfo *TInfo = nullptr; 5261 SourceLocation StartLoc; 5262 QualType DeclTy; 5263 if (!D.Type.getAsOpaquePtr()) { 5264 // OpenMP 5.0, 2.1.6 Iterators 5265 // In an iterator-specifier, if the iterator-type is not specified then 5266 // the type of that iterator is of int type. 5267 DeclTy = Context.IntTy; 5268 StartLoc = D.DeclIdentLoc; 5269 } else { 5270 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5271 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5272 } 5273 5274 bool IsDeclTyDependent = DeclTy->isDependentType() || 5275 DeclTy->containsUnexpandedParameterPack() || 5276 DeclTy->isInstantiationDependentType(); 5277 if (!IsDeclTyDependent) { 5278 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5279 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5280 // The iterator-type must be an integral or pointer type. 5281 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5282 << DeclTy; 5283 IsCorrect = false; 5284 continue; 5285 } 5286 if (DeclTy.isConstant(Context)) { 5287 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5288 // The iterator-type must not be const qualified. 5289 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5290 << DeclTy; 5291 IsCorrect = false; 5292 continue; 5293 } 5294 } 5295 5296 // Iterator declaration. 5297 assert(D.DeclIdent && "Identifier expected."); 5298 // Always try to create iterator declarator to avoid extra error messages 5299 // about unknown declarations use. 5300 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5301 D.DeclIdent, DeclTy, TInfo, SC_None); 5302 VD->setImplicit(); 5303 if (S) { 5304 // Check for conflicting previous declaration. 5305 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5306 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5307 ForVisibleRedeclaration); 5308 Previous.suppressDiagnostics(); 5309 LookupName(Previous, S); 5310 5311 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5312 /*AllowInlineNamespace=*/false); 5313 if (!Previous.empty()) { 5314 NamedDecl *Old = Previous.getRepresentativeDecl(); 5315 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5316 Diag(Old->getLocation(), diag::note_previous_definition); 5317 } else { 5318 PushOnScopeChains(VD, S); 5319 } 5320 } else { 5321 CurContext->addDecl(VD); 5322 } 5323 Expr *Begin = D.Range.Begin; 5324 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5325 ExprResult BeginRes = 5326 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5327 Begin = BeginRes.get(); 5328 } 5329 Expr *End = D.Range.End; 5330 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5331 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5332 End = EndRes.get(); 5333 } 5334 Expr *Step = D.Range.Step; 5335 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5336 if (!Step->getType()->isIntegralType(Context)) { 5337 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5338 << Step << Step->getSourceRange(); 5339 IsCorrect = false; 5340 continue; 5341 } 5342 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5343 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5344 // If the step expression of a range-specification equals zero, the 5345 // behavior is unspecified. 5346 if (Result && Result->isZero()) { 5347 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5348 << Step << Step->getSourceRange(); 5349 IsCorrect = false; 5350 continue; 5351 } 5352 } 5353 if (!Begin || !End || !IsCorrect) { 5354 IsCorrect = false; 5355 continue; 5356 } 5357 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5358 IDElem.IteratorDecl = VD; 5359 IDElem.AssignmentLoc = D.AssignLoc; 5360 IDElem.Range.Begin = Begin; 5361 IDElem.Range.End = End; 5362 IDElem.Range.Step = Step; 5363 IDElem.ColonLoc = D.ColonLoc; 5364 IDElem.SecondColonLoc = D.SecColonLoc; 5365 } 5366 if (!IsCorrect) { 5367 // Invalidate all created iterator declarations if error is found. 5368 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5369 if (Decl *ID = D.IteratorDecl) 5370 ID->setInvalidDecl(); 5371 } 5372 return ExprError(); 5373 } 5374 SmallVector<OMPIteratorHelperData, 4> Helpers; 5375 if (!CurContext->isDependentContext()) { 5376 // Build number of ityeration for each iteration range. 5377 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5378 // ((Begini-Stepi-1-Endi) / -Stepi); 5379 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5380 // (Endi - Begini) 5381 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5382 D.Range.Begin); 5383 if(!Res.isUsable()) { 5384 IsCorrect = false; 5385 continue; 5386 } 5387 ExprResult St, St1; 5388 if (D.Range.Step) { 5389 St = D.Range.Step; 5390 // (Endi - Begini) + Stepi 5391 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5392 if (!Res.isUsable()) { 5393 IsCorrect = false; 5394 continue; 5395 } 5396 // (Endi - Begini) + Stepi - 1 5397 Res = 5398 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5399 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5400 if (!Res.isUsable()) { 5401 IsCorrect = false; 5402 continue; 5403 } 5404 // ((Endi - Begini) + Stepi - 1) / Stepi 5405 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5406 if (!Res.isUsable()) { 5407 IsCorrect = false; 5408 continue; 5409 } 5410 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5411 // (Begini - Endi) 5412 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5413 D.Range.Begin, D.Range.End); 5414 if (!Res1.isUsable()) { 5415 IsCorrect = false; 5416 continue; 5417 } 5418 // (Begini - Endi) - Stepi 5419 Res1 = 5420 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5421 if (!Res1.isUsable()) { 5422 IsCorrect = false; 5423 continue; 5424 } 5425 // (Begini - Endi) - Stepi - 1 5426 Res1 = 5427 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5428 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5429 if (!Res1.isUsable()) { 5430 IsCorrect = false; 5431 continue; 5432 } 5433 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5434 Res1 = 5435 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5436 if (!Res1.isUsable()) { 5437 IsCorrect = false; 5438 continue; 5439 } 5440 // Stepi > 0. 5441 ExprResult CmpRes = 5442 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5443 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5444 if (!CmpRes.isUsable()) { 5445 IsCorrect = false; 5446 continue; 5447 } 5448 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5449 Res.get(), Res1.get()); 5450 if (!Res.isUsable()) { 5451 IsCorrect = false; 5452 continue; 5453 } 5454 } 5455 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5456 if (!Res.isUsable()) { 5457 IsCorrect = false; 5458 continue; 5459 } 5460 5461 // Build counter update. 5462 // Build counter. 5463 auto *CounterVD = 5464 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5465 D.IteratorDecl->getBeginLoc(), nullptr, 5466 Res.get()->getType(), nullptr, SC_None); 5467 CounterVD->setImplicit(); 5468 ExprResult RefRes = 5469 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5470 D.IteratorDecl->getBeginLoc()); 5471 // Build counter update. 5472 // I = Begini + counter * Stepi; 5473 ExprResult UpdateRes; 5474 if (D.Range.Step) { 5475 UpdateRes = CreateBuiltinBinOp( 5476 D.AssignmentLoc, BO_Mul, 5477 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5478 } else { 5479 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5480 } 5481 if (!UpdateRes.isUsable()) { 5482 IsCorrect = false; 5483 continue; 5484 } 5485 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5486 UpdateRes.get()); 5487 if (!UpdateRes.isUsable()) { 5488 IsCorrect = false; 5489 continue; 5490 } 5491 ExprResult VDRes = 5492 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5493 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5494 D.IteratorDecl->getBeginLoc()); 5495 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5496 UpdateRes.get()); 5497 if (!UpdateRes.isUsable()) { 5498 IsCorrect = false; 5499 continue; 5500 } 5501 UpdateRes = 5502 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5503 if (!UpdateRes.isUsable()) { 5504 IsCorrect = false; 5505 continue; 5506 } 5507 ExprResult CounterUpdateRes = 5508 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5509 if (!CounterUpdateRes.isUsable()) { 5510 IsCorrect = false; 5511 continue; 5512 } 5513 CounterUpdateRes = 5514 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5515 if (!CounterUpdateRes.isUsable()) { 5516 IsCorrect = false; 5517 continue; 5518 } 5519 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5520 HD.CounterVD = CounterVD; 5521 HD.Upper = Res.get(); 5522 HD.Update = UpdateRes.get(); 5523 HD.CounterUpdate = CounterUpdateRes.get(); 5524 } 5525 } else { 5526 Helpers.assign(ID.size(), {}); 5527 } 5528 if (!IsCorrect) { 5529 // Invalidate all created iterator declarations if error is found. 5530 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5531 if (Decl *ID = D.IteratorDecl) 5532 ID->setInvalidDecl(); 5533 } 5534 return ExprError(); 5535 } 5536 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5537 LLoc, RLoc, ID, Helpers); 5538 } 5539 5540 ExprResult 5541 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5542 Expr *Idx, SourceLocation RLoc) { 5543 Expr *LHSExp = Base; 5544 Expr *RHSExp = Idx; 5545 5546 ExprValueKind VK = VK_LValue; 5547 ExprObjectKind OK = OK_Ordinary; 5548 5549 // Per C++ core issue 1213, the result is an xvalue if either operand is 5550 // a non-lvalue array, and an lvalue otherwise. 5551 if (getLangOpts().CPlusPlus11) { 5552 for (auto *Op : {LHSExp, RHSExp}) { 5553 Op = Op->IgnoreImplicit(); 5554 if (Op->getType()->isArrayType() && !Op->isLValue()) 5555 VK = VK_XValue; 5556 } 5557 } 5558 5559 // Perform default conversions. 5560 if (!LHSExp->getType()->getAs<VectorType>()) { 5561 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5562 if (Result.isInvalid()) 5563 return ExprError(); 5564 LHSExp = Result.get(); 5565 } 5566 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5567 if (Result.isInvalid()) 5568 return ExprError(); 5569 RHSExp = Result.get(); 5570 5571 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5572 5573 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5574 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5575 // in the subscript position. As a result, we need to derive the array base 5576 // and index from the expression types. 5577 Expr *BaseExpr, *IndexExpr; 5578 QualType ResultType; 5579 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5580 BaseExpr = LHSExp; 5581 IndexExpr = RHSExp; 5582 ResultType = 5583 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); 5584 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5585 BaseExpr = LHSExp; 5586 IndexExpr = RHSExp; 5587 ResultType = PTy->getPointeeType(); 5588 } else if (const ObjCObjectPointerType *PTy = 5589 LHSTy->getAs<ObjCObjectPointerType>()) { 5590 BaseExpr = LHSExp; 5591 IndexExpr = RHSExp; 5592 5593 // Use custom logic if this should be the pseudo-object subscript 5594 // expression. 5595 if (!LangOpts.isSubscriptPointerArithmetic()) 5596 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5597 nullptr); 5598 5599 ResultType = PTy->getPointeeType(); 5600 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5601 // Handle the uncommon case of "123[Ptr]". 5602 BaseExpr = RHSExp; 5603 IndexExpr = LHSExp; 5604 ResultType = PTy->getPointeeType(); 5605 } else if (const ObjCObjectPointerType *PTy = 5606 RHSTy->getAs<ObjCObjectPointerType>()) { 5607 // Handle the uncommon case of "123[Ptr]". 5608 BaseExpr = RHSExp; 5609 IndexExpr = LHSExp; 5610 ResultType = PTy->getPointeeType(); 5611 if (!LangOpts.isSubscriptPointerArithmetic()) { 5612 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5613 << ResultType << BaseExpr->getSourceRange(); 5614 return ExprError(); 5615 } 5616 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5617 BaseExpr = LHSExp; // vectors: V[123] 5618 IndexExpr = RHSExp; 5619 // We apply C++ DR1213 to vector subscripting too. 5620 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5621 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5622 if (Materialized.isInvalid()) 5623 return ExprError(); 5624 LHSExp = Materialized.get(); 5625 } 5626 VK = LHSExp->getValueKind(); 5627 if (VK != VK_PRValue) 5628 OK = OK_VectorComponent; 5629 5630 ResultType = VTy->getElementType(); 5631 QualType BaseType = BaseExpr->getType(); 5632 Qualifiers BaseQuals = BaseType.getQualifiers(); 5633 Qualifiers MemberQuals = ResultType.getQualifiers(); 5634 Qualifiers Combined = BaseQuals + MemberQuals; 5635 if (Combined != MemberQuals) 5636 ResultType = Context.getQualifiedType(ResultType, Combined); 5637 } else if (LHSTy->isArrayType()) { 5638 // If we see an array that wasn't promoted by 5639 // DefaultFunctionArrayLvalueConversion, it must be an array that 5640 // wasn't promoted because of the C90 rule that doesn't 5641 // allow promoting non-lvalue arrays. Warn, then 5642 // force the promotion here. 5643 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5644 << LHSExp->getSourceRange(); 5645 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5646 CK_ArrayToPointerDecay).get(); 5647 LHSTy = LHSExp->getType(); 5648 5649 BaseExpr = LHSExp; 5650 IndexExpr = RHSExp; 5651 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5652 } else if (RHSTy->isArrayType()) { 5653 // Same as previous, except for 123[f().a] case 5654 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5655 << RHSExp->getSourceRange(); 5656 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5657 CK_ArrayToPointerDecay).get(); 5658 RHSTy = RHSExp->getType(); 5659 5660 BaseExpr = RHSExp; 5661 IndexExpr = LHSExp; 5662 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5663 } else { 5664 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5665 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5666 } 5667 // C99 6.5.2.1p1 5668 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5669 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5670 << IndexExpr->getSourceRange()); 5671 5672 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5673 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5674 && !IndexExpr->isTypeDependent()) 5675 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5676 5677 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5678 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5679 // type. Note that Functions are not objects, and that (in C99 parlance) 5680 // incomplete types are not object types. 5681 if (ResultType->isFunctionType()) { 5682 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5683 << ResultType << BaseExpr->getSourceRange(); 5684 return ExprError(); 5685 } 5686 5687 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5688 // GNU extension: subscripting on pointer to void 5689 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5690 << BaseExpr->getSourceRange(); 5691 5692 // C forbids expressions of unqualified void type from being l-values. 5693 // See IsCForbiddenLValueType. 5694 if (!ResultType.hasQualifiers()) 5695 VK = VK_PRValue; 5696 } else if (!ResultType->isDependentType() && 5697 RequireCompleteSizedType( 5698 LLoc, ResultType, 5699 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5700 return ExprError(); 5701 5702 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5703 !ResultType.isCForbiddenLValueType()); 5704 5705 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5706 FunctionScopes.size() > 1) { 5707 if (auto *TT = 5708 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5709 for (auto I = FunctionScopes.rbegin(), 5710 E = std::prev(FunctionScopes.rend()); 5711 I != E; ++I) { 5712 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5713 if (CSI == nullptr) 5714 break; 5715 DeclContext *DC = nullptr; 5716 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5717 DC = LSI->CallOperator; 5718 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5719 DC = CRSI->TheCapturedDecl; 5720 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5721 DC = BSI->TheDecl; 5722 if (DC) { 5723 if (DC->containsDecl(TT->getDecl())) 5724 break; 5725 captureVariablyModifiedType( 5726 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5727 } 5728 } 5729 } 5730 } 5731 5732 return new (Context) 5733 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5734 } 5735 5736 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5737 ParmVarDecl *Param) { 5738 if (Param->hasUnparsedDefaultArg()) { 5739 // If we've already cleared out the location for the default argument, 5740 // that means we're parsing it right now. 5741 if (!UnparsedDefaultArgLocs.count(Param)) { 5742 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5743 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5744 Param->setInvalidDecl(); 5745 return true; 5746 } 5747 5748 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5749 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5750 Diag(UnparsedDefaultArgLocs[Param], 5751 diag::note_default_argument_declared_here); 5752 return true; 5753 } 5754 5755 if (Param->hasUninstantiatedDefaultArg() && 5756 InstantiateDefaultArgument(CallLoc, FD, Param)) 5757 return true; 5758 5759 assert(Param->hasInit() && "default argument but no initializer?"); 5760 5761 // If the default expression creates temporaries, we need to 5762 // push them to the current stack of expression temporaries so they'll 5763 // be properly destroyed. 5764 // FIXME: We should really be rebuilding the default argument with new 5765 // bound temporaries; see the comment in PR5810. 5766 // We don't need to do that with block decls, though, because 5767 // blocks in default argument expression can never capture anything. 5768 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5769 // Set the "needs cleanups" bit regardless of whether there are 5770 // any explicit objects. 5771 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5772 5773 // Append all the objects to the cleanup list. Right now, this 5774 // should always be a no-op, because blocks in default argument 5775 // expressions should never be able to capture anything. 5776 assert(!Init->getNumObjects() && 5777 "default argument expression has capturing blocks?"); 5778 } 5779 5780 // We already type-checked the argument, so we know it works. 5781 // Just mark all of the declarations in this potentially-evaluated expression 5782 // as being "referenced". 5783 EnterExpressionEvaluationContext EvalContext( 5784 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5785 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5786 /*SkipLocalVariables=*/true); 5787 return false; 5788 } 5789 5790 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5791 FunctionDecl *FD, ParmVarDecl *Param) { 5792 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5793 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5794 return ExprError(); 5795 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5796 } 5797 5798 Sema::VariadicCallType 5799 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5800 Expr *Fn) { 5801 if (Proto && Proto->isVariadic()) { 5802 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 5803 return VariadicConstructor; 5804 else if (Fn && Fn->getType()->isBlockPointerType()) 5805 return VariadicBlock; 5806 else if (FDecl) { 5807 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5808 if (Method->isInstance()) 5809 return VariadicMethod; 5810 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5811 return VariadicMethod; 5812 return VariadicFunction; 5813 } 5814 return VariadicDoesNotApply; 5815 } 5816 5817 namespace { 5818 class FunctionCallCCC final : public FunctionCallFilterCCC { 5819 public: 5820 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5821 unsigned NumArgs, MemberExpr *ME) 5822 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5823 FunctionName(FuncName) {} 5824 5825 bool ValidateCandidate(const TypoCorrection &candidate) override { 5826 if (!candidate.getCorrectionSpecifier() || 5827 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5828 return false; 5829 } 5830 5831 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5832 } 5833 5834 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5835 return std::make_unique<FunctionCallCCC>(*this); 5836 } 5837 5838 private: 5839 const IdentifierInfo *const FunctionName; 5840 }; 5841 } 5842 5843 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5844 FunctionDecl *FDecl, 5845 ArrayRef<Expr *> Args) { 5846 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5847 DeclarationName FuncName = FDecl->getDeclName(); 5848 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5849 5850 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5851 if (TypoCorrection Corrected = S.CorrectTypo( 5852 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5853 S.getScopeForContext(S.CurContext), nullptr, CCC, 5854 Sema::CTK_ErrorRecovery)) { 5855 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5856 if (Corrected.isOverloaded()) { 5857 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5858 OverloadCandidateSet::iterator Best; 5859 for (NamedDecl *CD : Corrected) { 5860 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5861 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5862 OCS); 5863 } 5864 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5865 case OR_Success: 5866 ND = Best->FoundDecl; 5867 Corrected.setCorrectionDecl(ND); 5868 break; 5869 default: 5870 break; 5871 } 5872 } 5873 ND = ND->getUnderlyingDecl(); 5874 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5875 return Corrected; 5876 } 5877 } 5878 return TypoCorrection(); 5879 } 5880 5881 /// ConvertArgumentsForCall - Converts the arguments specified in 5882 /// Args/NumArgs to the parameter types of the function FDecl with 5883 /// function prototype Proto. Call is the call expression itself, and 5884 /// Fn is the function expression. For a C++ member function, this 5885 /// routine does not attempt to convert the object argument. Returns 5886 /// true if the call is ill-formed. 5887 bool 5888 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5889 FunctionDecl *FDecl, 5890 const FunctionProtoType *Proto, 5891 ArrayRef<Expr *> Args, 5892 SourceLocation RParenLoc, 5893 bool IsExecConfig) { 5894 // Bail out early if calling a builtin with custom typechecking. 5895 if (FDecl) 5896 if (unsigned ID = FDecl->getBuiltinID()) 5897 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5898 return false; 5899 5900 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5901 // assignment, to the types of the corresponding parameter, ... 5902 unsigned NumParams = Proto->getNumParams(); 5903 bool Invalid = false; 5904 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5905 unsigned FnKind = Fn->getType()->isBlockPointerType() 5906 ? 1 /* block */ 5907 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5908 : 0 /* function */); 5909 5910 // If too few arguments are available (and we don't have default 5911 // arguments for the remaining parameters), don't make the call. 5912 if (Args.size() < NumParams) { 5913 if (Args.size() < MinArgs) { 5914 TypoCorrection TC; 5915 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5916 unsigned diag_id = 5917 MinArgs == NumParams && !Proto->isVariadic() 5918 ? diag::err_typecheck_call_too_few_args_suggest 5919 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5920 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5921 << static_cast<unsigned>(Args.size()) 5922 << TC.getCorrectionRange()); 5923 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5924 Diag(RParenLoc, 5925 MinArgs == NumParams && !Proto->isVariadic() 5926 ? diag::err_typecheck_call_too_few_args_one 5927 : diag::err_typecheck_call_too_few_args_at_least_one) 5928 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5929 else 5930 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5931 ? diag::err_typecheck_call_too_few_args 5932 : diag::err_typecheck_call_too_few_args_at_least) 5933 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5934 << Fn->getSourceRange(); 5935 5936 // Emit the location of the prototype. 5937 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5938 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5939 5940 return true; 5941 } 5942 // We reserve space for the default arguments when we create 5943 // the call expression, before calling ConvertArgumentsForCall. 5944 assert((Call->getNumArgs() == NumParams) && 5945 "We should have reserved space for the default arguments before!"); 5946 } 5947 5948 // If too many are passed and not variadic, error on the extras and drop 5949 // them. 5950 if (Args.size() > NumParams) { 5951 if (!Proto->isVariadic()) { 5952 TypoCorrection TC; 5953 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5954 unsigned diag_id = 5955 MinArgs == NumParams && !Proto->isVariadic() 5956 ? diag::err_typecheck_call_too_many_args_suggest 5957 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5958 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5959 << static_cast<unsigned>(Args.size()) 5960 << TC.getCorrectionRange()); 5961 } else if (NumParams == 1 && FDecl && 5962 FDecl->getParamDecl(0)->getDeclName()) 5963 Diag(Args[NumParams]->getBeginLoc(), 5964 MinArgs == NumParams 5965 ? diag::err_typecheck_call_too_many_args_one 5966 : diag::err_typecheck_call_too_many_args_at_most_one) 5967 << FnKind << FDecl->getParamDecl(0) 5968 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5969 << SourceRange(Args[NumParams]->getBeginLoc(), 5970 Args.back()->getEndLoc()); 5971 else 5972 Diag(Args[NumParams]->getBeginLoc(), 5973 MinArgs == NumParams 5974 ? diag::err_typecheck_call_too_many_args 5975 : diag::err_typecheck_call_too_many_args_at_most) 5976 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5977 << Fn->getSourceRange() 5978 << SourceRange(Args[NumParams]->getBeginLoc(), 5979 Args.back()->getEndLoc()); 5980 5981 // Emit the location of the prototype. 5982 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5983 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5984 5985 // This deletes the extra arguments. 5986 Call->shrinkNumArgs(NumParams); 5987 return true; 5988 } 5989 } 5990 SmallVector<Expr *, 8> AllArgs; 5991 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5992 5993 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5994 AllArgs, CallType); 5995 if (Invalid) 5996 return true; 5997 unsigned TotalNumArgs = AllArgs.size(); 5998 for (unsigned i = 0; i < TotalNumArgs; ++i) 5999 Call->setArg(i, AllArgs[i]); 6000 6001 Call->computeDependence(); 6002 return false; 6003 } 6004 6005 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 6006 const FunctionProtoType *Proto, 6007 unsigned FirstParam, ArrayRef<Expr *> Args, 6008 SmallVectorImpl<Expr *> &AllArgs, 6009 VariadicCallType CallType, bool AllowExplicit, 6010 bool IsListInitialization) { 6011 unsigned NumParams = Proto->getNumParams(); 6012 bool Invalid = false; 6013 size_t ArgIx = 0; 6014 // Continue to check argument types (even if we have too few/many args). 6015 for (unsigned i = FirstParam; i < NumParams; i++) { 6016 QualType ProtoArgType = Proto->getParamType(i); 6017 6018 Expr *Arg; 6019 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 6020 if (ArgIx < Args.size()) { 6021 Arg = Args[ArgIx++]; 6022 6023 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 6024 diag::err_call_incomplete_argument, Arg)) 6025 return true; 6026 6027 // Strip the unbridged-cast placeholder expression off, if applicable. 6028 bool CFAudited = false; 6029 if (Arg->getType() == Context.ARCUnbridgedCastTy && 6030 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6031 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6032 Arg = stripARCUnbridgedCast(Arg); 6033 else if (getLangOpts().ObjCAutoRefCount && 6034 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6035 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6036 CFAudited = true; 6037 6038 if (Proto->getExtParameterInfo(i).isNoEscape() && 6039 ProtoArgType->isBlockPointerType()) 6040 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 6041 BE->getBlockDecl()->setDoesNotEscape(); 6042 6043 InitializedEntity Entity = 6044 Param ? InitializedEntity::InitializeParameter(Context, Param, 6045 ProtoArgType) 6046 : InitializedEntity::InitializeParameter( 6047 Context, ProtoArgType, Proto->isParamConsumed(i)); 6048 6049 // Remember that parameter belongs to a CF audited API. 6050 if (CFAudited) 6051 Entity.setParameterCFAudited(); 6052 6053 ExprResult ArgE = PerformCopyInitialization( 6054 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 6055 if (ArgE.isInvalid()) 6056 return true; 6057 6058 Arg = ArgE.getAs<Expr>(); 6059 } else { 6060 assert(Param && "can't use default arguments without a known callee"); 6061 6062 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 6063 if (ArgExpr.isInvalid()) 6064 return true; 6065 6066 Arg = ArgExpr.getAs<Expr>(); 6067 } 6068 6069 // Check for array bounds violations for each argument to the call. This 6070 // check only triggers warnings when the argument isn't a more complex Expr 6071 // with its own checking, such as a BinaryOperator. 6072 CheckArrayAccess(Arg); 6073 6074 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6075 CheckStaticArrayArgument(CallLoc, Param, Arg); 6076 6077 AllArgs.push_back(Arg); 6078 } 6079 6080 // If this is a variadic call, handle args passed through "...". 6081 if (CallType != VariadicDoesNotApply) { 6082 // Assume that extern "C" functions with variadic arguments that 6083 // return __unknown_anytype aren't *really* variadic. 6084 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6085 FDecl->isExternC()) { 6086 for (Expr *A : Args.slice(ArgIx)) { 6087 QualType paramType; // ignored 6088 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6089 Invalid |= arg.isInvalid(); 6090 AllArgs.push_back(arg.get()); 6091 } 6092 6093 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6094 } else { 6095 for (Expr *A : Args.slice(ArgIx)) { 6096 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6097 Invalid |= Arg.isInvalid(); 6098 AllArgs.push_back(Arg.get()); 6099 } 6100 } 6101 6102 // Check for array bounds violations. 6103 for (Expr *A : Args.slice(ArgIx)) 6104 CheckArrayAccess(A); 6105 } 6106 return Invalid; 6107 } 6108 6109 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6110 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6111 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6112 TL = DTL.getOriginalLoc(); 6113 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6114 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6115 << ATL.getLocalSourceRange(); 6116 } 6117 6118 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6119 /// array parameter, check that it is non-null, and that if it is formed by 6120 /// array-to-pointer decay, the underlying array is sufficiently large. 6121 /// 6122 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6123 /// array type derivation, then for each call to the function, the value of the 6124 /// corresponding actual argument shall provide access to the first element of 6125 /// an array with at least as many elements as specified by the size expression. 6126 void 6127 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6128 ParmVarDecl *Param, 6129 const Expr *ArgExpr) { 6130 // Static array parameters are not supported in C++. 6131 if (!Param || getLangOpts().CPlusPlus) 6132 return; 6133 6134 QualType OrigTy = Param->getOriginalType(); 6135 6136 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6137 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6138 return; 6139 6140 if (ArgExpr->isNullPointerConstant(Context, 6141 Expr::NPC_NeverValueDependent)) { 6142 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6143 DiagnoseCalleeStaticArrayParam(*this, Param); 6144 return; 6145 } 6146 6147 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6148 if (!CAT) 6149 return; 6150 6151 const ConstantArrayType *ArgCAT = 6152 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6153 if (!ArgCAT) 6154 return; 6155 6156 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6157 ArgCAT->getElementType())) { 6158 if (ArgCAT->getSize().ult(CAT->getSize())) { 6159 Diag(CallLoc, diag::warn_static_array_too_small) 6160 << ArgExpr->getSourceRange() 6161 << (unsigned)ArgCAT->getSize().getZExtValue() 6162 << (unsigned)CAT->getSize().getZExtValue() << 0; 6163 DiagnoseCalleeStaticArrayParam(*this, Param); 6164 } 6165 return; 6166 } 6167 6168 Optional<CharUnits> ArgSize = 6169 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6170 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6171 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6172 Diag(CallLoc, diag::warn_static_array_too_small) 6173 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6174 << (unsigned)ParmSize->getQuantity() << 1; 6175 DiagnoseCalleeStaticArrayParam(*this, Param); 6176 } 6177 } 6178 6179 /// Given a function expression of unknown-any type, try to rebuild it 6180 /// to have a function type. 6181 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6182 6183 /// Is the given type a placeholder that we need to lower out 6184 /// immediately during argument processing? 6185 static bool isPlaceholderToRemoveAsArg(QualType type) { 6186 // Placeholders are never sugared. 6187 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6188 if (!placeholder) return false; 6189 6190 switch (placeholder->getKind()) { 6191 // Ignore all the non-placeholder types. 6192 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6193 case BuiltinType::Id: 6194 #include "clang/Basic/OpenCLImageTypes.def" 6195 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6196 case BuiltinType::Id: 6197 #include "clang/Basic/OpenCLExtensionTypes.def" 6198 // In practice we'll never use this, since all SVE types are sugared 6199 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6200 #define SVE_TYPE(Name, Id, SingletonId) \ 6201 case BuiltinType::Id: 6202 #include "clang/Basic/AArch64SVEACLETypes.def" 6203 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6204 case BuiltinType::Id: 6205 #include "clang/Basic/PPCTypes.def" 6206 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6207 #include "clang/Basic/RISCVVTypes.def" 6208 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6209 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6210 #include "clang/AST/BuiltinTypes.def" 6211 return false; 6212 6213 // We cannot lower out overload sets; they might validly be resolved 6214 // by the call machinery. 6215 case BuiltinType::Overload: 6216 return false; 6217 6218 // Unbridged casts in ARC can be handled in some call positions and 6219 // should be left in place. 6220 case BuiltinType::ARCUnbridgedCast: 6221 return false; 6222 6223 // Pseudo-objects should be converted as soon as possible. 6224 case BuiltinType::PseudoObject: 6225 return true; 6226 6227 // The debugger mode could theoretically but currently does not try 6228 // to resolve unknown-typed arguments based on known parameter types. 6229 case BuiltinType::UnknownAny: 6230 return true; 6231 6232 // These are always invalid as call arguments and should be reported. 6233 case BuiltinType::BoundMember: 6234 case BuiltinType::BuiltinFn: 6235 case BuiltinType::IncompleteMatrixIdx: 6236 case BuiltinType::OMPArraySection: 6237 case BuiltinType::OMPArrayShaping: 6238 case BuiltinType::OMPIterator: 6239 return true; 6240 6241 } 6242 llvm_unreachable("bad builtin type kind"); 6243 } 6244 6245 /// Check an argument list for placeholders that we won't try to 6246 /// handle later. 6247 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6248 // Apply this processing to all the arguments at once instead of 6249 // dying at the first failure. 6250 bool hasInvalid = false; 6251 for (size_t i = 0, e = args.size(); i != e; i++) { 6252 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6253 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6254 if (result.isInvalid()) hasInvalid = true; 6255 else args[i] = result.get(); 6256 } 6257 } 6258 return hasInvalid; 6259 } 6260 6261 /// If a builtin function has a pointer argument with no explicit address 6262 /// space, then it should be able to accept a pointer to any address 6263 /// space as input. In order to do this, we need to replace the 6264 /// standard builtin declaration with one that uses the same address space 6265 /// as the call. 6266 /// 6267 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6268 /// it does not contain any pointer arguments without 6269 /// an address space qualifer. Otherwise the rewritten 6270 /// FunctionDecl is returned. 6271 /// TODO: Handle pointer return types. 6272 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6273 FunctionDecl *FDecl, 6274 MultiExprArg ArgExprs) { 6275 6276 QualType DeclType = FDecl->getType(); 6277 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6278 6279 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6280 ArgExprs.size() < FT->getNumParams()) 6281 return nullptr; 6282 6283 bool NeedsNewDecl = false; 6284 unsigned i = 0; 6285 SmallVector<QualType, 8> OverloadParams; 6286 6287 for (QualType ParamType : FT->param_types()) { 6288 6289 // Convert array arguments to pointer to simplify type lookup. 6290 ExprResult ArgRes = 6291 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6292 if (ArgRes.isInvalid()) 6293 return nullptr; 6294 Expr *Arg = ArgRes.get(); 6295 QualType ArgType = Arg->getType(); 6296 if (!ParamType->isPointerType() || 6297 ParamType.hasAddressSpace() || 6298 !ArgType->isPointerType() || 6299 !ArgType->getPointeeType().hasAddressSpace()) { 6300 OverloadParams.push_back(ParamType); 6301 continue; 6302 } 6303 6304 QualType PointeeType = ParamType->getPointeeType(); 6305 if (PointeeType.hasAddressSpace()) 6306 continue; 6307 6308 NeedsNewDecl = true; 6309 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6310 6311 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6312 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6313 } 6314 6315 if (!NeedsNewDecl) 6316 return nullptr; 6317 6318 FunctionProtoType::ExtProtoInfo EPI; 6319 EPI.Variadic = FT->isVariadic(); 6320 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6321 OverloadParams, EPI); 6322 DeclContext *Parent = FDecl->getParent(); 6323 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6324 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6325 FDecl->getIdentifier(), OverloadTy, 6326 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6327 false, 6328 /*hasPrototype=*/true); 6329 SmallVector<ParmVarDecl*, 16> Params; 6330 FT = cast<FunctionProtoType>(OverloadTy); 6331 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6332 QualType ParamType = FT->getParamType(i); 6333 ParmVarDecl *Parm = 6334 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6335 SourceLocation(), nullptr, ParamType, 6336 /*TInfo=*/nullptr, SC_None, nullptr); 6337 Parm->setScopeInfo(0, i); 6338 Params.push_back(Parm); 6339 } 6340 OverloadDecl->setParams(Params); 6341 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6342 return OverloadDecl; 6343 } 6344 6345 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6346 FunctionDecl *Callee, 6347 MultiExprArg ArgExprs) { 6348 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6349 // similar attributes) really don't like it when functions are called with an 6350 // invalid number of args. 6351 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6352 /*PartialOverloading=*/false) && 6353 !Callee->isVariadic()) 6354 return; 6355 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6356 return; 6357 6358 if (const EnableIfAttr *Attr = 6359 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6360 S.Diag(Fn->getBeginLoc(), 6361 isa<CXXMethodDecl>(Callee) 6362 ? diag::err_ovl_no_viable_member_function_in_call 6363 : diag::err_ovl_no_viable_function_in_call) 6364 << Callee << Callee->getSourceRange(); 6365 S.Diag(Callee->getLocation(), 6366 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6367 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6368 return; 6369 } 6370 } 6371 6372 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6373 const UnresolvedMemberExpr *const UME, Sema &S) { 6374 6375 const auto GetFunctionLevelDCIfCXXClass = 6376 [](Sema &S) -> const CXXRecordDecl * { 6377 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6378 if (!DC || !DC->getParent()) 6379 return nullptr; 6380 6381 // If the call to some member function was made from within a member 6382 // function body 'M' return return 'M's parent. 6383 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6384 return MD->getParent()->getCanonicalDecl(); 6385 // else the call was made from within a default member initializer of a 6386 // class, so return the class. 6387 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6388 return RD->getCanonicalDecl(); 6389 return nullptr; 6390 }; 6391 // If our DeclContext is neither a member function nor a class (in the 6392 // case of a lambda in a default member initializer), we can't have an 6393 // enclosing 'this'. 6394 6395 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6396 if (!CurParentClass) 6397 return false; 6398 6399 // The naming class for implicit member functions call is the class in which 6400 // name lookup starts. 6401 const CXXRecordDecl *const NamingClass = 6402 UME->getNamingClass()->getCanonicalDecl(); 6403 assert(NamingClass && "Must have naming class even for implicit access"); 6404 6405 // If the unresolved member functions were found in a 'naming class' that is 6406 // related (either the same or derived from) to the class that contains the 6407 // member function that itself contained the implicit member access. 6408 6409 return CurParentClass == NamingClass || 6410 CurParentClass->isDerivedFrom(NamingClass); 6411 } 6412 6413 static void 6414 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6415 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6416 6417 if (!UME) 6418 return; 6419 6420 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6421 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6422 // already been captured, or if this is an implicit member function call (if 6423 // it isn't, an attempt to capture 'this' should already have been made). 6424 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6425 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6426 return; 6427 6428 // Check if the naming class in which the unresolved members were found is 6429 // related (same as or is a base of) to the enclosing class. 6430 6431 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6432 return; 6433 6434 6435 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6436 // If the enclosing function is not dependent, then this lambda is 6437 // capture ready, so if we can capture this, do so. 6438 if (!EnclosingFunctionCtx->isDependentContext()) { 6439 // If the current lambda and all enclosing lambdas can capture 'this' - 6440 // then go ahead and capture 'this' (since our unresolved overload set 6441 // contains at least one non-static member function). 6442 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6443 S.CheckCXXThisCapture(CallLoc); 6444 } else if (S.CurContext->isDependentContext()) { 6445 // ... since this is an implicit member reference, that might potentially 6446 // involve a 'this' capture, mark 'this' for potential capture in 6447 // enclosing lambdas. 6448 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6449 CurLSI->addPotentialThisCapture(CallLoc); 6450 } 6451 } 6452 6453 // Once a call is fully resolved, warn for unqualified calls to specific 6454 // C++ standard functions, like move and forward. 6455 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) { 6456 // We are only checking unary move and forward so exit early here. 6457 if (Call->getNumArgs() != 1) 6458 return; 6459 6460 Expr *E = Call->getCallee()->IgnoreParenImpCasts(); 6461 if (!E || isa<UnresolvedLookupExpr>(E)) 6462 return; 6463 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E); 6464 if (!DRE || !DRE->getLocation().isValid()) 6465 return; 6466 6467 if (DRE->getQualifier()) 6468 return; 6469 6470 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl()); 6471 if (!D || !D->isInStdNamespace()) 6472 return; 6473 6474 // Only warn for some functions deemed more frequent or problematic. 6475 static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"}; 6476 auto it = llvm::find(SpecialFunctions, D->getName()); 6477 if (it == std::end(SpecialFunctions)) 6478 return; 6479 6480 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function) 6481 << D->getQualifiedNameAsString() 6482 << FixItHint::CreateInsertion(DRE->getLocation(), "std::"); 6483 } 6484 6485 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6486 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6487 Expr *ExecConfig) { 6488 ExprResult Call = 6489 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6490 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6491 if (Call.isInvalid()) 6492 return Call; 6493 6494 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6495 // language modes. 6496 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6497 if (ULE->hasExplicitTemplateArgs() && 6498 ULE->decls_begin() == ULE->decls_end()) { 6499 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6500 ? diag::warn_cxx17_compat_adl_only_template_id 6501 : diag::ext_adl_only_template_id) 6502 << ULE->getName(); 6503 } 6504 } 6505 6506 if (LangOpts.OpenMP) 6507 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6508 ExecConfig); 6509 if (LangOpts.CPlusPlus) { 6510 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6511 if (CE) 6512 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE); 6513 } 6514 return Call; 6515 } 6516 6517 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6518 /// This provides the location of the left/right parens and a list of comma 6519 /// locations. 6520 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6521 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6522 Expr *ExecConfig, bool IsExecConfig, 6523 bool AllowRecovery) { 6524 // Since this might be a postfix expression, get rid of ParenListExprs. 6525 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6526 if (Result.isInvalid()) return ExprError(); 6527 Fn = Result.get(); 6528 6529 if (checkArgsForPlaceholders(*this, ArgExprs)) 6530 return ExprError(); 6531 6532 if (getLangOpts().CPlusPlus) { 6533 // If this is a pseudo-destructor expression, build the call immediately. 6534 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6535 if (!ArgExprs.empty()) { 6536 // Pseudo-destructor calls should not have any arguments. 6537 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6538 << FixItHint::CreateRemoval( 6539 SourceRange(ArgExprs.front()->getBeginLoc(), 6540 ArgExprs.back()->getEndLoc())); 6541 } 6542 6543 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6544 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6545 } 6546 if (Fn->getType() == Context.PseudoObjectTy) { 6547 ExprResult result = CheckPlaceholderExpr(Fn); 6548 if (result.isInvalid()) return ExprError(); 6549 Fn = result.get(); 6550 } 6551 6552 // Determine whether this is a dependent call inside a C++ template, 6553 // in which case we won't do any semantic analysis now. 6554 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6555 if (ExecConfig) { 6556 return CUDAKernelCallExpr::Create(Context, Fn, 6557 cast<CallExpr>(ExecConfig), ArgExprs, 6558 Context.DependentTy, VK_PRValue, 6559 RParenLoc, CurFPFeatureOverrides()); 6560 } else { 6561 6562 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6563 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6564 Fn->getBeginLoc()); 6565 6566 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6567 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6568 } 6569 } 6570 6571 // Determine whether this is a call to an object (C++ [over.call.object]). 6572 if (Fn->getType()->isRecordType()) 6573 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6574 RParenLoc); 6575 6576 if (Fn->getType() == Context.UnknownAnyTy) { 6577 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6578 if (result.isInvalid()) return ExprError(); 6579 Fn = result.get(); 6580 } 6581 6582 if (Fn->getType() == Context.BoundMemberTy) { 6583 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6584 RParenLoc, ExecConfig, IsExecConfig, 6585 AllowRecovery); 6586 } 6587 } 6588 6589 // Check for overloaded calls. This can happen even in C due to extensions. 6590 if (Fn->getType() == Context.OverloadTy) { 6591 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6592 6593 // We aren't supposed to apply this logic if there's an '&' involved. 6594 if (!find.HasFormOfMemberPointer) { 6595 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6596 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6597 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6598 OverloadExpr *ovl = find.Expression; 6599 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6600 return BuildOverloadedCallExpr( 6601 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6602 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6603 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6604 RParenLoc, ExecConfig, IsExecConfig, 6605 AllowRecovery); 6606 } 6607 } 6608 6609 // If we're directly calling a function, get the appropriate declaration. 6610 if (Fn->getType() == Context.UnknownAnyTy) { 6611 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6612 if (result.isInvalid()) return ExprError(); 6613 Fn = result.get(); 6614 } 6615 6616 Expr *NakedFn = Fn->IgnoreParens(); 6617 6618 bool CallingNDeclIndirectly = false; 6619 NamedDecl *NDecl = nullptr; 6620 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6621 if (UnOp->getOpcode() == UO_AddrOf) { 6622 CallingNDeclIndirectly = true; 6623 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6624 } 6625 } 6626 6627 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6628 NDecl = DRE->getDecl(); 6629 6630 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6631 if (FDecl && FDecl->getBuiltinID()) { 6632 // Rewrite the function decl for this builtin by replacing parameters 6633 // with no explicit address space with the address space of the arguments 6634 // in ArgExprs. 6635 if ((FDecl = 6636 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6637 NDecl = FDecl; 6638 Fn = DeclRefExpr::Create( 6639 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6640 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6641 nullptr, DRE->isNonOdrUse()); 6642 } 6643 } 6644 } else if (isa<MemberExpr>(NakedFn)) 6645 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6646 6647 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6648 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6649 FD, /*Complain=*/true, Fn->getBeginLoc())) 6650 return ExprError(); 6651 6652 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6653 6654 // If this expression is a call to a builtin function in HIP device 6655 // compilation, allow a pointer-type argument to default address space to be 6656 // passed as a pointer-type parameter to a non-default address space. 6657 // If Arg is declared in the default address space and Param is declared 6658 // in a non-default address space, perform an implicit address space cast to 6659 // the parameter type. 6660 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6661 FD->getBuiltinID()) { 6662 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6663 ParmVarDecl *Param = FD->getParamDecl(Idx); 6664 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6665 !ArgExprs[Idx]->getType()->isPointerType()) 6666 continue; 6667 6668 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6669 auto ArgTy = ArgExprs[Idx]->getType(); 6670 auto ArgPtTy = ArgTy->getPointeeType(); 6671 auto ArgAS = ArgPtTy.getAddressSpace(); 6672 6673 // Add address space cast if target address spaces are different 6674 bool NeedImplicitASC = 6675 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6676 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6677 // or from specific AS which has target AS matching that of Param. 6678 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6679 if (!NeedImplicitASC) 6680 continue; 6681 6682 // First, ensure that the Arg is an RValue. 6683 if (ArgExprs[Idx]->isGLValue()) { 6684 ArgExprs[Idx] = ImplicitCastExpr::Create( 6685 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6686 nullptr, VK_PRValue, FPOptionsOverride()); 6687 } 6688 6689 // Construct a new arg type with address space of Param 6690 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6691 ArgPtQuals.setAddressSpace(ParamAS); 6692 auto NewArgPtTy = 6693 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6694 auto NewArgTy = 6695 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6696 ArgTy.getQualifiers()); 6697 6698 // Finally perform an implicit address space cast 6699 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6700 CK_AddressSpaceConversion) 6701 .get(); 6702 } 6703 } 6704 } 6705 6706 if (Context.isDependenceAllowed() && 6707 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6708 assert(!getLangOpts().CPlusPlus); 6709 assert((Fn->containsErrors() || 6710 llvm::any_of(ArgExprs, 6711 [](clang::Expr *E) { return E->containsErrors(); })) && 6712 "should only occur in error-recovery path."); 6713 QualType ReturnType = 6714 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6715 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6716 : Context.DependentTy; 6717 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6718 Expr::getValueKindForType(ReturnType), RParenLoc, 6719 CurFPFeatureOverrides()); 6720 } 6721 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6722 ExecConfig, IsExecConfig); 6723 } 6724 6725 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6726 // with the specified CallArgs 6727 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6728 MultiExprArg CallArgs) { 6729 StringRef Name = Context.BuiltinInfo.getName(Id); 6730 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6731 Sema::LookupOrdinaryName); 6732 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6733 6734 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6735 assert(BuiltInDecl && "failed to find builtin declaration"); 6736 6737 ExprResult DeclRef = 6738 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6739 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6740 6741 ExprResult Call = 6742 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6743 6744 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6745 return Call.get(); 6746 } 6747 6748 /// Parse a __builtin_astype expression. 6749 /// 6750 /// __builtin_astype( value, dst type ) 6751 /// 6752 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6753 SourceLocation BuiltinLoc, 6754 SourceLocation RParenLoc) { 6755 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6756 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6757 } 6758 6759 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6760 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6761 SourceLocation BuiltinLoc, 6762 SourceLocation RParenLoc) { 6763 ExprValueKind VK = VK_PRValue; 6764 ExprObjectKind OK = OK_Ordinary; 6765 QualType SrcTy = E->getType(); 6766 if (!SrcTy->isDependentType() && 6767 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6768 return ExprError( 6769 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6770 << DestTy << SrcTy << E->getSourceRange()); 6771 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6772 } 6773 6774 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6775 /// provided arguments. 6776 /// 6777 /// __builtin_convertvector( value, dst type ) 6778 /// 6779 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6780 SourceLocation BuiltinLoc, 6781 SourceLocation RParenLoc) { 6782 TypeSourceInfo *TInfo; 6783 GetTypeFromParser(ParsedDestTy, &TInfo); 6784 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6785 } 6786 6787 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6788 /// i.e. an expression not of \p OverloadTy. The expression should 6789 /// unary-convert to an expression of function-pointer or 6790 /// block-pointer type. 6791 /// 6792 /// \param NDecl the declaration being called, if available 6793 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6794 SourceLocation LParenLoc, 6795 ArrayRef<Expr *> Args, 6796 SourceLocation RParenLoc, Expr *Config, 6797 bool IsExecConfig, ADLCallKind UsesADL) { 6798 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6799 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6800 6801 // Functions with 'interrupt' attribute cannot be called directly. 6802 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6803 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6804 return ExprError(); 6805 } 6806 6807 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6808 // so there's some risk when calling out to non-interrupt handler functions 6809 // that the callee might not preserve them. This is easy to diagnose here, 6810 // but can be very challenging to debug. 6811 // Likewise, X86 interrupt handlers may only call routines with attribute 6812 // no_caller_saved_registers since there is no efficient way to 6813 // save and restore the non-GPR state. 6814 if (auto *Caller = getCurFunctionDecl()) { 6815 if (Caller->hasAttr<ARMInterruptAttr>()) { 6816 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6817 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6818 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6819 if (FDecl) 6820 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6821 } 6822 } 6823 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6824 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6825 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6826 if (FDecl) 6827 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6828 } 6829 } 6830 6831 // Promote the function operand. 6832 // We special-case function promotion here because we only allow promoting 6833 // builtin functions to function pointers in the callee of a call. 6834 ExprResult Result; 6835 QualType ResultTy; 6836 if (BuiltinID && 6837 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6838 // Extract the return type from the (builtin) function pointer type. 6839 // FIXME Several builtins still have setType in 6840 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6841 // Builtins.def to ensure they are correct before removing setType calls. 6842 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6843 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6844 ResultTy = FDecl->getCallResultType(); 6845 } else { 6846 Result = CallExprUnaryConversions(Fn); 6847 ResultTy = Context.BoolTy; 6848 } 6849 if (Result.isInvalid()) 6850 return ExprError(); 6851 Fn = Result.get(); 6852 6853 // Check for a valid function type, but only if it is not a builtin which 6854 // requires custom type checking. These will be handled by 6855 // CheckBuiltinFunctionCall below just after creation of the call expression. 6856 const FunctionType *FuncT = nullptr; 6857 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6858 retry: 6859 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6860 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6861 // have type pointer to function". 6862 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6863 if (!FuncT) 6864 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6865 << Fn->getType() << Fn->getSourceRange()); 6866 } else if (const BlockPointerType *BPT = 6867 Fn->getType()->getAs<BlockPointerType>()) { 6868 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6869 } else { 6870 // Handle calls to expressions of unknown-any type. 6871 if (Fn->getType() == Context.UnknownAnyTy) { 6872 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6873 if (rewrite.isInvalid()) 6874 return ExprError(); 6875 Fn = rewrite.get(); 6876 goto retry; 6877 } 6878 6879 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6880 << Fn->getType() << Fn->getSourceRange()); 6881 } 6882 } 6883 6884 // Get the number of parameters in the function prototype, if any. 6885 // We will allocate space for max(Args.size(), NumParams) arguments 6886 // in the call expression. 6887 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6888 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6889 6890 CallExpr *TheCall; 6891 if (Config) { 6892 assert(UsesADL == ADLCallKind::NotADL && 6893 "CUDAKernelCallExpr should not use ADL"); 6894 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6895 Args, ResultTy, VK_PRValue, RParenLoc, 6896 CurFPFeatureOverrides(), NumParams); 6897 } else { 6898 TheCall = 6899 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6900 CurFPFeatureOverrides(), NumParams, UsesADL); 6901 } 6902 6903 if (!Context.isDependenceAllowed()) { 6904 // Forget about the nulled arguments since typo correction 6905 // do not handle them well. 6906 TheCall->shrinkNumArgs(Args.size()); 6907 // C cannot always handle TypoExpr nodes in builtin calls and direct 6908 // function calls as their argument checking don't necessarily handle 6909 // dependent types properly, so make sure any TypoExprs have been 6910 // dealt with. 6911 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6912 if (!Result.isUsable()) return ExprError(); 6913 CallExpr *TheOldCall = TheCall; 6914 TheCall = dyn_cast<CallExpr>(Result.get()); 6915 bool CorrectedTypos = TheCall != TheOldCall; 6916 if (!TheCall) return Result; 6917 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6918 6919 // A new call expression node was created if some typos were corrected. 6920 // However it may not have been constructed with enough storage. In this 6921 // case, rebuild the node with enough storage. The waste of space is 6922 // immaterial since this only happens when some typos were corrected. 6923 if (CorrectedTypos && Args.size() < NumParams) { 6924 if (Config) 6925 TheCall = CUDAKernelCallExpr::Create( 6926 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6927 RParenLoc, CurFPFeatureOverrides(), NumParams); 6928 else 6929 TheCall = 6930 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6931 CurFPFeatureOverrides(), NumParams, UsesADL); 6932 } 6933 // We can now handle the nulled arguments for the default arguments. 6934 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6935 } 6936 6937 // Bail out early if calling a builtin with custom type checking. 6938 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6939 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6940 6941 if (getLangOpts().CUDA) { 6942 if (Config) { 6943 // CUDA: Kernel calls must be to global functions 6944 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6945 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6946 << FDecl << Fn->getSourceRange()); 6947 6948 // CUDA: Kernel function must have 'void' return type 6949 if (!FuncT->getReturnType()->isVoidType() && 6950 !FuncT->getReturnType()->getAs<AutoType>() && 6951 !FuncT->getReturnType()->isInstantiationDependentType()) 6952 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6953 << Fn->getType() << Fn->getSourceRange()); 6954 } else { 6955 // CUDA: Calls to global functions must be configured 6956 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6957 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6958 << FDecl << Fn->getSourceRange()); 6959 } 6960 } 6961 6962 // Check for a valid return type 6963 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6964 FDecl)) 6965 return ExprError(); 6966 6967 // We know the result type of the call, set it. 6968 TheCall->setType(FuncT->getCallResultType(Context)); 6969 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6970 6971 if (Proto) { 6972 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6973 IsExecConfig)) 6974 return ExprError(); 6975 } else { 6976 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6977 6978 if (FDecl) { 6979 // Check if we have too few/too many template arguments, based 6980 // on our knowledge of the function definition. 6981 const FunctionDecl *Def = nullptr; 6982 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6983 Proto = Def->getType()->getAs<FunctionProtoType>(); 6984 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6985 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6986 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6987 } 6988 6989 // If the function we're calling isn't a function prototype, but we have 6990 // a function prototype from a prior declaratiom, use that prototype. 6991 if (!FDecl->hasPrototype()) 6992 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6993 } 6994 6995 // Promote the arguments (C99 6.5.2.2p6). 6996 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6997 Expr *Arg = Args[i]; 6998 6999 if (Proto && i < Proto->getNumParams()) { 7000 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7001 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 7002 ExprResult ArgE = 7003 PerformCopyInitialization(Entity, SourceLocation(), Arg); 7004 if (ArgE.isInvalid()) 7005 return true; 7006 7007 Arg = ArgE.getAs<Expr>(); 7008 7009 } else { 7010 ExprResult ArgE = DefaultArgumentPromotion(Arg); 7011 7012 if (ArgE.isInvalid()) 7013 return true; 7014 7015 Arg = ArgE.getAs<Expr>(); 7016 } 7017 7018 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 7019 diag::err_call_incomplete_argument, Arg)) 7020 return ExprError(); 7021 7022 TheCall->setArg(i, Arg); 7023 } 7024 TheCall->computeDependence(); 7025 } 7026 7027 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 7028 if (!Method->isStatic()) 7029 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 7030 << Fn->getSourceRange()); 7031 7032 // Check for sentinels 7033 if (NDecl) 7034 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 7035 7036 // Warn for unions passing across security boundary (CMSE). 7037 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 7038 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7039 if (const auto *RT = 7040 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 7041 if (RT->getDecl()->isOrContainsUnion()) 7042 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 7043 << 0 << i; 7044 } 7045 } 7046 } 7047 7048 // Do special checking on direct calls to functions. 7049 if (FDecl) { 7050 if (CheckFunctionCall(FDecl, TheCall, Proto)) 7051 return ExprError(); 7052 7053 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 7054 7055 if (BuiltinID) 7056 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7057 } else if (NDecl) { 7058 if (CheckPointerCall(NDecl, TheCall, Proto)) 7059 return ExprError(); 7060 } else { 7061 if (CheckOtherCall(TheCall, Proto)) 7062 return ExprError(); 7063 } 7064 7065 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 7066 } 7067 7068 ExprResult 7069 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 7070 SourceLocation RParenLoc, Expr *InitExpr) { 7071 assert(Ty && "ActOnCompoundLiteral(): missing type"); 7072 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 7073 7074 TypeSourceInfo *TInfo; 7075 QualType literalType = GetTypeFromParser(Ty, &TInfo); 7076 if (!TInfo) 7077 TInfo = Context.getTrivialTypeSourceInfo(literalType); 7078 7079 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 7080 } 7081 7082 ExprResult 7083 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 7084 SourceLocation RParenLoc, Expr *LiteralExpr) { 7085 QualType literalType = TInfo->getType(); 7086 7087 if (literalType->isArrayType()) { 7088 if (RequireCompleteSizedType( 7089 LParenLoc, Context.getBaseElementType(literalType), 7090 diag::err_array_incomplete_or_sizeless_type, 7091 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7092 return ExprError(); 7093 if (literalType->isVariableArrayType()) { 7094 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 7095 diag::err_variable_object_no_init)) { 7096 return ExprError(); 7097 } 7098 } 7099 } else if (!literalType->isDependentType() && 7100 RequireCompleteType(LParenLoc, literalType, 7101 diag::err_typecheck_decl_incomplete_type, 7102 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7103 return ExprError(); 7104 7105 InitializedEntity Entity 7106 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 7107 InitializationKind Kind 7108 = InitializationKind::CreateCStyleCast(LParenLoc, 7109 SourceRange(LParenLoc, RParenLoc), 7110 /*InitList=*/true); 7111 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 7112 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 7113 &literalType); 7114 if (Result.isInvalid()) 7115 return ExprError(); 7116 LiteralExpr = Result.get(); 7117 7118 bool isFileScope = !CurContext->isFunctionOrMethod(); 7119 7120 // In C, compound literals are l-values for some reason. 7121 // For GCC compatibility, in C++, file-scope array compound literals with 7122 // constant initializers are also l-values, and compound literals are 7123 // otherwise prvalues. 7124 // 7125 // (GCC also treats C++ list-initialized file-scope array prvalues with 7126 // constant initializers as l-values, but that's non-conforming, so we don't 7127 // follow it there.) 7128 // 7129 // FIXME: It would be better to handle the lvalue cases as materializing and 7130 // lifetime-extending a temporary object, but our materialized temporaries 7131 // representation only supports lifetime extension from a variable, not "out 7132 // of thin air". 7133 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7134 // is bound to the result of applying array-to-pointer decay to the compound 7135 // literal. 7136 // FIXME: GCC supports compound literals of reference type, which should 7137 // obviously have a value kind derived from the kind of reference involved. 7138 ExprValueKind VK = 7139 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7140 ? VK_PRValue 7141 : VK_LValue; 7142 7143 if (isFileScope) 7144 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7145 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7146 Expr *Init = ILE->getInit(i); 7147 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7148 } 7149 7150 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7151 VK, LiteralExpr, isFileScope); 7152 if (isFileScope) { 7153 if (!LiteralExpr->isTypeDependent() && 7154 !LiteralExpr->isValueDependent() && 7155 !literalType->isDependentType()) // C99 6.5.2.5p3 7156 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7157 return ExprError(); 7158 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7159 literalType.getAddressSpace() != LangAS::Default) { 7160 // Embedded-C extensions to C99 6.5.2.5: 7161 // "If the compound literal occurs inside the body of a function, the 7162 // type name shall not be qualified by an address-space qualifier." 7163 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7164 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7165 return ExprError(); 7166 } 7167 7168 if (!isFileScope && !getLangOpts().CPlusPlus) { 7169 // Compound literals that have automatic storage duration are destroyed at 7170 // the end of the scope in C; in C++, they're just temporaries. 7171 7172 // Emit diagnostics if it is or contains a C union type that is non-trivial 7173 // to destruct. 7174 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7175 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7176 NTCUC_CompoundLiteral, NTCUK_Destruct); 7177 7178 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7179 if (literalType.isDestructedType()) { 7180 Cleanup.setExprNeedsCleanups(true); 7181 ExprCleanupObjects.push_back(E); 7182 getCurFunction()->setHasBranchProtectedScope(); 7183 } 7184 } 7185 7186 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7187 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7188 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7189 E->getInitializer()->getExprLoc()); 7190 7191 return MaybeBindToTemporary(E); 7192 } 7193 7194 ExprResult 7195 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7196 SourceLocation RBraceLoc) { 7197 // Only produce each kind of designated initialization diagnostic once. 7198 SourceLocation FirstDesignator; 7199 bool DiagnosedArrayDesignator = false; 7200 bool DiagnosedNestedDesignator = false; 7201 bool DiagnosedMixedDesignator = false; 7202 7203 // Check that any designated initializers are syntactically valid in the 7204 // current language mode. 7205 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7206 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7207 if (FirstDesignator.isInvalid()) 7208 FirstDesignator = DIE->getBeginLoc(); 7209 7210 if (!getLangOpts().CPlusPlus) 7211 break; 7212 7213 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7214 DiagnosedNestedDesignator = true; 7215 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7216 << DIE->getDesignatorsSourceRange(); 7217 } 7218 7219 for (auto &Desig : DIE->designators()) { 7220 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7221 DiagnosedArrayDesignator = true; 7222 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7223 << Desig.getSourceRange(); 7224 } 7225 } 7226 7227 if (!DiagnosedMixedDesignator && 7228 !isa<DesignatedInitExpr>(InitArgList[0])) { 7229 DiagnosedMixedDesignator = true; 7230 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7231 << DIE->getSourceRange(); 7232 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7233 << InitArgList[0]->getSourceRange(); 7234 } 7235 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7236 isa<DesignatedInitExpr>(InitArgList[0])) { 7237 DiagnosedMixedDesignator = true; 7238 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7239 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7240 << DIE->getSourceRange(); 7241 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7242 << InitArgList[I]->getSourceRange(); 7243 } 7244 } 7245 7246 if (FirstDesignator.isValid()) { 7247 // Only diagnose designated initiaization as a C++20 extension if we didn't 7248 // already diagnose use of (non-C++20) C99 designator syntax. 7249 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7250 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7251 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7252 ? diag::warn_cxx17_compat_designated_init 7253 : diag::ext_cxx_designated_init); 7254 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7255 Diag(FirstDesignator, diag::ext_designated_init); 7256 } 7257 } 7258 7259 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7260 } 7261 7262 ExprResult 7263 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7264 SourceLocation RBraceLoc) { 7265 // Semantic analysis for initializers is done by ActOnDeclarator() and 7266 // CheckInitializer() - it requires knowledge of the object being initialized. 7267 7268 // Immediately handle non-overload placeholders. Overloads can be 7269 // resolved contextually, but everything else here can't. 7270 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7271 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7272 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7273 7274 // Ignore failures; dropping the entire initializer list because 7275 // of one failure would be terrible for indexing/etc. 7276 if (result.isInvalid()) continue; 7277 7278 InitArgList[I] = result.get(); 7279 } 7280 } 7281 7282 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7283 RBraceLoc); 7284 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7285 return E; 7286 } 7287 7288 /// Do an explicit extend of the given block pointer if we're in ARC. 7289 void Sema::maybeExtendBlockObject(ExprResult &E) { 7290 assert(E.get()->getType()->isBlockPointerType()); 7291 assert(E.get()->isPRValue()); 7292 7293 // Only do this in an r-value context. 7294 if (!getLangOpts().ObjCAutoRefCount) return; 7295 7296 E = ImplicitCastExpr::Create( 7297 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7298 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7299 Cleanup.setExprNeedsCleanups(true); 7300 } 7301 7302 /// Prepare a conversion of the given expression to an ObjC object 7303 /// pointer type. 7304 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7305 QualType type = E.get()->getType(); 7306 if (type->isObjCObjectPointerType()) { 7307 return CK_BitCast; 7308 } else if (type->isBlockPointerType()) { 7309 maybeExtendBlockObject(E); 7310 return CK_BlockPointerToObjCPointerCast; 7311 } else { 7312 assert(type->isPointerType()); 7313 return CK_CPointerToObjCPointerCast; 7314 } 7315 } 7316 7317 /// Prepares for a scalar cast, performing all the necessary stages 7318 /// except the final cast and returning the kind required. 7319 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7320 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7321 // Also, callers should have filtered out the invalid cases with 7322 // pointers. Everything else should be possible. 7323 7324 QualType SrcTy = Src.get()->getType(); 7325 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7326 return CK_NoOp; 7327 7328 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7329 case Type::STK_MemberPointer: 7330 llvm_unreachable("member pointer type in C"); 7331 7332 case Type::STK_CPointer: 7333 case Type::STK_BlockPointer: 7334 case Type::STK_ObjCObjectPointer: 7335 switch (DestTy->getScalarTypeKind()) { 7336 case Type::STK_CPointer: { 7337 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7338 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7339 if (SrcAS != DestAS) 7340 return CK_AddressSpaceConversion; 7341 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7342 return CK_NoOp; 7343 return CK_BitCast; 7344 } 7345 case Type::STK_BlockPointer: 7346 return (SrcKind == Type::STK_BlockPointer 7347 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7348 case Type::STK_ObjCObjectPointer: 7349 if (SrcKind == Type::STK_ObjCObjectPointer) 7350 return CK_BitCast; 7351 if (SrcKind == Type::STK_CPointer) 7352 return CK_CPointerToObjCPointerCast; 7353 maybeExtendBlockObject(Src); 7354 return CK_BlockPointerToObjCPointerCast; 7355 case Type::STK_Bool: 7356 return CK_PointerToBoolean; 7357 case Type::STK_Integral: 7358 return CK_PointerToIntegral; 7359 case Type::STK_Floating: 7360 case Type::STK_FloatingComplex: 7361 case Type::STK_IntegralComplex: 7362 case Type::STK_MemberPointer: 7363 case Type::STK_FixedPoint: 7364 llvm_unreachable("illegal cast from pointer"); 7365 } 7366 llvm_unreachable("Should have returned before this"); 7367 7368 case Type::STK_FixedPoint: 7369 switch (DestTy->getScalarTypeKind()) { 7370 case Type::STK_FixedPoint: 7371 return CK_FixedPointCast; 7372 case Type::STK_Bool: 7373 return CK_FixedPointToBoolean; 7374 case Type::STK_Integral: 7375 return CK_FixedPointToIntegral; 7376 case Type::STK_Floating: 7377 return CK_FixedPointToFloating; 7378 case Type::STK_IntegralComplex: 7379 case Type::STK_FloatingComplex: 7380 Diag(Src.get()->getExprLoc(), 7381 diag::err_unimplemented_conversion_with_fixed_point_type) 7382 << DestTy; 7383 return CK_IntegralCast; 7384 case Type::STK_CPointer: 7385 case Type::STK_ObjCObjectPointer: 7386 case Type::STK_BlockPointer: 7387 case Type::STK_MemberPointer: 7388 llvm_unreachable("illegal cast to pointer type"); 7389 } 7390 llvm_unreachable("Should have returned before this"); 7391 7392 case Type::STK_Bool: // casting from bool is like casting from an integer 7393 case Type::STK_Integral: 7394 switch (DestTy->getScalarTypeKind()) { 7395 case Type::STK_CPointer: 7396 case Type::STK_ObjCObjectPointer: 7397 case Type::STK_BlockPointer: 7398 if (Src.get()->isNullPointerConstant(Context, 7399 Expr::NPC_ValueDependentIsNull)) 7400 return CK_NullToPointer; 7401 return CK_IntegralToPointer; 7402 case Type::STK_Bool: 7403 return CK_IntegralToBoolean; 7404 case Type::STK_Integral: 7405 return CK_IntegralCast; 7406 case Type::STK_Floating: 7407 return CK_IntegralToFloating; 7408 case Type::STK_IntegralComplex: 7409 Src = ImpCastExprToType(Src.get(), 7410 DestTy->castAs<ComplexType>()->getElementType(), 7411 CK_IntegralCast); 7412 return CK_IntegralRealToComplex; 7413 case Type::STK_FloatingComplex: 7414 Src = ImpCastExprToType(Src.get(), 7415 DestTy->castAs<ComplexType>()->getElementType(), 7416 CK_IntegralToFloating); 7417 return CK_FloatingRealToComplex; 7418 case Type::STK_MemberPointer: 7419 llvm_unreachable("member pointer type in C"); 7420 case Type::STK_FixedPoint: 7421 return CK_IntegralToFixedPoint; 7422 } 7423 llvm_unreachable("Should have returned before this"); 7424 7425 case Type::STK_Floating: 7426 switch (DestTy->getScalarTypeKind()) { 7427 case Type::STK_Floating: 7428 return CK_FloatingCast; 7429 case Type::STK_Bool: 7430 return CK_FloatingToBoolean; 7431 case Type::STK_Integral: 7432 return CK_FloatingToIntegral; 7433 case Type::STK_FloatingComplex: 7434 Src = ImpCastExprToType(Src.get(), 7435 DestTy->castAs<ComplexType>()->getElementType(), 7436 CK_FloatingCast); 7437 return CK_FloatingRealToComplex; 7438 case Type::STK_IntegralComplex: 7439 Src = ImpCastExprToType(Src.get(), 7440 DestTy->castAs<ComplexType>()->getElementType(), 7441 CK_FloatingToIntegral); 7442 return CK_IntegralRealToComplex; 7443 case Type::STK_CPointer: 7444 case Type::STK_ObjCObjectPointer: 7445 case Type::STK_BlockPointer: 7446 llvm_unreachable("valid float->pointer cast?"); 7447 case Type::STK_MemberPointer: 7448 llvm_unreachable("member pointer type in C"); 7449 case Type::STK_FixedPoint: 7450 return CK_FloatingToFixedPoint; 7451 } 7452 llvm_unreachable("Should have returned before this"); 7453 7454 case Type::STK_FloatingComplex: 7455 switch (DestTy->getScalarTypeKind()) { 7456 case Type::STK_FloatingComplex: 7457 return CK_FloatingComplexCast; 7458 case Type::STK_IntegralComplex: 7459 return CK_FloatingComplexToIntegralComplex; 7460 case Type::STK_Floating: { 7461 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7462 if (Context.hasSameType(ET, DestTy)) 7463 return CK_FloatingComplexToReal; 7464 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7465 return CK_FloatingCast; 7466 } 7467 case Type::STK_Bool: 7468 return CK_FloatingComplexToBoolean; 7469 case Type::STK_Integral: 7470 Src = ImpCastExprToType(Src.get(), 7471 SrcTy->castAs<ComplexType>()->getElementType(), 7472 CK_FloatingComplexToReal); 7473 return CK_FloatingToIntegral; 7474 case Type::STK_CPointer: 7475 case Type::STK_ObjCObjectPointer: 7476 case Type::STK_BlockPointer: 7477 llvm_unreachable("valid complex float->pointer cast?"); 7478 case Type::STK_MemberPointer: 7479 llvm_unreachable("member pointer type in C"); 7480 case Type::STK_FixedPoint: 7481 Diag(Src.get()->getExprLoc(), 7482 diag::err_unimplemented_conversion_with_fixed_point_type) 7483 << SrcTy; 7484 return CK_IntegralCast; 7485 } 7486 llvm_unreachable("Should have returned before this"); 7487 7488 case Type::STK_IntegralComplex: 7489 switch (DestTy->getScalarTypeKind()) { 7490 case Type::STK_FloatingComplex: 7491 return CK_IntegralComplexToFloatingComplex; 7492 case Type::STK_IntegralComplex: 7493 return CK_IntegralComplexCast; 7494 case Type::STK_Integral: { 7495 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7496 if (Context.hasSameType(ET, DestTy)) 7497 return CK_IntegralComplexToReal; 7498 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7499 return CK_IntegralCast; 7500 } 7501 case Type::STK_Bool: 7502 return CK_IntegralComplexToBoolean; 7503 case Type::STK_Floating: 7504 Src = ImpCastExprToType(Src.get(), 7505 SrcTy->castAs<ComplexType>()->getElementType(), 7506 CK_IntegralComplexToReal); 7507 return CK_IntegralToFloating; 7508 case Type::STK_CPointer: 7509 case Type::STK_ObjCObjectPointer: 7510 case Type::STK_BlockPointer: 7511 llvm_unreachable("valid complex int->pointer cast?"); 7512 case Type::STK_MemberPointer: 7513 llvm_unreachable("member pointer type in C"); 7514 case Type::STK_FixedPoint: 7515 Diag(Src.get()->getExprLoc(), 7516 diag::err_unimplemented_conversion_with_fixed_point_type) 7517 << SrcTy; 7518 return CK_IntegralCast; 7519 } 7520 llvm_unreachable("Should have returned before this"); 7521 } 7522 7523 llvm_unreachable("Unhandled scalar cast"); 7524 } 7525 7526 static bool breakDownVectorType(QualType type, uint64_t &len, 7527 QualType &eltType) { 7528 // Vectors are simple. 7529 if (const VectorType *vecType = type->getAs<VectorType>()) { 7530 len = vecType->getNumElements(); 7531 eltType = vecType->getElementType(); 7532 assert(eltType->isScalarType()); 7533 return true; 7534 } 7535 7536 // We allow lax conversion to and from non-vector types, but only if 7537 // they're real types (i.e. non-complex, non-pointer scalar types). 7538 if (!type->isRealType()) return false; 7539 7540 len = 1; 7541 eltType = type; 7542 return true; 7543 } 7544 7545 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7546 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7547 /// allowed? 7548 /// 7549 /// This will also return false if the two given types do not make sense from 7550 /// the perspective of SVE bitcasts. 7551 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7552 assert(srcTy->isVectorType() || destTy->isVectorType()); 7553 7554 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7555 if (!FirstType->isSizelessBuiltinType()) 7556 return false; 7557 7558 const auto *VecTy = SecondType->getAs<VectorType>(); 7559 return VecTy && 7560 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7561 }; 7562 7563 return ValidScalableConversion(srcTy, destTy) || 7564 ValidScalableConversion(destTy, srcTy); 7565 } 7566 7567 /// Are the two types matrix types and do they have the same dimensions i.e. 7568 /// do they have the same number of rows and the same number of columns? 7569 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7570 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7571 return false; 7572 7573 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7574 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7575 7576 return matSrcType->getNumRows() == matDestType->getNumRows() && 7577 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7578 } 7579 7580 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7581 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7582 7583 uint64_t SrcLen, DestLen; 7584 QualType SrcEltTy, DestEltTy; 7585 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7586 return false; 7587 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7588 return false; 7589 7590 // ASTContext::getTypeSize will return the size rounded up to a 7591 // power of 2, so instead of using that, we need to use the raw 7592 // element size multiplied by the element count. 7593 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7594 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7595 7596 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7597 } 7598 7599 /// Are the two types lax-compatible vector types? That is, given 7600 /// that one of them is a vector, do they have equal storage sizes, 7601 /// where the storage size is the number of elements times the element 7602 /// size? 7603 /// 7604 /// This will also return false if either of the types is neither a 7605 /// vector nor a real type. 7606 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7607 assert(destTy->isVectorType() || srcTy->isVectorType()); 7608 7609 // Disallow lax conversions between scalars and ExtVectors (these 7610 // conversions are allowed for other vector types because common headers 7611 // depend on them). Most scalar OP ExtVector cases are handled by the 7612 // splat path anyway, which does what we want (convert, not bitcast). 7613 // What this rules out for ExtVectors is crazy things like char4*float. 7614 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7615 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7616 7617 return areVectorTypesSameSize(srcTy, destTy); 7618 } 7619 7620 /// Is this a legal conversion between two types, one of which is 7621 /// known to be a vector type? 7622 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7623 assert(destTy->isVectorType() || srcTy->isVectorType()); 7624 7625 switch (Context.getLangOpts().getLaxVectorConversions()) { 7626 case LangOptions::LaxVectorConversionKind::None: 7627 return false; 7628 7629 case LangOptions::LaxVectorConversionKind::Integer: 7630 if (!srcTy->isIntegralOrEnumerationType()) { 7631 auto *Vec = srcTy->getAs<VectorType>(); 7632 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7633 return false; 7634 } 7635 if (!destTy->isIntegralOrEnumerationType()) { 7636 auto *Vec = destTy->getAs<VectorType>(); 7637 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7638 return false; 7639 } 7640 // OK, integer (vector) -> integer (vector) bitcast. 7641 break; 7642 7643 case LangOptions::LaxVectorConversionKind::All: 7644 break; 7645 } 7646 7647 return areLaxCompatibleVectorTypes(srcTy, destTy); 7648 } 7649 7650 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7651 CastKind &Kind) { 7652 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7653 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7654 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7655 << DestTy << SrcTy << R; 7656 } 7657 } else if (SrcTy->isMatrixType()) { 7658 return Diag(R.getBegin(), 7659 diag::err_invalid_conversion_between_matrix_and_type) 7660 << SrcTy << DestTy << R; 7661 } else if (DestTy->isMatrixType()) { 7662 return Diag(R.getBegin(), 7663 diag::err_invalid_conversion_between_matrix_and_type) 7664 << DestTy << SrcTy << R; 7665 } 7666 7667 Kind = CK_MatrixCast; 7668 return false; 7669 } 7670 7671 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7672 CastKind &Kind) { 7673 assert(VectorTy->isVectorType() && "Not a vector type!"); 7674 7675 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7676 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7677 return Diag(R.getBegin(), 7678 Ty->isVectorType() ? 7679 diag::err_invalid_conversion_between_vectors : 7680 diag::err_invalid_conversion_between_vector_and_integer) 7681 << VectorTy << Ty << R; 7682 } else 7683 return Diag(R.getBegin(), 7684 diag::err_invalid_conversion_between_vector_and_scalar) 7685 << VectorTy << Ty << R; 7686 7687 Kind = CK_BitCast; 7688 return false; 7689 } 7690 7691 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7692 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7693 7694 if (DestElemTy == SplattedExpr->getType()) 7695 return SplattedExpr; 7696 7697 assert(DestElemTy->isFloatingType() || 7698 DestElemTy->isIntegralOrEnumerationType()); 7699 7700 CastKind CK; 7701 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7702 // OpenCL requires that we convert `true` boolean expressions to -1, but 7703 // only when splatting vectors. 7704 if (DestElemTy->isFloatingType()) { 7705 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7706 // in two steps: boolean to signed integral, then to floating. 7707 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7708 CK_BooleanToSignedIntegral); 7709 SplattedExpr = CastExprRes.get(); 7710 CK = CK_IntegralToFloating; 7711 } else { 7712 CK = CK_BooleanToSignedIntegral; 7713 } 7714 } else { 7715 ExprResult CastExprRes = SplattedExpr; 7716 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7717 if (CastExprRes.isInvalid()) 7718 return ExprError(); 7719 SplattedExpr = CastExprRes.get(); 7720 } 7721 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7722 } 7723 7724 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7725 Expr *CastExpr, CastKind &Kind) { 7726 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7727 7728 QualType SrcTy = CastExpr->getType(); 7729 7730 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7731 // an ExtVectorType. 7732 // In OpenCL, casts between vectors of different types are not allowed. 7733 // (See OpenCL 6.2). 7734 if (SrcTy->isVectorType()) { 7735 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7736 (getLangOpts().OpenCL && 7737 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7738 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7739 << DestTy << SrcTy << R; 7740 return ExprError(); 7741 } 7742 Kind = CK_BitCast; 7743 return CastExpr; 7744 } 7745 7746 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7747 // conversion will take place first from scalar to elt type, and then 7748 // splat from elt type to vector. 7749 if (SrcTy->isPointerType()) 7750 return Diag(R.getBegin(), 7751 diag::err_invalid_conversion_between_vector_and_scalar) 7752 << DestTy << SrcTy << R; 7753 7754 Kind = CK_VectorSplat; 7755 return prepareVectorSplat(DestTy, CastExpr); 7756 } 7757 7758 ExprResult 7759 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7760 Declarator &D, ParsedType &Ty, 7761 SourceLocation RParenLoc, Expr *CastExpr) { 7762 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7763 "ActOnCastExpr(): missing type or expr"); 7764 7765 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7766 if (D.isInvalidType()) 7767 return ExprError(); 7768 7769 if (getLangOpts().CPlusPlus) { 7770 // Check that there are no default arguments (C++ only). 7771 CheckExtraCXXDefaultArguments(D); 7772 } else { 7773 // Make sure any TypoExprs have been dealt with. 7774 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7775 if (!Res.isUsable()) 7776 return ExprError(); 7777 CastExpr = Res.get(); 7778 } 7779 7780 checkUnusedDeclAttributes(D); 7781 7782 QualType castType = castTInfo->getType(); 7783 Ty = CreateParsedType(castType, castTInfo); 7784 7785 bool isVectorLiteral = false; 7786 7787 // Check for an altivec or OpenCL literal, 7788 // i.e. all the elements are integer constants. 7789 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7790 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7791 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7792 && castType->isVectorType() && (PE || PLE)) { 7793 if (PLE && PLE->getNumExprs() == 0) { 7794 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7795 return ExprError(); 7796 } 7797 if (PE || PLE->getNumExprs() == 1) { 7798 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7799 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7800 isVectorLiteral = true; 7801 } 7802 else 7803 isVectorLiteral = true; 7804 } 7805 7806 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7807 // then handle it as such. 7808 if (isVectorLiteral) 7809 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7810 7811 // If the Expr being casted is a ParenListExpr, handle it specially. 7812 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7813 // sequence of BinOp comma operators. 7814 if (isa<ParenListExpr>(CastExpr)) { 7815 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7816 if (Result.isInvalid()) return ExprError(); 7817 CastExpr = Result.get(); 7818 } 7819 7820 if (getLangOpts().CPlusPlus && !castType->isVoidType()) 7821 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7822 7823 CheckTollFreeBridgeCast(castType, CastExpr); 7824 7825 CheckObjCBridgeRelatedCast(castType, CastExpr); 7826 7827 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7828 7829 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7830 } 7831 7832 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7833 SourceLocation RParenLoc, Expr *E, 7834 TypeSourceInfo *TInfo) { 7835 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7836 "Expected paren or paren list expression"); 7837 7838 Expr **exprs; 7839 unsigned numExprs; 7840 Expr *subExpr; 7841 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7842 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7843 LiteralLParenLoc = PE->getLParenLoc(); 7844 LiteralRParenLoc = PE->getRParenLoc(); 7845 exprs = PE->getExprs(); 7846 numExprs = PE->getNumExprs(); 7847 } else { // isa<ParenExpr> by assertion at function entrance 7848 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7849 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7850 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7851 exprs = &subExpr; 7852 numExprs = 1; 7853 } 7854 7855 QualType Ty = TInfo->getType(); 7856 assert(Ty->isVectorType() && "Expected vector type"); 7857 7858 SmallVector<Expr *, 8> initExprs; 7859 const VectorType *VTy = Ty->castAs<VectorType>(); 7860 unsigned numElems = VTy->getNumElements(); 7861 7862 // '(...)' form of vector initialization in AltiVec: the number of 7863 // initializers must be one or must match the size of the vector. 7864 // If a single value is specified in the initializer then it will be 7865 // replicated to all the components of the vector 7866 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7867 VTy->getElementType())) 7868 return ExprError(); 7869 if (ShouldSplatAltivecScalarInCast(VTy)) { 7870 // The number of initializers must be one or must match the size of the 7871 // vector. If a single value is specified in the initializer then it will 7872 // be replicated to all the components of the vector 7873 if (numExprs == 1) { 7874 QualType ElemTy = VTy->getElementType(); 7875 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7876 if (Literal.isInvalid()) 7877 return ExprError(); 7878 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7879 PrepareScalarCast(Literal, ElemTy)); 7880 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7881 } 7882 else if (numExprs < numElems) { 7883 Diag(E->getExprLoc(), 7884 diag::err_incorrect_number_of_vector_initializers); 7885 return ExprError(); 7886 } 7887 else 7888 initExprs.append(exprs, exprs + numExprs); 7889 } 7890 else { 7891 // For OpenCL, when the number of initializers is a single value, 7892 // it will be replicated to all components of the vector. 7893 if (getLangOpts().OpenCL && 7894 VTy->getVectorKind() == VectorType::GenericVector && 7895 numExprs == 1) { 7896 QualType ElemTy = VTy->getElementType(); 7897 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7898 if (Literal.isInvalid()) 7899 return ExprError(); 7900 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7901 PrepareScalarCast(Literal, ElemTy)); 7902 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7903 } 7904 7905 initExprs.append(exprs, exprs + numExprs); 7906 } 7907 // FIXME: This means that pretty-printing the final AST will produce curly 7908 // braces instead of the original commas. 7909 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7910 initExprs, LiteralRParenLoc); 7911 initE->setType(Ty); 7912 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7913 } 7914 7915 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7916 /// the ParenListExpr into a sequence of comma binary operators. 7917 ExprResult 7918 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7919 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7920 if (!E) 7921 return OrigExpr; 7922 7923 ExprResult Result(E->getExpr(0)); 7924 7925 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7926 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7927 E->getExpr(i)); 7928 7929 if (Result.isInvalid()) return ExprError(); 7930 7931 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7932 } 7933 7934 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7935 SourceLocation R, 7936 MultiExprArg Val) { 7937 return ParenListExpr::Create(Context, L, Val, R); 7938 } 7939 7940 /// Emit a specialized diagnostic when one expression is a null pointer 7941 /// constant and the other is not a pointer. Returns true if a diagnostic is 7942 /// emitted. 7943 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7944 SourceLocation QuestionLoc) { 7945 Expr *NullExpr = LHSExpr; 7946 Expr *NonPointerExpr = RHSExpr; 7947 Expr::NullPointerConstantKind NullKind = 7948 NullExpr->isNullPointerConstant(Context, 7949 Expr::NPC_ValueDependentIsNotNull); 7950 7951 if (NullKind == Expr::NPCK_NotNull) { 7952 NullExpr = RHSExpr; 7953 NonPointerExpr = LHSExpr; 7954 NullKind = 7955 NullExpr->isNullPointerConstant(Context, 7956 Expr::NPC_ValueDependentIsNotNull); 7957 } 7958 7959 if (NullKind == Expr::NPCK_NotNull) 7960 return false; 7961 7962 if (NullKind == Expr::NPCK_ZeroExpression) 7963 return false; 7964 7965 if (NullKind == Expr::NPCK_ZeroLiteral) { 7966 // In this case, check to make sure that we got here from a "NULL" 7967 // string in the source code. 7968 NullExpr = NullExpr->IgnoreParenImpCasts(); 7969 SourceLocation loc = NullExpr->getExprLoc(); 7970 if (!findMacroSpelling(loc, "NULL")) 7971 return false; 7972 } 7973 7974 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7975 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7976 << NonPointerExpr->getType() << DiagType 7977 << NonPointerExpr->getSourceRange(); 7978 return true; 7979 } 7980 7981 /// Return false if the condition expression is valid, true otherwise. 7982 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7983 QualType CondTy = Cond->getType(); 7984 7985 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7986 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7987 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7988 << CondTy << Cond->getSourceRange(); 7989 return true; 7990 } 7991 7992 // C99 6.5.15p2 7993 if (CondTy->isScalarType()) return false; 7994 7995 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7996 << CondTy << Cond->getSourceRange(); 7997 return true; 7998 } 7999 8000 /// Handle when one or both operands are void type. 8001 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 8002 ExprResult &RHS) { 8003 Expr *LHSExpr = LHS.get(); 8004 Expr *RHSExpr = RHS.get(); 8005 8006 if (!LHSExpr->getType()->isVoidType()) 8007 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8008 << RHSExpr->getSourceRange(); 8009 if (!RHSExpr->getType()->isVoidType()) 8010 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8011 << LHSExpr->getSourceRange(); 8012 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 8013 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 8014 return S.Context.VoidTy; 8015 } 8016 8017 /// Return false if the NullExpr can be promoted to PointerTy, 8018 /// true otherwise. 8019 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 8020 QualType PointerTy) { 8021 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 8022 !NullExpr.get()->isNullPointerConstant(S.Context, 8023 Expr::NPC_ValueDependentIsNull)) 8024 return true; 8025 8026 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 8027 return false; 8028 } 8029 8030 /// Checks compatibility between two pointers and return the resulting 8031 /// type. 8032 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 8033 ExprResult &RHS, 8034 SourceLocation Loc) { 8035 QualType LHSTy = LHS.get()->getType(); 8036 QualType RHSTy = RHS.get()->getType(); 8037 8038 if (S.Context.hasSameType(LHSTy, RHSTy)) { 8039 // Two identical pointers types are always compatible. 8040 return LHSTy; 8041 } 8042 8043 QualType lhptee, rhptee; 8044 8045 // Get the pointee types. 8046 bool IsBlockPointer = false; 8047 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 8048 lhptee = LHSBTy->getPointeeType(); 8049 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 8050 IsBlockPointer = true; 8051 } else { 8052 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8053 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8054 } 8055 8056 // C99 6.5.15p6: If both operands are pointers to compatible types or to 8057 // differently qualified versions of compatible types, the result type is 8058 // a pointer to an appropriately qualified version of the composite 8059 // type. 8060 8061 // Only CVR-qualifiers exist in the standard, and the differently-qualified 8062 // clause doesn't make sense for our extensions. E.g. address space 2 should 8063 // be incompatible with address space 3: they may live on different devices or 8064 // anything. 8065 Qualifiers lhQual = lhptee.getQualifiers(); 8066 Qualifiers rhQual = rhptee.getQualifiers(); 8067 8068 LangAS ResultAddrSpace = LangAS::Default; 8069 LangAS LAddrSpace = lhQual.getAddressSpace(); 8070 LangAS RAddrSpace = rhQual.getAddressSpace(); 8071 8072 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 8073 // spaces is disallowed. 8074 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 8075 ResultAddrSpace = LAddrSpace; 8076 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 8077 ResultAddrSpace = RAddrSpace; 8078 else { 8079 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8080 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 8081 << RHS.get()->getSourceRange(); 8082 return QualType(); 8083 } 8084 8085 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 8086 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 8087 lhQual.removeCVRQualifiers(); 8088 rhQual.removeCVRQualifiers(); 8089 8090 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 8091 // (C99 6.7.3) for address spaces. We assume that the check should behave in 8092 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 8093 // qual types are compatible iff 8094 // * corresponded types are compatible 8095 // * CVR qualifiers are equal 8096 // * address spaces are equal 8097 // Thus for conditional operator we merge CVR and address space unqualified 8098 // pointees and if there is a composite type we return a pointer to it with 8099 // merged qualifiers. 8100 LHSCastKind = 8101 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8102 RHSCastKind = 8103 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8104 lhQual.removeAddressSpace(); 8105 rhQual.removeAddressSpace(); 8106 8107 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 8108 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 8109 8110 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 8111 8112 if (CompositeTy.isNull()) { 8113 // In this situation, we assume void* type. No especially good 8114 // reason, but this is what gcc does, and we do have to pick 8115 // to get a consistent AST. 8116 QualType incompatTy; 8117 incompatTy = S.Context.getPointerType( 8118 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 8119 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 8120 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 8121 8122 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 8123 // for casts between types with incompatible address space qualifiers. 8124 // For the following code the compiler produces casts between global and 8125 // local address spaces of the corresponded innermost pointees: 8126 // local int *global *a; 8127 // global int *global *b; 8128 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8129 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8130 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8131 << RHS.get()->getSourceRange(); 8132 8133 return incompatTy; 8134 } 8135 8136 // The pointer types are compatible. 8137 // In case of OpenCL ResultTy should have the address space qualifier 8138 // which is a superset of address spaces of both the 2nd and the 3rd 8139 // operands of the conditional operator. 8140 QualType ResultTy = [&, ResultAddrSpace]() { 8141 if (S.getLangOpts().OpenCL) { 8142 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8143 CompositeQuals.setAddressSpace(ResultAddrSpace); 8144 return S.Context 8145 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8146 .withCVRQualifiers(MergedCVRQual); 8147 } 8148 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8149 }(); 8150 if (IsBlockPointer) 8151 ResultTy = S.Context.getBlockPointerType(ResultTy); 8152 else 8153 ResultTy = S.Context.getPointerType(ResultTy); 8154 8155 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8156 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8157 return ResultTy; 8158 } 8159 8160 /// Return the resulting type when the operands are both block pointers. 8161 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8162 ExprResult &LHS, 8163 ExprResult &RHS, 8164 SourceLocation Loc) { 8165 QualType LHSTy = LHS.get()->getType(); 8166 QualType RHSTy = RHS.get()->getType(); 8167 8168 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8169 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8170 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8171 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8172 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8173 return destType; 8174 } 8175 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8176 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8177 << RHS.get()->getSourceRange(); 8178 return QualType(); 8179 } 8180 8181 // We have 2 block pointer types. 8182 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8183 } 8184 8185 /// Return the resulting type when the operands are both pointers. 8186 static QualType 8187 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8188 ExprResult &RHS, 8189 SourceLocation Loc) { 8190 // get the pointer types 8191 QualType LHSTy = LHS.get()->getType(); 8192 QualType RHSTy = RHS.get()->getType(); 8193 8194 // get the "pointed to" types 8195 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8196 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8197 8198 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8199 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8200 // Figure out necessary qualifiers (C99 6.5.15p6) 8201 QualType destPointee 8202 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8203 QualType destType = S.Context.getPointerType(destPointee); 8204 // Add qualifiers if necessary. 8205 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8206 // Promote to void*. 8207 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8208 return destType; 8209 } 8210 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8211 QualType destPointee 8212 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8213 QualType destType = S.Context.getPointerType(destPointee); 8214 // Add qualifiers if necessary. 8215 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8216 // Promote to void*. 8217 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8218 return destType; 8219 } 8220 8221 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8222 } 8223 8224 /// Return false if the first expression is not an integer and the second 8225 /// expression is not a pointer, true otherwise. 8226 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8227 Expr* PointerExpr, SourceLocation Loc, 8228 bool IsIntFirstExpr) { 8229 if (!PointerExpr->getType()->isPointerType() || 8230 !Int.get()->getType()->isIntegerType()) 8231 return false; 8232 8233 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8234 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8235 8236 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8237 << Expr1->getType() << Expr2->getType() 8238 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8239 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8240 CK_IntegralToPointer); 8241 return true; 8242 } 8243 8244 /// Simple conversion between integer and floating point types. 8245 /// 8246 /// Used when handling the OpenCL conditional operator where the 8247 /// condition is a vector while the other operands are scalar. 8248 /// 8249 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8250 /// types are either integer or floating type. Between the two 8251 /// operands, the type with the higher rank is defined as the "result 8252 /// type". The other operand needs to be promoted to the same type. No 8253 /// other type promotion is allowed. We cannot use 8254 /// UsualArithmeticConversions() for this purpose, since it always 8255 /// promotes promotable types. 8256 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8257 ExprResult &RHS, 8258 SourceLocation QuestionLoc) { 8259 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8260 if (LHS.isInvalid()) 8261 return QualType(); 8262 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8263 if (RHS.isInvalid()) 8264 return QualType(); 8265 8266 // For conversion purposes, we ignore any qualifiers. 8267 // For example, "const float" and "float" are equivalent. 8268 QualType LHSType = 8269 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8270 QualType RHSType = 8271 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8272 8273 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8274 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8275 << LHSType << LHS.get()->getSourceRange(); 8276 return QualType(); 8277 } 8278 8279 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8280 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8281 << RHSType << RHS.get()->getSourceRange(); 8282 return QualType(); 8283 } 8284 8285 // If both types are identical, no conversion is needed. 8286 if (LHSType == RHSType) 8287 return LHSType; 8288 8289 // Now handle "real" floating types (i.e. float, double, long double). 8290 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8291 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8292 /*IsCompAssign = */ false); 8293 8294 // Finally, we have two differing integer types. 8295 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8296 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8297 } 8298 8299 /// Convert scalar operands to a vector that matches the 8300 /// condition in length. 8301 /// 8302 /// Used when handling the OpenCL conditional operator where the 8303 /// condition is a vector while the other operands are scalar. 8304 /// 8305 /// We first compute the "result type" for the scalar operands 8306 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8307 /// into a vector of that type where the length matches the condition 8308 /// vector type. s6.11.6 requires that the element types of the result 8309 /// and the condition must have the same number of bits. 8310 static QualType 8311 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8312 QualType CondTy, SourceLocation QuestionLoc) { 8313 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8314 if (ResTy.isNull()) return QualType(); 8315 8316 const VectorType *CV = CondTy->getAs<VectorType>(); 8317 assert(CV); 8318 8319 // Determine the vector result type 8320 unsigned NumElements = CV->getNumElements(); 8321 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8322 8323 // Ensure that all types have the same number of bits 8324 if (S.Context.getTypeSize(CV->getElementType()) 8325 != S.Context.getTypeSize(ResTy)) { 8326 // Since VectorTy is created internally, it does not pretty print 8327 // with an OpenCL name. Instead, we just print a description. 8328 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8329 SmallString<64> Str; 8330 llvm::raw_svector_ostream OS(Str); 8331 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8332 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8333 << CondTy << OS.str(); 8334 return QualType(); 8335 } 8336 8337 // Convert operands to the vector result type 8338 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8339 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8340 8341 return VectorTy; 8342 } 8343 8344 /// Return false if this is a valid OpenCL condition vector 8345 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8346 SourceLocation QuestionLoc) { 8347 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8348 // integral type. 8349 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8350 assert(CondTy); 8351 QualType EleTy = CondTy->getElementType(); 8352 if (EleTy->isIntegerType()) return false; 8353 8354 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8355 << Cond->getType() << Cond->getSourceRange(); 8356 return true; 8357 } 8358 8359 /// Return false if the vector condition type and the vector 8360 /// result type are compatible. 8361 /// 8362 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8363 /// number of elements, and their element types have the same number 8364 /// of bits. 8365 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8366 SourceLocation QuestionLoc) { 8367 const VectorType *CV = CondTy->getAs<VectorType>(); 8368 const VectorType *RV = VecResTy->getAs<VectorType>(); 8369 assert(CV && RV); 8370 8371 if (CV->getNumElements() != RV->getNumElements()) { 8372 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8373 << CondTy << VecResTy; 8374 return true; 8375 } 8376 8377 QualType CVE = CV->getElementType(); 8378 QualType RVE = RV->getElementType(); 8379 8380 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8381 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8382 << CondTy << VecResTy; 8383 return true; 8384 } 8385 8386 return false; 8387 } 8388 8389 /// Return the resulting type for the conditional operator in 8390 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8391 /// s6.3.i) when the condition is a vector type. 8392 static QualType 8393 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8394 ExprResult &LHS, ExprResult &RHS, 8395 SourceLocation QuestionLoc) { 8396 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8397 if (Cond.isInvalid()) 8398 return QualType(); 8399 QualType CondTy = Cond.get()->getType(); 8400 8401 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8402 return QualType(); 8403 8404 // If either operand is a vector then find the vector type of the 8405 // result as specified in OpenCL v1.1 s6.3.i. 8406 if (LHS.get()->getType()->isVectorType() || 8407 RHS.get()->getType()->isVectorType()) { 8408 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8409 /*isCompAssign*/false, 8410 /*AllowBothBool*/true, 8411 /*AllowBoolConversions*/false); 8412 if (VecResTy.isNull()) return QualType(); 8413 // The result type must match the condition type as specified in 8414 // OpenCL v1.1 s6.11.6. 8415 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8416 return QualType(); 8417 return VecResTy; 8418 } 8419 8420 // Both operands are scalar. 8421 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8422 } 8423 8424 /// Return true if the Expr is block type 8425 static bool checkBlockType(Sema &S, const Expr *E) { 8426 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8427 QualType Ty = CE->getCallee()->getType(); 8428 if (Ty->isBlockPointerType()) { 8429 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8430 return true; 8431 } 8432 } 8433 return false; 8434 } 8435 8436 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8437 /// In that case, LHS = cond. 8438 /// C99 6.5.15 8439 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8440 ExprResult &RHS, ExprValueKind &VK, 8441 ExprObjectKind &OK, 8442 SourceLocation QuestionLoc) { 8443 8444 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8445 if (!LHSResult.isUsable()) return QualType(); 8446 LHS = LHSResult; 8447 8448 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8449 if (!RHSResult.isUsable()) return QualType(); 8450 RHS = RHSResult; 8451 8452 // C++ is sufficiently different to merit its own checker. 8453 if (getLangOpts().CPlusPlus) 8454 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8455 8456 VK = VK_PRValue; 8457 OK = OK_Ordinary; 8458 8459 if (Context.isDependenceAllowed() && 8460 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8461 RHS.get()->isTypeDependent())) { 8462 assert(!getLangOpts().CPlusPlus); 8463 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8464 RHS.get()->containsErrors()) && 8465 "should only occur in error-recovery path."); 8466 return Context.DependentTy; 8467 } 8468 8469 // The OpenCL operator with a vector condition is sufficiently 8470 // different to merit its own checker. 8471 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8472 Cond.get()->getType()->isExtVectorType()) 8473 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8474 8475 // First, check the condition. 8476 Cond = UsualUnaryConversions(Cond.get()); 8477 if (Cond.isInvalid()) 8478 return QualType(); 8479 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8480 return QualType(); 8481 8482 // Now check the two expressions. 8483 if (LHS.get()->getType()->isVectorType() || 8484 RHS.get()->getType()->isVectorType()) 8485 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8486 /*AllowBothBool*/true, 8487 /*AllowBoolConversions*/false); 8488 8489 QualType ResTy = 8490 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8491 if (LHS.isInvalid() || RHS.isInvalid()) 8492 return QualType(); 8493 8494 QualType LHSTy = LHS.get()->getType(); 8495 QualType RHSTy = RHS.get()->getType(); 8496 8497 // Diagnose attempts to convert between __ibm128, __float128 and long double 8498 // where such conversions currently can't be handled. 8499 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8500 Diag(QuestionLoc, 8501 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8502 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8503 return QualType(); 8504 } 8505 8506 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8507 // selection operator (?:). 8508 if (getLangOpts().OpenCL && 8509 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8510 return QualType(); 8511 } 8512 8513 // If both operands have arithmetic type, do the usual arithmetic conversions 8514 // to find a common type: C99 6.5.15p3,5. 8515 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8516 // Disallow invalid arithmetic conversions, such as those between bit- 8517 // precise integers types of different sizes, or between a bit-precise 8518 // integer and another type. 8519 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { 8520 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8521 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8522 << RHS.get()->getSourceRange(); 8523 return QualType(); 8524 } 8525 8526 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8527 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8528 8529 return ResTy; 8530 } 8531 8532 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8533 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8534 return LHSTy; 8535 } 8536 8537 // If both operands are the same structure or union type, the result is that 8538 // type. 8539 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8540 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8541 if (LHSRT->getDecl() == RHSRT->getDecl()) 8542 // "If both the operands have structure or union type, the result has 8543 // that type." This implies that CV qualifiers are dropped. 8544 return LHSTy.getUnqualifiedType(); 8545 // FIXME: Type of conditional expression must be complete in C mode. 8546 } 8547 8548 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8549 // The following || allows only one side to be void (a GCC-ism). 8550 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8551 return checkConditionalVoidType(*this, LHS, RHS); 8552 } 8553 8554 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8555 // the type of the other operand." 8556 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8557 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8558 8559 // All objective-c pointer type analysis is done here. 8560 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8561 QuestionLoc); 8562 if (LHS.isInvalid() || RHS.isInvalid()) 8563 return QualType(); 8564 if (!compositeType.isNull()) 8565 return compositeType; 8566 8567 8568 // Handle block pointer types. 8569 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8570 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8571 QuestionLoc); 8572 8573 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8574 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8575 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8576 QuestionLoc); 8577 8578 // GCC compatibility: soften pointer/integer mismatch. Note that 8579 // null pointers have been filtered out by this point. 8580 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8581 /*IsIntFirstExpr=*/true)) 8582 return RHSTy; 8583 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8584 /*IsIntFirstExpr=*/false)) 8585 return LHSTy; 8586 8587 // Allow ?: operations in which both operands have the same 8588 // built-in sizeless type. 8589 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8590 return LHSTy; 8591 8592 // Emit a better diagnostic if one of the expressions is a null pointer 8593 // constant and the other is not a pointer type. In this case, the user most 8594 // likely forgot to take the address of the other expression. 8595 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8596 return QualType(); 8597 8598 // Otherwise, the operands are not compatible. 8599 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8600 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8601 << RHS.get()->getSourceRange(); 8602 return QualType(); 8603 } 8604 8605 /// FindCompositeObjCPointerType - Helper method to find composite type of 8606 /// two objective-c pointer types of the two input expressions. 8607 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8608 SourceLocation QuestionLoc) { 8609 QualType LHSTy = LHS.get()->getType(); 8610 QualType RHSTy = RHS.get()->getType(); 8611 8612 // Handle things like Class and struct objc_class*. Here we case the result 8613 // to the pseudo-builtin, because that will be implicitly cast back to the 8614 // redefinition type if an attempt is made to access its fields. 8615 if (LHSTy->isObjCClassType() && 8616 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8617 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8618 return LHSTy; 8619 } 8620 if (RHSTy->isObjCClassType() && 8621 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8622 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8623 return RHSTy; 8624 } 8625 // And the same for struct objc_object* / id 8626 if (LHSTy->isObjCIdType() && 8627 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8628 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8629 return LHSTy; 8630 } 8631 if (RHSTy->isObjCIdType() && 8632 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8633 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8634 return RHSTy; 8635 } 8636 // And the same for struct objc_selector* / SEL 8637 if (Context.isObjCSelType(LHSTy) && 8638 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8639 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8640 return LHSTy; 8641 } 8642 if (Context.isObjCSelType(RHSTy) && 8643 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8644 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8645 return RHSTy; 8646 } 8647 // Check constraints for Objective-C object pointers types. 8648 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8649 8650 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8651 // Two identical object pointer types are always compatible. 8652 return LHSTy; 8653 } 8654 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8655 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8656 QualType compositeType = LHSTy; 8657 8658 // If both operands are interfaces and either operand can be 8659 // assigned to the other, use that type as the composite 8660 // type. This allows 8661 // xxx ? (A*) a : (B*) b 8662 // where B is a subclass of A. 8663 // 8664 // Additionally, as for assignment, if either type is 'id' 8665 // allow silent coercion. Finally, if the types are 8666 // incompatible then make sure to use 'id' as the composite 8667 // type so the result is acceptable for sending messages to. 8668 8669 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8670 // It could return the composite type. 8671 if (!(compositeType = 8672 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8673 // Nothing more to do. 8674 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8675 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8676 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8677 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8678 } else if ((LHSOPT->isObjCQualifiedIdType() || 8679 RHSOPT->isObjCQualifiedIdType()) && 8680 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8681 true)) { 8682 // Need to handle "id<xx>" explicitly. 8683 // GCC allows qualified id and any Objective-C type to devolve to 8684 // id. Currently localizing to here until clear this should be 8685 // part of ObjCQualifiedIdTypesAreCompatible. 8686 compositeType = Context.getObjCIdType(); 8687 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8688 compositeType = Context.getObjCIdType(); 8689 } else { 8690 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8691 << LHSTy << RHSTy 8692 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8693 QualType incompatTy = Context.getObjCIdType(); 8694 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8695 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8696 return incompatTy; 8697 } 8698 // The object pointer types are compatible. 8699 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8700 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8701 return compositeType; 8702 } 8703 // Check Objective-C object pointer types and 'void *' 8704 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8705 if (getLangOpts().ObjCAutoRefCount) { 8706 // ARC forbids the implicit conversion of object pointers to 'void *', 8707 // so these types are not compatible. 8708 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8709 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8710 LHS = RHS = true; 8711 return QualType(); 8712 } 8713 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8714 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8715 QualType destPointee 8716 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8717 QualType destType = Context.getPointerType(destPointee); 8718 // Add qualifiers if necessary. 8719 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8720 // Promote to void*. 8721 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8722 return destType; 8723 } 8724 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8725 if (getLangOpts().ObjCAutoRefCount) { 8726 // ARC forbids the implicit conversion of object pointers to 'void *', 8727 // so these types are not compatible. 8728 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8729 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8730 LHS = RHS = true; 8731 return QualType(); 8732 } 8733 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8734 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8735 QualType destPointee 8736 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8737 QualType destType = Context.getPointerType(destPointee); 8738 // Add qualifiers if necessary. 8739 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8740 // Promote to void*. 8741 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8742 return destType; 8743 } 8744 return QualType(); 8745 } 8746 8747 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8748 /// ParenRange in parentheses. 8749 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8750 const PartialDiagnostic &Note, 8751 SourceRange ParenRange) { 8752 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8753 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8754 EndLoc.isValid()) { 8755 Self.Diag(Loc, Note) 8756 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8757 << FixItHint::CreateInsertion(EndLoc, ")"); 8758 } else { 8759 // We can't display the parentheses, so just show the bare note. 8760 Self.Diag(Loc, Note) << ParenRange; 8761 } 8762 } 8763 8764 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8765 return BinaryOperator::isAdditiveOp(Opc) || 8766 BinaryOperator::isMultiplicativeOp(Opc) || 8767 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8768 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8769 // not any of the logical operators. Bitwise-xor is commonly used as a 8770 // logical-xor because there is no logical-xor operator. The logical 8771 // operators, including uses of xor, have a high false positive rate for 8772 // precedence warnings. 8773 } 8774 8775 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8776 /// expression, either using a built-in or overloaded operator, 8777 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8778 /// expression. 8779 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8780 Expr **RHSExprs) { 8781 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8782 E = E->IgnoreImpCasts(); 8783 E = E->IgnoreConversionOperatorSingleStep(); 8784 E = E->IgnoreImpCasts(); 8785 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8786 E = MTE->getSubExpr(); 8787 E = E->IgnoreImpCasts(); 8788 } 8789 8790 // Built-in binary operator. 8791 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8792 if (IsArithmeticOp(OP->getOpcode())) { 8793 *Opcode = OP->getOpcode(); 8794 *RHSExprs = OP->getRHS(); 8795 return true; 8796 } 8797 } 8798 8799 // Overloaded operator. 8800 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8801 if (Call->getNumArgs() != 2) 8802 return false; 8803 8804 // Make sure this is really a binary operator that is safe to pass into 8805 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8806 OverloadedOperatorKind OO = Call->getOperator(); 8807 if (OO < OO_Plus || OO > OO_Arrow || 8808 OO == OO_PlusPlus || OO == OO_MinusMinus) 8809 return false; 8810 8811 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8812 if (IsArithmeticOp(OpKind)) { 8813 *Opcode = OpKind; 8814 *RHSExprs = Call->getArg(1); 8815 return true; 8816 } 8817 } 8818 8819 return false; 8820 } 8821 8822 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8823 /// or is a logical expression such as (x==y) which has int type, but is 8824 /// commonly interpreted as boolean. 8825 static bool ExprLooksBoolean(Expr *E) { 8826 E = E->IgnoreParenImpCasts(); 8827 8828 if (E->getType()->isBooleanType()) 8829 return true; 8830 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8831 return OP->isComparisonOp() || OP->isLogicalOp(); 8832 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8833 return OP->getOpcode() == UO_LNot; 8834 if (E->getType()->isPointerType()) 8835 return true; 8836 // FIXME: What about overloaded operator calls returning "unspecified boolean 8837 // type"s (commonly pointer-to-members)? 8838 8839 return false; 8840 } 8841 8842 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8843 /// and binary operator are mixed in a way that suggests the programmer assumed 8844 /// the conditional operator has higher precedence, for example: 8845 /// "int x = a + someBinaryCondition ? 1 : 2". 8846 static void DiagnoseConditionalPrecedence(Sema &Self, 8847 SourceLocation OpLoc, 8848 Expr *Condition, 8849 Expr *LHSExpr, 8850 Expr *RHSExpr) { 8851 BinaryOperatorKind CondOpcode; 8852 Expr *CondRHS; 8853 8854 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8855 return; 8856 if (!ExprLooksBoolean(CondRHS)) 8857 return; 8858 8859 // The condition is an arithmetic binary expression, with a right- 8860 // hand side that looks boolean, so warn. 8861 8862 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8863 ? diag::warn_precedence_bitwise_conditional 8864 : diag::warn_precedence_conditional; 8865 8866 Self.Diag(OpLoc, DiagID) 8867 << Condition->getSourceRange() 8868 << BinaryOperator::getOpcodeStr(CondOpcode); 8869 8870 SuggestParentheses( 8871 Self, OpLoc, 8872 Self.PDiag(diag::note_precedence_silence) 8873 << BinaryOperator::getOpcodeStr(CondOpcode), 8874 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8875 8876 SuggestParentheses(Self, OpLoc, 8877 Self.PDiag(diag::note_precedence_conditional_first), 8878 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8879 } 8880 8881 /// Compute the nullability of a conditional expression. 8882 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8883 QualType LHSTy, QualType RHSTy, 8884 ASTContext &Ctx) { 8885 if (!ResTy->isAnyPointerType()) 8886 return ResTy; 8887 8888 auto GetNullability = [&Ctx](QualType Ty) { 8889 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8890 if (Kind) { 8891 // For our purposes, treat _Nullable_result as _Nullable. 8892 if (*Kind == NullabilityKind::NullableResult) 8893 return NullabilityKind::Nullable; 8894 return *Kind; 8895 } 8896 return NullabilityKind::Unspecified; 8897 }; 8898 8899 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8900 NullabilityKind MergedKind; 8901 8902 // Compute nullability of a binary conditional expression. 8903 if (IsBin) { 8904 if (LHSKind == NullabilityKind::NonNull) 8905 MergedKind = NullabilityKind::NonNull; 8906 else 8907 MergedKind = RHSKind; 8908 // Compute nullability of a normal conditional expression. 8909 } else { 8910 if (LHSKind == NullabilityKind::Nullable || 8911 RHSKind == NullabilityKind::Nullable) 8912 MergedKind = NullabilityKind::Nullable; 8913 else if (LHSKind == NullabilityKind::NonNull) 8914 MergedKind = RHSKind; 8915 else if (RHSKind == NullabilityKind::NonNull) 8916 MergedKind = LHSKind; 8917 else 8918 MergedKind = NullabilityKind::Unspecified; 8919 } 8920 8921 // Return if ResTy already has the correct nullability. 8922 if (GetNullability(ResTy) == MergedKind) 8923 return ResTy; 8924 8925 // Strip all nullability from ResTy. 8926 while (ResTy->getNullability(Ctx)) 8927 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8928 8929 // Create a new AttributedType with the new nullability kind. 8930 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8931 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8932 } 8933 8934 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8935 /// in the case of a the GNU conditional expr extension. 8936 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8937 SourceLocation ColonLoc, 8938 Expr *CondExpr, Expr *LHSExpr, 8939 Expr *RHSExpr) { 8940 if (!Context.isDependenceAllowed()) { 8941 // C cannot handle TypoExpr nodes in the condition because it 8942 // doesn't handle dependent types properly, so make sure any TypoExprs have 8943 // been dealt with before checking the operands. 8944 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8945 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8946 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8947 8948 if (!CondResult.isUsable()) 8949 return ExprError(); 8950 8951 if (LHSExpr) { 8952 if (!LHSResult.isUsable()) 8953 return ExprError(); 8954 } 8955 8956 if (!RHSResult.isUsable()) 8957 return ExprError(); 8958 8959 CondExpr = CondResult.get(); 8960 LHSExpr = LHSResult.get(); 8961 RHSExpr = RHSResult.get(); 8962 } 8963 8964 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8965 // was the condition. 8966 OpaqueValueExpr *opaqueValue = nullptr; 8967 Expr *commonExpr = nullptr; 8968 if (!LHSExpr) { 8969 commonExpr = CondExpr; 8970 // Lower out placeholder types first. This is important so that we don't 8971 // try to capture a placeholder. This happens in few cases in C++; such 8972 // as Objective-C++'s dictionary subscripting syntax. 8973 if (commonExpr->hasPlaceholderType()) { 8974 ExprResult result = CheckPlaceholderExpr(commonExpr); 8975 if (!result.isUsable()) return ExprError(); 8976 commonExpr = result.get(); 8977 } 8978 // We usually want to apply unary conversions *before* saving, except 8979 // in the special case of a C++ l-value conditional. 8980 if (!(getLangOpts().CPlusPlus 8981 && !commonExpr->isTypeDependent() 8982 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8983 && commonExpr->isGLValue() 8984 && commonExpr->isOrdinaryOrBitFieldObject() 8985 && RHSExpr->isOrdinaryOrBitFieldObject() 8986 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8987 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8988 if (commonRes.isInvalid()) 8989 return ExprError(); 8990 commonExpr = commonRes.get(); 8991 } 8992 8993 // If the common expression is a class or array prvalue, materialize it 8994 // so that we can safely refer to it multiple times. 8995 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8996 commonExpr->getType()->isArrayType())) { 8997 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8998 if (MatExpr.isInvalid()) 8999 return ExprError(); 9000 commonExpr = MatExpr.get(); 9001 } 9002 9003 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 9004 commonExpr->getType(), 9005 commonExpr->getValueKind(), 9006 commonExpr->getObjectKind(), 9007 commonExpr); 9008 LHSExpr = CondExpr = opaqueValue; 9009 } 9010 9011 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 9012 ExprValueKind VK = VK_PRValue; 9013 ExprObjectKind OK = OK_Ordinary; 9014 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 9015 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 9016 VK, OK, QuestionLoc); 9017 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 9018 RHS.isInvalid()) 9019 return ExprError(); 9020 9021 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 9022 RHS.get()); 9023 9024 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 9025 9026 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 9027 Context); 9028 9029 if (!commonExpr) 9030 return new (Context) 9031 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 9032 RHS.get(), result, VK, OK); 9033 9034 return new (Context) BinaryConditionalOperator( 9035 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 9036 ColonLoc, result, VK, OK); 9037 } 9038 9039 // Check if we have a conversion between incompatible cmse function pointer 9040 // types, that is, a conversion between a function pointer with the 9041 // cmse_nonsecure_call attribute and one without. 9042 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 9043 QualType ToType) { 9044 if (const auto *ToFn = 9045 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 9046 if (const auto *FromFn = 9047 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 9048 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 9049 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 9050 9051 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 9052 } 9053 } 9054 return false; 9055 } 9056 9057 // checkPointerTypesForAssignment - This is a very tricky routine (despite 9058 // being closely modeled after the C99 spec:-). The odd characteristic of this 9059 // routine is it effectively iqnores the qualifiers on the top level pointee. 9060 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 9061 // FIXME: add a couple examples in this comment. 9062 static Sema::AssignConvertType 9063 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 9064 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9065 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9066 9067 // get the "pointed to" type (ignoring qualifiers at the top level) 9068 const Type *lhptee, *rhptee; 9069 Qualifiers lhq, rhq; 9070 std::tie(lhptee, lhq) = 9071 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 9072 std::tie(rhptee, rhq) = 9073 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 9074 9075 Sema::AssignConvertType ConvTy = Sema::Compatible; 9076 9077 // C99 6.5.16.1p1: This following citation is common to constraints 9078 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 9079 // qualifiers of the type *pointed to* by the right; 9080 9081 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 9082 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 9083 lhq.compatiblyIncludesObjCLifetime(rhq)) { 9084 // Ignore lifetime for further calculation. 9085 lhq.removeObjCLifetime(); 9086 rhq.removeObjCLifetime(); 9087 } 9088 9089 if (!lhq.compatiblyIncludes(rhq)) { 9090 // Treat address-space mismatches as fatal. 9091 if (!lhq.isAddressSpaceSupersetOf(rhq)) 9092 return Sema::IncompatiblePointerDiscardsQualifiers; 9093 9094 // It's okay to add or remove GC or lifetime qualifiers when converting to 9095 // and from void*. 9096 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 9097 .compatiblyIncludes( 9098 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 9099 && (lhptee->isVoidType() || rhptee->isVoidType())) 9100 ; // keep old 9101 9102 // Treat lifetime mismatches as fatal. 9103 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 9104 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 9105 9106 // For GCC/MS compatibility, other qualifier mismatches are treated 9107 // as still compatible in C. 9108 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9109 } 9110 9111 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 9112 // incomplete type and the other is a pointer to a qualified or unqualified 9113 // version of void... 9114 if (lhptee->isVoidType()) { 9115 if (rhptee->isIncompleteOrObjectType()) 9116 return ConvTy; 9117 9118 // As an extension, we allow cast to/from void* to function pointer. 9119 assert(rhptee->isFunctionType()); 9120 return Sema::FunctionVoidPointer; 9121 } 9122 9123 if (rhptee->isVoidType()) { 9124 if (lhptee->isIncompleteOrObjectType()) 9125 return ConvTy; 9126 9127 // As an extension, we allow cast to/from void* to function pointer. 9128 assert(lhptee->isFunctionType()); 9129 return Sema::FunctionVoidPointer; 9130 } 9131 9132 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9133 // unqualified versions of compatible types, ... 9134 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9135 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9136 // Check if the pointee types are compatible ignoring the sign. 9137 // We explicitly check for char so that we catch "char" vs 9138 // "unsigned char" on systems where "char" is unsigned. 9139 if (lhptee->isCharType()) 9140 ltrans = S.Context.UnsignedCharTy; 9141 else if (lhptee->hasSignedIntegerRepresentation()) 9142 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9143 9144 if (rhptee->isCharType()) 9145 rtrans = S.Context.UnsignedCharTy; 9146 else if (rhptee->hasSignedIntegerRepresentation()) 9147 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9148 9149 if (ltrans == rtrans) { 9150 // Types are compatible ignoring the sign. Qualifier incompatibility 9151 // takes priority over sign incompatibility because the sign 9152 // warning can be disabled. 9153 if (ConvTy != Sema::Compatible) 9154 return ConvTy; 9155 9156 return Sema::IncompatiblePointerSign; 9157 } 9158 9159 // If we are a multi-level pointer, it's possible that our issue is simply 9160 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9161 // the eventual target type is the same and the pointers have the same 9162 // level of indirection, this must be the issue. 9163 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9164 do { 9165 std::tie(lhptee, lhq) = 9166 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9167 std::tie(rhptee, rhq) = 9168 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9169 9170 // Inconsistent address spaces at this point is invalid, even if the 9171 // address spaces would be compatible. 9172 // FIXME: This doesn't catch address space mismatches for pointers of 9173 // different nesting levels, like: 9174 // __local int *** a; 9175 // int ** b = a; 9176 // It's not clear how to actually determine when such pointers are 9177 // invalidly incompatible. 9178 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9179 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9180 9181 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9182 9183 if (lhptee == rhptee) 9184 return Sema::IncompatibleNestedPointerQualifiers; 9185 } 9186 9187 // General pointer incompatibility takes priority over qualifiers. 9188 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9189 return Sema::IncompatibleFunctionPointer; 9190 return Sema::IncompatiblePointer; 9191 } 9192 if (!S.getLangOpts().CPlusPlus && 9193 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9194 return Sema::IncompatibleFunctionPointer; 9195 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9196 return Sema::IncompatibleFunctionPointer; 9197 return ConvTy; 9198 } 9199 9200 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9201 /// block pointer types are compatible or whether a block and normal pointer 9202 /// are compatible. It is more restrict than comparing two function pointer 9203 // types. 9204 static Sema::AssignConvertType 9205 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9206 QualType RHSType) { 9207 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9208 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9209 9210 QualType lhptee, rhptee; 9211 9212 // get the "pointed to" type (ignoring qualifiers at the top level) 9213 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9214 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9215 9216 // In C++, the types have to match exactly. 9217 if (S.getLangOpts().CPlusPlus) 9218 return Sema::IncompatibleBlockPointer; 9219 9220 Sema::AssignConvertType ConvTy = Sema::Compatible; 9221 9222 // For blocks we enforce that qualifiers are identical. 9223 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9224 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9225 if (S.getLangOpts().OpenCL) { 9226 LQuals.removeAddressSpace(); 9227 RQuals.removeAddressSpace(); 9228 } 9229 if (LQuals != RQuals) 9230 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9231 9232 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9233 // assignment. 9234 // The current behavior is similar to C++ lambdas. A block might be 9235 // assigned to a variable iff its return type and parameters are compatible 9236 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9237 // an assignment. Presumably it should behave in way that a function pointer 9238 // assignment does in C, so for each parameter and return type: 9239 // * CVR and address space of LHS should be a superset of CVR and address 9240 // space of RHS. 9241 // * unqualified types should be compatible. 9242 if (S.getLangOpts().OpenCL) { 9243 if (!S.Context.typesAreBlockPointerCompatible( 9244 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9245 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9246 return Sema::IncompatibleBlockPointer; 9247 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9248 return Sema::IncompatibleBlockPointer; 9249 9250 return ConvTy; 9251 } 9252 9253 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9254 /// for assignment compatibility. 9255 static Sema::AssignConvertType 9256 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9257 QualType RHSType) { 9258 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9259 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9260 9261 if (LHSType->isObjCBuiltinType()) { 9262 // Class is not compatible with ObjC object pointers. 9263 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9264 !RHSType->isObjCQualifiedClassType()) 9265 return Sema::IncompatiblePointer; 9266 return Sema::Compatible; 9267 } 9268 if (RHSType->isObjCBuiltinType()) { 9269 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9270 !LHSType->isObjCQualifiedClassType()) 9271 return Sema::IncompatiblePointer; 9272 return Sema::Compatible; 9273 } 9274 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9275 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9276 9277 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9278 // make an exception for id<P> 9279 !LHSType->isObjCQualifiedIdType()) 9280 return Sema::CompatiblePointerDiscardsQualifiers; 9281 9282 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9283 return Sema::Compatible; 9284 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9285 return Sema::IncompatibleObjCQualifiedId; 9286 return Sema::IncompatiblePointer; 9287 } 9288 9289 Sema::AssignConvertType 9290 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9291 QualType LHSType, QualType RHSType) { 9292 // Fake up an opaque expression. We don't actually care about what 9293 // cast operations are required, so if CheckAssignmentConstraints 9294 // adds casts to this they'll be wasted, but fortunately that doesn't 9295 // usually happen on valid code. 9296 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9297 ExprResult RHSPtr = &RHSExpr; 9298 CastKind K; 9299 9300 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9301 } 9302 9303 /// This helper function returns true if QT is a vector type that has element 9304 /// type ElementType. 9305 static bool isVector(QualType QT, QualType ElementType) { 9306 if (const VectorType *VT = QT->getAs<VectorType>()) 9307 return VT->getElementType().getCanonicalType() == ElementType; 9308 return false; 9309 } 9310 9311 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9312 /// has code to accommodate several GCC extensions when type checking 9313 /// pointers. Here are some objectionable examples that GCC considers warnings: 9314 /// 9315 /// int a, *pint; 9316 /// short *pshort; 9317 /// struct foo *pfoo; 9318 /// 9319 /// pint = pshort; // warning: assignment from incompatible pointer type 9320 /// a = pint; // warning: assignment makes integer from pointer without a cast 9321 /// pint = a; // warning: assignment makes pointer from integer without a cast 9322 /// pint = pfoo; // warning: assignment from incompatible pointer type 9323 /// 9324 /// As a result, the code for dealing with pointers is more complex than the 9325 /// C99 spec dictates. 9326 /// 9327 /// Sets 'Kind' for any result kind except Incompatible. 9328 Sema::AssignConvertType 9329 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9330 CastKind &Kind, bool ConvertRHS) { 9331 QualType RHSType = RHS.get()->getType(); 9332 QualType OrigLHSType = LHSType; 9333 9334 // Get canonical types. We're not formatting these types, just comparing 9335 // them. 9336 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9337 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9338 9339 // Common case: no conversion required. 9340 if (LHSType == RHSType) { 9341 Kind = CK_NoOp; 9342 return Compatible; 9343 } 9344 9345 // If we have an atomic type, try a non-atomic assignment, then just add an 9346 // atomic qualification step. 9347 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9348 Sema::AssignConvertType result = 9349 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9350 if (result != Compatible) 9351 return result; 9352 if (Kind != CK_NoOp && ConvertRHS) 9353 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9354 Kind = CK_NonAtomicToAtomic; 9355 return Compatible; 9356 } 9357 9358 // If the left-hand side is a reference type, then we are in a 9359 // (rare!) case where we've allowed the use of references in C, 9360 // e.g., as a parameter type in a built-in function. In this case, 9361 // just make sure that the type referenced is compatible with the 9362 // right-hand side type. The caller is responsible for adjusting 9363 // LHSType so that the resulting expression does not have reference 9364 // type. 9365 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9366 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9367 Kind = CK_LValueBitCast; 9368 return Compatible; 9369 } 9370 return Incompatible; 9371 } 9372 9373 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9374 // to the same ExtVector type. 9375 if (LHSType->isExtVectorType()) { 9376 if (RHSType->isExtVectorType()) 9377 return Incompatible; 9378 if (RHSType->isArithmeticType()) { 9379 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9380 if (ConvertRHS) 9381 RHS = prepareVectorSplat(LHSType, RHS.get()); 9382 Kind = CK_VectorSplat; 9383 return Compatible; 9384 } 9385 } 9386 9387 // Conversions to or from vector type. 9388 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9389 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9390 // Allow assignments of an AltiVec vector type to an equivalent GCC 9391 // vector type and vice versa 9392 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9393 Kind = CK_BitCast; 9394 return Compatible; 9395 } 9396 9397 // If we are allowing lax vector conversions, and LHS and RHS are both 9398 // vectors, the total size only needs to be the same. This is a bitcast; 9399 // no bits are changed but the result type is different. 9400 if (isLaxVectorConversion(RHSType, LHSType)) { 9401 Kind = CK_BitCast; 9402 return IncompatibleVectors; 9403 } 9404 } 9405 9406 // When the RHS comes from another lax conversion (e.g. binops between 9407 // scalars and vectors) the result is canonicalized as a vector. When the 9408 // LHS is also a vector, the lax is allowed by the condition above. Handle 9409 // the case where LHS is a scalar. 9410 if (LHSType->isScalarType()) { 9411 const VectorType *VecType = RHSType->getAs<VectorType>(); 9412 if (VecType && VecType->getNumElements() == 1 && 9413 isLaxVectorConversion(RHSType, LHSType)) { 9414 ExprResult *VecExpr = &RHS; 9415 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9416 Kind = CK_BitCast; 9417 return Compatible; 9418 } 9419 } 9420 9421 // Allow assignments between fixed-length and sizeless SVE vectors. 9422 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9423 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9424 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9425 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9426 Kind = CK_BitCast; 9427 return Compatible; 9428 } 9429 9430 return Incompatible; 9431 } 9432 9433 // Diagnose attempts to convert between __ibm128, __float128 and long double 9434 // where such conversions currently can't be handled. 9435 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9436 return Incompatible; 9437 9438 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9439 // discards the imaginary part. 9440 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9441 !LHSType->getAs<ComplexType>()) 9442 return Incompatible; 9443 9444 // Arithmetic conversions. 9445 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9446 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9447 if (ConvertRHS) 9448 Kind = PrepareScalarCast(RHS, LHSType); 9449 return Compatible; 9450 } 9451 9452 // Conversions to normal pointers. 9453 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9454 // U* -> T* 9455 if (isa<PointerType>(RHSType)) { 9456 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9457 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9458 if (AddrSpaceL != AddrSpaceR) 9459 Kind = CK_AddressSpaceConversion; 9460 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9461 Kind = CK_NoOp; 9462 else 9463 Kind = CK_BitCast; 9464 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9465 } 9466 9467 // int -> T* 9468 if (RHSType->isIntegerType()) { 9469 Kind = CK_IntegralToPointer; // FIXME: null? 9470 return IntToPointer; 9471 } 9472 9473 // C pointers are not compatible with ObjC object pointers, 9474 // with two exceptions: 9475 if (isa<ObjCObjectPointerType>(RHSType)) { 9476 // - conversions to void* 9477 if (LHSPointer->getPointeeType()->isVoidType()) { 9478 Kind = CK_BitCast; 9479 return Compatible; 9480 } 9481 9482 // - conversions from 'Class' to the redefinition type 9483 if (RHSType->isObjCClassType() && 9484 Context.hasSameType(LHSType, 9485 Context.getObjCClassRedefinitionType())) { 9486 Kind = CK_BitCast; 9487 return Compatible; 9488 } 9489 9490 Kind = CK_BitCast; 9491 return IncompatiblePointer; 9492 } 9493 9494 // U^ -> void* 9495 if (RHSType->getAs<BlockPointerType>()) { 9496 if (LHSPointer->getPointeeType()->isVoidType()) { 9497 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9498 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9499 ->getPointeeType() 9500 .getAddressSpace(); 9501 Kind = 9502 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9503 return Compatible; 9504 } 9505 } 9506 9507 return Incompatible; 9508 } 9509 9510 // Conversions to block pointers. 9511 if (isa<BlockPointerType>(LHSType)) { 9512 // U^ -> T^ 9513 if (RHSType->isBlockPointerType()) { 9514 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9515 ->getPointeeType() 9516 .getAddressSpace(); 9517 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9518 ->getPointeeType() 9519 .getAddressSpace(); 9520 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9521 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9522 } 9523 9524 // int or null -> T^ 9525 if (RHSType->isIntegerType()) { 9526 Kind = CK_IntegralToPointer; // FIXME: null 9527 return IntToBlockPointer; 9528 } 9529 9530 // id -> T^ 9531 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9532 Kind = CK_AnyPointerToBlockPointerCast; 9533 return Compatible; 9534 } 9535 9536 // void* -> T^ 9537 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9538 if (RHSPT->getPointeeType()->isVoidType()) { 9539 Kind = CK_AnyPointerToBlockPointerCast; 9540 return Compatible; 9541 } 9542 9543 return Incompatible; 9544 } 9545 9546 // Conversions to Objective-C pointers. 9547 if (isa<ObjCObjectPointerType>(LHSType)) { 9548 // A* -> B* 9549 if (RHSType->isObjCObjectPointerType()) { 9550 Kind = CK_BitCast; 9551 Sema::AssignConvertType result = 9552 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9553 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9554 result == Compatible && 9555 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9556 result = IncompatibleObjCWeakRef; 9557 return result; 9558 } 9559 9560 // int or null -> A* 9561 if (RHSType->isIntegerType()) { 9562 Kind = CK_IntegralToPointer; // FIXME: null 9563 return IntToPointer; 9564 } 9565 9566 // In general, C pointers are not compatible with ObjC object pointers, 9567 // with two exceptions: 9568 if (isa<PointerType>(RHSType)) { 9569 Kind = CK_CPointerToObjCPointerCast; 9570 9571 // - conversions from 'void*' 9572 if (RHSType->isVoidPointerType()) { 9573 return Compatible; 9574 } 9575 9576 // - conversions to 'Class' from its redefinition type 9577 if (LHSType->isObjCClassType() && 9578 Context.hasSameType(RHSType, 9579 Context.getObjCClassRedefinitionType())) { 9580 return Compatible; 9581 } 9582 9583 return IncompatiblePointer; 9584 } 9585 9586 // Only under strict condition T^ is compatible with an Objective-C pointer. 9587 if (RHSType->isBlockPointerType() && 9588 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9589 if (ConvertRHS) 9590 maybeExtendBlockObject(RHS); 9591 Kind = CK_BlockPointerToObjCPointerCast; 9592 return Compatible; 9593 } 9594 9595 return Incompatible; 9596 } 9597 9598 // Conversions from pointers that are not covered by the above. 9599 if (isa<PointerType>(RHSType)) { 9600 // T* -> _Bool 9601 if (LHSType == Context.BoolTy) { 9602 Kind = CK_PointerToBoolean; 9603 return Compatible; 9604 } 9605 9606 // T* -> int 9607 if (LHSType->isIntegerType()) { 9608 Kind = CK_PointerToIntegral; 9609 return PointerToInt; 9610 } 9611 9612 return Incompatible; 9613 } 9614 9615 // Conversions from Objective-C pointers that are not covered by the above. 9616 if (isa<ObjCObjectPointerType>(RHSType)) { 9617 // T* -> _Bool 9618 if (LHSType == Context.BoolTy) { 9619 Kind = CK_PointerToBoolean; 9620 return Compatible; 9621 } 9622 9623 // T* -> int 9624 if (LHSType->isIntegerType()) { 9625 Kind = CK_PointerToIntegral; 9626 return PointerToInt; 9627 } 9628 9629 return Incompatible; 9630 } 9631 9632 // struct A -> struct B 9633 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9634 if (Context.typesAreCompatible(LHSType, RHSType)) { 9635 Kind = CK_NoOp; 9636 return Compatible; 9637 } 9638 } 9639 9640 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9641 Kind = CK_IntToOCLSampler; 9642 return Compatible; 9643 } 9644 9645 return Incompatible; 9646 } 9647 9648 /// Constructs a transparent union from an expression that is 9649 /// used to initialize the transparent union. 9650 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9651 ExprResult &EResult, QualType UnionType, 9652 FieldDecl *Field) { 9653 // Build an initializer list that designates the appropriate member 9654 // of the transparent union. 9655 Expr *E = EResult.get(); 9656 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9657 E, SourceLocation()); 9658 Initializer->setType(UnionType); 9659 Initializer->setInitializedFieldInUnion(Field); 9660 9661 // Build a compound literal constructing a value of the transparent 9662 // union type from this initializer list. 9663 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9664 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9665 VK_PRValue, Initializer, false); 9666 } 9667 9668 Sema::AssignConvertType 9669 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9670 ExprResult &RHS) { 9671 QualType RHSType = RHS.get()->getType(); 9672 9673 // If the ArgType is a Union type, we want to handle a potential 9674 // transparent_union GCC extension. 9675 const RecordType *UT = ArgType->getAsUnionType(); 9676 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9677 return Incompatible; 9678 9679 // The field to initialize within the transparent union. 9680 RecordDecl *UD = UT->getDecl(); 9681 FieldDecl *InitField = nullptr; 9682 // It's compatible if the expression matches any of the fields. 9683 for (auto *it : UD->fields()) { 9684 if (it->getType()->isPointerType()) { 9685 // If the transparent union contains a pointer type, we allow: 9686 // 1) void pointer 9687 // 2) null pointer constant 9688 if (RHSType->isPointerType()) 9689 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9690 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9691 InitField = it; 9692 break; 9693 } 9694 9695 if (RHS.get()->isNullPointerConstant(Context, 9696 Expr::NPC_ValueDependentIsNull)) { 9697 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9698 CK_NullToPointer); 9699 InitField = it; 9700 break; 9701 } 9702 } 9703 9704 CastKind Kind; 9705 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9706 == Compatible) { 9707 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9708 InitField = it; 9709 break; 9710 } 9711 } 9712 9713 if (!InitField) 9714 return Incompatible; 9715 9716 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9717 return Compatible; 9718 } 9719 9720 Sema::AssignConvertType 9721 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9722 bool Diagnose, 9723 bool DiagnoseCFAudited, 9724 bool ConvertRHS) { 9725 // We need to be able to tell the caller whether we diagnosed a problem, if 9726 // they ask us to issue diagnostics. 9727 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9728 9729 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9730 // we can't avoid *all* modifications at the moment, so we need some somewhere 9731 // to put the updated value. 9732 ExprResult LocalRHS = CallerRHS; 9733 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9734 9735 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9736 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9737 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9738 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9739 Diag(RHS.get()->getExprLoc(), 9740 diag::warn_noderef_to_dereferenceable_pointer) 9741 << RHS.get()->getSourceRange(); 9742 } 9743 } 9744 } 9745 9746 if (getLangOpts().CPlusPlus) { 9747 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9748 // C++ 5.17p3: If the left operand is not of class type, the 9749 // expression is implicitly converted (C++ 4) to the 9750 // cv-unqualified type of the left operand. 9751 QualType RHSType = RHS.get()->getType(); 9752 if (Diagnose) { 9753 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9754 AA_Assigning); 9755 } else { 9756 ImplicitConversionSequence ICS = 9757 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9758 /*SuppressUserConversions=*/false, 9759 AllowedExplicit::None, 9760 /*InOverloadResolution=*/false, 9761 /*CStyle=*/false, 9762 /*AllowObjCWritebackConversion=*/false); 9763 if (ICS.isFailure()) 9764 return Incompatible; 9765 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9766 ICS, AA_Assigning); 9767 } 9768 if (RHS.isInvalid()) 9769 return Incompatible; 9770 Sema::AssignConvertType result = Compatible; 9771 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9772 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9773 result = IncompatibleObjCWeakRef; 9774 return result; 9775 } 9776 9777 // FIXME: Currently, we fall through and treat C++ classes like C 9778 // structures. 9779 // FIXME: We also fall through for atomics; not sure what should 9780 // happen there, though. 9781 } else if (RHS.get()->getType() == Context.OverloadTy) { 9782 // As a set of extensions to C, we support overloading on functions. These 9783 // functions need to be resolved here. 9784 DeclAccessPair DAP; 9785 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9786 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9787 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9788 else 9789 return Incompatible; 9790 } 9791 9792 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9793 // a null pointer constant. 9794 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9795 LHSType->isBlockPointerType()) && 9796 RHS.get()->isNullPointerConstant(Context, 9797 Expr::NPC_ValueDependentIsNull)) { 9798 if (Diagnose || ConvertRHS) { 9799 CastKind Kind; 9800 CXXCastPath Path; 9801 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9802 /*IgnoreBaseAccess=*/false, Diagnose); 9803 if (ConvertRHS) 9804 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9805 } 9806 return Compatible; 9807 } 9808 9809 // OpenCL queue_t type assignment. 9810 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9811 Context, Expr::NPC_ValueDependentIsNull)) { 9812 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9813 return Compatible; 9814 } 9815 9816 // This check seems unnatural, however it is necessary to ensure the proper 9817 // conversion of functions/arrays. If the conversion were done for all 9818 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9819 // expressions that suppress this implicit conversion (&, sizeof). 9820 // 9821 // Suppress this for references: C++ 8.5.3p5. 9822 if (!LHSType->isReferenceType()) { 9823 // FIXME: We potentially allocate here even if ConvertRHS is false. 9824 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9825 if (RHS.isInvalid()) 9826 return Incompatible; 9827 } 9828 CastKind Kind; 9829 Sema::AssignConvertType result = 9830 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9831 9832 // C99 6.5.16.1p2: The value of the right operand is converted to the 9833 // type of the assignment expression. 9834 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9835 // so that we can use references in built-in functions even in C. 9836 // The getNonReferenceType() call makes sure that the resulting expression 9837 // does not have reference type. 9838 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9839 QualType Ty = LHSType.getNonLValueExprType(Context); 9840 Expr *E = RHS.get(); 9841 9842 // Check for various Objective-C errors. If we are not reporting 9843 // diagnostics and just checking for errors, e.g., during overload 9844 // resolution, return Incompatible to indicate the failure. 9845 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9846 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9847 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9848 if (!Diagnose) 9849 return Incompatible; 9850 } 9851 if (getLangOpts().ObjC && 9852 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9853 E->getType(), E, Diagnose) || 9854 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9855 if (!Diagnose) 9856 return Incompatible; 9857 // Replace the expression with a corrected version and continue so we 9858 // can find further errors. 9859 RHS = E; 9860 return Compatible; 9861 } 9862 9863 if (ConvertRHS) 9864 RHS = ImpCastExprToType(E, Ty, Kind); 9865 } 9866 9867 return result; 9868 } 9869 9870 namespace { 9871 /// The original operand to an operator, prior to the application of the usual 9872 /// arithmetic conversions and converting the arguments of a builtin operator 9873 /// candidate. 9874 struct OriginalOperand { 9875 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9876 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9877 Op = MTE->getSubExpr(); 9878 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9879 Op = BTE->getSubExpr(); 9880 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9881 Orig = ICE->getSubExprAsWritten(); 9882 Conversion = ICE->getConversionFunction(); 9883 } 9884 } 9885 9886 QualType getType() const { return Orig->getType(); } 9887 9888 Expr *Orig; 9889 NamedDecl *Conversion; 9890 }; 9891 } 9892 9893 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9894 ExprResult &RHS) { 9895 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9896 9897 Diag(Loc, diag::err_typecheck_invalid_operands) 9898 << OrigLHS.getType() << OrigRHS.getType() 9899 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9900 9901 // If a user-defined conversion was applied to either of the operands prior 9902 // to applying the built-in operator rules, tell the user about it. 9903 if (OrigLHS.Conversion) { 9904 Diag(OrigLHS.Conversion->getLocation(), 9905 diag::note_typecheck_invalid_operands_converted) 9906 << 0 << LHS.get()->getType(); 9907 } 9908 if (OrigRHS.Conversion) { 9909 Diag(OrigRHS.Conversion->getLocation(), 9910 diag::note_typecheck_invalid_operands_converted) 9911 << 1 << RHS.get()->getType(); 9912 } 9913 9914 return QualType(); 9915 } 9916 9917 // Diagnose cases where a scalar was implicitly converted to a vector and 9918 // diagnose the underlying types. Otherwise, diagnose the error 9919 // as invalid vector logical operands for non-C++ cases. 9920 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9921 ExprResult &RHS) { 9922 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9923 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9924 9925 bool LHSNatVec = LHSType->isVectorType(); 9926 bool RHSNatVec = RHSType->isVectorType(); 9927 9928 if (!(LHSNatVec && RHSNatVec)) { 9929 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9930 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9931 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9932 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9933 << Vector->getSourceRange(); 9934 return QualType(); 9935 } 9936 9937 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9938 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9939 << RHS.get()->getSourceRange(); 9940 9941 return QualType(); 9942 } 9943 9944 /// Try to convert a value of non-vector type to a vector type by converting 9945 /// the type to the element type of the vector and then performing a splat. 9946 /// If the language is OpenCL, we only use conversions that promote scalar 9947 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9948 /// for float->int. 9949 /// 9950 /// OpenCL V2.0 6.2.6.p2: 9951 /// An error shall occur if any scalar operand type has greater rank 9952 /// than the type of the vector element. 9953 /// 9954 /// \param scalar - if non-null, actually perform the conversions 9955 /// \return true if the operation fails (but without diagnosing the failure) 9956 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9957 QualType scalarTy, 9958 QualType vectorEltTy, 9959 QualType vectorTy, 9960 unsigned &DiagID) { 9961 // The conversion to apply to the scalar before splatting it, 9962 // if necessary. 9963 CastKind scalarCast = CK_NoOp; 9964 9965 if (vectorEltTy->isIntegralType(S.Context)) { 9966 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9967 (scalarTy->isIntegerType() && 9968 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9969 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9970 return true; 9971 } 9972 if (!scalarTy->isIntegralType(S.Context)) 9973 return true; 9974 scalarCast = CK_IntegralCast; 9975 } else if (vectorEltTy->isRealFloatingType()) { 9976 if (scalarTy->isRealFloatingType()) { 9977 if (S.getLangOpts().OpenCL && 9978 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9979 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9980 return true; 9981 } 9982 scalarCast = CK_FloatingCast; 9983 } 9984 else if (scalarTy->isIntegralType(S.Context)) 9985 scalarCast = CK_IntegralToFloating; 9986 else 9987 return true; 9988 } else { 9989 return true; 9990 } 9991 9992 // Adjust scalar if desired. 9993 if (scalar) { 9994 if (scalarCast != CK_NoOp) 9995 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9996 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9997 } 9998 return false; 9999 } 10000 10001 /// Convert vector E to a vector with the same number of elements but different 10002 /// element type. 10003 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 10004 const auto *VecTy = E->getType()->getAs<VectorType>(); 10005 assert(VecTy && "Expression E must be a vector"); 10006 QualType NewVecTy = S.Context.getVectorType(ElementType, 10007 VecTy->getNumElements(), 10008 VecTy->getVectorKind()); 10009 10010 // Look through the implicit cast. Return the subexpression if its type is 10011 // NewVecTy. 10012 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10013 if (ICE->getSubExpr()->getType() == NewVecTy) 10014 return ICE->getSubExpr(); 10015 10016 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 10017 return S.ImpCastExprToType(E, NewVecTy, Cast); 10018 } 10019 10020 /// Test if a (constant) integer Int can be casted to another integer type 10021 /// IntTy without losing precision. 10022 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 10023 QualType OtherIntTy) { 10024 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10025 10026 // Reject cases where the value of the Int is unknown as that would 10027 // possibly cause truncation, but accept cases where the scalar can be 10028 // demoted without loss of precision. 10029 Expr::EvalResult EVResult; 10030 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10031 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 10032 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 10033 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 10034 10035 if (CstInt) { 10036 // If the scalar is constant and is of a higher order and has more active 10037 // bits that the vector element type, reject it. 10038 llvm::APSInt Result = EVResult.Val.getInt(); 10039 unsigned NumBits = IntSigned 10040 ? (Result.isNegative() ? Result.getMinSignedBits() 10041 : Result.getActiveBits()) 10042 : Result.getActiveBits(); 10043 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 10044 return true; 10045 10046 // If the signedness of the scalar type and the vector element type 10047 // differs and the number of bits is greater than that of the vector 10048 // element reject it. 10049 return (IntSigned != OtherIntSigned && 10050 NumBits > S.Context.getIntWidth(OtherIntTy)); 10051 } 10052 10053 // Reject cases where the value of the scalar is not constant and it's 10054 // order is greater than that of the vector element type. 10055 return (Order < 0); 10056 } 10057 10058 /// Test if a (constant) integer Int can be casted to floating point type 10059 /// FloatTy without losing precision. 10060 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 10061 QualType FloatTy) { 10062 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10063 10064 // Determine if the integer constant can be expressed as a floating point 10065 // number of the appropriate type. 10066 Expr::EvalResult EVResult; 10067 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10068 10069 uint64_t Bits = 0; 10070 if (CstInt) { 10071 // Reject constants that would be truncated if they were converted to 10072 // the floating point type. Test by simple to/from conversion. 10073 // FIXME: Ideally the conversion to an APFloat and from an APFloat 10074 // could be avoided if there was a convertFromAPInt method 10075 // which could signal back if implicit truncation occurred. 10076 llvm::APSInt Result = EVResult.Val.getInt(); 10077 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 10078 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 10079 llvm::APFloat::rmTowardZero); 10080 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 10081 !IntTy->hasSignedIntegerRepresentation()); 10082 bool Ignored = false; 10083 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 10084 &Ignored); 10085 if (Result != ConvertBack) 10086 return true; 10087 } else { 10088 // Reject types that cannot be fully encoded into the mantissa of 10089 // the float. 10090 Bits = S.Context.getTypeSize(IntTy); 10091 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 10092 S.Context.getFloatTypeSemantics(FloatTy)); 10093 if (Bits > FloatPrec) 10094 return true; 10095 } 10096 10097 return false; 10098 } 10099 10100 /// Attempt to convert and splat Scalar into a vector whose types matches 10101 /// Vector following GCC conversion rules. The rule is that implicit 10102 /// conversion can occur when Scalar can be casted to match Vector's element 10103 /// type without causing truncation of Scalar. 10104 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 10105 ExprResult *Vector) { 10106 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 10107 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 10108 const auto *VT = VectorTy->castAs<VectorType>(); 10109 10110 assert(!isa<ExtVectorType>(VT) && 10111 "ExtVectorTypes should not be handled here!"); 10112 10113 QualType VectorEltTy = VT->getElementType(); 10114 10115 // Reject cases where the vector element type or the scalar element type are 10116 // not integral or floating point types. 10117 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 10118 return true; 10119 10120 // The conversion to apply to the scalar before splatting it, 10121 // if necessary. 10122 CastKind ScalarCast = CK_NoOp; 10123 10124 // Accept cases where the vector elements are integers and the scalar is 10125 // an integer. 10126 // FIXME: Notionally if the scalar was a floating point value with a precise 10127 // integral representation, we could cast it to an appropriate integer 10128 // type and then perform the rest of the checks here. GCC will perform 10129 // this conversion in some cases as determined by the input language. 10130 // We should accept it on a language independent basis. 10131 if (VectorEltTy->isIntegralType(S.Context) && 10132 ScalarTy->isIntegralType(S.Context) && 10133 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10134 10135 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10136 return true; 10137 10138 ScalarCast = CK_IntegralCast; 10139 } else if (VectorEltTy->isIntegralType(S.Context) && 10140 ScalarTy->isRealFloatingType()) { 10141 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10142 ScalarCast = CK_FloatingToIntegral; 10143 else 10144 return true; 10145 } else if (VectorEltTy->isRealFloatingType()) { 10146 if (ScalarTy->isRealFloatingType()) { 10147 10148 // Reject cases where the scalar type is not a constant and has a higher 10149 // Order than the vector element type. 10150 llvm::APFloat Result(0.0); 10151 10152 // Determine whether this is a constant scalar. In the event that the 10153 // value is dependent (and thus cannot be evaluated by the constant 10154 // evaluator), skip the evaluation. This will then diagnose once the 10155 // expression is instantiated. 10156 bool CstScalar = Scalar->get()->isValueDependent() || 10157 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10158 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10159 if (!CstScalar && Order < 0) 10160 return true; 10161 10162 // If the scalar cannot be safely casted to the vector element type, 10163 // reject it. 10164 if (CstScalar) { 10165 bool Truncated = false; 10166 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10167 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10168 if (Truncated) 10169 return true; 10170 } 10171 10172 ScalarCast = CK_FloatingCast; 10173 } else if (ScalarTy->isIntegralType(S.Context)) { 10174 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10175 return true; 10176 10177 ScalarCast = CK_IntegralToFloating; 10178 } else 10179 return true; 10180 } else if (ScalarTy->isEnumeralType()) 10181 return true; 10182 10183 // Adjust scalar if desired. 10184 if (Scalar) { 10185 if (ScalarCast != CK_NoOp) 10186 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10187 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10188 } 10189 return false; 10190 } 10191 10192 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10193 SourceLocation Loc, bool IsCompAssign, 10194 bool AllowBothBool, 10195 bool AllowBoolConversions) { 10196 if (!IsCompAssign) { 10197 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10198 if (LHS.isInvalid()) 10199 return QualType(); 10200 } 10201 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10202 if (RHS.isInvalid()) 10203 return QualType(); 10204 10205 // For conversion purposes, we ignore any qualifiers. 10206 // For example, "const float" and "float" are equivalent. 10207 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10208 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10209 10210 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10211 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10212 assert(LHSVecType || RHSVecType); 10213 10214 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10215 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10216 return InvalidOperands(Loc, LHS, RHS); 10217 10218 // AltiVec-style "vector bool op vector bool" combinations are allowed 10219 // for some operators but not others. 10220 if (!AllowBothBool && 10221 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10222 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10223 return InvalidOperands(Loc, LHS, RHS); 10224 10225 // If the vector types are identical, return. 10226 if (Context.hasSameType(LHSType, RHSType)) 10227 return LHSType; 10228 10229 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10230 if (LHSVecType && RHSVecType && 10231 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10232 if (isa<ExtVectorType>(LHSVecType)) { 10233 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10234 return LHSType; 10235 } 10236 10237 if (!IsCompAssign) 10238 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10239 return RHSType; 10240 } 10241 10242 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10243 // can be mixed, with the result being the non-bool type. The non-bool 10244 // operand must have integer element type. 10245 if (AllowBoolConversions && LHSVecType && RHSVecType && 10246 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10247 (Context.getTypeSize(LHSVecType->getElementType()) == 10248 Context.getTypeSize(RHSVecType->getElementType()))) { 10249 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10250 LHSVecType->getElementType()->isIntegerType() && 10251 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10252 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10253 return LHSType; 10254 } 10255 if (!IsCompAssign && 10256 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10257 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10258 RHSVecType->getElementType()->isIntegerType()) { 10259 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10260 return RHSType; 10261 } 10262 } 10263 10264 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10265 // since the ambiguity can affect the ABI. 10266 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10267 const VectorType *VecType = SecondType->getAs<VectorType>(); 10268 return FirstType->isSizelessBuiltinType() && VecType && 10269 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10270 VecType->getVectorKind() == 10271 VectorType::SveFixedLengthPredicateVector); 10272 }; 10273 10274 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10275 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10276 return QualType(); 10277 } 10278 10279 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10280 // since the ambiguity can affect the ABI. 10281 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10282 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10283 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10284 10285 if (FirstVecType && SecondVecType) 10286 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10287 (SecondVecType->getVectorKind() == 10288 VectorType::SveFixedLengthDataVector || 10289 SecondVecType->getVectorKind() == 10290 VectorType::SveFixedLengthPredicateVector); 10291 10292 return FirstType->isSizelessBuiltinType() && SecondVecType && 10293 SecondVecType->getVectorKind() == VectorType::GenericVector; 10294 }; 10295 10296 if (IsSveGnuConversion(LHSType, RHSType) || 10297 IsSveGnuConversion(RHSType, LHSType)) { 10298 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10299 return QualType(); 10300 } 10301 10302 // If there's a vector type and a scalar, try to convert the scalar to 10303 // the vector element type and splat. 10304 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10305 if (!RHSVecType) { 10306 if (isa<ExtVectorType>(LHSVecType)) { 10307 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10308 LHSVecType->getElementType(), LHSType, 10309 DiagID)) 10310 return LHSType; 10311 } else { 10312 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10313 return LHSType; 10314 } 10315 } 10316 if (!LHSVecType) { 10317 if (isa<ExtVectorType>(RHSVecType)) { 10318 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10319 LHSType, RHSVecType->getElementType(), 10320 RHSType, DiagID)) 10321 return RHSType; 10322 } else { 10323 if (LHS.get()->isLValue() || 10324 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10325 return RHSType; 10326 } 10327 } 10328 10329 // FIXME: The code below also handles conversion between vectors and 10330 // non-scalars, we should break this down into fine grained specific checks 10331 // and emit proper diagnostics. 10332 QualType VecType = LHSVecType ? LHSType : RHSType; 10333 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10334 QualType OtherType = LHSVecType ? RHSType : LHSType; 10335 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10336 if (isLaxVectorConversion(OtherType, VecType)) { 10337 // If we're allowing lax vector conversions, only the total (data) size 10338 // needs to be the same. For non compound assignment, if one of the types is 10339 // scalar, the result is always the vector type. 10340 if (!IsCompAssign) { 10341 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10342 return VecType; 10343 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10344 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10345 // type. Note that this is already done by non-compound assignments in 10346 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10347 // <1 x T> -> T. The result is also a vector type. 10348 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10349 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10350 ExprResult *RHSExpr = &RHS; 10351 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10352 return VecType; 10353 } 10354 } 10355 10356 // Okay, the expression is invalid. 10357 10358 // If there's a non-vector, non-real operand, diagnose that. 10359 if ((!RHSVecType && !RHSType->isRealType()) || 10360 (!LHSVecType && !LHSType->isRealType())) { 10361 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10362 << LHSType << RHSType 10363 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10364 return QualType(); 10365 } 10366 10367 // OpenCL V1.1 6.2.6.p1: 10368 // If the operands are of more than one vector type, then an error shall 10369 // occur. Implicit conversions between vector types are not permitted, per 10370 // section 6.2.1. 10371 if (getLangOpts().OpenCL && 10372 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10373 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10374 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10375 << RHSType; 10376 return QualType(); 10377 } 10378 10379 10380 // If there is a vector type that is not a ExtVector and a scalar, we reach 10381 // this point if scalar could not be converted to the vector's element type 10382 // without truncation. 10383 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10384 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10385 QualType Scalar = LHSVecType ? RHSType : LHSType; 10386 QualType Vector = LHSVecType ? LHSType : RHSType; 10387 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10388 Diag(Loc, 10389 diag::err_typecheck_vector_not_convertable_implict_truncation) 10390 << ScalarOrVector << Scalar << Vector; 10391 10392 return QualType(); 10393 } 10394 10395 // Otherwise, use the generic diagnostic. 10396 Diag(Loc, DiagID) 10397 << LHSType << RHSType 10398 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10399 return QualType(); 10400 } 10401 10402 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10403 // expression. These are mainly cases where the null pointer is used as an 10404 // integer instead of a pointer. 10405 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10406 SourceLocation Loc, bool IsCompare) { 10407 // The canonical way to check for a GNU null is with isNullPointerConstant, 10408 // but we use a bit of a hack here for speed; this is a relatively 10409 // hot path, and isNullPointerConstant is slow. 10410 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10411 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10412 10413 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10414 10415 // Avoid analyzing cases where the result will either be invalid (and 10416 // diagnosed as such) or entirely valid and not something to warn about. 10417 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10418 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10419 return; 10420 10421 // Comparison operations would not make sense with a null pointer no matter 10422 // what the other expression is. 10423 if (!IsCompare) { 10424 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10425 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10426 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10427 return; 10428 } 10429 10430 // The rest of the operations only make sense with a null pointer 10431 // if the other expression is a pointer. 10432 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10433 NonNullType->canDecayToPointerType()) 10434 return; 10435 10436 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10437 << LHSNull /* LHS is NULL */ << NonNullType 10438 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10439 } 10440 10441 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10442 SourceLocation Loc) { 10443 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10444 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10445 if (!LUE || !RUE) 10446 return; 10447 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10448 RUE->getKind() != UETT_SizeOf) 10449 return; 10450 10451 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10452 QualType LHSTy = LHSArg->getType(); 10453 QualType RHSTy; 10454 10455 if (RUE->isArgumentType()) 10456 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10457 else 10458 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10459 10460 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10461 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10462 return; 10463 10464 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10465 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10466 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10467 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10468 << LHSArgDecl; 10469 } 10470 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10471 QualType ArrayElemTy = ArrayTy->getElementType(); 10472 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10473 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10474 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10475 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10476 return; 10477 S.Diag(Loc, diag::warn_division_sizeof_array) 10478 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10479 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10480 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10481 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10482 << LHSArgDecl; 10483 } 10484 10485 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10486 } 10487 } 10488 10489 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10490 ExprResult &RHS, 10491 SourceLocation Loc, bool IsDiv) { 10492 // Check for division/remainder by zero. 10493 Expr::EvalResult RHSValue; 10494 if (!RHS.get()->isValueDependent() && 10495 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10496 RHSValue.Val.getInt() == 0) 10497 S.DiagRuntimeBehavior(Loc, RHS.get(), 10498 S.PDiag(diag::warn_remainder_division_by_zero) 10499 << IsDiv << RHS.get()->getSourceRange()); 10500 } 10501 10502 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10503 SourceLocation Loc, 10504 bool IsCompAssign, bool IsDiv) { 10505 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10506 10507 QualType LHSTy = LHS.get()->getType(); 10508 QualType RHSTy = RHS.get()->getType(); 10509 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10510 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10511 /*AllowBothBool*/getLangOpts().AltiVec, 10512 /*AllowBoolConversions*/false); 10513 if (!IsDiv && 10514 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10515 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10516 // For division, only matrix-by-scalar is supported. Other combinations with 10517 // matrix types are invalid. 10518 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10519 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10520 10521 QualType compType = UsualArithmeticConversions( 10522 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10523 if (LHS.isInvalid() || RHS.isInvalid()) 10524 return QualType(); 10525 10526 10527 if (compType.isNull() || !compType->isArithmeticType()) 10528 return InvalidOperands(Loc, LHS, RHS); 10529 if (IsDiv) { 10530 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10531 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10532 } 10533 return compType; 10534 } 10535 10536 QualType Sema::CheckRemainderOperands( 10537 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10538 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10539 10540 if (LHS.get()->getType()->isVectorType() || 10541 RHS.get()->getType()->isVectorType()) { 10542 if (LHS.get()->getType()->hasIntegerRepresentation() && 10543 RHS.get()->getType()->hasIntegerRepresentation()) 10544 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10545 /*AllowBothBool*/getLangOpts().AltiVec, 10546 /*AllowBoolConversions*/false); 10547 return InvalidOperands(Loc, LHS, RHS); 10548 } 10549 10550 QualType compType = UsualArithmeticConversions( 10551 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10552 if (LHS.isInvalid() || RHS.isInvalid()) 10553 return QualType(); 10554 10555 if (compType.isNull() || !compType->isIntegerType()) 10556 return InvalidOperands(Loc, LHS, RHS); 10557 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10558 return compType; 10559 } 10560 10561 /// Diagnose invalid arithmetic on two void pointers. 10562 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10563 Expr *LHSExpr, Expr *RHSExpr) { 10564 S.Diag(Loc, S.getLangOpts().CPlusPlus 10565 ? diag::err_typecheck_pointer_arith_void_type 10566 : diag::ext_gnu_void_ptr) 10567 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10568 << RHSExpr->getSourceRange(); 10569 } 10570 10571 /// Diagnose invalid arithmetic on a void pointer. 10572 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10573 Expr *Pointer) { 10574 S.Diag(Loc, S.getLangOpts().CPlusPlus 10575 ? diag::err_typecheck_pointer_arith_void_type 10576 : diag::ext_gnu_void_ptr) 10577 << 0 /* one pointer */ << Pointer->getSourceRange(); 10578 } 10579 10580 /// Diagnose invalid arithmetic on a null pointer. 10581 /// 10582 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10583 /// idiom, which we recognize as a GNU extension. 10584 /// 10585 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10586 Expr *Pointer, bool IsGNUIdiom) { 10587 if (IsGNUIdiom) 10588 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10589 << Pointer->getSourceRange(); 10590 else 10591 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10592 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10593 } 10594 10595 /// Diagnose invalid subraction on a null pointer. 10596 /// 10597 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10598 Expr *Pointer, bool BothNull) { 10599 // Null - null is valid in C++ [expr.add]p7 10600 if (BothNull && S.getLangOpts().CPlusPlus) 10601 return; 10602 10603 // Is this s a macro from a system header? 10604 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10605 return; 10606 10607 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10608 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10609 } 10610 10611 /// Diagnose invalid arithmetic on two function pointers. 10612 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10613 Expr *LHS, Expr *RHS) { 10614 assert(LHS->getType()->isAnyPointerType()); 10615 assert(RHS->getType()->isAnyPointerType()); 10616 S.Diag(Loc, S.getLangOpts().CPlusPlus 10617 ? diag::err_typecheck_pointer_arith_function_type 10618 : diag::ext_gnu_ptr_func_arith) 10619 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10620 // We only show the second type if it differs from the first. 10621 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10622 RHS->getType()) 10623 << RHS->getType()->getPointeeType() 10624 << LHS->getSourceRange() << RHS->getSourceRange(); 10625 } 10626 10627 /// Diagnose invalid arithmetic on a function pointer. 10628 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10629 Expr *Pointer) { 10630 assert(Pointer->getType()->isAnyPointerType()); 10631 S.Diag(Loc, S.getLangOpts().CPlusPlus 10632 ? diag::err_typecheck_pointer_arith_function_type 10633 : diag::ext_gnu_ptr_func_arith) 10634 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10635 << 0 /* one pointer, so only one type */ 10636 << Pointer->getSourceRange(); 10637 } 10638 10639 /// Emit error if Operand is incomplete pointer type 10640 /// 10641 /// \returns True if pointer has incomplete type 10642 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10643 Expr *Operand) { 10644 QualType ResType = Operand->getType(); 10645 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10646 ResType = ResAtomicType->getValueType(); 10647 10648 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10649 QualType PointeeTy = ResType->getPointeeType(); 10650 return S.RequireCompleteSizedType( 10651 Loc, PointeeTy, 10652 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10653 Operand->getSourceRange()); 10654 } 10655 10656 /// Check the validity of an arithmetic pointer operand. 10657 /// 10658 /// If the operand has pointer type, this code will check for pointer types 10659 /// which are invalid in arithmetic operations. These will be diagnosed 10660 /// appropriately, including whether or not the use is supported as an 10661 /// extension. 10662 /// 10663 /// \returns True when the operand is valid to use (even if as an extension). 10664 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10665 Expr *Operand) { 10666 QualType ResType = Operand->getType(); 10667 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10668 ResType = ResAtomicType->getValueType(); 10669 10670 if (!ResType->isAnyPointerType()) return true; 10671 10672 QualType PointeeTy = ResType->getPointeeType(); 10673 if (PointeeTy->isVoidType()) { 10674 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10675 return !S.getLangOpts().CPlusPlus; 10676 } 10677 if (PointeeTy->isFunctionType()) { 10678 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10679 return !S.getLangOpts().CPlusPlus; 10680 } 10681 10682 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10683 10684 return true; 10685 } 10686 10687 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10688 /// operands. 10689 /// 10690 /// This routine will diagnose any invalid arithmetic on pointer operands much 10691 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10692 /// for emitting a single diagnostic even for operations where both LHS and RHS 10693 /// are (potentially problematic) pointers. 10694 /// 10695 /// \returns True when the operand is valid to use (even if as an extension). 10696 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10697 Expr *LHSExpr, Expr *RHSExpr) { 10698 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10699 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10700 if (!isLHSPointer && !isRHSPointer) return true; 10701 10702 QualType LHSPointeeTy, RHSPointeeTy; 10703 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10704 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10705 10706 // if both are pointers check if operation is valid wrt address spaces 10707 if (isLHSPointer && isRHSPointer) { 10708 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10709 S.Diag(Loc, 10710 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10711 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10712 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10713 return false; 10714 } 10715 } 10716 10717 // Check for arithmetic on pointers to incomplete types. 10718 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10719 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10720 if (isLHSVoidPtr || isRHSVoidPtr) { 10721 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10722 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10723 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10724 10725 return !S.getLangOpts().CPlusPlus; 10726 } 10727 10728 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10729 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10730 if (isLHSFuncPtr || isRHSFuncPtr) { 10731 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10732 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10733 RHSExpr); 10734 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10735 10736 return !S.getLangOpts().CPlusPlus; 10737 } 10738 10739 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10740 return false; 10741 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10742 return false; 10743 10744 return true; 10745 } 10746 10747 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10748 /// literal. 10749 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10750 Expr *LHSExpr, Expr *RHSExpr) { 10751 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10752 Expr* IndexExpr = RHSExpr; 10753 if (!StrExpr) { 10754 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10755 IndexExpr = LHSExpr; 10756 } 10757 10758 bool IsStringPlusInt = StrExpr && 10759 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10760 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10761 return; 10762 10763 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10764 Self.Diag(OpLoc, diag::warn_string_plus_int) 10765 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10766 10767 // Only print a fixit for "str" + int, not for int + "str". 10768 if (IndexExpr == RHSExpr) { 10769 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10770 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10771 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10772 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10773 << FixItHint::CreateInsertion(EndLoc, "]"); 10774 } else 10775 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10776 } 10777 10778 /// Emit a warning when adding a char literal to a string. 10779 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10780 Expr *LHSExpr, Expr *RHSExpr) { 10781 const Expr *StringRefExpr = LHSExpr; 10782 const CharacterLiteral *CharExpr = 10783 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10784 10785 if (!CharExpr) { 10786 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10787 StringRefExpr = RHSExpr; 10788 } 10789 10790 if (!CharExpr || !StringRefExpr) 10791 return; 10792 10793 const QualType StringType = StringRefExpr->getType(); 10794 10795 // Return if not a PointerType. 10796 if (!StringType->isAnyPointerType()) 10797 return; 10798 10799 // Return if not a CharacterType. 10800 if (!StringType->getPointeeType()->isAnyCharacterType()) 10801 return; 10802 10803 ASTContext &Ctx = Self.getASTContext(); 10804 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10805 10806 const QualType CharType = CharExpr->getType(); 10807 if (!CharType->isAnyCharacterType() && 10808 CharType->isIntegerType() && 10809 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10810 Self.Diag(OpLoc, diag::warn_string_plus_char) 10811 << DiagRange << Ctx.CharTy; 10812 } else { 10813 Self.Diag(OpLoc, diag::warn_string_plus_char) 10814 << DiagRange << CharExpr->getType(); 10815 } 10816 10817 // Only print a fixit for str + char, not for char + str. 10818 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10819 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10820 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10821 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10822 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10823 << FixItHint::CreateInsertion(EndLoc, "]"); 10824 } else { 10825 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10826 } 10827 } 10828 10829 /// Emit error when two pointers are incompatible. 10830 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10831 Expr *LHSExpr, Expr *RHSExpr) { 10832 assert(LHSExpr->getType()->isAnyPointerType()); 10833 assert(RHSExpr->getType()->isAnyPointerType()); 10834 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10835 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10836 << RHSExpr->getSourceRange(); 10837 } 10838 10839 // C99 6.5.6 10840 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10841 SourceLocation Loc, BinaryOperatorKind Opc, 10842 QualType* CompLHSTy) { 10843 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10844 10845 if (LHS.get()->getType()->isVectorType() || 10846 RHS.get()->getType()->isVectorType()) { 10847 QualType compType = CheckVectorOperands( 10848 LHS, RHS, Loc, CompLHSTy, 10849 /*AllowBothBool*/getLangOpts().AltiVec, 10850 /*AllowBoolConversions*/getLangOpts().ZVector); 10851 if (CompLHSTy) *CompLHSTy = compType; 10852 return compType; 10853 } 10854 10855 if (LHS.get()->getType()->isConstantMatrixType() || 10856 RHS.get()->getType()->isConstantMatrixType()) { 10857 QualType compType = 10858 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10859 if (CompLHSTy) 10860 *CompLHSTy = compType; 10861 return compType; 10862 } 10863 10864 QualType compType = UsualArithmeticConversions( 10865 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10866 if (LHS.isInvalid() || RHS.isInvalid()) 10867 return QualType(); 10868 10869 // Diagnose "string literal" '+' int and string '+' "char literal". 10870 if (Opc == BO_Add) { 10871 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10872 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10873 } 10874 10875 // handle the common case first (both operands are arithmetic). 10876 if (!compType.isNull() && compType->isArithmeticType()) { 10877 if (CompLHSTy) *CompLHSTy = compType; 10878 return compType; 10879 } 10880 10881 // Type-checking. Ultimately the pointer's going to be in PExp; 10882 // note that we bias towards the LHS being the pointer. 10883 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10884 10885 bool isObjCPointer; 10886 if (PExp->getType()->isPointerType()) { 10887 isObjCPointer = false; 10888 } else if (PExp->getType()->isObjCObjectPointerType()) { 10889 isObjCPointer = true; 10890 } else { 10891 std::swap(PExp, IExp); 10892 if (PExp->getType()->isPointerType()) { 10893 isObjCPointer = false; 10894 } else if (PExp->getType()->isObjCObjectPointerType()) { 10895 isObjCPointer = true; 10896 } else { 10897 return InvalidOperands(Loc, LHS, RHS); 10898 } 10899 } 10900 assert(PExp->getType()->isAnyPointerType()); 10901 10902 if (!IExp->getType()->isIntegerType()) 10903 return InvalidOperands(Loc, LHS, RHS); 10904 10905 // Adding to a null pointer results in undefined behavior. 10906 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10907 Context, Expr::NPC_ValueDependentIsNotNull)) { 10908 // In C++ adding zero to a null pointer is defined. 10909 Expr::EvalResult KnownVal; 10910 if (!getLangOpts().CPlusPlus || 10911 (!IExp->isValueDependent() && 10912 (!IExp->EvaluateAsInt(KnownVal, Context) || 10913 KnownVal.Val.getInt() != 0))) { 10914 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10915 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10916 Context, BO_Add, PExp, IExp); 10917 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10918 } 10919 } 10920 10921 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10922 return QualType(); 10923 10924 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10925 return QualType(); 10926 10927 // Check array bounds for pointer arithemtic 10928 CheckArrayAccess(PExp, IExp); 10929 10930 if (CompLHSTy) { 10931 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10932 if (LHSTy.isNull()) { 10933 LHSTy = LHS.get()->getType(); 10934 if (LHSTy->isPromotableIntegerType()) 10935 LHSTy = Context.getPromotedIntegerType(LHSTy); 10936 } 10937 *CompLHSTy = LHSTy; 10938 } 10939 10940 return PExp->getType(); 10941 } 10942 10943 // C99 6.5.6 10944 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10945 SourceLocation Loc, 10946 QualType* CompLHSTy) { 10947 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10948 10949 if (LHS.get()->getType()->isVectorType() || 10950 RHS.get()->getType()->isVectorType()) { 10951 QualType compType = CheckVectorOperands( 10952 LHS, RHS, Loc, CompLHSTy, 10953 /*AllowBothBool*/getLangOpts().AltiVec, 10954 /*AllowBoolConversions*/getLangOpts().ZVector); 10955 if (CompLHSTy) *CompLHSTy = compType; 10956 return compType; 10957 } 10958 10959 if (LHS.get()->getType()->isConstantMatrixType() || 10960 RHS.get()->getType()->isConstantMatrixType()) { 10961 QualType compType = 10962 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10963 if (CompLHSTy) 10964 *CompLHSTy = compType; 10965 return compType; 10966 } 10967 10968 QualType compType = UsualArithmeticConversions( 10969 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10970 if (LHS.isInvalid() || RHS.isInvalid()) 10971 return QualType(); 10972 10973 // Enforce type constraints: C99 6.5.6p3. 10974 10975 // Handle the common case first (both operands are arithmetic). 10976 if (!compType.isNull() && compType->isArithmeticType()) { 10977 if (CompLHSTy) *CompLHSTy = compType; 10978 return compType; 10979 } 10980 10981 // Either ptr - int or ptr - ptr. 10982 if (LHS.get()->getType()->isAnyPointerType()) { 10983 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10984 10985 // Diagnose bad cases where we step over interface counts. 10986 if (LHS.get()->getType()->isObjCObjectPointerType() && 10987 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10988 return QualType(); 10989 10990 // The result type of a pointer-int computation is the pointer type. 10991 if (RHS.get()->getType()->isIntegerType()) { 10992 // Subtracting from a null pointer should produce a warning. 10993 // The last argument to the diagnose call says this doesn't match the 10994 // GNU int-to-pointer idiom. 10995 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10996 Expr::NPC_ValueDependentIsNotNull)) { 10997 // In C++ adding zero to a null pointer is defined. 10998 Expr::EvalResult KnownVal; 10999 if (!getLangOpts().CPlusPlus || 11000 (!RHS.get()->isValueDependent() && 11001 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 11002 KnownVal.Val.getInt() != 0))) { 11003 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 11004 } 11005 } 11006 11007 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 11008 return QualType(); 11009 11010 // Check array bounds for pointer arithemtic 11011 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 11012 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 11013 11014 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11015 return LHS.get()->getType(); 11016 } 11017 11018 // Handle pointer-pointer subtractions. 11019 if (const PointerType *RHSPTy 11020 = RHS.get()->getType()->getAs<PointerType>()) { 11021 QualType rpointee = RHSPTy->getPointeeType(); 11022 11023 if (getLangOpts().CPlusPlus) { 11024 // Pointee types must be the same: C++ [expr.add] 11025 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 11026 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11027 } 11028 } else { 11029 // Pointee types must be compatible C99 6.5.6p3 11030 if (!Context.typesAreCompatible( 11031 Context.getCanonicalType(lpointee).getUnqualifiedType(), 11032 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 11033 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11034 return QualType(); 11035 } 11036 } 11037 11038 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 11039 LHS.get(), RHS.get())) 11040 return QualType(); 11041 11042 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11043 Context, Expr::NPC_ValueDependentIsNotNull); 11044 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11045 Context, Expr::NPC_ValueDependentIsNotNull); 11046 11047 // Subtracting nullptr or from nullptr is suspect 11048 if (LHSIsNullPtr) 11049 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 11050 if (RHSIsNullPtr) 11051 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 11052 11053 // The pointee type may have zero size. As an extension, a structure or 11054 // union may have zero size or an array may have zero length. In this 11055 // case subtraction does not make sense. 11056 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 11057 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 11058 if (ElementSize.isZero()) { 11059 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 11060 << rpointee.getUnqualifiedType() 11061 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11062 } 11063 } 11064 11065 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11066 return Context.getPointerDiffType(); 11067 } 11068 } 11069 11070 return InvalidOperands(Loc, LHS, RHS); 11071 } 11072 11073 static bool isScopedEnumerationType(QualType T) { 11074 if (const EnumType *ET = T->getAs<EnumType>()) 11075 return ET->getDecl()->isScoped(); 11076 return false; 11077 } 11078 11079 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 11080 SourceLocation Loc, BinaryOperatorKind Opc, 11081 QualType LHSType) { 11082 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 11083 // so skip remaining warnings as we don't want to modify values within Sema. 11084 if (S.getLangOpts().OpenCL) 11085 return; 11086 11087 // Check right/shifter operand 11088 Expr::EvalResult RHSResult; 11089 if (RHS.get()->isValueDependent() || 11090 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 11091 return; 11092 llvm::APSInt Right = RHSResult.Val.getInt(); 11093 11094 if (Right.isNegative()) { 11095 S.DiagRuntimeBehavior(Loc, RHS.get(), 11096 S.PDiag(diag::warn_shift_negative) 11097 << RHS.get()->getSourceRange()); 11098 return; 11099 } 11100 11101 QualType LHSExprType = LHS.get()->getType(); 11102 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 11103 if (LHSExprType->isBitIntType()) 11104 LeftSize = S.Context.getIntWidth(LHSExprType); 11105 else if (LHSExprType->isFixedPointType()) { 11106 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 11107 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 11108 } 11109 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 11110 if (Right.uge(LeftBits)) { 11111 S.DiagRuntimeBehavior(Loc, RHS.get(), 11112 S.PDiag(diag::warn_shift_gt_typewidth) 11113 << RHS.get()->getSourceRange()); 11114 return; 11115 } 11116 11117 // FIXME: We probably need to handle fixed point types specially here. 11118 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 11119 return; 11120 11121 // When left shifting an ICE which is signed, we can check for overflow which 11122 // according to C++ standards prior to C++2a has undefined behavior 11123 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 11124 // more than the maximum value representable in the result type, so never 11125 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11126 // expression is still probably a bug.) 11127 Expr::EvalResult LHSResult; 11128 if (LHS.get()->isValueDependent() || 11129 LHSType->hasUnsignedIntegerRepresentation() || 11130 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11131 return; 11132 llvm::APSInt Left = LHSResult.Val.getInt(); 11133 11134 // If LHS does not have a signed type and non-negative value 11135 // then, the behavior is undefined before C++2a. Warn about it. 11136 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11137 !S.getLangOpts().CPlusPlus20) { 11138 S.DiagRuntimeBehavior(Loc, LHS.get(), 11139 S.PDiag(diag::warn_shift_lhs_negative) 11140 << LHS.get()->getSourceRange()); 11141 return; 11142 } 11143 11144 llvm::APInt ResultBits = 11145 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11146 if (LeftBits.uge(ResultBits)) 11147 return; 11148 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11149 Result = Result.shl(Right); 11150 11151 // Print the bit representation of the signed integer as an unsigned 11152 // hexadecimal number. 11153 SmallString<40> HexResult; 11154 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11155 11156 // If we are only missing a sign bit, this is less likely to result in actual 11157 // bugs -- if the result is cast back to an unsigned type, it will have the 11158 // expected value. Thus we place this behind a different warning that can be 11159 // turned off separately if needed. 11160 if (LeftBits == ResultBits - 1) { 11161 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11162 << HexResult << LHSType 11163 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11164 return; 11165 } 11166 11167 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11168 << HexResult.str() << Result.getMinSignedBits() << LHSType 11169 << Left.getBitWidth() << LHS.get()->getSourceRange() 11170 << RHS.get()->getSourceRange(); 11171 } 11172 11173 /// Return the resulting type when a vector is shifted 11174 /// by a scalar or vector shift amount. 11175 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11176 SourceLocation Loc, bool IsCompAssign) { 11177 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11178 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11179 !LHS.get()->getType()->isVectorType()) { 11180 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11181 << RHS.get()->getType() << LHS.get()->getType() 11182 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11183 return QualType(); 11184 } 11185 11186 if (!IsCompAssign) { 11187 LHS = S.UsualUnaryConversions(LHS.get()); 11188 if (LHS.isInvalid()) return QualType(); 11189 } 11190 11191 RHS = S.UsualUnaryConversions(RHS.get()); 11192 if (RHS.isInvalid()) return QualType(); 11193 11194 QualType LHSType = LHS.get()->getType(); 11195 // Note that LHS might be a scalar because the routine calls not only in 11196 // OpenCL case. 11197 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11198 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11199 11200 // Note that RHS might not be a vector. 11201 QualType RHSType = RHS.get()->getType(); 11202 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11203 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11204 11205 // The operands need to be integers. 11206 if (!LHSEleType->isIntegerType()) { 11207 S.Diag(Loc, diag::err_typecheck_expect_int) 11208 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11209 return QualType(); 11210 } 11211 11212 if (!RHSEleType->isIntegerType()) { 11213 S.Diag(Loc, diag::err_typecheck_expect_int) 11214 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11215 return QualType(); 11216 } 11217 11218 if (!LHSVecTy) { 11219 assert(RHSVecTy); 11220 if (IsCompAssign) 11221 return RHSType; 11222 if (LHSEleType != RHSEleType) { 11223 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11224 LHSEleType = RHSEleType; 11225 } 11226 QualType VecTy = 11227 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11228 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11229 LHSType = VecTy; 11230 } else if (RHSVecTy) { 11231 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11232 // are applied component-wise. So if RHS is a vector, then ensure 11233 // that the number of elements is the same as LHS... 11234 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11235 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11236 << LHS.get()->getType() << RHS.get()->getType() 11237 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11238 return QualType(); 11239 } 11240 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11241 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11242 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11243 if (LHSBT != RHSBT && 11244 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11245 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11246 << LHS.get()->getType() << RHS.get()->getType() 11247 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11248 } 11249 } 11250 } else { 11251 // ...else expand RHS to match the number of elements in LHS. 11252 QualType VecTy = 11253 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11254 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11255 } 11256 11257 return LHSType; 11258 } 11259 11260 // C99 6.5.7 11261 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11262 SourceLocation Loc, BinaryOperatorKind Opc, 11263 bool IsCompAssign) { 11264 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11265 11266 // Vector shifts promote their scalar inputs to vector type. 11267 if (LHS.get()->getType()->isVectorType() || 11268 RHS.get()->getType()->isVectorType()) { 11269 if (LangOpts.ZVector) { 11270 // The shift operators for the z vector extensions work basically 11271 // like general shifts, except that neither the LHS nor the RHS is 11272 // allowed to be a "vector bool". 11273 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11274 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11275 return InvalidOperands(Loc, LHS, RHS); 11276 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11277 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11278 return InvalidOperands(Loc, LHS, RHS); 11279 } 11280 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11281 } 11282 11283 // Shifts don't perform usual arithmetic conversions, they just do integer 11284 // promotions on each operand. C99 6.5.7p3 11285 11286 // For the LHS, do usual unary conversions, but then reset them away 11287 // if this is a compound assignment. 11288 ExprResult OldLHS = LHS; 11289 LHS = UsualUnaryConversions(LHS.get()); 11290 if (LHS.isInvalid()) 11291 return QualType(); 11292 QualType LHSType = LHS.get()->getType(); 11293 if (IsCompAssign) LHS = OldLHS; 11294 11295 // The RHS is simpler. 11296 RHS = UsualUnaryConversions(RHS.get()); 11297 if (RHS.isInvalid()) 11298 return QualType(); 11299 QualType RHSType = RHS.get()->getType(); 11300 11301 // C99 6.5.7p2: Each of the operands shall have integer type. 11302 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11303 if ((!LHSType->isFixedPointOrIntegerType() && 11304 !LHSType->hasIntegerRepresentation()) || 11305 !RHSType->hasIntegerRepresentation()) 11306 return InvalidOperands(Loc, LHS, RHS); 11307 11308 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11309 // hasIntegerRepresentation() above instead of this. 11310 if (isScopedEnumerationType(LHSType) || 11311 isScopedEnumerationType(RHSType)) { 11312 return InvalidOperands(Loc, LHS, RHS); 11313 } 11314 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11315 11316 // "The type of the result is that of the promoted left operand." 11317 return LHSType; 11318 } 11319 11320 /// Diagnose bad pointer comparisons. 11321 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11322 ExprResult &LHS, ExprResult &RHS, 11323 bool IsError) { 11324 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11325 : diag::ext_typecheck_comparison_of_distinct_pointers) 11326 << LHS.get()->getType() << RHS.get()->getType() 11327 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11328 } 11329 11330 /// Returns false if the pointers are converted to a composite type, 11331 /// true otherwise. 11332 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11333 ExprResult &LHS, ExprResult &RHS) { 11334 // C++ [expr.rel]p2: 11335 // [...] Pointer conversions (4.10) and qualification 11336 // conversions (4.4) are performed on pointer operands (or on 11337 // a pointer operand and a null pointer constant) to bring 11338 // them to their composite pointer type. [...] 11339 // 11340 // C++ [expr.eq]p1 uses the same notion for (in)equality 11341 // comparisons of pointers. 11342 11343 QualType LHSType = LHS.get()->getType(); 11344 QualType RHSType = RHS.get()->getType(); 11345 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11346 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11347 11348 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11349 if (T.isNull()) { 11350 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11351 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11352 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11353 else 11354 S.InvalidOperands(Loc, LHS, RHS); 11355 return true; 11356 } 11357 11358 return false; 11359 } 11360 11361 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11362 ExprResult &LHS, 11363 ExprResult &RHS, 11364 bool IsError) { 11365 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11366 : diag::ext_typecheck_comparison_of_fptr_to_void) 11367 << LHS.get()->getType() << RHS.get()->getType() 11368 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11369 } 11370 11371 static bool isObjCObjectLiteral(ExprResult &E) { 11372 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11373 case Stmt::ObjCArrayLiteralClass: 11374 case Stmt::ObjCDictionaryLiteralClass: 11375 case Stmt::ObjCStringLiteralClass: 11376 case Stmt::ObjCBoxedExprClass: 11377 return true; 11378 default: 11379 // Note that ObjCBoolLiteral is NOT an object literal! 11380 return false; 11381 } 11382 } 11383 11384 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11385 const ObjCObjectPointerType *Type = 11386 LHS->getType()->getAs<ObjCObjectPointerType>(); 11387 11388 // If this is not actually an Objective-C object, bail out. 11389 if (!Type) 11390 return false; 11391 11392 // Get the LHS object's interface type. 11393 QualType InterfaceType = Type->getPointeeType(); 11394 11395 // If the RHS isn't an Objective-C object, bail out. 11396 if (!RHS->getType()->isObjCObjectPointerType()) 11397 return false; 11398 11399 // Try to find the -isEqual: method. 11400 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11401 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11402 InterfaceType, 11403 /*IsInstance=*/true); 11404 if (!Method) { 11405 if (Type->isObjCIdType()) { 11406 // For 'id', just check the global pool. 11407 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11408 /*receiverId=*/true); 11409 } else { 11410 // Check protocols. 11411 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11412 /*IsInstance=*/true); 11413 } 11414 } 11415 11416 if (!Method) 11417 return false; 11418 11419 QualType T = Method->parameters()[0]->getType(); 11420 if (!T->isObjCObjectPointerType()) 11421 return false; 11422 11423 QualType R = Method->getReturnType(); 11424 if (!R->isScalarType()) 11425 return false; 11426 11427 return true; 11428 } 11429 11430 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11431 FromE = FromE->IgnoreParenImpCasts(); 11432 switch (FromE->getStmtClass()) { 11433 default: 11434 break; 11435 case Stmt::ObjCStringLiteralClass: 11436 // "string literal" 11437 return LK_String; 11438 case Stmt::ObjCArrayLiteralClass: 11439 // "array literal" 11440 return LK_Array; 11441 case Stmt::ObjCDictionaryLiteralClass: 11442 // "dictionary literal" 11443 return LK_Dictionary; 11444 case Stmt::BlockExprClass: 11445 return LK_Block; 11446 case Stmt::ObjCBoxedExprClass: { 11447 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11448 switch (Inner->getStmtClass()) { 11449 case Stmt::IntegerLiteralClass: 11450 case Stmt::FloatingLiteralClass: 11451 case Stmt::CharacterLiteralClass: 11452 case Stmt::ObjCBoolLiteralExprClass: 11453 case Stmt::CXXBoolLiteralExprClass: 11454 // "numeric literal" 11455 return LK_Numeric; 11456 case Stmt::ImplicitCastExprClass: { 11457 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11458 // Boolean literals can be represented by implicit casts. 11459 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11460 return LK_Numeric; 11461 break; 11462 } 11463 default: 11464 break; 11465 } 11466 return LK_Boxed; 11467 } 11468 } 11469 return LK_None; 11470 } 11471 11472 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11473 ExprResult &LHS, ExprResult &RHS, 11474 BinaryOperator::Opcode Opc){ 11475 Expr *Literal; 11476 Expr *Other; 11477 if (isObjCObjectLiteral(LHS)) { 11478 Literal = LHS.get(); 11479 Other = RHS.get(); 11480 } else { 11481 Literal = RHS.get(); 11482 Other = LHS.get(); 11483 } 11484 11485 // Don't warn on comparisons against nil. 11486 Other = Other->IgnoreParenCasts(); 11487 if (Other->isNullPointerConstant(S.getASTContext(), 11488 Expr::NPC_ValueDependentIsNotNull)) 11489 return; 11490 11491 // This should be kept in sync with warn_objc_literal_comparison. 11492 // LK_String should always be after the other literals, since it has its own 11493 // warning flag. 11494 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11495 assert(LiteralKind != Sema::LK_Block); 11496 if (LiteralKind == Sema::LK_None) { 11497 llvm_unreachable("Unknown Objective-C object literal kind"); 11498 } 11499 11500 if (LiteralKind == Sema::LK_String) 11501 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11502 << Literal->getSourceRange(); 11503 else 11504 S.Diag(Loc, diag::warn_objc_literal_comparison) 11505 << LiteralKind << Literal->getSourceRange(); 11506 11507 if (BinaryOperator::isEqualityOp(Opc) && 11508 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11509 SourceLocation Start = LHS.get()->getBeginLoc(); 11510 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11511 CharSourceRange OpRange = 11512 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11513 11514 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11515 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11516 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11517 << FixItHint::CreateInsertion(End, "]"); 11518 } 11519 } 11520 11521 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11522 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11523 ExprResult &RHS, SourceLocation Loc, 11524 BinaryOperatorKind Opc) { 11525 // Check that left hand side is !something. 11526 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11527 if (!UO || UO->getOpcode() != UO_LNot) return; 11528 11529 // Only check if the right hand side is non-bool arithmetic type. 11530 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11531 11532 // Make sure that the something in !something is not bool. 11533 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11534 if (SubExpr->isKnownToHaveBooleanValue()) return; 11535 11536 // Emit warning. 11537 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11538 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11539 << Loc << IsBitwiseOp; 11540 11541 // First note suggest !(x < y) 11542 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11543 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11544 FirstClose = S.getLocForEndOfToken(FirstClose); 11545 if (FirstClose.isInvalid()) 11546 FirstOpen = SourceLocation(); 11547 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11548 << IsBitwiseOp 11549 << FixItHint::CreateInsertion(FirstOpen, "(") 11550 << FixItHint::CreateInsertion(FirstClose, ")"); 11551 11552 // Second note suggests (!x) < y 11553 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11554 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11555 SecondClose = S.getLocForEndOfToken(SecondClose); 11556 if (SecondClose.isInvalid()) 11557 SecondOpen = SourceLocation(); 11558 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11559 << FixItHint::CreateInsertion(SecondOpen, "(") 11560 << FixItHint::CreateInsertion(SecondClose, ")"); 11561 } 11562 11563 // Returns true if E refers to a non-weak array. 11564 static bool checkForArray(const Expr *E) { 11565 const ValueDecl *D = nullptr; 11566 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11567 D = DR->getDecl(); 11568 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11569 if (Mem->isImplicitAccess()) 11570 D = Mem->getMemberDecl(); 11571 } 11572 if (!D) 11573 return false; 11574 return D->getType()->isArrayType() && !D->isWeak(); 11575 } 11576 11577 /// Diagnose some forms of syntactically-obvious tautological comparison. 11578 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11579 Expr *LHS, Expr *RHS, 11580 BinaryOperatorKind Opc) { 11581 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11582 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11583 11584 QualType LHSType = LHS->getType(); 11585 QualType RHSType = RHS->getType(); 11586 if (LHSType->hasFloatingRepresentation() || 11587 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11588 S.inTemplateInstantiation()) 11589 return; 11590 11591 // Comparisons between two array types are ill-formed for operator<=>, so 11592 // we shouldn't emit any additional warnings about it. 11593 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11594 return; 11595 11596 // For non-floating point types, check for self-comparisons of the form 11597 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11598 // often indicate logic errors in the program. 11599 // 11600 // NOTE: Don't warn about comparison expressions resulting from macro 11601 // expansion. Also don't warn about comparisons which are only self 11602 // comparisons within a template instantiation. The warnings should catch 11603 // obvious cases in the definition of the template anyways. The idea is to 11604 // warn when the typed comparison operator will always evaluate to the same 11605 // result. 11606 11607 // Used for indexing into %select in warn_comparison_always 11608 enum { 11609 AlwaysConstant, 11610 AlwaysTrue, 11611 AlwaysFalse, 11612 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11613 }; 11614 11615 // C++2a [depr.array.comp]: 11616 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11617 // operands of array type are deprecated. 11618 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11619 RHSStripped->getType()->isArrayType()) { 11620 S.Diag(Loc, diag::warn_depr_array_comparison) 11621 << LHS->getSourceRange() << RHS->getSourceRange() 11622 << LHSStripped->getType() << RHSStripped->getType(); 11623 // Carry on to produce the tautological comparison warning, if this 11624 // expression is potentially-evaluated, we can resolve the array to a 11625 // non-weak declaration, and so on. 11626 } 11627 11628 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11629 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11630 unsigned Result; 11631 switch (Opc) { 11632 case BO_EQ: 11633 case BO_LE: 11634 case BO_GE: 11635 Result = AlwaysTrue; 11636 break; 11637 case BO_NE: 11638 case BO_LT: 11639 case BO_GT: 11640 Result = AlwaysFalse; 11641 break; 11642 case BO_Cmp: 11643 Result = AlwaysEqual; 11644 break; 11645 default: 11646 Result = AlwaysConstant; 11647 break; 11648 } 11649 S.DiagRuntimeBehavior(Loc, nullptr, 11650 S.PDiag(diag::warn_comparison_always) 11651 << 0 /*self-comparison*/ 11652 << Result); 11653 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11654 // What is it always going to evaluate to? 11655 unsigned Result; 11656 switch (Opc) { 11657 case BO_EQ: // e.g. array1 == array2 11658 Result = AlwaysFalse; 11659 break; 11660 case BO_NE: // e.g. array1 != array2 11661 Result = AlwaysTrue; 11662 break; 11663 default: // e.g. array1 <= array2 11664 // The best we can say is 'a constant' 11665 Result = AlwaysConstant; 11666 break; 11667 } 11668 S.DiagRuntimeBehavior(Loc, nullptr, 11669 S.PDiag(diag::warn_comparison_always) 11670 << 1 /*array comparison*/ 11671 << Result); 11672 } 11673 } 11674 11675 if (isa<CastExpr>(LHSStripped)) 11676 LHSStripped = LHSStripped->IgnoreParenCasts(); 11677 if (isa<CastExpr>(RHSStripped)) 11678 RHSStripped = RHSStripped->IgnoreParenCasts(); 11679 11680 // Warn about comparisons against a string constant (unless the other 11681 // operand is null); the user probably wants string comparison function. 11682 Expr *LiteralString = nullptr; 11683 Expr *LiteralStringStripped = nullptr; 11684 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11685 !RHSStripped->isNullPointerConstant(S.Context, 11686 Expr::NPC_ValueDependentIsNull)) { 11687 LiteralString = LHS; 11688 LiteralStringStripped = LHSStripped; 11689 } else if ((isa<StringLiteral>(RHSStripped) || 11690 isa<ObjCEncodeExpr>(RHSStripped)) && 11691 !LHSStripped->isNullPointerConstant(S.Context, 11692 Expr::NPC_ValueDependentIsNull)) { 11693 LiteralString = RHS; 11694 LiteralStringStripped = RHSStripped; 11695 } 11696 11697 if (LiteralString) { 11698 S.DiagRuntimeBehavior(Loc, nullptr, 11699 S.PDiag(diag::warn_stringcompare) 11700 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11701 << LiteralString->getSourceRange()); 11702 } 11703 } 11704 11705 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11706 switch (CK) { 11707 default: { 11708 #ifndef NDEBUG 11709 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11710 << "\n"; 11711 #endif 11712 llvm_unreachable("unhandled cast kind"); 11713 } 11714 case CK_UserDefinedConversion: 11715 return ICK_Identity; 11716 case CK_LValueToRValue: 11717 return ICK_Lvalue_To_Rvalue; 11718 case CK_ArrayToPointerDecay: 11719 return ICK_Array_To_Pointer; 11720 case CK_FunctionToPointerDecay: 11721 return ICK_Function_To_Pointer; 11722 case CK_IntegralCast: 11723 return ICK_Integral_Conversion; 11724 case CK_FloatingCast: 11725 return ICK_Floating_Conversion; 11726 case CK_IntegralToFloating: 11727 case CK_FloatingToIntegral: 11728 return ICK_Floating_Integral; 11729 case CK_IntegralComplexCast: 11730 case CK_FloatingComplexCast: 11731 case CK_FloatingComplexToIntegralComplex: 11732 case CK_IntegralComplexToFloatingComplex: 11733 return ICK_Complex_Conversion; 11734 case CK_FloatingComplexToReal: 11735 case CK_FloatingRealToComplex: 11736 case CK_IntegralComplexToReal: 11737 case CK_IntegralRealToComplex: 11738 return ICK_Complex_Real; 11739 } 11740 } 11741 11742 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11743 QualType FromType, 11744 SourceLocation Loc) { 11745 // Check for a narrowing implicit conversion. 11746 StandardConversionSequence SCS; 11747 SCS.setAsIdentityConversion(); 11748 SCS.setToType(0, FromType); 11749 SCS.setToType(1, ToType); 11750 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11751 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11752 11753 APValue PreNarrowingValue; 11754 QualType PreNarrowingType; 11755 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11756 PreNarrowingType, 11757 /*IgnoreFloatToIntegralConversion*/ true)) { 11758 case NK_Dependent_Narrowing: 11759 // Implicit conversion to a narrower type, but the expression is 11760 // value-dependent so we can't tell whether it's actually narrowing. 11761 case NK_Not_Narrowing: 11762 return false; 11763 11764 case NK_Constant_Narrowing: 11765 // Implicit conversion to a narrower type, and the value is not a constant 11766 // expression. 11767 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11768 << /*Constant*/ 1 11769 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11770 return true; 11771 11772 case NK_Variable_Narrowing: 11773 // Implicit conversion to a narrower type, and the value is not a constant 11774 // expression. 11775 case NK_Type_Narrowing: 11776 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11777 << /*Constant*/ 0 << FromType << ToType; 11778 // TODO: It's not a constant expression, but what if the user intended it 11779 // to be? Can we produce notes to help them figure out why it isn't? 11780 return true; 11781 } 11782 llvm_unreachable("unhandled case in switch"); 11783 } 11784 11785 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11786 ExprResult &LHS, 11787 ExprResult &RHS, 11788 SourceLocation Loc) { 11789 QualType LHSType = LHS.get()->getType(); 11790 QualType RHSType = RHS.get()->getType(); 11791 // Dig out the original argument type and expression before implicit casts 11792 // were applied. These are the types/expressions we need to check the 11793 // [expr.spaceship] requirements against. 11794 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11795 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11796 QualType LHSStrippedType = LHSStripped.get()->getType(); 11797 QualType RHSStrippedType = RHSStripped.get()->getType(); 11798 11799 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11800 // other is not, the program is ill-formed. 11801 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11802 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11803 return QualType(); 11804 } 11805 11806 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11807 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11808 RHSStrippedType->isEnumeralType(); 11809 if (NumEnumArgs == 1) { 11810 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11811 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11812 if (OtherTy->hasFloatingRepresentation()) { 11813 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11814 return QualType(); 11815 } 11816 } 11817 if (NumEnumArgs == 2) { 11818 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11819 // type E, the operator yields the result of converting the operands 11820 // to the underlying type of E and applying <=> to the converted operands. 11821 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11822 S.InvalidOperands(Loc, LHS, RHS); 11823 return QualType(); 11824 } 11825 QualType IntType = 11826 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11827 assert(IntType->isArithmeticType()); 11828 11829 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11830 // promote the boolean type, and all other promotable integer types, to 11831 // avoid this. 11832 if (IntType->isPromotableIntegerType()) 11833 IntType = S.Context.getPromotedIntegerType(IntType); 11834 11835 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11836 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11837 LHSType = RHSType = IntType; 11838 } 11839 11840 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11841 // usual arithmetic conversions are applied to the operands. 11842 QualType Type = 11843 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11844 if (LHS.isInvalid() || RHS.isInvalid()) 11845 return QualType(); 11846 if (Type.isNull()) 11847 return S.InvalidOperands(Loc, LHS, RHS); 11848 11849 Optional<ComparisonCategoryType> CCT = 11850 getComparisonCategoryForBuiltinCmp(Type); 11851 if (!CCT) 11852 return S.InvalidOperands(Loc, LHS, RHS); 11853 11854 bool HasNarrowing = checkThreeWayNarrowingConversion( 11855 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11856 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11857 RHS.get()->getBeginLoc()); 11858 if (HasNarrowing) 11859 return QualType(); 11860 11861 assert(!Type.isNull() && "composite type for <=> has not been set"); 11862 11863 return S.CheckComparisonCategoryType( 11864 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11865 } 11866 11867 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11868 ExprResult &RHS, 11869 SourceLocation Loc, 11870 BinaryOperatorKind Opc) { 11871 if (Opc == BO_Cmp) 11872 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11873 11874 // C99 6.5.8p3 / C99 6.5.9p4 11875 QualType Type = 11876 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11877 if (LHS.isInvalid() || RHS.isInvalid()) 11878 return QualType(); 11879 if (Type.isNull()) 11880 return S.InvalidOperands(Loc, LHS, RHS); 11881 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11882 11883 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11884 return S.InvalidOperands(Loc, LHS, RHS); 11885 11886 // Check for comparisons of floating point operands using != and ==. 11887 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11888 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11889 11890 // The result of comparisons is 'bool' in C++, 'int' in C. 11891 return S.Context.getLogicalOperationType(); 11892 } 11893 11894 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11895 if (!NullE.get()->getType()->isAnyPointerType()) 11896 return; 11897 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11898 if (!E.get()->getType()->isAnyPointerType() && 11899 E.get()->isNullPointerConstant(Context, 11900 Expr::NPC_ValueDependentIsNotNull) == 11901 Expr::NPCK_ZeroExpression) { 11902 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11903 if (CL->getValue() == 0) 11904 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11905 << NullValue 11906 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11907 NullValue ? "NULL" : "(void *)0"); 11908 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11909 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11910 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11911 if (T == Context.CharTy) 11912 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11913 << NullValue 11914 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11915 NullValue ? "NULL" : "(void *)0"); 11916 } 11917 } 11918 } 11919 11920 // C99 6.5.8, C++ [expr.rel] 11921 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11922 SourceLocation Loc, 11923 BinaryOperatorKind Opc) { 11924 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11925 bool IsThreeWay = Opc == BO_Cmp; 11926 bool IsOrdered = IsRelational || IsThreeWay; 11927 auto IsAnyPointerType = [](ExprResult E) { 11928 QualType Ty = E.get()->getType(); 11929 return Ty->isPointerType() || Ty->isMemberPointerType(); 11930 }; 11931 11932 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11933 // type, array-to-pointer, ..., conversions are performed on both operands to 11934 // bring them to their composite type. 11935 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11936 // any type-related checks. 11937 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11938 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11939 if (LHS.isInvalid()) 11940 return QualType(); 11941 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11942 if (RHS.isInvalid()) 11943 return QualType(); 11944 } else { 11945 LHS = DefaultLvalueConversion(LHS.get()); 11946 if (LHS.isInvalid()) 11947 return QualType(); 11948 RHS = DefaultLvalueConversion(RHS.get()); 11949 if (RHS.isInvalid()) 11950 return QualType(); 11951 } 11952 11953 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11954 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11955 CheckPtrComparisonWithNullChar(LHS, RHS); 11956 CheckPtrComparisonWithNullChar(RHS, LHS); 11957 } 11958 11959 // Handle vector comparisons separately. 11960 if (LHS.get()->getType()->isVectorType() || 11961 RHS.get()->getType()->isVectorType()) 11962 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11963 11964 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11965 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11966 11967 QualType LHSType = LHS.get()->getType(); 11968 QualType RHSType = RHS.get()->getType(); 11969 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11970 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11971 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11972 11973 const Expr::NullPointerConstantKind LHSNullKind = 11974 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11975 const Expr::NullPointerConstantKind RHSNullKind = 11976 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11977 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11978 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11979 11980 auto computeResultTy = [&]() { 11981 if (Opc != BO_Cmp) 11982 return Context.getLogicalOperationType(); 11983 assert(getLangOpts().CPlusPlus); 11984 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11985 11986 QualType CompositeTy = LHS.get()->getType(); 11987 assert(!CompositeTy->isReferenceType()); 11988 11989 Optional<ComparisonCategoryType> CCT = 11990 getComparisonCategoryForBuiltinCmp(CompositeTy); 11991 if (!CCT) 11992 return InvalidOperands(Loc, LHS, RHS); 11993 11994 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11995 // P0946R0: Comparisons between a null pointer constant and an object 11996 // pointer result in std::strong_equality, which is ill-formed under 11997 // P1959R0. 11998 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11999 << (LHSIsNull ? LHS.get()->getSourceRange() 12000 : RHS.get()->getSourceRange()); 12001 return QualType(); 12002 } 12003 12004 return CheckComparisonCategoryType( 12005 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 12006 }; 12007 12008 if (!IsOrdered && LHSIsNull != RHSIsNull) { 12009 bool IsEquality = Opc == BO_EQ; 12010 if (RHSIsNull) 12011 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 12012 RHS.get()->getSourceRange()); 12013 else 12014 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 12015 LHS.get()->getSourceRange()); 12016 } 12017 12018 if (IsOrdered && LHSType->isFunctionPointerType() && 12019 RHSType->isFunctionPointerType()) { 12020 // Valid unless a relational comparison of function pointers 12021 bool IsError = Opc == BO_Cmp; 12022 auto DiagID = 12023 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 12024 : getLangOpts().CPlusPlus 12025 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 12026 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 12027 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 12028 << RHS.get()->getSourceRange(); 12029 if (IsError) 12030 return QualType(); 12031 } 12032 12033 if ((LHSType->isIntegerType() && !LHSIsNull) || 12034 (RHSType->isIntegerType() && !RHSIsNull)) { 12035 // Skip normal pointer conversion checks in this case; we have better 12036 // diagnostics for this below. 12037 } else if (getLangOpts().CPlusPlus) { 12038 // Equality comparison of a function pointer to a void pointer is invalid, 12039 // but we allow it as an extension. 12040 // FIXME: If we really want to allow this, should it be part of composite 12041 // pointer type computation so it works in conditionals too? 12042 if (!IsOrdered && 12043 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 12044 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 12045 // This is a gcc extension compatibility comparison. 12046 // In a SFINAE context, we treat this as a hard error to maintain 12047 // conformance with the C++ standard. 12048 diagnoseFunctionPointerToVoidComparison( 12049 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 12050 12051 if (isSFINAEContext()) 12052 return QualType(); 12053 12054 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12055 return computeResultTy(); 12056 } 12057 12058 // C++ [expr.eq]p2: 12059 // If at least one operand is a pointer [...] bring them to their 12060 // composite pointer type. 12061 // C++ [expr.spaceship]p6 12062 // If at least one of the operands is of pointer type, [...] bring them 12063 // to their composite pointer type. 12064 // C++ [expr.rel]p2: 12065 // If both operands are pointers, [...] bring them to their composite 12066 // pointer type. 12067 // For <=>, the only valid non-pointer types are arrays and functions, and 12068 // we already decayed those, so this is really the same as the relational 12069 // comparison rule. 12070 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 12071 (IsOrdered ? 2 : 1) && 12072 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 12073 RHSType->isObjCObjectPointerType()))) { 12074 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12075 return QualType(); 12076 return computeResultTy(); 12077 } 12078 } else if (LHSType->isPointerType() && 12079 RHSType->isPointerType()) { // C99 6.5.8p2 12080 // All of the following pointer-related warnings are GCC extensions, except 12081 // when handling null pointer constants. 12082 QualType LCanPointeeTy = 12083 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12084 QualType RCanPointeeTy = 12085 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12086 12087 // C99 6.5.9p2 and C99 6.5.8p2 12088 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 12089 RCanPointeeTy.getUnqualifiedType())) { 12090 if (IsRelational) { 12091 // Pointers both need to point to complete or incomplete types 12092 if ((LCanPointeeTy->isIncompleteType() != 12093 RCanPointeeTy->isIncompleteType()) && 12094 !getLangOpts().C11) { 12095 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 12096 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 12097 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 12098 << RCanPointeeTy->isIncompleteType(); 12099 } 12100 } 12101 } else if (!IsRelational && 12102 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 12103 // Valid unless comparison between non-null pointer and function pointer 12104 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 12105 && !LHSIsNull && !RHSIsNull) 12106 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 12107 /*isError*/false); 12108 } else { 12109 // Invalid 12110 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 12111 } 12112 if (LCanPointeeTy != RCanPointeeTy) { 12113 // Treat NULL constant as a special case in OpenCL. 12114 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 12115 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 12116 Diag(Loc, 12117 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 12118 << LHSType << RHSType << 0 /* comparison */ 12119 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12120 } 12121 } 12122 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 12123 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12124 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12125 : CK_BitCast; 12126 if (LHSIsNull && !RHSIsNull) 12127 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12128 else 12129 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12130 } 12131 return computeResultTy(); 12132 } 12133 12134 if (getLangOpts().CPlusPlus) { 12135 // C++ [expr.eq]p4: 12136 // Two operands of type std::nullptr_t or one operand of type 12137 // std::nullptr_t and the other a null pointer constant compare equal. 12138 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12139 if (LHSType->isNullPtrType()) { 12140 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12141 return computeResultTy(); 12142 } 12143 if (RHSType->isNullPtrType()) { 12144 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12145 return computeResultTy(); 12146 } 12147 } 12148 12149 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12150 // These aren't covered by the composite pointer type rules. 12151 if (!IsOrdered && RHSType->isNullPtrType() && 12152 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12153 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12154 return computeResultTy(); 12155 } 12156 if (!IsOrdered && LHSType->isNullPtrType() && 12157 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12158 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12159 return computeResultTy(); 12160 } 12161 12162 if (IsRelational && 12163 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12164 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12165 // HACK: Relational comparison of nullptr_t against a pointer type is 12166 // invalid per DR583, but we allow it within std::less<> and friends, 12167 // since otherwise common uses of it break. 12168 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12169 // friends to have std::nullptr_t overload candidates. 12170 DeclContext *DC = CurContext; 12171 if (isa<FunctionDecl>(DC)) 12172 DC = DC->getParent(); 12173 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12174 if (CTSD->isInStdNamespace() && 12175 llvm::StringSwitch<bool>(CTSD->getName()) 12176 .Cases("less", "less_equal", "greater", "greater_equal", true) 12177 .Default(false)) { 12178 if (RHSType->isNullPtrType()) 12179 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12180 else 12181 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12182 return computeResultTy(); 12183 } 12184 } 12185 } 12186 12187 // C++ [expr.eq]p2: 12188 // If at least one operand is a pointer to member, [...] bring them to 12189 // their composite pointer type. 12190 if (!IsOrdered && 12191 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12192 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12193 return QualType(); 12194 else 12195 return computeResultTy(); 12196 } 12197 } 12198 12199 // Handle block pointer types. 12200 if (!IsOrdered && LHSType->isBlockPointerType() && 12201 RHSType->isBlockPointerType()) { 12202 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12203 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12204 12205 if (!LHSIsNull && !RHSIsNull && 12206 !Context.typesAreCompatible(lpointee, rpointee)) { 12207 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12208 << LHSType << RHSType << LHS.get()->getSourceRange() 12209 << RHS.get()->getSourceRange(); 12210 } 12211 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12212 return computeResultTy(); 12213 } 12214 12215 // Allow block pointers to be compared with null pointer constants. 12216 if (!IsOrdered 12217 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12218 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12219 if (!LHSIsNull && !RHSIsNull) { 12220 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12221 ->getPointeeType()->isVoidType()) 12222 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12223 ->getPointeeType()->isVoidType()))) 12224 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12225 << LHSType << RHSType << LHS.get()->getSourceRange() 12226 << RHS.get()->getSourceRange(); 12227 } 12228 if (LHSIsNull && !RHSIsNull) 12229 LHS = ImpCastExprToType(LHS.get(), RHSType, 12230 RHSType->isPointerType() ? CK_BitCast 12231 : CK_AnyPointerToBlockPointerCast); 12232 else 12233 RHS = ImpCastExprToType(RHS.get(), LHSType, 12234 LHSType->isPointerType() ? CK_BitCast 12235 : CK_AnyPointerToBlockPointerCast); 12236 return computeResultTy(); 12237 } 12238 12239 if (LHSType->isObjCObjectPointerType() || 12240 RHSType->isObjCObjectPointerType()) { 12241 const PointerType *LPT = LHSType->getAs<PointerType>(); 12242 const PointerType *RPT = RHSType->getAs<PointerType>(); 12243 if (LPT || RPT) { 12244 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12245 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12246 12247 if (!LPtrToVoid && !RPtrToVoid && 12248 !Context.typesAreCompatible(LHSType, RHSType)) { 12249 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12250 /*isError*/false); 12251 } 12252 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12253 // the RHS, but we have test coverage for this behavior. 12254 // FIXME: Consider using convertPointersToCompositeType in C++. 12255 if (LHSIsNull && !RHSIsNull) { 12256 Expr *E = LHS.get(); 12257 if (getLangOpts().ObjCAutoRefCount) 12258 CheckObjCConversion(SourceRange(), RHSType, E, 12259 CCK_ImplicitConversion); 12260 LHS = ImpCastExprToType(E, RHSType, 12261 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12262 } 12263 else { 12264 Expr *E = RHS.get(); 12265 if (getLangOpts().ObjCAutoRefCount) 12266 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12267 /*Diagnose=*/true, 12268 /*DiagnoseCFAudited=*/false, Opc); 12269 RHS = ImpCastExprToType(E, LHSType, 12270 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12271 } 12272 return computeResultTy(); 12273 } 12274 if (LHSType->isObjCObjectPointerType() && 12275 RHSType->isObjCObjectPointerType()) { 12276 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12277 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12278 /*isError*/false); 12279 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12280 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12281 12282 if (LHSIsNull && !RHSIsNull) 12283 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12284 else 12285 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12286 return computeResultTy(); 12287 } 12288 12289 if (!IsOrdered && LHSType->isBlockPointerType() && 12290 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12291 LHS = ImpCastExprToType(LHS.get(), RHSType, 12292 CK_BlockPointerToObjCPointerCast); 12293 return computeResultTy(); 12294 } else if (!IsOrdered && 12295 LHSType->isBlockCompatibleObjCPointerType(Context) && 12296 RHSType->isBlockPointerType()) { 12297 RHS = ImpCastExprToType(RHS.get(), LHSType, 12298 CK_BlockPointerToObjCPointerCast); 12299 return computeResultTy(); 12300 } 12301 } 12302 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12303 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12304 unsigned DiagID = 0; 12305 bool isError = false; 12306 if (LangOpts.DebuggerSupport) { 12307 // Under a debugger, allow the comparison of pointers to integers, 12308 // since users tend to want to compare addresses. 12309 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12310 (RHSIsNull && RHSType->isIntegerType())) { 12311 if (IsOrdered) { 12312 isError = getLangOpts().CPlusPlus; 12313 DiagID = 12314 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12315 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12316 } 12317 } else if (getLangOpts().CPlusPlus) { 12318 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12319 isError = true; 12320 } else if (IsOrdered) 12321 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12322 else 12323 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12324 12325 if (DiagID) { 12326 Diag(Loc, DiagID) 12327 << LHSType << RHSType << LHS.get()->getSourceRange() 12328 << RHS.get()->getSourceRange(); 12329 if (isError) 12330 return QualType(); 12331 } 12332 12333 if (LHSType->isIntegerType()) 12334 LHS = ImpCastExprToType(LHS.get(), RHSType, 12335 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12336 else 12337 RHS = ImpCastExprToType(RHS.get(), LHSType, 12338 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12339 return computeResultTy(); 12340 } 12341 12342 // Handle block pointers. 12343 if (!IsOrdered && RHSIsNull 12344 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12345 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12346 return computeResultTy(); 12347 } 12348 if (!IsOrdered && LHSIsNull 12349 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12350 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12351 return computeResultTy(); 12352 } 12353 12354 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12355 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12356 return computeResultTy(); 12357 } 12358 12359 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12360 return computeResultTy(); 12361 } 12362 12363 if (LHSIsNull && RHSType->isQueueT()) { 12364 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12365 return computeResultTy(); 12366 } 12367 12368 if (LHSType->isQueueT() && RHSIsNull) { 12369 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12370 return computeResultTy(); 12371 } 12372 } 12373 12374 return InvalidOperands(Loc, LHS, RHS); 12375 } 12376 12377 // Return a signed ext_vector_type that is of identical size and number of 12378 // elements. For floating point vectors, return an integer type of identical 12379 // size and number of elements. In the non ext_vector_type case, search from 12380 // the largest type to the smallest type to avoid cases where long long == long, 12381 // where long gets picked over long long. 12382 QualType Sema::GetSignedVectorType(QualType V) { 12383 const VectorType *VTy = V->castAs<VectorType>(); 12384 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12385 12386 if (isa<ExtVectorType>(VTy)) { 12387 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12388 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12389 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12390 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12391 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12392 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12393 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12394 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); 12395 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12396 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12397 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12398 "Unhandled vector element size in vector compare"); 12399 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12400 } 12401 12402 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12403 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), 12404 VectorType::GenericVector); 12405 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12406 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12407 VectorType::GenericVector); 12408 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12409 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12410 VectorType::GenericVector); 12411 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12412 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12413 VectorType::GenericVector); 12414 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12415 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12416 VectorType::GenericVector); 12417 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12418 "Unhandled vector element size in vector compare"); 12419 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12420 VectorType::GenericVector); 12421 } 12422 12423 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12424 /// operates on extended vector types. Instead of producing an IntTy result, 12425 /// like a scalar comparison, a vector comparison produces a vector of integer 12426 /// types. 12427 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12428 SourceLocation Loc, 12429 BinaryOperatorKind Opc) { 12430 if (Opc == BO_Cmp) { 12431 Diag(Loc, diag::err_three_way_vector_comparison); 12432 return QualType(); 12433 } 12434 12435 // Check to make sure we're operating on vectors of the same type and width, 12436 // Allowing one side to be a scalar of element type. 12437 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12438 /*AllowBothBool*/true, 12439 /*AllowBoolConversions*/getLangOpts().ZVector); 12440 if (vType.isNull()) 12441 return vType; 12442 12443 QualType LHSType = LHS.get()->getType(); 12444 12445 // Determine the return type of a vector compare. By default clang will return 12446 // a scalar for all vector compares except vector bool and vector pixel. 12447 // With the gcc compiler we will always return a vector type and with the xl 12448 // compiler we will always return a scalar type. This switch allows choosing 12449 // which behavior is prefered. 12450 if (getLangOpts().AltiVec) { 12451 switch (getLangOpts().getAltivecSrcCompat()) { 12452 case LangOptions::AltivecSrcCompatKind::Mixed: 12453 // If AltiVec, the comparison results in a numeric type, i.e. 12454 // bool for C++, int for C 12455 if (vType->castAs<VectorType>()->getVectorKind() == 12456 VectorType::AltiVecVector) 12457 return Context.getLogicalOperationType(); 12458 else 12459 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12460 break; 12461 case LangOptions::AltivecSrcCompatKind::GCC: 12462 // For GCC we always return the vector type. 12463 break; 12464 case LangOptions::AltivecSrcCompatKind::XL: 12465 return Context.getLogicalOperationType(); 12466 break; 12467 } 12468 } 12469 12470 // For non-floating point types, check for self-comparisons of the form 12471 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12472 // often indicate logic errors in the program. 12473 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12474 12475 // Check for comparisons of floating point operands using != and ==. 12476 if (BinaryOperator::isEqualityOp(Opc) && 12477 LHSType->hasFloatingRepresentation()) { 12478 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12479 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12480 } 12481 12482 // Return a signed type for the vector. 12483 return GetSignedVectorType(vType); 12484 } 12485 12486 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12487 const ExprResult &XorRHS, 12488 const SourceLocation Loc) { 12489 // Do not diagnose macros. 12490 if (Loc.isMacroID()) 12491 return; 12492 12493 // Do not diagnose if both LHS and RHS are macros. 12494 if (XorLHS.get()->getExprLoc().isMacroID() && 12495 XorRHS.get()->getExprLoc().isMacroID()) 12496 return; 12497 12498 bool Negative = false; 12499 bool ExplicitPlus = false; 12500 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12501 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12502 12503 if (!LHSInt) 12504 return; 12505 if (!RHSInt) { 12506 // Check negative literals. 12507 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12508 UnaryOperatorKind Opc = UO->getOpcode(); 12509 if (Opc != UO_Minus && Opc != UO_Plus) 12510 return; 12511 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12512 if (!RHSInt) 12513 return; 12514 Negative = (Opc == UO_Minus); 12515 ExplicitPlus = !Negative; 12516 } else { 12517 return; 12518 } 12519 } 12520 12521 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12522 llvm::APInt RightSideValue = RHSInt->getValue(); 12523 if (LeftSideValue != 2 && LeftSideValue != 10) 12524 return; 12525 12526 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12527 return; 12528 12529 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12530 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12531 llvm::StringRef ExprStr = 12532 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12533 12534 CharSourceRange XorRange = 12535 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12536 llvm::StringRef XorStr = 12537 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12538 // Do not diagnose if xor keyword/macro is used. 12539 if (XorStr == "xor") 12540 return; 12541 12542 std::string LHSStr = std::string(Lexer::getSourceText( 12543 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12544 S.getSourceManager(), S.getLangOpts())); 12545 std::string RHSStr = std::string(Lexer::getSourceText( 12546 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12547 S.getSourceManager(), S.getLangOpts())); 12548 12549 if (Negative) { 12550 RightSideValue = -RightSideValue; 12551 RHSStr = "-" + RHSStr; 12552 } else if (ExplicitPlus) { 12553 RHSStr = "+" + RHSStr; 12554 } 12555 12556 StringRef LHSStrRef = LHSStr; 12557 StringRef RHSStrRef = RHSStr; 12558 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12559 // literals. 12560 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12561 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12562 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12563 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12564 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12565 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12566 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12567 return; 12568 12569 bool SuggestXor = 12570 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12571 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12572 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12573 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12574 std::string SuggestedExpr = "1 << " + RHSStr; 12575 bool Overflow = false; 12576 llvm::APInt One = (LeftSideValue - 1); 12577 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12578 if (Overflow) { 12579 if (RightSideIntValue < 64) 12580 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12581 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12582 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12583 else if (RightSideIntValue == 64) 12584 S.Diag(Loc, diag::warn_xor_used_as_pow) 12585 << ExprStr << toString(XorValue, 10, true); 12586 else 12587 return; 12588 } else { 12589 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12590 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12591 << toString(PowValue, 10, true) 12592 << FixItHint::CreateReplacement( 12593 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12594 } 12595 12596 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12597 << ("0x2 ^ " + RHSStr) << SuggestXor; 12598 } else if (LeftSideValue == 10) { 12599 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12600 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12601 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12602 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12603 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12604 << ("0xA ^ " + RHSStr) << SuggestXor; 12605 } 12606 } 12607 12608 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12609 SourceLocation Loc) { 12610 // Ensure that either both operands are of the same vector type, or 12611 // one operand is of a vector type and the other is of its element type. 12612 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12613 /*AllowBothBool*/true, 12614 /*AllowBoolConversions*/false); 12615 if (vType.isNull()) 12616 return InvalidOperands(Loc, LHS, RHS); 12617 if (getLangOpts().OpenCL && 12618 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12619 vType->hasFloatingRepresentation()) 12620 return InvalidOperands(Loc, LHS, RHS); 12621 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12622 // usage of the logical operators && and || with vectors in C. This 12623 // check could be notionally dropped. 12624 if (!getLangOpts().CPlusPlus && 12625 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12626 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12627 12628 return GetSignedVectorType(LHS.get()->getType()); 12629 } 12630 12631 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12632 SourceLocation Loc, 12633 bool IsCompAssign) { 12634 if (!IsCompAssign) { 12635 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12636 if (LHS.isInvalid()) 12637 return QualType(); 12638 } 12639 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12640 if (RHS.isInvalid()) 12641 return QualType(); 12642 12643 // For conversion purposes, we ignore any qualifiers. 12644 // For example, "const float" and "float" are equivalent. 12645 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12646 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12647 12648 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12649 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12650 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12651 12652 if (Context.hasSameType(LHSType, RHSType)) 12653 return LHSType; 12654 12655 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12656 // case we have to return InvalidOperands. 12657 ExprResult OriginalLHS = LHS; 12658 ExprResult OriginalRHS = RHS; 12659 if (LHSMatType && !RHSMatType) { 12660 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12661 if (!RHS.isInvalid()) 12662 return LHSType; 12663 12664 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12665 } 12666 12667 if (!LHSMatType && RHSMatType) { 12668 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12669 if (!LHS.isInvalid()) 12670 return RHSType; 12671 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12672 } 12673 12674 return InvalidOperands(Loc, LHS, RHS); 12675 } 12676 12677 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12678 SourceLocation Loc, 12679 bool IsCompAssign) { 12680 if (!IsCompAssign) { 12681 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12682 if (LHS.isInvalid()) 12683 return QualType(); 12684 } 12685 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12686 if (RHS.isInvalid()) 12687 return QualType(); 12688 12689 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12690 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12691 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12692 12693 if (LHSMatType && RHSMatType) { 12694 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12695 return InvalidOperands(Loc, LHS, RHS); 12696 12697 if (!Context.hasSameType(LHSMatType->getElementType(), 12698 RHSMatType->getElementType())) 12699 return InvalidOperands(Loc, LHS, RHS); 12700 12701 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12702 LHSMatType->getNumRows(), 12703 RHSMatType->getNumColumns()); 12704 } 12705 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12706 } 12707 12708 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12709 SourceLocation Loc, 12710 BinaryOperatorKind Opc) { 12711 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12712 12713 bool IsCompAssign = 12714 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12715 12716 if (LHS.get()->getType()->isVectorType() || 12717 RHS.get()->getType()->isVectorType()) { 12718 if (LHS.get()->getType()->hasIntegerRepresentation() && 12719 RHS.get()->getType()->hasIntegerRepresentation()) 12720 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12721 /*AllowBothBool*/true, 12722 /*AllowBoolConversions*/getLangOpts().ZVector); 12723 return InvalidOperands(Loc, LHS, RHS); 12724 } 12725 12726 if (Opc == BO_And) 12727 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12728 12729 if (LHS.get()->getType()->hasFloatingRepresentation() || 12730 RHS.get()->getType()->hasFloatingRepresentation()) 12731 return InvalidOperands(Loc, LHS, RHS); 12732 12733 ExprResult LHSResult = LHS, RHSResult = RHS; 12734 QualType compType = UsualArithmeticConversions( 12735 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12736 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12737 return QualType(); 12738 LHS = LHSResult.get(); 12739 RHS = RHSResult.get(); 12740 12741 if (Opc == BO_Xor) 12742 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12743 12744 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12745 return compType; 12746 return InvalidOperands(Loc, LHS, RHS); 12747 } 12748 12749 // C99 6.5.[13,14] 12750 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12751 SourceLocation Loc, 12752 BinaryOperatorKind Opc) { 12753 // Check vector operands differently. 12754 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12755 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12756 12757 bool EnumConstantInBoolContext = false; 12758 for (const ExprResult &HS : {LHS, RHS}) { 12759 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12760 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12761 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12762 EnumConstantInBoolContext = true; 12763 } 12764 } 12765 12766 if (EnumConstantInBoolContext) 12767 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12768 12769 // Diagnose cases where the user write a logical and/or but probably meant a 12770 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12771 // is a constant. 12772 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12773 !LHS.get()->getType()->isBooleanType() && 12774 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12775 // Don't warn in macros or template instantiations. 12776 !Loc.isMacroID() && !inTemplateInstantiation()) { 12777 // If the RHS can be constant folded, and if it constant folds to something 12778 // that isn't 0 or 1 (which indicate a potential logical operation that 12779 // happened to fold to true/false) then warn. 12780 // Parens on the RHS are ignored. 12781 Expr::EvalResult EVResult; 12782 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12783 llvm::APSInt Result = EVResult.Val.getInt(); 12784 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12785 !RHS.get()->getExprLoc().isMacroID()) || 12786 (Result != 0 && Result != 1)) { 12787 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12788 << RHS.get()->getSourceRange() 12789 << (Opc == BO_LAnd ? "&&" : "||"); 12790 // Suggest replacing the logical operator with the bitwise version 12791 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12792 << (Opc == BO_LAnd ? "&" : "|") 12793 << FixItHint::CreateReplacement(SourceRange( 12794 Loc, getLocForEndOfToken(Loc)), 12795 Opc == BO_LAnd ? "&" : "|"); 12796 if (Opc == BO_LAnd) 12797 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12798 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12799 << FixItHint::CreateRemoval( 12800 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12801 RHS.get()->getEndLoc())); 12802 } 12803 } 12804 } 12805 12806 if (!Context.getLangOpts().CPlusPlus) { 12807 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12808 // not operate on the built-in scalar and vector float types. 12809 if (Context.getLangOpts().OpenCL && 12810 Context.getLangOpts().OpenCLVersion < 120) { 12811 if (LHS.get()->getType()->isFloatingType() || 12812 RHS.get()->getType()->isFloatingType()) 12813 return InvalidOperands(Loc, LHS, RHS); 12814 } 12815 12816 LHS = UsualUnaryConversions(LHS.get()); 12817 if (LHS.isInvalid()) 12818 return QualType(); 12819 12820 RHS = UsualUnaryConversions(RHS.get()); 12821 if (RHS.isInvalid()) 12822 return QualType(); 12823 12824 if (!LHS.get()->getType()->isScalarType() || 12825 !RHS.get()->getType()->isScalarType()) 12826 return InvalidOperands(Loc, LHS, RHS); 12827 12828 return Context.IntTy; 12829 } 12830 12831 // The following is safe because we only use this method for 12832 // non-overloadable operands. 12833 12834 // C++ [expr.log.and]p1 12835 // C++ [expr.log.or]p1 12836 // The operands are both contextually converted to type bool. 12837 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12838 if (LHSRes.isInvalid()) 12839 return InvalidOperands(Loc, LHS, RHS); 12840 LHS = LHSRes; 12841 12842 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12843 if (RHSRes.isInvalid()) 12844 return InvalidOperands(Loc, LHS, RHS); 12845 RHS = RHSRes; 12846 12847 // C++ [expr.log.and]p2 12848 // C++ [expr.log.or]p2 12849 // The result is a bool. 12850 return Context.BoolTy; 12851 } 12852 12853 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12854 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12855 if (!ME) return false; 12856 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12857 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12858 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12859 if (!Base) return false; 12860 return Base->getMethodDecl() != nullptr; 12861 } 12862 12863 /// Is the given expression (which must be 'const') a reference to a 12864 /// variable which was originally non-const, but which has become 12865 /// 'const' due to being captured within a block? 12866 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12867 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12868 assert(E->isLValue() && E->getType().isConstQualified()); 12869 E = E->IgnoreParens(); 12870 12871 // Must be a reference to a declaration from an enclosing scope. 12872 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12873 if (!DRE) return NCCK_None; 12874 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12875 12876 // The declaration must be a variable which is not declared 'const'. 12877 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12878 if (!var) return NCCK_None; 12879 if (var->getType().isConstQualified()) return NCCK_None; 12880 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12881 12882 // Decide whether the first capture was for a block or a lambda. 12883 DeclContext *DC = S.CurContext, *Prev = nullptr; 12884 // Decide whether the first capture was for a block or a lambda. 12885 while (DC) { 12886 // For init-capture, it is possible that the variable belongs to the 12887 // template pattern of the current context. 12888 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12889 if (var->isInitCapture() && 12890 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12891 break; 12892 if (DC == var->getDeclContext()) 12893 break; 12894 Prev = DC; 12895 DC = DC->getParent(); 12896 } 12897 // Unless we have an init-capture, we've gone one step too far. 12898 if (!var->isInitCapture()) 12899 DC = Prev; 12900 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12901 } 12902 12903 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12904 Ty = Ty.getNonReferenceType(); 12905 if (IsDereference && Ty->isPointerType()) 12906 Ty = Ty->getPointeeType(); 12907 return !Ty.isConstQualified(); 12908 } 12909 12910 // Update err_typecheck_assign_const and note_typecheck_assign_const 12911 // when this enum is changed. 12912 enum { 12913 ConstFunction, 12914 ConstVariable, 12915 ConstMember, 12916 ConstMethod, 12917 NestedConstMember, 12918 ConstUnknown, // Keep as last element 12919 }; 12920 12921 /// Emit the "read-only variable not assignable" error and print notes to give 12922 /// more information about why the variable is not assignable, such as pointing 12923 /// to the declaration of a const variable, showing that a method is const, or 12924 /// that the function is returning a const reference. 12925 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12926 SourceLocation Loc) { 12927 SourceRange ExprRange = E->getSourceRange(); 12928 12929 // Only emit one error on the first const found. All other consts will emit 12930 // a note to the error. 12931 bool DiagnosticEmitted = false; 12932 12933 // Track if the current expression is the result of a dereference, and if the 12934 // next checked expression is the result of a dereference. 12935 bool IsDereference = false; 12936 bool NextIsDereference = false; 12937 12938 // Loop to process MemberExpr chains. 12939 while (true) { 12940 IsDereference = NextIsDereference; 12941 12942 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12943 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12944 NextIsDereference = ME->isArrow(); 12945 const ValueDecl *VD = ME->getMemberDecl(); 12946 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12947 // Mutable fields can be modified even if the class is const. 12948 if (Field->isMutable()) { 12949 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12950 break; 12951 } 12952 12953 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12954 if (!DiagnosticEmitted) { 12955 S.Diag(Loc, diag::err_typecheck_assign_const) 12956 << ExprRange << ConstMember << false /*static*/ << Field 12957 << Field->getType(); 12958 DiagnosticEmitted = true; 12959 } 12960 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12961 << ConstMember << false /*static*/ << Field << Field->getType() 12962 << Field->getSourceRange(); 12963 } 12964 E = ME->getBase(); 12965 continue; 12966 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12967 if (VDecl->getType().isConstQualified()) { 12968 if (!DiagnosticEmitted) { 12969 S.Diag(Loc, diag::err_typecheck_assign_const) 12970 << ExprRange << ConstMember << true /*static*/ << VDecl 12971 << VDecl->getType(); 12972 DiagnosticEmitted = true; 12973 } 12974 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12975 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12976 << VDecl->getSourceRange(); 12977 } 12978 // Static fields do not inherit constness from parents. 12979 break; 12980 } 12981 break; // End MemberExpr 12982 } else if (const ArraySubscriptExpr *ASE = 12983 dyn_cast<ArraySubscriptExpr>(E)) { 12984 E = ASE->getBase()->IgnoreParenImpCasts(); 12985 continue; 12986 } else if (const ExtVectorElementExpr *EVE = 12987 dyn_cast<ExtVectorElementExpr>(E)) { 12988 E = EVE->getBase()->IgnoreParenImpCasts(); 12989 continue; 12990 } 12991 break; 12992 } 12993 12994 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12995 // Function calls 12996 const FunctionDecl *FD = CE->getDirectCallee(); 12997 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12998 if (!DiagnosticEmitted) { 12999 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13000 << ConstFunction << FD; 13001 DiagnosticEmitted = true; 13002 } 13003 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 13004 diag::note_typecheck_assign_const) 13005 << ConstFunction << FD << FD->getReturnType() 13006 << FD->getReturnTypeSourceRange(); 13007 } 13008 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13009 // Point to variable declaration. 13010 if (const ValueDecl *VD = DRE->getDecl()) { 13011 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 13012 if (!DiagnosticEmitted) { 13013 S.Diag(Loc, diag::err_typecheck_assign_const) 13014 << ExprRange << ConstVariable << VD << VD->getType(); 13015 DiagnosticEmitted = true; 13016 } 13017 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13018 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 13019 } 13020 } 13021 } else if (isa<CXXThisExpr>(E)) { 13022 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 13023 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 13024 if (MD->isConst()) { 13025 if (!DiagnosticEmitted) { 13026 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13027 << ConstMethod << MD; 13028 DiagnosticEmitted = true; 13029 } 13030 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 13031 << ConstMethod << MD << MD->getSourceRange(); 13032 } 13033 } 13034 } 13035 } 13036 13037 if (DiagnosticEmitted) 13038 return; 13039 13040 // Can't determine a more specific message, so display the generic error. 13041 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 13042 } 13043 13044 enum OriginalExprKind { 13045 OEK_Variable, 13046 OEK_Member, 13047 OEK_LValue 13048 }; 13049 13050 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 13051 const RecordType *Ty, 13052 SourceLocation Loc, SourceRange Range, 13053 OriginalExprKind OEK, 13054 bool &DiagnosticEmitted) { 13055 std::vector<const RecordType *> RecordTypeList; 13056 RecordTypeList.push_back(Ty); 13057 unsigned NextToCheckIndex = 0; 13058 // We walk the record hierarchy breadth-first to ensure that we print 13059 // diagnostics in field nesting order. 13060 while (RecordTypeList.size() > NextToCheckIndex) { 13061 bool IsNested = NextToCheckIndex > 0; 13062 for (const FieldDecl *Field : 13063 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 13064 // First, check every field for constness. 13065 QualType FieldTy = Field->getType(); 13066 if (FieldTy.isConstQualified()) { 13067 if (!DiagnosticEmitted) { 13068 S.Diag(Loc, diag::err_typecheck_assign_const) 13069 << Range << NestedConstMember << OEK << VD 13070 << IsNested << Field; 13071 DiagnosticEmitted = true; 13072 } 13073 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 13074 << NestedConstMember << IsNested << Field 13075 << FieldTy << Field->getSourceRange(); 13076 } 13077 13078 // Then we append it to the list to check next in order. 13079 FieldTy = FieldTy.getCanonicalType(); 13080 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 13081 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 13082 RecordTypeList.push_back(FieldRecTy); 13083 } 13084 } 13085 ++NextToCheckIndex; 13086 } 13087 } 13088 13089 /// Emit an error for the case where a record we are trying to assign to has a 13090 /// const-qualified field somewhere in its hierarchy. 13091 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 13092 SourceLocation Loc) { 13093 QualType Ty = E->getType(); 13094 assert(Ty->isRecordType() && "lvalue was not record?"); 13095 SourceRange Range = E->getSourceRange(); 13096 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 13097 bool DiagEmitted = false; 13098 13099 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 13100 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 13101 Range, OEK_Member, DiagEmitted); 13102 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13103 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 13104 Range, OEK_Variable, DiagEmitted); 13105 else 13106 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 13107 Range, OEK_LValue, DiagEmitted); 13108 if (!DiagEmitted) 13109 DiagnoseConstAssignment(S, E, Loc); 13110 } 13111 13112 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 13113 /// emit an error and return true. If so, return false. 13114 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 13115 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 13116 13117 S.CheckShadowingDeclModification(E, Loc); 13118 13119 SourceLocation OrigLoc = Loc; 13120 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 13121 &Loc); 13122 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 13123 IsLV = Expr::MLV_InvalidMessageExpression; 13124 if (IsLV == Expr::MLV_Valid) 13125 return false; 13126 13127 unsigned DiagID = 0; 13128 bool NeedType = false; 13129 switch (IsLV) { // C99 6.5.16p2 13130 case Expr::MLV_ConstQualified: 13131 // Use a specialized diagnostic when we're assigning to an object 13132 // from an enclosing function or block. 13133 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13134 if (NCCK == NCCK_Block) 13135 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13136 else 13137 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13138 break; 13139 } 13140 13141 // In ARC, use some specialized diagnostics for occasions where we 13142 // infer 'const'. These are always pseudo-strong variables. 13143 if (S.getLangOpts().ObjCAutoRefCount) { 13144 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13145 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13146 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13147 13148 // Use the normal diagnostic if it's pseudo-__strong but the 13149 // user actually wrote 'const'. 13150 if (var->isARCPseudoStrong() && 13151 (!var->getTypeSourceInfo() || 13152 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13153 // There are three pseudo-strong cases: 13154 // - self 13155 ObjCMethodDecl *method = S.getCurMethodDecl(); 13156 if (method && var == method->getSelfDecl()) { 13157 DiagID = method->isClassMethod() 13158 ? diag::err_typecheck_arc_assign_self_class_method 13159 : diag::err_typecheck_arc_assign_self; 13160 13161 // - Objective-C externally_retained attribute. 13162 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13163 isa<ParmVarDecl>(var)) { 13164 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13165 13166 // - fast enumeration variables 13167 } else { 13168 DiagID = diag::err_typecheck_arr_assign_enumeration; 13169 } 13170 13171 SourceRange Assign; 13172 if (Loc != OrigLoc) 13173 Assign = SourceRange(OrigLoc, OrigLoc); 13174 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13175 // We need to preserve the AST regardless, so migration tool 13176 // can do its job. 13177 return false; 13178 } 13179 } 13180 } 13181 13182 // If none of the special cases above are triggered, then this is a 13183 // simple const assignment. 13184 if (DiagID == 0) { 13185 DiagnoseConstAssignment(S, E, Loc); 13186 return true; 13187 } 13188 13189 break; 13190 case Expr::MLV_ConstAddrSpace: 13191 DiagnoseConstAssignment(S, E, Loc); 13192 return true; 13193 case Expr::MLV_ConstQualifiedField: 13194 DiagnoseRecursiveConstFields(S, E, Loc); 13195 return true; 13196 case Expr::MLV_ArrayType: 13197 case Expr::MLV_ArrayTemporary: 13198 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13199 NeedType = true; 13200 break; 13201 case Expr::MLV_NotObjectType: 13202 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13203 NeedType = true; 13204 break; 13205 case Expr::MLV_LValueCast: 13206 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13207 break; 13208 case Expr::MLV_Valid: 13209 llvm_unreachable("did not take early return for MLV_Valid"); 13210 case Expr::MLV_InvalidExpression: 13211 case Expr::MLV_MemberFunction: 13212 case Expr::MLV_ClassTemporary: 13213 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13214 break; 13215 case Expr::MLV_IncompleteType: 13216 case Expr::MLV_IncompleteVoidType: 13217 return S.RequireCompleteType(Loc, E->getType(), 13218 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13219 case Expr::MLV_DuplicateVectorComponents: 13220 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13221 break; 13222 case Expr::MLV_NoSetterProperty: 13223 llvm_unreachable("readonly properties should be processed differently"); 13224 case Expr::MLV_InvalidMessageExpression: 13225 DiagID = diag::err_readonly_message_assignment; 13226 break; 13227 case Expr::MLV_SubObjCPropertySetting: 13228 DiagID = diag::err_no_subobject_property_setting; 13229 break; 13230 } 13231 13232 SourceRange Assign; 13233 if (Loc != OrigLoc) 13234 Assign = SourceRange(OrigLoc, OrigLoc); 13235 if (NeedType) 13236 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13237 else 13238 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13239 return true; 13240 } 13241 13242 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13243 SourceLocation Loc, 13244 Sema &Sema) { 13245 if (Sema.inTemplateInstantiation()) 13246 return; 13247 if (Sema.isUnevaluatedContext()) 13248 return; 13249 if (Loc.isInvalid() || Loc.isMacroID()) 13250 return; 13251 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13252 return; 13253 13254 // C / C++ fields 13255 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13256 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13257 if (ML && MR) { 13258 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13259 return; 13260 const ValueDecl *LHSDecl = 13261 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13262 const ValueDecl *RHSDecl = 13263 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13264 if (LHSDecl != RHSDecl) 13265 return; 13266 if (LHSDecl->getType().isVolatileQualified()) 13267 return; 13268 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13269 if (RefTy->getPointeeType().isVolatileQualified()) 13270 return; 13271 13272 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13273 } 13274 13275 // Objective-C instance variables 13276 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13277 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13278 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13279 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13280 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13281 if (RL && RR && RL->getDecl() == RR->getDecl()) 13282 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13283 } 13284 } 13285 13286 // C99 6.5.16.1 13287 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13288 SourceLocation Loc, 13289 QualType CompoundType) { 13290 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13291 13292 // Verify that LHS is a modifiable lvalue, and emit error if not. 13293 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13294 return QualType(); 13295 13296 QualType LHSType = LHSExpr->getType(); 13297 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13298 CompoundType; 13299 // OpenCL v1.2 s6.1.1.1 p2: 13300 // The half data type can only be used to declare a pointer to a buffer that 13301 // contains half values 13302 if (getLangOpts().OpenCL && 13303 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13304 LHSType->isHalfType()) { 13305 Diag(Loc, diag::err_opencl_half_load_store) << 1 13306 << LHSType.getUnqualifiedType(); 13307 return QualType(); 13308 } 13309 13310 AssignConvertType ConvTy; 13311 if (CompoundType.isNull()) { 13312 Expr *RHSCheck = RHS.get(); 13313 13314 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13315 13316 QualType LHSTy(LHSType); 13317 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13318 if (RHS.isInvalid()) 13319 return QualType(); 13320 // Special case of NSObject attributes on c-style pointer types. 13321 if (ConvTy == IncompatiblePointer && 13322 ((Context.isObjCNSObjectType(LHSType) && 13323 RHSType->isObjCObjectPointerType()) || 13324 (Context.isObjCNSObjectType(RHSType) && 13325 LHSType->isObjCObjectPointerType()))) 13326 ConvTy = Compatible; 13327 13328 if (ConvTy == Compatible && 13329 LHSType->isObjCObjectType()) 13330 Diag(Loc, diag::err_objc_object_assignment) 13331 << LHSType; 13332 13333 // If the RHS is a unary plus or minus, check to see if they = and + are 13334 // right next to each other. If so, the user may have typo'd "x =+ 4" 13335 // instead of "x += 4". 13336 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13337 RHSCheck = ICE->getSubExpr(); 13338 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13339 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13340 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13341 // Only if the two operators are exactly adjacent. 13342 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13343 // And there is a space or other character before the subexpr of the 13344 // unary +/-. We don't want to warn on "x=-1". 13345 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13346 UO->getSubExpr()->getBeginLoc().isFileID()) { 13347 Diag(Loc, diag::warn_not_compound_assign) 13348 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13349 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13350 } 13351 } 13352 13353 if (ConvTy == Compatible) { 13354 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13355 // Warn about retain cycles where a block captures the LHS, but 13356 // not if the LHS is a simple variable into which the block is 13357 // being stored...unless that variable can be captured by reference! 13358 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13359 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13360 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13361 checkRetainCycles(LHSExpr, RHS.get()); 13362 } 13363 13364 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13365 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13366 // It is safe to assign a weak reference into a strong variable. 13367 // Although this code can still have problems: 13368 // id x = self.weakProp; 13369 // id y = self.weakProp; 13370 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13371 // paths through the function. This should be revisited if 13372 // -Wrepeated-use-of-weak is made flow-sensitive. 13373 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13374 // variable, which will be valid for the current autorelease scope. 13375 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13376 RHS.get()->getBeginLoc())) 13377 getCurFunction()->markSafeWeakUse(RHS.get()); 13378 13379 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13380 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13381 } 13382 } 13383 } else { 13384 // Compound assignment "x += y" 13385 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13386 } 13387 13388 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13389 RHS.get(), AA_Assigning)) 13390 return QualType(); 13391 13392 CheckForNullPointerDereference(*this, LHSExpr); 13393 13394 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13395 if (CompoundType.isNull()) { 13396 // C++2a [expr.ass]p5: 13397 // A simple-assignment whose left operand is of a volatile-qualified 13398 // type is deprecated unless the assignment is either a discarded-value 13399 // expression or an unevaluated operand 13400 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13401 } else { 13402 // C++2a [expr.ass]p6: 13403 // [Compound-assignment] expressions are deprecated if E1 has 13404 // volatile-qualified type 13405 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13406 } 13407 } 13408 13409 // C99 6.5.16p3: The type of an assignment expression is the type of the 13410 // left operand unless the left operand has qualified type, in which case 13411 // it is the unqualified version of the type of the left operand. 13412 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13413 // is converted to the type of the assignment expression (above). 13414 // C++ 5.17p1: the type of the assignment expression is that of its left 13415 // operand. 13416 return (getLangOpts().CPlusPlus 13417 ? LHSType : LHSType.getUnqualifiedType()); 13418 } 13419 13420 // Only ignore explicit casts to void. 13421 static bool IgnoreCommaOperand(const Expr *E) { 13422 E = E->IgnoreParens(); 13423 13424 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13425 if (CE->getCastKind() == CK_ToVoid) { 13426 return true; 13427 } 13428 13429 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13430 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13431 CE->getSubExpr()->getType()->isDependentType()) { 13432 return true; 13433 } 13434 } 13435 13436 return false; 13437 } 13438 13439 // Look for instances where it is likely the comma operator is confused with 13440 // another operator. There is an explicit list of acceptable expressions for 13441 // the left hand side of the comma operator, otherwise emit a warning. 13442 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13443 // No warnings in macros 13444 if (Loc.isMacroID()) 13445 return; 13446 13447 // Don't warn in template instantiations. 13448 if (inTemplateInstantiation()) 13449 return; 13450 13451 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13452 // instead, skip more than needed, then call back into here with the 13453 // CommaVisitor in SemaStmt.cpp. 13454 // The listed locations are the initialization and increment portions 13455 // of a for loop. The additional checks are on the condition of 13456 // if statements, do/while loops, and for loops. 13457 // Differences in scope flags for C89 mode requires the extra logic. 13458 const unsigned ForIncrementFlags = 13459 getLangOpts().C99 || getLangOpts().CPlusPlus 13460 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13461 : Scope::ContinueScope | Scope::BreakScope; 13462 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13463 const unsigned ScopeFlags = getCurScope()->getFlags(); 13464 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13465 (ScopeFlags & ForInitFlags) == ForInitFlags) 13466 return; 13467 13468 // If there are multiple comma operators used together, get the RHS of the 13469 // of the comma operator as the LHS. 13470 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13471 if (BO->getOpcode() != BO_Comma) 13472 break; 13473 LHS = BO->getRHS(); 13474 } 13475 13476 // Only allow some expressions on LHS to not warn. 13477 if (IgnoreCommaOperand(LHS)) 13478 return; 13479 13480 Diag(Loc, diag::warn_comma_operator); 13481 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13482 << LHS->getSourceRange() 13483 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13484 LangOpts.CPlusPlus ? "static_cast<void>(" 13485 : "(void)(") 13486 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13487 ")"); 13488 } 13489 13490 // C99 6.5.17 13491 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13492 SourceLocation Loc) { 13493 LHS = S.CheckPlaceholderExpr(LHS.get()); 13494 RHS = S.CheckPlaceholderExpr(RHS.get()); 13495 if (LHS.isInvalid() || RHS.isInvalid()) 13496 return QualType(); 13497 13498 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13499 // operands, but not unary promotions. 13500 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13501 13502 // So we treat the LHS as a ignored value, and in C++ we allow the 13503 // containing site to determine what should be done with the RHS. 13504 LHS = S.IgnoredValueConversions(LHS.get()); 13505 if (LHS.isInvalid()) 13506 return QualType(); 13507 13508 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13509 13510 if (!S.getLangOpts().CPlusPlus) { 13511 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13512 if (RHS.isInvalid()) 13513 return QualType(); 13514 if (!RHS.get()->getType()->isVoidType()) 13515 S.RequireCompleteType(Loc, RHS.get()->getType(), 13516 diag::err_incomplete_type); 13517 } 13518 13519 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13520 S.DiagnoseCommaOperator(LHS.get(), Loc); 13521 13522 return RHS.get()->getType(); 13523 } 13524 13525 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13526 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13527 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13528 ExprValueKind &VK, 13529 ExprObjectKind &OK, 13530 SourceLocation OpLoc, 13531 bool IsInc, bool IsPrefix) { 13532 if (Op->isTypeDependent()) 13533 return S.Context.DependentTy; 13534 13535 QualType ResType = Op->getType(); 13536 // Atomic types can be used for increment / decrement where the non-atomic 13537 // versions can, so ignore the _Atomic() specifier for the purpose of 13538 // checking. 13539 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13540 ResType = ResAtomicType->getValueType(); 13541 13542 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13543 13544 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13545 // Decrement of bool is not allowed. 13546 if (!IsInc) { 13547 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13548 return QualType(); 13549 } 13550 // Increment of bool sets it to true, but is deprecated. 13551 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13552 : diag::warn_increment_bool) 13553 << Op->getSourceRange(); 13554 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13555 // Error on enum increments and decrements in C++ mode 13556 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13557 return QualType(); 13558 } else if (ResType->isRealType()) { 13559 // OK! 13560 } else if (ResType->isPointerType()) { 13561 // C99 6.5.2.4p2, 6.5.6p2 13562 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13563 return QualType(); 13564 } else if (ResType->isObjCObjectPointerType()) { 13565 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13566 // Otherwise, we just need a complete type. 13567 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13568 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13569 return QualType(); 13570 } else if (ResType->isAnyComplexType()) { 13571 // C99 does not support ++/-- on complex types, we allow as an extension. 13572 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13573 << ResType << Op->getSourceRange(); 13574 } else if (ResType->isPlaceholderType()) { 13575 ExprResult PR = S.CheckPlaceholderExpr(Op); 13576 if (PR.isInvalid()) return QualType(); 13577 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13578 IsInc, IsPrefix); 13579 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13580 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13581 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13582 (ResType->castAs<VectorType>()->getVectorKind() != 13583 VectorType::AltiVecBool)) { 13584 // The z vector extensions allow ++ and -- for non-bool vectors. 13585 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13586 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13587 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13588 } else { 13589 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13590 << ResType << int(IsInc) << Op->getSourceRange(); 13591 return QualType(); 13592 } 13593 // At this point, we know we have a real, complex or pointer type. 13594 // Now make sure the operand is a modifiable lvalue. 13595 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13596 return QualType(); 13597 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13598 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13599 // An operand with volatile-qualified type is deprecated 13600 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13601 << IsInc << ResType; 13602 } 13603 // In C++, a prefix increment is the same type as the operand. Otherwise 13604 // (in C or with postfix), the increment is the unqualified type of the 13605 // operand. 13606 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13607 VK = VK_LValue; 13608 OK = Op->getObjectKind(); 13609 return ResType; 13610 } else { 13611 VK = VK_PRValue; 13612 return ResType.getUnqualifiedType(); 13613 } 13614 } 13615 13616 13617 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13618 /// This routine allows us to typecheck complex/recursive expressions 13619 /// where the declaration is needed for type checking. We only need to 13620 /// handle cases when the expression references a function designator 13621 /// or is an lvalue. Here are some examples: 13622 /// - &(x) => x 13623 /// - &*****f => f for f a function designator. 13624 /// - &s.xx => s 13625 /// - &s.zz[1].yy -> s, if zz is an array 13626 /// - *(x + 1) -> x, if x is an array 13627 /// - &"123"[2] -> 0 13628 /// - & __real__ x -> x 13629 /// 13630 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13631 /// members. 13632 static ValueDecl *getPrimaryDecl(Expr *E) { 13633 switch (E->getStmtClass()) { 13634 case Stmt::DeclRefExprClass: 13635 return cast<DeclRefExpr>(E)->getDecl(); 13636 case Stmt::MemberExprClass: 13637 // If this is an arrow operator, the address is an offset from 13638 // the base's value, so the object the base refers to is 13639 // irrelevant. 13640 if (cast<MemberExpr>(E)->isArrow()) 13641 return nullptr; 13642 // Otherwise, the expression refers to a part of the base 13643 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13644 case Stmt::ArraySubscriptExprClass: { 13645 // FIXME: This code shouldn't be necessary! We should catch the implicit 13646 // promotion of register arrays earlier. 13647 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13648 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13649 if (ICE->getSubExpr()->getType()->isArrayType()) 13650 return getPrimaryDecl(ICE->getSubExpr()); 13651 } 13652 return nullptr; 13653 } 13654 case Stmt::UnaryOperatorClass: { 13655 UnaryOperator *UO = cast<UnaryOperator>(E); 13656 13657 switch(UO->getOpcode()) { 13658 case UO_Real: 13659 case UO_Imag: 13660 case UO_Extension: 13661 return getPrimaryDecl(UO->getSubExpr()); 13662 default: 13663 return nullptr; 13664 } 13665 } 13666 case Stmt::ParenExprClass: 13667 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13668 case Stmt::ImplicitCastExprClass: 13669 // If the result of an implicit cast is an l-value, we care about 13670 // the sub-expression; otherwise, the result here doesn't matter. 13671 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13672 case Stmt::CXXUuidofExprClass: 13673 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13674 default: 13675 return nullptr; 13676 } 13677 } 13678 13679 namespace { 13680 enum { 13681 AO_Bit_Field = 0, 13682 AO_Vector_Element = 1, 13683 AO_Property_Expansion = 2, 13684 AO_Register_Variable = 3, 13685 AO_Matrix_Element = 4, 13686 AO_No_Error = 5 13687 }; 13688 } 13689 /// Diagnose invalid operand for address of operations. 13690 /// 13691 /// \param Type The type of operand which cannot have its address taken. 13692 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13693 Expr *E, unsigned Type) { 13694 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13695 } 13696 13697 /// CheckAddressOfOperand - The operand of & must be either a function 13698 /// designator or an lvalue designating an object. If it is an lvalue, the 13699 /// object cannot be declared with storage class register or be a bit field. 13700 /// Note: The usual conversions are *not* applied to the operand of the & 13701 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13702 /// In C++, the operand might be an overloaded function name, in which case 13703 /// we allow the '&' but retain the overloaded-function type. 13704 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13705 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13706 if (PTy->getKind() == BuiltinType::Overload) { 13707 Expr *E = OrigOp.get()->IgnoreParens(); 13708 if (!isa<OverloadExpr>(E)) { 13709 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13710 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13711 << OrigOp.get()->getSourceRange(); 13712 return QualType(); 13713 } 13714 13715 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13716 if (isa<UnresolvedMemberExpr>(Ovl)) 13717 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13718 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13719 << OrigOp.get()->getSourceRange(); 13720 return QualType(); 13721 } 13722 13723 return Context.OverloadTy; 13724 } 13725 13726 if (PTy->getKind() == BuiltinType::UnknownAny) 13727 return Context.UnknownAnyTy; 13728 13729 if (PTy->getKind() == BuiltinType::BoundMember) { 13730 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13731 << OrigOp.get()->getSourceRange(); 13732 return QualType(); 13733 } 13734 13735 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13736 if (OrigOp.isInvalid()) return QualType(); 13737 } 13738 13739 if (OrigOp.get()->isTypeDependent()) 13740 return Context.DependentTy; 13741 13742 assert(!OrigOp.get()->hasPlaceholderType()); 13743 13744 // Make sure to ignore parentheses in subsequent checks 13745 Expr *op = OrigOp.get()->IgnoreParens(); 13746 13747 // In OpenCL captures for blocks called as lambda functions 13748 // are located in the private address space. Blocks used in 13749 // enqueue_kernel can be located in a different address space 13750 // depending on a vendor implementation. Thus preventing 13751 // taking an address of the capture to avoid invalid AS casts. 13752 if (LangOpts.OpenCL) { 13753 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13754 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13755 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13756 return QualType(); 13757 } 13758 } 13759 13760 if (getLangOpts().C99) { 13761 // Implement C99-only parts of addressof rules. 13762 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13763 if (uOp->getOpcode() == UO_Deref) 13764 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13765 // (assuming the deref expression is valid). 13766 return uOp->getSubExpr()->getType(); 13767 } 13768 // Technically, there should be a check for array subscript 13769 // expressions here, but the result of one is always an lvalue anyway. 13770 } 13771 ValueDecl *dcl = getPrimaryDecl(op); 13772 13773 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13774 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13775 op->getBeginLoc())) 13776 return QualType(); 13777 13778 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13779 unsigned AddressOfError = AO_No_Error; 13780 13781 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13782 bool sfinae = (bool)isSFINAEContext(); 13783 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13784 : diag::ext_typecheck_addrof_temporary) 13785 << op->getType() << op->getSourceRange(); 13786 if (sfinae) 13787 return QualType(); 13788 // Materialize the temporary as an lvalue so that we can take its address. 13789 OrigOp = op = 13790 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13791 } else if (isa<ObjCSelectorExpr>(op)) { 13792 return Context.getPointerType(op->getType()); 13793 } else if (lval == Expr::LV_MemberFunction) { 13794 // If it's an instance method, make a member pointer. 13795 // The expression must have exactly the form &A::foo. 13796 13797 // If the underlying expression isn't a decl ref, give up. 13798 if (!isa<DeclRefExpr>(op)) { 13799 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13800 << OrigOp.get()->getSourceRange(); 13801 return QualType(); 13802 } 13803 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13804 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13805 13806 // The id-expression was parenthesized. 13807 if (OrigOp.get() != DRE) { 13808 Diag(OpLoc, diag::err_parens_pointer_member_function) 13809 << OrigOp.get()->getSourceRange(); 13810 13811 // The method was named without a qualifier. 13812 } else if (!DRE->getQualifier()) { 13813 if (MD->getParent()->getName().empty()) 13814 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13815 << op->getSourceRange(); 13816 else { 13817 SmallString<32> Str; 13818 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13819 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13820 << op->getSourceRange() 13821 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13822 } 13823 } 13824 13825 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13826 if (isa<CXXDestructorDecl>(MD)) 13827 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13828 13829 QualType MPTy = Context.getMemberPointerType( 13830 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13831 // Under the MS ABI, lock down the inheritance model now. 13832 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13833 (void)isCompleteType(OpLoc, MPTy); 13834 return MPTy; 13835 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13836 // C99 6.5.3.2p1 13837 // The operand must be either an l-value or a function designator 13838 if (!op->getType()->isFunctionType()) { 13839 // Use a special diagnostic for loads from property references. 13840 if (isa<PseudoObjectExpr>(op)) { 13841 AddressOfError = AO_Property_Expansion; 13842 } else { 13843 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13844 << op->getType() << op->getSourceRange(); 13845 return QualType(); 13846 } 13847 } 13848 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13849 // The operand cannot be a bit-field 13850 AddressOfError = AO_Bit_Field; 13851 } else if (op->getObjectKind() == OK_VectorComponent) { 13852 // The operand cannot be an element of a vector 13853 AddressOfError = AO_Vector_Element; 13854 } else if (op->getObjectKind() == OK_MatrixComponent) { 13855 // The operand cannot be an element of a matrix. 13856 AddressOfError = AO_Matrix_Element; 13857 } else if (dcl) { // C99 6.5.3.2p1 13858 // We have an lvalue with a decl. Make sure the decl is not declared 13859 // with the register storage-class specifier. 13860 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13861 // in C++ it is not error to take address of a register 13862 // variable (c++03 7.1.1P3) 13863 if (vd->getStorageClass() == SC_Register && 13864 !getLangOpts().CPlusPlus) { 13865 AddressOfError = AO_Register_Variable; 13866 } 13867 } else if (isa<MSPropertyDecl>(dcl)) { 13868 AddressOfError = AO_Property_Expansion; 13869 } else if (isa<FunctionTemplateDecl>(dcl)) { 13870 return Context.OverloadTy; 13871 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13872 // Okay: we can take the address of a field. 13873 // Could be a pointer to member, though, if there is an explicit 13874 // scope qualifier for the class. 13875 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13876 DeclContext *Ctx = dcl->getDeclContext(); 13877 if (Ctx && Ctx->isRecord()) { 13878 if (dcl->getType()->isReferenceType()) { 13879 Diag(OpLoc, 13880 diag::err_cannot_form_pointer_to_member_of_reference_type) 13881 << dcl->getDeclName() << dcl->getType(); 13882 return QualType(); 13883 } 13884 13885 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13886 Ctx = Ctx->getParent(); 13887 13888 QualType MPTy = Context.getMemberPointerType( 13889 op->getType(), 13890 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13891 // Under the MS ABI, lock down the inheritance model now. 13892 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13893 (void)isCompleteType(OpLoc, MPTy); 13894 return MPTy; 13895 } 13896 } 13897 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13898 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13899 llvm_unreachable("Unknown/unexpected decl type"); 13900 } 13901 13902 if (AddressOfError != AO_No_Error) { 13903 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13904 return QualType(); 13905 } 13906 13907 if (lval == Expr::LV_IncompleteVoidType) { 13908 // Taking the address of a void variable is technically illegal, but we 13909 // allow it in cases which are otherwise valid. 13910 // Example: "extern void x; void* y = &x;". 13911 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13912 } 13913 13914 // If the operand has type "type", the result has type "pointer to type". 13915 if (op->getType()->isObjCObjectType()) 13916 return Context.getObjCObjectPointerType(op->getType()); 13917 13918 CheckAddressOfPackedMember(op); 13919 13920 return Context.getPointerType(op->getType()); 13921 } 13922 13923 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13924 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13925 if (!DRE) 13926 return; 13927 const Decl *D = DRE->getDecl(); 13928 if (!D) 13929 return; 13930 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13931 if (!Param) 13932 return; 13933 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13934 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13935 return; 13936 if (FunctionScopeInfo *FD = S.getCurFunction()) 13937 if (!FD->ModifiedNonNullParams.count(Param)) 13938 FD->ModifiedNonNullParams.insert(Param); 13939 } 13940 13941 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13942 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13943 SourceLocation OpLoc) { 13944 if (Op->isTypeDependent()) 13945 return S.Context.DependentTy; 13946 13947 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13948 if (ConvResult.isInvalid()) 13949 return QualType(); 13950 Op = ConvResult.get(); 13951 QualType OpTy = Op->getType(); 13952 QualType Result; 13953 13954 if (isa<CXXReinterpretCastExpr>(Op)) { 13955 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13956 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13957 Op->getSourceRange()); 13958 } 13959 13960 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13961 { 13962 Result = PT->getPointeeType(); 13963 } 13964 else if (const ObjCObjectPointerType *OPT = 13965 OpTy->getAs<ObjCObjectPointerType>()) 13966 Result = OPT->getPointeeType(); 13967 else { 13968 ExprResult PR = S.CheckPlaceholderExpr(Op); 13969 if (PR.isInvalid()) return QualType(); 13970 if (PR.get() != Op) 13971 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13972 } 13973 13974 if (Result.isNull()) { 13975 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13976 << OpTy << Op->getSourceRange(); 13977 return QualType(); 13978 } 13979 13980 // Note that per both C89 and C99, indirection is always legal, even if Result 13981 // is an incomplete type or void. It would be possible to warn about 13982 // dereferencing a void pointer, but it's completely well-defined, and such a 13983 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13984 // for pointers to 'void' but is fine for any other pointer type: 13985 // 13986 // C++ [expr.unary.op]p1: 13987 // [...] the expression to which [the unary * operator] is applied shall 13988 // be a pointer to an object type, or a pointer to a function type 13989 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13990 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13991 << OpTy << Op->getSourceRange(); 13992 13993 // Dereferences are usually l-values... 13994 VK = VK_LValue; 13995 13996 // ...except that certain expressions are never l-values in C. 13997 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13998 VK = VK_PRValue; 13999 14000 return Result; 14001 } 14002 14003 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 14004 BinaryOperatorKind Opc; 14005 switch (Kind) { 14006 default: llvm_unreachable("Unknown binop!"); 14007 case tok::periodstar: Opc = BO_PtrMemD; break; 14008 case tok::arrowstar: Opc = BO_PtrMemI; break; 14009 case tok::star: Opc = BO_Mul; break; 14010 case tok::slash: Opc = BO_Div; break; 14011 case tok::percent: Opc = BO_Rem; break; 14012 case tok::plus: Opc = BO_Add; break; 14013 case tok::minus: Opc = BO_Sub; break; 14014 case tok::lessless: Opc = BO_Shl; break; 14015 case tok::greatergreater: Opc = BO_Shr; break; 14016 case tok::lessequal: Opc = BO_LE; break; 14017 case tok::less: Opc = BO_LT; break; 14018 case tok::greaterequal: Opc = BO_GE; break; 14019 case tok::greater: Opc = BO_GT; break; 14020 case tok::exclaimequal: Opc = BO_NE; break; 14021 case tok::equalequal: Opc = BO_EQ; break; 14022 case tok::spaceship: Opc = BO_Cmp; break; 14023 case tok::amp: Opc = BO_And; break; 14024 case tok::caret: Opc = BO_Xor; break; 14025 case tok::pipe: Opc = BO_Or; break; 14026 case tok::ampamp: Opc = BO_LAnd; break; 14027 case tok::pipepipe: Opc = BO_LOr; break; 14028 case tok::equal: Opc = BO_Assign; break; 14029 case tok::starequal: Opc = BO_MulAssign; break; 14030 case tok::slashequal: Opc = BO_DivAssign; break; 14031 case tok::percentequal: Opc = BO_RemAssign; break; 14032 case tok::plusequal: Opc = BO_AddAssign; break; 14033 case tok::minusequal: Opc = BO_SubAssign; break; 14034 case tok::lesslessequal: Opc = BO_ShlAssign; break; 14035 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 14036 case tok::ampequal: Opc = BO_AndAssign; break; 14037 case tok::caretequal: Opc = BO_XorAssign; break; 14038 case tok::pipeequal: Opc = BO_OrAssign; break; 14039 case tok::comma: Opc = BO_Comma; break; 14040 } 14041 return Opc; 14042 } 14043 14044 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 14045 tok::TokenKind Kind) { 14046 UnaryOperatorKind Opc; 14047 switch (Kind) { 14048 default: llvm_unreachable("Unknown unary op!"); 14049 case tok::plusplus: Opc = UO_PreInc; break; 14050 case tok::minusminus: Opc = UO_PreDec; break; 14051 case tok::amp: Opc = UO_AddrOf; break; 14052 case tok::star: Opc = UO_Deref; break; 14053 case tok::plus: Opc = UO_Plus; break; 14054 case tok::minus: Opc = UO_Minus; break; 14055 case tok::tilde: Opc = UO_Not; break; 14056 case tok::exclaim: Opc = UO_LNot; break; 14057 case tok::kw___real: Opc = UO_Real; break; 14058 case tok::kw___imag: Opc = UO_Imag; break; 14059 case tok::kw___extension__: Opc = UO_Extension; break; 14060 } 14061 return Opc; 14062 } 14063 14064 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 14065 /// This warning suppressed in the event of macro expansions. 14066 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 14067 SourceLocation OpLoc, bool IsBuiltin) { 14068 if (S.inTemplateInstantiation()) 14069 return; 14070 if (S.isUnevaluatedContext()) 14071 return; 14072 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 14073 return; 14074 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14075 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14076 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14077 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14078 if (!LHSDeclRef || !RHSDeclRef || 14079 LHSDeclRef->getLocation().isMacroID() || 14080 RHSDeclRef->getLocation().isMacroID()) 14081 return; 14082 const ValueDecl *LHSDecl = 14083 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 14084 const ValueDecl *RHSDecl = 14085 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 14086 if (LHSDecl != RHSDecl) 14087 return; 14088 if (LHSDecl->getType().isVolatileQualified()) 14089 return; 14090 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 14091 if (RefTy->getPointeeType().isVolatileQualified()) 14092 return; 14093 14094 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 14095 : diag::warn_self_assignment_overloaded) 14096 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 14097 << RHSExpr->getSourceRange(); 14098 } 14099 14100 /// Check if a bitwise-& is performed on an Objective-C pointer. This 14101 /// is usually indicative of introspection within the Objective-C pointer. 14102 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 14103 SourceLocation OpLoc) { 14104 if (!S.getLangOpts().ObjC) 14105 return; 14106 14107 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 14108 const Expr *LHS = L.get(); 14109 const Expr *RHS = R.get(); 14110 14111 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14112 ObjCPointerExpr = LHS; 14113 OtherExpr = RHS; 14114 } 14115 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14116 ObjCPointerExpr = RHS; 14117 OtherExpr = LHS; 14118 } 14119 14120 // This warning is deliberately made very specific to reduce false 14121 // positives with logic that uses '&' for hashing. This logic mainly 14122 // looks for code trying to introspect into tagged pointers, which 14123 // code should generally never do. 14124 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 14125 unsigned Diag = diag::warn_objc_pointer_masking; 14126 // Determine if we are introspecting the result of performSelectorXXX. 14127 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 14128 // Special case messages to -performSelector and friends, which 14129 // can return non-pointer values boxed in a pointer value. 14130 // Some clients may wish to silence warnings in this subcase. 14131 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14132 Selector S = ME->getSelector(); 14133 StringRef SelArg0 = S.getNameForSlot(0); 14134 if (SelArg0.startswith("performSelector")) 14135 Diag = diag::warn_objc_pointer_masking_performSelector; 14136 } 14137 14138 S.Diag(OpLoc, Diag) 14139 << ObjCPointerExpr->getSourceRange(); 14140 } 14141 } 14142 14143 static NamedDecl *getDeclFromExpr(Expr *E) { 14144 if (!E) 14145 return nullptr; 14146 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14147 return DRE->getDecl(); 14148 if (auto *ME = dyn_cast<MemberExpr>(E)) 14149 return ME->getMemberDecl(); 14150 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14151 return IRE->getDecl(); 14152 return nullptr; 14153 } 14154 14155 // This helper function promotes a binary operator's operands (which are of a 14156 // half vector type) to a vector of floats and then truncates the result to 14157 // a vector of either half or short. 14158 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14159 BinaryOperatorKind Opc, QualType ResultTy, 14160 ExprValueKind VK, ExprObjectKind OK, 14161 bool IsCompAssign, SourceLocation OpLoc, 14162 FPOptionsOverride FPFeatures) { 14163 auto &Context = S.getASTContext(); 14164 assert((isVector(ResultTy, Context.HalfTy) || 14165 isVector(ResultTy, Context.ShortTy)) && 14166 "Result must be a vector of half or short"); 14167 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14168 isVector(RHS.get()->getType(), Context.HalfTy) && 14169 "both operands expected to be a half vector"); 14170 14171 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14172 QualType BinOpResTy = RHS.get()->getType(); 14173 14174 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14175 // change BinOpResTy to a vector of ints. 14176 if (isVector(ResultTy, Context.ShortTy)) 14177 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14178 14179 if (IsCompAssign) 14180 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14181 ResultTy, VK, OK, OpLoc, FPFeatures, 14182 BinOpResTy, BinOpResTy); 14183 14184 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14185 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14186 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14187 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14188 } 14189 14190 static std::pair<ExprResult, ExprResult> 14191 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14192 Expr *RHSExpr) { 14193 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14194 if (!S.Context.isDependenceAllowed()) { 14195 // C cannot handle TypoExpr nodes on either side of a binop because it 14196 // doesn't handle dependent types properly, so make sure any TypoExprs have 14197 // been dealt with before checking the operands. 14198 LHS = S.CorrectDelayedTyposInExpr(LHS); 14199 RHS = S.CorrectDelayedTyposInExpr( 14200 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14201 [Opc, LHS](Expr *E) { 14202 if (Opc != BO_Assign) 14203 return ExprResult(E); 14204 // Avoid correcting the RHS to the same Expr as the LHS. 14205 Decl *D = getDeclFromExpr(E); 14206 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14207 }); 14208 } 14209 return std::make_pair(LHS, RHS); 14210 } 14211 14212 /// Returns true if conversion between vectors of halfs and vectors of floats 14213 /// is needed. 14214 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14215 Expr *E0, Expr *E1 = nullptr) { 14216 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14217 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14218 return false; 14219 14220 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14221 QualType Ty = E->IgnoreImplicit()->getType(); 14222 14223 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14224 // to vectors of floats. Although the element type of the vectors is __fp16, 14225 // the vectors shouldn't be treated as storage-only types. See the 14226 // discussion here: https://reviews.llvm.org/rG825235c140e7 14227 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14228 if (VT->getVectorKind() == VectorType::NeonVector) 14229 return false; 14230 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14231 } 14232 return false; 14233 }; 14234 14235 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14236 } 14237 14238 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14239 /// operator @p Opc at location @c TokLoc. This routine only supports 14240 /// built-in operations; ActOnBinOp handles overloaded operators. 14241 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14242 BinaryOperatorKind Opc, 14243 Expr *LHSExpr, Expr *RHSExpr) { 14244 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14245 // The syntax only allows initializer lists on the RHS of assignment, 14246 // so we don't need to worry about accepting invalid code for 14247 // non-assignment operators. 14248 // C++11 5.17p9: 14249 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14250 // of x = {} is x = T(). 14251 InitializationKind Kind = InitializationKind::CreateDirectList( 14252 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14253 InitializedEntity Entity = 14254 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14255 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14256 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14257 if (Init.isInvalid()) 14258 return Init; 14259 RHSExpr = Init.get(); 14260 } 14261 14262 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14263 QualType ResultTy; // Result type of the binary operator. 14264 // The following two variables are used for compound assignment operators 14265 QualType CompLHSTy; // Type of LHS after promotions for computation 14266 QualType CompResultTy; // Type of computation result 14267 ExprValueKind VK = VK_PRValue; 14268 ExprObjectKind OK = OK_Ordinary; 14269 bool ConvertHalfVec = false; 14270 14271 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14272 if (!LHS.isUsable() || !RHS.isUsable()) 14273 return ExprError(); 14274 14275 if (getLangOpts().OpenCL) { 14276 QualType LHSTy = LHSExpr->getType(); 14277 QualType RHSTy = RHSExpr->getType(); 14278 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14279 // the ATOMIC_VAR_INIT macro. 14280 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14281 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14282 if (BO_Assign == Opc) 14283 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14284 else 14285 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14286 return ExprError(); 14287 } 14288 14289 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14290 // only with a builtin functions and therefore should be disallowed here. 14291 if (LHSTy->isImageType() || RHSTy->isImageType() || 14292 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14293 LHSTy->isPipeType() || RHSTy->isPipeType() || 14294 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14295 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14296 return ExprError(); 14297 } 14298 } 14299 14300 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14301 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14302 14303 switch (Opc) { 14304 case BO_Assign: 14305 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14306 if (getLangOpts().CPlusPlus && 14307 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14308 VK = LHS.get()->getValueKind(); 14309 OK = LHS.get()->getObjectKind(); 14310 } 14311 if (!ResultTy.isNull()) { 14312 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14313 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14314 14315 // Avoid copying a block to the heap if the block is assigned to a local 14316 // auto variable that is declared in the same scope as the block. This 14317 // optimization is unsafe if the local variable is declared in an outer 14318 // scope. For example: 14319 // 14320 // BlockTy b; 14321 // { 14322 // b = ^{...}; 14323 // } 14324 // // It is unsafe to invoke the block here if it wasn't copied to the 14325 // // heap. 14326 // b(); 14327 14328 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14329 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14330 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14331 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14332 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14333 14334 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14335 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14336 NTCUC_Assignment, NTCUK_Copy); 14337 } 14338 RecordModifiableNonNullParam(*this, LHS.get()); 14339 break; 14340 case BO_PtrMemD: 14341 case BO_PtrMemI: 14342 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14343 Opc == BO_PtrMemI); 14344 break; 14345 case BO_Mul: 14346 case BO_Div: 14347 ConvertHalfVec = true; 14348 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14349 Opc == BO_Div); 14350 break; 14351 case BO_Rem: 14352 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14353 break; 14354 case BO_Add: 14355 ConvertHalfVec = true; 14356 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14357 break; 14358 case BO_Sub: 14359 ConvertHalfVec = true; 14360 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14361 break; 14362 case BO_Shl: 14363 case BO_Shr: 14364 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14365 break; 14366 case BO_LE: 14367 case BO_LT: 14368 case BO_GE: 14369 case BO_GT: 14370 ConvertHalfVec = true; 14371 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14372 break; 14373 case BO_EQ: 14374 case BO_NE: 14375 ConvertHalfVec = true; 14376 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14377 break; 14378 case BO_Cmp: 14379 ConvertHalfVec = true; 14380 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14381 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14382 break; 14383 case BO_And: 14384 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14385 LLVM_FALLTHROUGH; 14386 case BO_Xor: 14387 case BO_Or: 14388 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14389 break; 14390 case BO_LAnd: 14391 case BO_LOr: 14392 ConvertHalfVec = true; 14393 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14394 break; 14395 case BO_MulAssign: 14396 case BO_DivAssign: 14397 ConvertHalfVec = true; 14398 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14399 Opc == BO_DivAssign); 14400 CompLHSTy = CompResultTy; 14401 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14402 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14403 break; 14404 case BO_RemAssign: 14405 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14406 CompLHSTy = CompResultTy; 14407 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14408 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14409 break; 14410 case BO_AddAssign: 14411 ConvertHalfVec = true; 14412 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14413 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14414 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14415 break; 14416 case BO_SubAssign: 14417 ConvertHalfVec = true; 14418 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14419 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14420 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14421 break; 14422 case BO_ShlAssign: 14423 case BO_ShrAssign: 14424 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14425 CompLHSTy = CompResultTy; 14426 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14427 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14428 break; 14429 case BO_AndAssign: 14430 case BO_OrAssign: // fallthrough 14431 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14432 LLVM_FALLTHROUGH; 14433 case BO_XorAssign: 14434 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14435 CompLHSTy = CompResultTy; 14436 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14437 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14438 break; 14439 case BO_Comma: 14440 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14441 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14442 VK = RHS.get()->getValueKind(); 14443 OK = RHS.get()->getObjectKind(); 14444 } 14445 break; 14446 } 14447 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14448 return ExprError(); 14449 14450 // Some of the binary operations require promoting operands of half vector to 14451 // float vectors and truncating the result back to half vector. For now, we do 14452 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14453 // arm64). 14454 assert( 14455 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14456 isVector(LHS.get()->getType(), Context.HalfTy)) && 14457 "both sides are half vectors or neither sides are"); 14458 ConvertHalfVec = 14459 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14460 14461 // Check for array bounds violations for both sides of the BinaryOperator 14462 CheckArrayAccess(LHS.get()); 14463 CheckArrayAccess(RHS.get()); 14464 14465 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14466 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14467 &Context.Idents.get("object_setClass"), 14468 SourceLocation(), LookupOrdinaryName); 14469 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14470 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14471 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14472 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14473 "object_setClass(") 14474 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14475 ",") 14476 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14477 } 14478 else 14479 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14480 } 14481 else if (const ObjCIvarRefExpr *OIRE = 14482 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14483 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14484 14485 // Opc is not a compound assignment if CompResultTy is null. 14486 if (CompResultTy.isNull()) { 14487 if (ConvertHalfVec) 14488 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14489 OpLoc, CurFPFeatureOverrides()); 14490 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14491 VK, OK, OpLoc, CurFPFeatureOverrides()); 14492 } 14493 14494 // Handle compound assignments. 14495 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14496 OK_ObjCProperty) { 14497 VK = VK_LValue; 14498 OK = LHS.get()->getObjectKind(); 14499 } 14500 14501 // The LHS is not converted to the result type for fixed-point compound 14502 // assignment as the common type is computed on demand. Reset the CompLHSTy 14503 // to the LHS type we would have gotten after unary conversions. 14504 if (CompResultTy->isFixedPointType()) 14505 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14506 14507 if (ConvertHalfVec) 14508 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14509 OpLoc, CurFPFeatureOverrides()); 14510 14511 return CompoundAssignOperator::Create( 14512 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14513 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14514 } 14515 14516 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14517 /// operators are mixed in a way that suggests that the programmer forgot that 14518 /// comparison operators have higher precedence. The most typical example of 14519 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14520 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14521 SourceLocation OpLoc, Expr *LHSExpr, 14522 Expr *RHSExpr) { 14523 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14524 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14525 14526 // Check that one of the sides is a comparison operator and the other isn't. 14527 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14528 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14529 if (isLeftComp == isRightComp) 14530 return; 14531 14532 // Bitwise operations are sometimes used as eager logical ops. 14533 // Don't diagnose this. 14534 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14535 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14536 if (isLeftBitwise || isRightBitwise) 14537 return; 14538 14539 SourceRange DiagRange = isLeftComp 14540 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14541 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14542 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14543 SourceRange ParensRange = 14544 isLeftComp 14545 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14546 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14547 14548 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14549 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14550 SuggestParentheses(Self, OpLoc, 14551 Self.PDiag(diag::note_precedence_silence) << OpStr, 14552 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14553 SuggestParentheses(Self, OpLoc, 14554 Self.PDiag(diag::note_precedence_bitwise_first) 14555 << BinaryOperator::getOpcodeStr(Opc), 14556 ParensRange); 14557 } 14558 14559 /// It accepts a '&&' expr that is inside a '||' one. 14560 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14561 /// in parentheses. 14562 static void 14563 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14564 BinaryOperator *Bop) { 14565 assert(Bop->getOpcode() == BO_LAnd); 14566 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14567 << Bop->getSourceRange() << OpLoc; 14568 SuggestParentheses(Self, Bop->getOperatorLoc(), 14569 Self.PDiag(diag::note_precedence_silence) 14570 << Bop->getOpcodeStr(), 14571 Bop->getSourceRange()); 14572 } 14573 14574 /// Returns true if the given expression can be evaluated as a constant 14575 /// 'true'. 14576 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14577 bool Res; 14578 return !E->isValueDependent() && 14579 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14580 } 14581 14582 /// Returns true if the given expression can be evaluated as a constant 14583 /// 'false'. 14584 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14585 bool Res; 14586 return !E->isValueDependent() && 14587 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14588 } 14589 14590 /// Look for '&&' in the left hand of a '||' expr. 14591 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14592 Expr *LHSExpr, Expr *RHSExpr) { 14593 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14594 if (Bop->getOpcode() == BO_LAnd) { 14595 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14596 if (EvaluatesAsFalse(S, RHSExpr)) 14597 return; 14598 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14599 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14600 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14601 } else if (Bop->getOpcode() == BO_LOr) { 14602 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14603 // If it's "a || b && 1 || c" we didn't warn earlier for 14604 // "a || b && 1", but warn now. 14605 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14606 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14607 } 14608 } 14609 } 14610 } 14611 14612 /// Look for '&&' in the right hand of a '||' expr. 14613 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14614 Expr *LHSExpr, Expr *RHSExpr) { 14615 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14616 if (Bop->getOpcode() == BO_LAnd) { 14617 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14618 if (EvaluatesAsFalse(S, LHSExpr)) 14619 return; 14620 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14621 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14622 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14623 } 14624 } 14625 } 14626 14627 /// Look for bitwise op in the left or right hand of a bitwise op with 14628 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14629 /// the '&' expression in parentheses. 14630 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14631 SourceLocation OpLoc, Expr *SubExpr) { 14632 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14633 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14634 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14635 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14636 << Bop->getSourceRange() << OpLoc; 14637 SuggestParentheses(S, Bop->getOperatorLoc(), 14638 S.PDiag(diag::note_precedence_silence) 14639 << Bop->getOpcodeStr(), 14640 Bop->getSourceRange()); 14641 } 14642 } 14643 } 14644 14645 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14646 Expr *SubExpr, StringRef Shift) { 14647 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14648 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14649 StringRef Op = Bop->getOpcodeStr(); 14650 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14651 << Bop->getSourceRange() << OpLoc << Shift << Op; 14652 SuggestParentheses(S, Bop->getOperatorLoc(), 14653 S.PDiag(diag::note_precedence_silence) << Op, 14654 Bop->getSourceRange()); 14655 } 14656 } 14657 } 14658 14659 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14660 Expr *LHSExpr, Expr *RHSExpr) { 14661 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14662 if (!OCE) 14663 return; 14664 14665 FunctionDecl *FD = OCE->getDirectCallee(); 14666 if (!FD || !FD->isOverloadedOperator()) 14667 return; 14668 14669 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14670 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14671 return; 14672 14673 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14674 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14675 << (Kind == OO_LessLess); 14676 SuggestParentheses(S, OCE->getOperatorLoc(), 14677 S.PDiag(diag::note_precedence_silence) 14678 << (Kind == OO_LessLess ? "<<" : ">>"), 14679 OCE->getSourceRange()); 14680 SuggestParentheses( 14681 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14682 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14683 } 14684 14685 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14686 /// precedence. 14687 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14688 SourceLocation OpLoc, Expr *LHSExpr, 14689 Expr *RHSExpr){ 14690 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14691 if (BinaryOperator::isBitwiseOp(Opc)) 14692 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14693 14694 // Diagnose "arg1 & arg2 | arg3" 14695 if ((Opc == BO_Or || Opc == BO_Xor) && 14696 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14697 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14698 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14699 } 14700 14701 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14702 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14703 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14704 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14705 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14706 } 14707 14708 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14709 || Opc == BO_Shr) { 14710 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14711 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14712 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14713 } 14714 14715 // Warn on overloaded shift operators and comparisons, such as: 14716 // cout << 5 == 4; 14717 if (BinaryOperator::isComparisonOp(Opc)) 14718 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14719 } 14720 14721 // Binary Operators. 'Tok' is the token for the operator. 14722 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14723 tok::TokenKind Kind, 14724 Expr *LHSExpr, Expr *RHSExpr) { 14725 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14726 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14727 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14728 14729 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14730 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14731 14732 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14733 } 14734 14735 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14736 UnresolvedSetImpl &Functions) { 14737 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14738 if (OverOp != OO_None && OverOp != OO_Equal) 14739 LookupOverloadedOperatorName(OverOp, S, Functions); 14740 14741 // In C++20 onwards, we may have a second operator to look up. 14742 if (getLangOpts().CPlusPlus20) { 14743 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14744 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14745 } 14746 } 14747 14748 /// Build an overloaded binary operator expression in the given scope. 14749 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14750 BinaryOperatorKind Opc, 14751 Expr *LHS, Expr *RHS) { 14752 switch (Opc) { 14753 case BO_Assign: 14754 case BO_DivAssign: 14755 case BO_RemAssign: 14756 case BO_SubAssign: 14757 case BO_AndAssign: 14758 case BO_OrAssign: 14759 case BO_XorAssign: 14760 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14761 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14762 break; 14763 default: 14764 break; 14765 } 14766 14767 // Find all of the overloaded operators visible from this point. 14768 UnresolvedSet<16> Functions; 14769 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14770 14771 // Build the (potentially-overloaded, potentially-dependent) 14772 // binary operation. 14773 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14774 } 14775 14776 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14777 BinaryOperatorKind Opc, 14778 Expr *LHSExpr, Expr *RHSExpr) { 14779 ExprResult LHS, RHS; 14780 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14781 if (!LHS.isUsable() || !RHS.isUsable()) 14782 return ExprError(); 14783 LHSExpr = LHS.get(); 14784 RHSExpr = RHS.get(); 14785 14786 // We want to end up calling one of checkPseudoObjectAssignment 14787 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14788 // both expressions are overloadable or either is type-dependent), 14789 // or CreateBuiltinBinOp (in any other case). We also want to get 14790 // any placeholder types out of the way. 14791 14792 // Handle pseudo-objects in the LHS. 14793 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14794 // Assignments with a pseudo-object l-value need special analysis. 14795 if (pty->getKind() == BuiltinType::PseudoObject && 14796 BinaryOperator::isAssignmentOp(Opc)) 14797 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14798 14799 // Don't resolve overloads if the other type is overloadable. 14800 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14801 // We can't actually test that if we still have a placeholder, 14802 // though. Fortunately, none of the exceptions we see in that 14803 // code below are valid when the LHS is an overload set. Note 14804 // that an overload set can be dependently-typed, but it never 14805 // instantiates to having an overloadable type. 14806 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14807 if (resolvedRHS.isInvalid()) return ExprError(); 14808 RHSExpr = resolvedRHS.get(); 14809 14810 if (RHSExpr->isTypeDependent() || 14811 RHSExpr->getType()->isOverloadableType()) 14812 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14813 } 14814 14815 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14816 // template, diagnose the missing 'template' keyword instead of diagnosing 14817 // an invalid use of a bound member function. 14818 // 14819 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14820 // to C++1z [over.over]/1.4, but we already checked for that case above. 14821 if (Opc == BO_LT && inTemplateInstantiation() && 14822 (pty->getKind() == BuiltinType::BoundMember || 14823 pty->getKind() == BuiltinType::Overload)) { 14824 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14825 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14826 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14827 return isa<FunctionTemplateDecl>(ND); 14828 })) { 14829 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14830 : OE->getNameLoc(), 14831 diag::err_template_kw_missing) 14832 << OE->getName().getAsString() << ""; 14833 return ExprError(); 14834 } 14835 } 14836 14837 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14838 if (LHS.isInvalid()) return ExprError(); 14839 LHSExpr = LHS.get(); 14840 } 14841 14842 // Handle pseudo-objects in the RHS. 14843 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14844 // An overload in the RHS can potentially be resolved by the type 14845 // being assigned to. 14846 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14847 if (getLangOpts().CPlusPlus && 14848 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14849 LHSExpr->getType()->isOverloadableType())) 14850 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14851 14852 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14853 } 14854 14855 // Don't resolve overloads if the other type is overloadable. 14856 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14857 LHSExpr->getType()->isOverloadableType()) 14858 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14859 14860 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14861 if (!resolvedRHS.isUsable()) return ExprError(); 14862 RHSExpr = resolvedRHS.get(); 14863 } 14864 14865 if (getLangOpts().CPlusPlus) { 14866 // If either expression is type-dependent, always build an 14867 // overloaded op. 14868 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14869 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14870 14871 // Otherwise, build an overloaded op if either expression has an 14872 // overloadable type. 14873 if (LHSExpr->getType()->isOverloadableType() || 14874 RHSExpr->getType()->isOverloadableType()) 14875 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14876 } 14877 14878 if (getLangOpts().RecoveryAST && 14879 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14880 assert(!getLangOpts().CPlusPlus); 14881 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14882 "Should only occur in error-recovery path."); 14883 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14884 // C [6.15.16] p3: 14885 // An assignment expression has the value of the left operand after the 14886 // assignment, but is not an lvalue. 14887 return CompoundAssignOperator::Create( 14888 Context, LHSExpr, RHSExpr, Opc, 14889 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14890 OpLoc, CurFPFeatureOverrides()); 14891 QualType ResultType; 14892 switch (Opc) { 14893 case BO_Assign: 14894 ResultType = LHSExpr->getType().getUnqualifiedType(); 14895 break; 14896 case BO_LT: 14897 case BO_GT: 14898 case BO_LE: 14899 case BO_GE: 14900 case BO_EQ: 14901 case BO_NE: 14902 case BO_LAnd: 14903 case BO_LOr: 14904 // These operators have a fixed result type regardless of operands. 14905 ResultType = Context.IntTy; 14906 break; 14907 case BO_Comma: 14908 ResultType = RHSExpr->getType(); 14909 break; 14910 default: 14911 ResultType = Context.DependentTy; 14912 break; 14913 } 14914 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14915 VK_PRValue, OK_Ordinary, OpLoc, 14916 CurFPFeatureOverrides()); 14917 } 14918 14919 // Build a built-in binary operation. 14920 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14921 } 14922 14923 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14924 if (T.isNull() || T->isDependentType()) 14925 return false; 14926 14927 if (!T->isPromotableIntegerType()) 14928 return true; 14929 14930 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14931 } 14932 14933 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14934 UnaryOperatorKind Opc, 14935 Expr *InputExpr) { 14936 ExprResult Input = InputExpr; 14937 ExprValueKind VK = VK_PRValue; 14938 ExprObjectKind OK = OK_Ordinary; 14939 QualType resultType; 14940 bool CanOverflow = false; 14941 14942 bool ConvertHalfVec = false; 14943 if (getLangOpts().OpenCL) { 14944 QualType Ty = InputExpr->getType(); 14945 // The only legal unary operation for atomics is '&'. 14946 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14947 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14948 // only with a builtin functions and therefore should be disallowed here. 14949 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14950 || Ty->isBlockPointerType())) { 14951 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14952 << InputExpr->getType() 14953 << Input.get()->getSourceRange()); 14954 } 14955 } 14956 14957 switch (Opc) { 14958 case UO_PreInc: 14959 case UO_PreDec: 14960 case UO_PostInc: 14961 case UO_PostDec: 14962 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14963 OpLoc, 14964 Opc == UO_PreInc || 14965 Opc == UO_PostInc, 14966 Opc == UO_PreInc || 14967 Opc == UO_PreDec); 14968 CanOverflow = isOverflowingIntegerType(Context, resultType); 14969 break; 14970 case UO_AddrOf: 14971 resultType = CheckAddressOfOperand(Input, OpLoc); 14972 CheckAddressOfNoDeref(InputExpr); 14973 RecordModifiableNonNullParam(*this, InputExpr); 14974 break; 14975 case UO_Deref: { 14976 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14977 if (Input.isInvalid()) return ExprError(); 14978 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14979 break; 14980 } 14981 case UO_Plus: 14982 case UO_Minus: 14983 CanOverflow = Opc == UO_Minus && 14984 isOverflowingIntegerType(Context, Input.get()->getType()); 14985 Input = UsualUnaryConversions(Input.get()); 14986 if (Input.isInvalid()) return ExprError(); 14987 // Unary plus and minus require promoting an operand of half vector to a 14988 // float vector and truncating the result back to a half vector. For now, we 14989 // do this only when HalfArgsAndReturns is set (that is, when the target is 14990 // arm or arm64). 14991 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14992 14993 // If the operand is a half vector, promote it to a float vector. 14994 if (ConvertHalfVec) 14995 Input = convertVector(Input.get(), Context.FloatTy, *this); 14996 resultType = Input.get()->getType(); 14997 if (resultType->isDependentType()) 14998 break; 14999 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 15000 break; 15001 else if (resultType->isVectorType() && 15002 // The z vector extensions don't allow + or - with bool vectors. 15003 (!Context.getLangOpts().ZVector || 15004 resultType->castAs<VectorType>()->getVectorKind() != 15005 VectorType::AltiVecBool)) 15006 break; 15007 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 15008 Opc == UO_Plus && 15009 resultType->isPointerType()) 15010 break; 15011 15012 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15013 << resultType << Input.get()->getSourceRange()); 15014 15015 case UO_Not: // bitwise complement 15016 Input = UsualUnaryConversions(Input.get()); 15017 if (Input.isInvalid()) 15018 return ExprError(); 15019 resultType = Input.get()->getType(); 15020 if (resultType->isDependentType()) 15021 break; 15022 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 15023 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 15024 // C99 does not support '~' for complex conjugation. 15025 Diag(OpLoc, diag::ext_integer_complement_complex) 15026 << resultType << Input.get()->getSourceRange(); 15027 else if (resultType->hasIntegerRepresentation()) 15028 break; 15029 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 15030 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 15031 // on vector float types. 15032 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15033 if (!T->isIntegerType()) 15034 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15035 << resultType << Input.get()->getSourceRange()); 15036 } else { 15037 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15038 << resultType << Input.get()->getSourceRange()); 15039 } 15040 break; 15041 15042 case UO_LNot: // logical negation 15043 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 15044 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15045 if (Input.isInvalid()) return ExprError(); 15046 resultType = Input.get()->getType(); 15047 15048 // Though we still have to promote half FP to float... 15049 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 15050 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 15051 resultType = Context.FloatTy; 15052 } 15053 15054 if (resultType->isDependentType()) 15055 break; 15056 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 15057 // C99 6.5.3.3p1: ok, fallthrough; 15058 if (Context.getLangOpts().CPlusPlus) { 15059 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 15060 // operand contextually converted to bool. 15061 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 15062 ScalarTypeToBooleanCastKind(resultType)); 15063 } else if (Context.getLangOpts().OpenCL && 15064 Context.getLangOpts().OpenCLVersion < 120) { 15065 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15066 // operate on scalar float types. 15067 if (!resultType->isIntegerType() && !resultType->isPointerType()) 15068 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15069 << resultType << Input.get()->getSourceRange()); 15070 } 15071 } else if (resultType->isExtVectorType()) { 15072 if (Context.getLangOpts().OpenCL && 15073 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 15074 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15075 // operate on vector float types. 15076 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15077 if (!T->isIntegerType()) 15078 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15079 << resultType << Input.get()->getSourceRange()); 15080 } 15081 // Vector logical not returns the signed variant of the operand type. 15082 resultType = GetSignedVectorType(resultType); 15083 break; 15084 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 15085 const VectorType *VTy = resultType->castAs<VectorType>(); 15086 if (VTy->getVectorKind() != VectorType::GenericVector) 15087 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15088 << resultType << Input.get()->getSourceRange()); 15089 15090 // Vector logical not returns the signed variant of the operand type. 15091 resultType = GetSignedVectorType(resultType); 15092 break; 15093 } else { 15094 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15095 << resultType << Input.get()->getSourceRange()); 15096 } 15097 15098 // LNot always has type int. C99 6.5.3.3p5. 15099 // In C++, it's bool. C++ 5.3.1p8 15100 resultType = Context.getLogicalOperationType(); 15101 break; 15102 case UO_Real: 15103 case UO_Imag: 15104 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 15105 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 15106 // complex l-values to ordinary l-values and all other values to r-values. 15107 if (Input.isInvalid()) return ExprError(); 15108 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 15109 if (Input.get()->isGLValue() && 15110 Input.get()->getObjectKind() == OK_Ordinary) 15111 VK = Input.get()->getValueKind(); 15112 } else if (!getLangOpts().CPlusPlus) { 15113 // In C, a volatile scalar is read by __imag. In C++, it is not. 15114 Input = DefaultLvalueConversion(Input.get()); 15115 } 15116 break; 15117 case UO_Extension: 15118 resultType = Input.get()->getType(); 15119 VK = Input.get()->getValueKind(); 15120 OK = Input.get()->getObjectKind(); 15121 break; 15122 case UO_Coawait: 15123 // It's unnecessary to represent the pass-through operator co_await in the 15124 // AST; just return the input expression instead. 15125 assert(!Input.get()->getType()->isDependentType() && 15126 "the co_await expression must be non-dependant before " 15127 "building operator co_await"); 15128 return Input; 15129 } 15130 if (resultType.isNull() || Input.isInvalid()) 15131 return ExprError(); 15132 15133 // Check for array bounds violations in the operand of the UnaryOperator, 15134 // except for the '*' and '&' operators that have to be handled specially 15135 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15136 // that are explicitly defined as valid by the standard). 15137 if (Opc != UO_AddrOf && Opc != UO_Deref) 15138 CheckArrayAccess(Input.get()); 15139 15140 auto *UO = 15141 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15142 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15143 15144 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15145 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15146 !isUnevaluatedContext()) 15147 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15148 15149 // Convert the result back to a half vector. 15150 if (ConvertHalfVec) 15151 return convertVector(UO, Context.HalfTy, *this); 15152 return UO; 15153 } 15154 15155 /// Determine whether the given expression is a qualified member 15156 /// access expression, of a form that could be turned into a pointer to member 15157 /// with the address-of operator. 15158 bool Sema::isQualifiedMemberAccess(Expr *E) { 15159 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15160 if (!DRE->getQualifier()) 15161 return false; 15162 15163 ValueDecl *VD = DRE->getDecl(); 15164 if (!VD->isCXXClassMember()) 15165 return false; 15166 15167 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15168 return true; 15169 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15170 return Method->isInstance(); 15171 15172 return false; 15173 } 15174 15175 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15176 if (!ULE->getQualifier()) 15177 return false; 15178 15179 for (NamedDecl *D : ULE->decls()) { 15180 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15181 if (Method->isInstance()) 15182 return true; 15183 } else { 15184 // Overload set does not contain methods. 15185 break; 15186 } 15187 } 15188 15189 return false; 15190 } 15191 15192 return false; 15193 } 15194 15195 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15196 UnaryOperatorKind Opc, Expr *Input) { 15197 // First things first: handle placeholders so that the 15198 // overloaded-operator check considers the right type. 15199 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15200 // Increment and decrement of pseudo-object references. 15201 if (pty->getKind() == BuiltinType::PseudoObject && 15202 UnaryOperator::isIncrementDecrementOp(Opc)) 15203 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15204 15205 // extension is always a builtin operator. 15206 if (Opc == UO_Extension) 15207 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15208 15209 // & gets special logic for several kinds of placeholder. 15210 // The builtin code knows what to do. 15211 if (Opc == UO_AddrOf && 15212 (pty->getKind() == BuiltinType::Overload || 15213 pty->getKind() == BuiltinType::UnknownAny || 15214 pty->getKind() == BuiltinType::BoundMember)) 15215 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15216 15217 // Anything else needs to be handled now. 15218 ExprResult Result = CheckPlaceholderExpr(Input); 15219 if (Result.isInvalid()) return ExprError(); 15220 Input = Result.get(); 15221 } 15222 15223 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15224 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15225 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15226 // Find all of the overloaded operators visible from this point. 15227 UnresolvedSet<16> Functions; 15228 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15229 if (S && OverOp != OO_None) 15230 LookupOverloadedOperatorName(OverOp, S, Functions); 15231 15232 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15233 } 15234 15235 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15236 } 15237 15238 // Unary Operators. 'Tok' is the token for the operator. 15239 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15240 tok::TokenKind Op, Expr *Input) { 15241 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15242 } 15243 15244 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15245 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15246 LabelDecl *TheDecl) { 15247 TheDecl->markUsed(Context); 15248 // Create the AST node. The address of a label always has type 'void*'. 15249 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15250 Context.getPointerType(Context.VoidTy)); 15251 } 15252 15253 void Sema::ActOnStartStmtExpr() { 15254 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15255 } 15256 15257 void Sema::ActOnStmtExprError() { 15258 // Note that function is also called by TreeTransform when leaving a 15259 // StmtExpr scope without rebuilding anything. 15260 15261 DiscardCleanupsInEvaluationContext(); 15262 PopExpressionEvaluationContext(); 15263 } 15264 15265 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15266 SourceLocation RPLoc) { 15267 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15268 } 15269 15270 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15271 SourceLocation RPLoc, unsigned TemplateDepth) { 15272 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15273 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15274 15275 if (hasAnyUnrecoverableErrorsInThisFunction()) 15276 DiscardCleanupsInEvaluationContext(); 15277 assert(!Cleanup.exprNeedsCleanups() && 15278 "cleanups within StmtExpr not correctly bound!"); 15279 PopExpressionEvaluationContext(); 15280 15281 // FIXME: there are a variety of strange constraints to enforce here, for 15282 // example, it is not possible to goto into a stmt expression apparently. 15283 // More semantic analysis is needed. 15284 15285 // If there are sub-stmts in the compound stmt, take the type of the last one 15286 // as the type of the stmtexpr. 15287 QualType Ty = Context.VoidTy; 15288 bool StmtExprMayBindToTemp = false; 15289 if (!Compound->body_empty()) { 15290 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15291 if (const auto *LastStmt = 15292 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15293 if (const Expr *Value = LastStmt->getExprStmt()) { 15294 StmtExprMayBindToTemp = true; 15295 Ty = Value->getType(); 15296 } 15297 } 15298 } 15299 15300 // FIXME: Check that expression type is complete/non-abstract; statement 15301 // expressions are not lvalues. 15302 Expr *ResStmtExpr = 15303 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15304 if (StmtExprMayBindToTemp) 15305 return MaybeBindToTemporary(ResStmtExpr); 15306 return ResStmtExpr; 15307 } 15308 15309 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15310 if (ER.isInvalid()) 15311 return ExprError(); 15312 15313 // Do function/array conversion on the last expression, but not 15314 // lvalue-to-rvalue. However, initialize an unqualified type. 15315 ER = DefaultFunctionArrayConversion(ER.get()); 15316 if (ER.isInvalid()) 15317 return ExprError(); 15318 Expr *E = ER.get(); 15319 15320 if (E->isTypeDependent()) 15321 return E; 15322 15323 // In ARC, if the final expression ends in a consume, splice 15324 // the consume out and bind it later. In the alternate case 15325 // (when dealing with a retainable type), the result 15326 // initialization will create a produce. In both cases the 15327 // result will be +1, and we'll need to balance that out with 15328 // a bind. 15329 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15330 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15331 return Cast->getSubExpr(); 15332 15333 // FIXME: Provide a better location for the initialization. 15334 return PerformCopyInitialization( 15335 InitializedEntity::InitializeStmtExprResult( 15336 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15337 SourceLocation(), E); 15338 } 15339 15340 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15341 TypeSourceInfo *TInfo, 15342 ArrayRef<OffsetOfComponent> Components, 15343 SourceLocation RParenLoc) { 15344 QualType ArgTy = TInfo->getType(); 15345 bool Dependent = ArgTy->isDependentType(); 15346 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15347 15348 // We must have at least one component that refers to the type, and the first 15349 // one is known to be a field designator. Verify that the ArgTy represents 15350 // a struct/union/class. 15351 if (!Dependent && !ArgTy->isRecordType()) 15352 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15353 << ArgTy << TypeRange); 15354 15355 // Type must be complete per C99 7.17p3 because a declaring a variable 15356 // with an incomplete type would be ill-formed. 15357 if (!Dependent 15358 && RequireCompleteType(BuiltinLoc, ArgTy, 15359 diag::err_offsetof_incomplete_type, TypeRange)) 15360 return ExprError(); 15361 15362 bool DidWarnAboutNonPOD = false; 15363 QualType CurrentType = ArgTy; 15364 SmallVector<OffsetOfNode, 4> Comps; 15365 SmallVector<Expr*, 4> Exprs; 15366 for (const OffsetOfComponent &OC : Components) { 15367 if (OC.isBrackets) { 15368 // Offset of an array sub-field. TODO: Should we allow vector elements? 15369 if (!CurrentType->isDependentType()) { 15370 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15371 if(!AT) 15372 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15373 << CurrentType); 15374 CurrentType = AT->getElementType(); 15375 } else 15376 CurrentType = Context.DependentTy; 15377 15378 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15379 if (IdxRval.isInvalid()) 15380 return ExprError(); 15381 Expr *Idx = IdxRval.get(); 15382 15383 // The expression must be an integral expression. 15384 // FIXME: An integral constant expression? 15385 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15386 !Idx->getType()->isIntegerType()) 15387 return ExprError( 15388 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15389 << Idx->getSourceRange()); 15390 15391 // Record this array index. 15392 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15393 Exprs.push_back(Idx); 15394 continue; 15395 } 15396 15397 // Offset of a field. 15398 if (CurrentType->isDependentType()) { 15399 // We have the offset of a field, but we can't look into the dependent 15400 // type. Just record the identifier of the field. 15401 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15402 CurrentType = Context.DependentTy; 15403 continue; 15404 } 15405 15406 // We need to have a complete type to look into. 15407 if (RequireCompleteType(OC.LocStart, CurrentType, 15408 diag::err_offsetof_incomplete_type)) 15409 return ExprError(); 15410 15411 // Look for the designated field. 15412 const RecordType *RC = CurrentType->getAs<RecordType>(); 15413 if (!RC) 15414 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15415 << CurrentType); 15416 RecordDecl *RD = RC->getDecl(); 15417 15418 // C++ [lib.support.types]p5: 15419 // The macro offsetof accepts a restricted set of type arguments in this 15420 // International Standard. type shall be a POD structure or a POD union 15421 // (clause 9). 15422 // C++11 [support.types]p4: 15423 // If type is not a standard-layout class (Clause 9), the results are 15424 // undefined. 15425 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15426 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15427 unsigned DiagID = 15428 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15429 : diag::ext_offsetof_non_pod_type; 15430 15431 if (!IsSafe && !DidWarnAboutNonPOD && 15432 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15433 PDiag(DiagID) 15434 << SourceRange(Components[0].LocStart, OC.LocEnd) 15435 << CurrentType)) 15436 DidWarnAboutNonPOD = true; 15437 } 15438 15439 // Look for the field. 15440 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15441 LookupQualifiedName(R, RD); 15442 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15443 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15444 if (!MemberDecl) { 15445 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15446 MemberDecl = IndirectMemberDecl->getAnonField(); 15447 } 15448 15449 if (!MemberDecl) 15450 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15451 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15452 OC.LocEnd)); 15453 15454 // C99 7.17p3: 15455 // (If the specified member is a bit-field, the behavior is undefined.) 15456 // 15457 // We diagnose this as an error. 15458 if (MemberDecl->isBitField()) { 15459 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15460 << MemberDecl->getDeclName() 15461 << SourceRange(BuiltinLoc, RParenLoc); 15462 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15463 return ExprError(); 15464 } 15465 15466 RecordDecl *Parent = MemberDecl->getParent(); 15467 if (IndirectMemberDecl) 15468 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15469 15470 // If the member was found in a base class, introduce OffsetOfNodes for 15471 // the base class indirections. 15472 CXXBasePaths Paths; 15473 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15474 Paths)) { 15475 if (Paths.getDetectedVirtual()) { 15476 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15477 << MemberDecl->getDeclName() 15478 << SourceRange(BuiltinLoc, RParenLoc); 15479 return ExprError(); 15480 } 15481 15482 CXXBasePath &Path = Paths.front(); 15483 for (const CXXBasePathElement &B : Path) 15484 Comps.push_back(OffsetOfNode(B.Base)); 15485 } 15486 15487 if (IndirectMemberDecl) { 15488 for (auto *FI : IndirectMemberDecl->chain()) { 15489 assert(isa<FieldDecl>(FI)); 15490 Comps.push_back(OffsetOfNode(OC.LocStart, 15491 cast<FieldDecl>(FI), OC.LocEnd)); 15492 } 15493 } else 15494 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15495 15496 CurrentType = MemberDecl->getType().getNonReferenceType(); 15497 } 15498 15499 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15500 Comps, Exprs, RParenLoc); 15501 } 15502 15503 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15504 SourceLocation BuiltinLoc, 15505 SourceLocation TypeLoc, 15506 ParsedType ParsedArgTy, 15507 ArrayRef<OffsetOfComponent> Components, 15508 SourceLocation RParenLoc) { 15509 15510 TypeSourceInfo *ArgTInfo; 15511 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15512 if (ArgTy.isNull()) 15513 return ExprError(); 15514 15515 if (!ArgTInfo) 15516 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15517 15518 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15519 } 15520 15521 15522 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15523 Expr *CondExpr, 15524 Expr *LHSExpr, Expr *RHSExpr, 15525 SourceLocation RPLoc) { 15526 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15527 15528 ExprValueKind VK = VK_PRValue; 15529 ExprObjectKind OK = OK_Ordinary; 15530 QualType resType; 15531 bool CondIsTrue = false; 15532 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15533 resType = Context.DependentTy; 15534 } else { 15535 // The conditional expression is required to be a constant expression. 15536 llvm::APSInt condEval(32); 15537 ExprResult CondICE = VerifyIntegerConstantExpression( 15538 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15539 if (CondICE.isInvalid()) 15540 return ExprError(); 15541 CondExpr = CondICE.get(); 15542 CondIsTrue = condEval.getZExtValue(); 15543 15544 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15545 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15546 15547 resType = ActiveExpr->getType(); 15548 VK = ActiveExpr->getValueKind(); 15549 OK = ActiveExpr->getObjectKind(); 15550 } 15551 15552 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15553 resType, VK, OK, RPLoc, CondIsTrue); 15554 } 15555 15556 //===----------------------------------------------------------------------===// 15557 // Clang Extensions. 15558 //===----------------------------------------------------------------------===// 15559 15560 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15561 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15562 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15563 15564 if (LangOpts.CPlusPlus) { 15565 MangleNumberingContext *MCtx; 15566 Decl *ManglingContextDecl; 15567 std::tie(MCtx, ManglingContextDecl) = 15568 getCurrentMangleNumberContext(Block->getDeclContext()); 15569 if (MCtx) { 15570 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15571 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15572 } 15573 } 15574 15575 PushBlockScope(CurScope, Block); 15576 CurContext->addDecl(Block); 15577 if (CurScope) 15578 PushDeclContext(CurScope, Block); 15579 else 15580 CurContext = Block; 15581 15582 getCurBlock()->HasImplicitReturnType = true; 15583 15584 // Enter a new evaluation context to insulate the block from any 15585 // cleanups from the enclosing full-expression. 15586 PushExpressionEvaluationContext( 15587 ExpressionEvaluationContext::PotentiallyEvaluated); 15588 } 15589 15590 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15591 Scope *CurScope) { 15592 assert(ParamInfo.getIdentifier() == nullptr && 15593 "block-id should have no identifier!"); 15594 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15595 BlockScopeInfo *CurBlock = getCurBlock(); 15596 15597 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15598 QualType T = Sig->getType(); 15599 15600 // FIXME: We should allow unexpanded parameter packs here, but that would, 15601 // in turn, make the block expression contain unexpanded parameter packs. 15602 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15603 // Drop the parameters. 15604 FunctionProtoType::ExtProtoInfo EPI; 15605 EPI.HasTrailingReturn = false; 15606 EPI.TypeQuals.addConst(); 15607 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15608 Sig = Context.getTrivialTypeSourceInfo(T); 15609 } 15610 15611 // GetTypeForDeclarator always produces a function type for a block 15612 // literal signature. Furthermore, it is always a FunctionProtoType 15613 // unless the function was written with a typedef. 15614 assert(T->isFunctionType() && 15615 "GetTypeForDeclarator made a non-function block signature"); 15616 15617 // Look for an explicit signature in that function type. 15618 FunctionProtoTypeLoc ExplicitSignature; 15619 15620 if ((ExplicitSignature = Sig->getTypeLoc() 15621 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15622 15623 // Check whether that explicit signature was synthesized by 15624 // GetTypeForDeclarator. If so, don't save that as part of the 15625 // written signature. 15626 if (ExplicitSignature.getLocalRangeBegin() == 15627 ExplicitSignature.getLocalRangeEnd()) { 15628 // This would be much cheaper if we stored TypeLocs instead of 15629 // TypeSourceInfos. 15630 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15631 unsigned Size = Result.getFullDataSize(); 15632 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15633 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15634 15635 ExplicitSignature = FunctionProtoTypeLoc(); 15636 } 15637 } 15638 15639 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15640 CurBlock->FunctionType = T; 15641 15642 const auto *Fn = T->castAs<FunctionType>(); 15643 QualType RetTy = Fn->getReturnType(); 15644 bool isVariadic = 15645 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15646 15647 CurBlock->TheDecl->setIsVariadic(isVariadic); 15648 15649 // Context.DependentTy is used as a placeholder for a missing block 15650 // return type. TODO: what should we do with declarators like: 15651 // ^ * { ... } 15652 // If the answer is "apply template argument deduction".... 15653 if (RetTy != Context.DependentTy) { 15654 CurBlock->ReturnType = RetTy; 15655 CurBlock->TheDecl->setBlockMissingReturnType(false); 15656 CurBlock->HasImplicitReturnType = false; 15657 } 15658 15659 // Push block parameters from the declarator if we had them. 15660 SmallVector<ParmVarDecl*, 8> Params; 15661 if (ExplicitSignature) { 15662 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15663 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15664 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15665 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15666 // Diagnose this as an extension in C17 and earlier. 15667 if (!getLangOpts().C2x) 15668 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15669 } 15670 Params.push_back(Param); 15671 } 15672 15673 // Fake up parameter variables if we have a typedef, like 15674 // ^ fntype { ... } 15675 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15676 for (const auto &I : Fn->param_types()) { 15677 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15678 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15679 Params.push_back(Param); 15680 } 15681 } 15682 15683 // Set the parameters on the block decl. 15684 if (!Params.empty()) { 15685 CurBlock->TheDecl->setParams(Params); 15686 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15687 /*CheckParameterNames=*/false); 15688 } 15689 15690 // Finally we can process decl attributes. 15691 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15692 15693 // Put the parameter variables in scope. 15694 for (auto AI : CurBlock->TheDecl->parameters()) { 15695 AI->setOwningFunction(CurBlock->TheDecl); 15696 15697 // If this has an identifier, add it to the scope stack. 15698 if (AI->getIdentifier()) { 15699 CheckShadow(CurBlock->TheScope, AI); 15700 15701 PushOnScopeChains(AI, CurBlock->TheScope); 15702 } 15703 } 15704 } 15705 15706 /// ActOnBlockError - If there is an error parsing a block, this callback 15707 /// is invoked to pop the information about the block from the action impl. 15708 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15709 // Leave the expression-evaluation context. 15710 DiscardCleanupsInEvaluationContext(); 15711 PopExpressionEvaluationContext(); 15712 15713 // Pop off CurBlock, handle nested blocks. 15714 PopDeclContext(); 15715 PopFunctionScopeInfo(); 15716 } 15717 15718 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15719 /// literal was successfully completed. ^(int x){...} 15720 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15721 Stmt *Body, Scope *CurScope) { 15722 // If blocks are disabled, emit an error. 15723 if (!LangOpts.Blocks) 15724 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15725 15726 // Leave the expression-evaluation context. 15727 if (hasAnyUnrecoverableErrorsInThisFunction()) 15728 DiscardCleanupsInEvaluationContext(); 15729 assert(!Cleanup.exprNeedsCleanups() && 15730 "cleanups within block not correctly bound!"); 15731 PopExpressionEvaluationContext(); 15732 15733 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15734 BlockDecl *BD = BSI->TheDecl; 15735 15736 if (BSI->HasImplicitReturnType) 15737 deduceClosureReturnType(*BSI); 15738 15739 QualType RetTy = Context.VoidTy; 15740 if (!BSI->ReturnType.isNull()) 15741 RetTy = BSI->ReturnType; 15742 15743 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15744 QualType BlockTy; 15745 15746 // If the user wrote a function type in some form, try to use that. 15747 if (!BSI->FunctionType.isNull()) { 15748 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15749 15750 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15751 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15752 15753 // Turn protoless block types into nullary block types. 15754 if (isa<FunctionNoProtoType>(FTy)) { 15755 FunctionProtoType::ExtProtoInfo EPI; 15756 EPI.ExtInfo = Ext; 15757 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15758 15759 // Otherwise, if we don't need to change anything about the function type, 15760 // preserve its sugar structure. 15761 } else if (FTy->getReturnType() == RetTy && 15762 (!NoReturn || FTy->getNoReturnAttr())) { 15763 BlockTy = BSI->FunctionType; 15764 15765 // Otherwise, make the minimal modifications to the function type. 15766 } else { 15767 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15768 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15769 EPI.TypeQuals = Qualifiers(); 15770 EPI.ExtInfo = Ext; 15771 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15772 } 15773 15774 // If we don't have a function type, just build one from nothing. 15775 } else { 15776 FunctionProtoType::ExtProtoInfo EPI; 15777 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15778 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15779 } 15780 15781 DiagnoseUnusedParameters(BD->parameters()); 15782 BlockTy = Context.getBlockPointerType(BlockTy); 15783 15784 // If needed, diagnose invalid gotos and switches in the block. 15785 if (getCurFunction()->NeedsScopeChecking() && 15786 !PP.isCodeCompletionEnabled()) 15787 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15788 15789 BD->setBody(cast<CompoundStmt>(Body)); 15790 15791 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15792 DiagnoseUnguardedAvailabilityViolations(BD); 15793 15794 // Try to apply the named return value optimization. We have to check again 15795 // if we can do this, though, because blocks keep return statements around 15796 // to deduce an implicit return type. 15797 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15798 !BD->isDependentContext()) 15799 computeNRVO(Body, BSI); 15800 15801 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15802 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15803 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15804 NTCUK_Destruct|NTCUK_Copy); 15805 15806 PopDeclContext(); 15807 15808 // Set the captured variables on the block. 15809 SmallVector<BlockDecl::Capture, 4> Captures; 15810 for (Capture &Cap : BSI->Captures) { 15811 if (Cap.isInvalid() || Cap.isThisCapture()) 15812 continue; 15813 15814 VarDecl *Var = Cap.getVariable(); 15815 Expr *CopyExpr = nullptr; 15816 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15817 if (const RecordType *Record = 15818 Cap.getCaptureType()->getAs<RecordType>()) { 15819 // The capture logic needs the destructor, so make sure we mark it. 15820 // Usually this is unnecessary because most local variables have 15821 // their destructors marked at declaration time, but parameters are 15822 // an exception because it's technically only the call site that 15823 // actually requires the destructor. 15824 if (isa<ParmVarDecl>(Var)) 15825 FinalizeVarWithDestructor(Var, Record); 15826 15827 // Enter a separate potentially-evaluated context while building block 15828 // initializers to isolate their cleanups from those of the block 15829 // itself. 15830 // FIXME: Is this appropriate even when the block itself occurs in an 15831 // unevaluated operand? 15832 EnterExpressionEvaluationContext EvalContext( 15833 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15834 15835 SourceLocation Loc = Cap.getLocation(); 15836 15837 ExprResult Result = BuildDeclarationNameExpr( 15838 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15839 15840 // According to the blocks spec, the capture of a variable from 15841 // the stack requires a const copy constructor. This is not true 15842 // of the copy/move done to move a __block variable to the heap. 15843 if (!Result.isInvalid() && 15844 !Result.get()->getType().isConstQualified()) { 15845 Result = ImpCastExprToType(Result.get(), 15846 Result.get()->getType().withConst(), 15847 CK_NoOp, VK_LValue); 15848 } 15849 15850 if (!Result.isInvalid()) { 15851 Result = PerformCopyInitialization( 15852 InitializedEntity::InitializeBlock(Var->getLocation(), 15853 Cap.getCaptureType()), 15854 Loc, Result.get()); 15855 } 15856 15857 // Build a full-expression copy expression if initialization 15858 // succeeded and used a non-trivial constructor. Recover from 15859 // errors by pretending that the copy isn't necessary. 15860 if (!Result.isInvalid() && 15861 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15862 ->isTrivial()) { 15863 Result = MaybeCreateExprWithCleanups(Result); 15864 CopyExpr = Result.get(); 15865 } 15866 } 15867 } 15868 15869 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15870 CopyExpr); 15871 Captures.push_back(NewCap); 15872 } 15873 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15874 15875 // Pop the block scope now but keep it alive to the end of this function. 15876 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15877 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15878 15879 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15880 15881 // If the block isn't obviously global, i.e. it captures anything at 15882 // all, then we need to do a few things in the surrounding context: 15883 if (Result->getBlockDecl()->hasCaptures()) { 15884 // First, this expression has a new cleanup object. 15885 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15886 Cleanup.setExprNeedsCleanups(true); 15887 15888 // It also gets a branch-protected scope if any of the captured 15889 // variables needs destruction. 15890 for (const auto &CI : Result->getBlockDecl()->captures()) { 15891 const VarDecl *var = CI.getVariable(); 15892 if (var->getType().isDestructedType() != QualType::DK_none) { 15893 setFunctionHasBranchProtectedScope(); 15894 break; 15895 } 15896 } 15897 } 15898 15899 if (getCurFunction()) 15900 getCurFunction()->addBlock(BD); 15901 15902 return Result; 15903 } 15904 15905 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15906 SourceLocation RPLoc) { 15907 TypeSourceInfo *TInfo; 15908 GetTypeFromParser(Ty, &TInfo); 15909 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15910 } 15911 15912 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15913 Expr *E, TypeSourceInfo *TInfo, 15914 SourceLocation RPLoc) { 15915 Expr *OrigExpr = E; 15916 bool IsMS = false; 15917 15918 // CUDA device code does not support varargs. 15919 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15920 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15921 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15922 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15923 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15924 } 15925 } 15926 15927 // NVPTX does not support va_arg expression. 15928 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15929 Context.getTargetInfo().getTriple().isNVPTX()) 15930 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15931 15932 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15933 // as Microsoft ABI on an actual Microsoft platform, where 15934 // __builtin_ms_va_list and __builtin_va_list are the same.) 15935 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15936 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15937 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15938 if (Context.hasSameType(MSVaListType, E->getType())) { 15939 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15940 return ExprError(); 15941 IsMS = true; 15942 } 15943 } 15944 15945 // Get the va_list type 15946 QualType VaListType = Context.getBuiltinVaListType(); 15947 if (!IsMS) { 15948 if (VaListType->isArrayType()) { 15949 // Deal with implicit array decay; for example, on x86-64, 15950 // va_list is an array, but it's supposed to decay to 15951 // a pointer for va_arg. 15952 VaListType = Context.getArrayDecayedType(VaListType); 15953 // Make sure the input expression also decays appropriately. 15954 ExprResult Result = UsualUnaryConversions(E); 15955 if (Result.isInvalid()) 15956 return ExprError(); 15957 E = Result.get(); 15958 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15959 // If va_list is a record type and we are compiling in C++ mode, 15960 // check the argument using reference binding. 15961 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15962 Context, Context.getLValueReferenceType(VaListType), false); 15963 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15964 if (Init.isInvalid()) 15965 return ExprError(); 15966 E = Init.getAs<Expr>(); 15967 } else { 15968 // Otherwise, the va_list argument must be an l-value because 15969 // it is modified by va_arg. 15970 if (!E->isTypeDependent() && 15971 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15972 return ExprError(); 15973 } 15974 } 15975 15976 if (!IsMS && !E->isTypeDependent() && 15977 !Context.hasSameType(VaListType, E->getType())) 15978 return ExprError( 15979 Diag(E->getBeginLoc(), 15980 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15981 << OrigExpr->getType() << E->getSourceRange()); 15982 15983 if (!TInfo->getType()->isDependentType()) { 15984 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15985 diag::err_second_parameter_to_va_arg_incomplete, 15986 TInfo->getTypeLoc())) 15987 return ExprError(); 15988 15989 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15990 TInfo->getType(), 15991 diag::err_second_parameter_to_va_arg_abstract, 15992 TInfo->getTypeLoc())) 15993 return ExprError(); 15994 15995 if (!TInfo->getType().isPODType(Context)) { 15996 Diag(TInfo->getTypeLoc().getBeginLoc(), 15997 TInfo->getType()->isObjCLifetimeType() 15998 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15999 : diag::warn_second_parameter_to_va_arg_not_pod) 16000 << TInfo->getType() 16001 << TInfo->getTypeLoc().getSourceRange(); 16002 } 16003 16004 // Check for va_arg where arguments of the given type will be promoted 16005 // (i.e. this va_arg is guaranteed to have undefined behavior). 16006 QualType PromoteType; 16007 if (TInfo->getType()->isPromotableIntegerType()) { 16008 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 16009 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 16010 // and C2x 7.16.1.1p2 says, in part: 16011 // If type is not compatible with the type of the actual next argument 16012 // (as promoted according to the default argument promotions), the 16013 // behavior is undefined, except for the following cases: 16014 // - both types are pointers to qualified or unqualified versions of 16015 // compatible types; 16016 // - one type is a signed integer type, the other type is the 16017 // corresponding unsigned integer type, and the value is 16018 // representable in both types; 16019 // - one type is pointer to qualified or unqualified void and the 16020 // other is a pointer to a qualified or unqualified character type. 16021 // Given that type compatibility is the primary requirement (ignoring 16022 // qualifications), you would think we could call typesAreCompatible() 16023 // directly to test this. However, in C++, that checks for *same type*, 16024 // which causes false positives when passing an enumeration type to 16025 // va_arg. Instead, get the underlying type of the enumeration and pass 16026 // that. 16027 QualType UnderlyingType = TInfo->getType(); 16028 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 16029 UnderlyingType = ET->getDecl()->getIntegerType(); 16030 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16031 /*CompareUnqualified*/ true)) 16032 PromoteType = QualType(); 16033 16034 // If the types are still not compatible, we need to test whether the 16035 // promoted type and the underlying type are the same except for 16036 // signedness. Ask the AST for the correctly corresponding type and see 16037 // if that's compatible. 16038 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && 16039 PromoteType->isUnsignedIntegerType() != 16040 UnderlyingType->isUnsignedIntegerType()) { 16041 UnderlyingType = 16042 UnderlyingType->isUnsignedIntegerType() 16043 ? Context.getCorrespondingSignedType(UnderlyingType) 16044 : Context.getCorrespondingUnsignedType(UnderlyingType); 16045 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16046 /*CompareUnqualified*/ true)) 16047 PromoteType = QualType(); 16048 } 16049 } 16050 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 16051 PromoteType = Context.DoubleTy; 16052 if (!PromoteType.isNull()) 16053 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 16054 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 16055 << TInfo->getType() 16056 << PromoteType 16057 << TInfo->getTypeLoc().getSourceRange()); 16058 } 16059 16060 QualType T = TInfo->getType().getNonLValueExprType(Context); 16061 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 16062 } 16063 16064 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 16065 // The type of __null will be int or long, depending on the size of 16066 // pointers on the target. 16067 QualType Ty; 16068 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 16069 if (pw == Context.getTargetInfo().getIntWidth()) 16070 Ty = Context.IntTy; 16071 else if (pw == Context.getTargetInfo().getLongWidth()) 16072 Ty = Context.LongTy; 16073 else if (pw == Context.getTargetInfo().getLongLongWidth()) 16074 Ty = Context.LongLongTy; 16075 else { 16076 llvm_unreachable("I don't know size of pointer!"); 16077 } 16078 16079 return new (Context) GNUNullExpr(Ty, TokenLoc); 16080 } 16081 16082 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 16083 SourceLocation BuiltinLoc, 16084 SourceLocation RPLoc) { 16085 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 16086 } 16087 16088 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 16089 SourceLocation BuiltinLoc, 16090 SourceLocation RPLoc, 16091 DeclContext *ParentContext) { 16092 return new (Context) 16093 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 16094 } 16095 16096 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 16097 bool Diagnose) { 16098 if (!getLangOpts().ObjC) 16099 return false; 16100 16101 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 16102 if (!PT) 16103 return false; 16104 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 16105 16106 // Ignore any parens, implicit casts (should only be 16107 // array-to-pointer decays), and not-so-opaque values. The last is 16108 // important for making this trigger for property assignments. 16109 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 16110 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 16111 if (OV->getSourceExpr()) 16112 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 16113 16114 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 16115 if (!PT->isObjCIdType() && 16116 !(ID && ID->getIdentifier()->isStr("NSString"))) 16117 return false; 16118 if (!SL->isAscii()) 16119 return false; 16120 16121 if (Diagnose) { 16122 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 16123 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 16124 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 16125 } 16126 return true; 16127 } 16128 16129 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16130 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16131 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16132 !SrcExpr->isNullPointerConstant( 16133 getASTContext(), Expr::NPC_NeverValueDependent)) { 16134 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16135 return false; 16136 if (Diagnose) { 16137 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16138 << /*number*/1 16139 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16140 Expr *NumLit = 16141 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16142 if (NumLit) 16143 Exp = NumLit; 16144 } 16145 return true; 16146 } 16147 16148 return false; 16149 } 16150 16151 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16152 const Expr *SrcExpr) { 16153 if (!DstType->isFunctionPointerType() || 16154 !SrcExpr->getType()->isFunctionType()) 16155 return false; 16156 16157 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16158 if (!DRE) 16159 return false; 16160 16161 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16162 if (!FD) 16163 return false; 16164 16165 return !S.checkAddressOfFunctionIsAvailable(FD, 16166 /*Complain=*/true, 16167 SrcExpr->getBeginLoc()); 16168 } 16169 16170 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16171 SourceLocation Loc, 16172 QualType DstType, QualType SrcType, 16173 Expr *SrcExpr, AssignmentAction Action, 16174 bool *Complained) { 16175 if (Complained) 16176 *Complained = false; 16177 16178 // Decode the result (notice that AST's are still created for extensions). 16179 bool CheckInferredResultType = false; 16180 bool isInvalid = false; 16181 unsigned DiagKind = 0; 16182 ConversionFixItGenerator ConvHints; 16183 bool MayHaveConvFixit = false; 16184 bool MayHaveFunctionDiff = false; 16185 const ObjCInterfaceDecl *IFace = nullptr; 16186 const ObjCProtocolDecl *PDecl = nullptr; 16187 16188 switch (ConvTy) { 16189 case Compatible: 16190 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16191 return false; 16192 16193 case PointerToInt: 16194 if (getLangOpts().CPlusPlus) { 16195 DiagKind = diag::err_typecheck_convert_pointer_int; 16196 isInvalid = true; 16197 } else { 16198 DiagKind = diag::ext_typecheck_convert_pointer_int; 16199 } 16200 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16201 MayHaveConvFixit = true; 16202 break; 16203 case IntToPointer: 16204 if (getLangOpts().CPlusPlus) { 16205 DiagKind = diag::err_typecheck_convert_int_pointer; 16206 isInvalid = true; 16207 } else { 16208 DiagKind = diag::ext_typecheck_convert_int_pointer; 16209 } 16210 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16211 MayHaveConvFixit = true; 16212 break; 16213 case IncompatibleFunctionPointer: 16214 if (getLangOpts().CPlusPlus) { 16215 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16216 isInvalid = true; 16217 } else { 16218 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16219 } 16220 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16221 MayHaveConvFixit = true; 16222 break; 16223 case IncompatiblePointer: 16224 if (Action == AA_Passing_CFAudited) { 16225 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16226 } else if (getLangOpts().CPlusPlus) { 16227 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16228 isInvalid = true; 16229 } else { 16230 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16231 } 16232 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16233 SrcType->isObjCObjectPointerType(); 16234 if (!CheckInferredResultType) { 16235 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16236 } else if (CheckInferredResultType) { 16237 SrcType = SrcType.getUnqualifiedType(); 16238 DstType = DstType.getUnqualifiedType(); 16239 } 16240 MayHaveConvFixit = true; 16241 break; 16242 case IncompatiblePointerSign: 16243 if (getLangOpts().CPlusPlus) { 16244 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16245 isInvalid = true; 16246 } else { 16247 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16248 } 16249 break; 16250 case FunctionVoidPointer: 16251 if (getLangOpts().CPlusPlus) { 16252 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16253 isInvalid = true; 16254 } else { 16255 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16256 } 16257 break; 16258 case IncompatiblePointerDiscardsQualifiers: { 16259 // Perform array-to-pointer decay if necessary. 16260 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16261 16262 isInvalid = true; 16263 16264 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16265 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16266 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16267 DiagKind = diag::err_typecheck_incompatible_address_space; 16268 break; 16269 16270 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16271 DiagKind = diag::err_typecheck_incompatible_ownership; 16272 break; 16273 } 16274 16275 llvm_unreachable("unknown error case for discarding qualifiers!"); 16276 // fallthrough 16277 } 16278 case CompatiblePointerDiscardsQualifiers: 16279 // If the qualifiers lost were because we were applying the 16280 // (deprecated) C++ conversion from a string literal to a char* 16281 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16282 // Ideally, this check would be performed in 16283 // checkPointerTypesForAssignment. However, that would require a 16284 // bit of refactoring (so that the second argument is an 16285 // expression, rather than a type), which should be done as part 16286 // of a larger effort to fix checkPointerTypesForAssignment for 16287 // C++ semantics. 16288 if (getLangOpts().CPlusPlus && 16289 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16290 return false; 16291 if (getLangOpts().CPlusPlus) { 16292 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16293 isInvalid = true; 16294 } else { 16295 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16296 } 16297 16298 break; 16299 case IncompatibleNestedPointerQualifiers: 16300 if (getLangOpts().CPlusPlus) { 16301 isInvalid = true; 16302 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16303 } else { 16304 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16305 } 16306 break; 16307 case IncompatibleNestedPointerAddressSpaceMismatch: 16308 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16309 isInvalid = true; 16310 break; 16311 case IntToBlockPointer: 16312 DiagKind = diag::err_int_to_block_pointer; 16313 isInvalid = true; 16314 break; 16315 case IncompatibleBlockPointer: 16316 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16317 isInvalid = true; 16318 break; 16319 case IncompatibleObjCQualifiedId: { 16320 if (SrcType->isObjCQualifiedIdType()) { 16321 const ObjCObjectPointerType *srcOPT = 16322 SrcType->castAs<ObjCObjectPointerType>(); 16323 for (auto *srcProto : srcOPT->quals()) { 16324 PDecl = srcProto; 16325 break; 16326 } 16327 if (const ObjCInterfaceType *IFaceT = 16328 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16329 IFace = IFaceT->getDecl(); 16330 } 16331 else if (DstType->isObjCQualifiedIdType()) { 16332 const ObjCObjectPointerType *dstOPT = 16333 DstType->castAs<ObjCObjectPointerType>(); 16334 for (auto *dstProto : dstOPT->quals()) { 16335 PDecl = dstProto; 16336 break; 16337 } 16338 if (const ObjCInterfaceType *IFaceT = 16339 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16340 IFace = IFaceT->getDecl(); 16341 } 16342 if (getLangOpts().CPlusPlus) { 16343 DiagKind = diag::err_incompatible_qualified_id; 16344 isInvalid = true; 16345 } else { 16346 DiagKind = diag::warn_incompatible_qualified_id; 16347 } 16348 break; 16349 } 16350 case IncompatibleVectors: 16351 if (getLangOpts().CPlusPlus) { 16352 DiagKind = diag::err_incompatible_vectors; 16353 isInvalid = true; 16354 } else { 16355 DiagKind = diag::warn_incompatible_vectors; 16356 } 16357 break; 16358 case IncompatibleObjCWeakRef: 16359 DiagKind = diag::err_arc_weak_unavailable_assign; 16360 isInvalid = true; 16361 break; 16362 case Incompatible: 16363 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16364 if (Complained) 16365 *Complained = true; 16366 return true; 16367 } 16368 16369 DiagKind = diag::err_typecheck_convert_incompatible; 16370 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16371 MayHaveConvFixit = true; 16372 isInvalid = true; 16373 MayHaveFunctionDiff = true; 16374 break; 16375 } 16376 16377 QualType FirstType, SecondType; 16378 switch (Action) { 16379 case AA_Assigning: 16380 case AA_Initializing: 16381 // The destination type comes first. 16382 FirstType = DstType; 16383 SecondType = SrcType; 16384 break; 16385 16386 case AA_Returning: 16387 case AA_Passing: 16388 case AA_Passing_CFAudited: 16389 case AA_Converting: 16390 case AA_Sending: 16391 case AA_Casting: 16392 // The source type comes first. 16393 FirstType = SrcType; 16394 SecondType = DstType; 16395 break; 16396 } 16397 16398 PartialDiagnostic FDiag = PDiag(DiagKind); 16399 if (Action == AA_Passing_CFAudited) 16400 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16401 else 16402 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16403 16404 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16405 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16406 auto isPlainChar = [](const clang::Type *Type) { 16407 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16408 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16409 }; 16410 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16411 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16412 } 16413 16414 // If we can fix the conversion, suggest the FixIts. 16415 if (!ConvHints.isNull()) { 16416 for (FixItHint &H : ConvHints.Hints) 16417 FDiag << H; 16418 } 16419 16420 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16421 16422 if (MayHaveFunctionDiff) 16423 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16424 16425 Diag(Loc, FDiag); 16426 if ((DiagKind == diag::warn_incompatible_qualified_id || 16427 DiagKind == diag::err_incompatible_qualified_id) && 16428 PDecl && IFace && !IFace->hasDefinition()) 16429 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16430 << IFace << PDecl; 16431 16432 if (SecondType == Context.OverloadTy) 16433 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16434 FirstType, /*TakingAddress=*/true); 16435 16436 if (CheckInferredResultType) 16437 EmitRelatedResultTypeNote(SrcExpr); 16438 16439 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16440 EmitRelatedResultTypeNoteForReturn(DstType); 16441 16442 if (Complained) 16443 *Complained = true; 16444 return isInvalid; 16445 } 16446 16447 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16448 llvm::APSInt *Result, 16449 AllowFoldKind CanFold) { 16450 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16451 public: 16452 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16453 QualType T) override { 16454 return S.Diag(Loc, diag::err_ice_not_integral) 16455 << T << S.LangOpts.CPlusPlus; 16456 } 16457 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16458 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16459 } 16460 } Diagnoser; 16461 16462 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16463 } 16464 16465 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16466 llvm::APSInt *Result, 16467 unsigned DiagID, 16468 AllowFoldKind CanFold) { 16469 class IDDiagnoser : public VerifyICEDiagnoser { 16470 unsigned DiagID; 16471 16472 public: 16473 IDDiagnoser(unsigned DiagID) 16474 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16475 16476 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16477 return S.Diag(Loc, DiagID); 16478 } 16479 } Diagnoser(DiagID); 16480 16481 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16482 } 16483 16484 Sema::SemaDiagnosticBuilder 16485 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16486 QualType T) { 16487 return diagnoseNotICE(S, Loc); 16488 } 16489 16490 Sema::SemaDiagnosticBuilder 16491 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16492 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16493 } 16494 16495 ExprResult 16496 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16497 VerifyICEDiagnoser &Diagnoser, 16498 AllowFoldKind CanFold) { 16499 SourceLocation DiagLoc = E->getBeginLoc(); 16500 16501 if (getLangOpts().CPlusPlus11) { 16502 // C++11 [expr.const]p5: 16503 // If an expression of literal class type is used in a context where an 16504 // integral constant expression is required, then that class type shall 16505 // have a single non-explicit conversion function to an integral or 16506 // unscoped enumeration type 16507 ExprResult Converted; 16508 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16509 VerifyICEDiagnoser &BaseDiagnoser; 16510 public: 16511 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16512 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16513 BaseDiagnoser.Suppress, true), 16514 BaseDiagnoser(BaseDiagnoser) {} 16515 16516 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16517 QualType T) override { 16518 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16519 } 16520 16521 SemaDiagnosticBuilder diagnoseIncomplete( 16522 Sema &S, SourceLocation Loc, QualType T) override { 16523 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16524 } 16525 16526 SemaDiagnosticBuilder diagnoseExplicitConv( 16527 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16528 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16529 } 16530 16531 SemaDiagnosticBuilder noteExplicitConv( 16532 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16533 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16534 << ConvTy->isEnumeralType() << ConvTy; 16535 } 16536 16537 SemaDiagnosticBuilder diagnoseAmbiguous( 16538 Sema &S, SourceLocation Loc, QualType T) override { 16539 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16540 } 16541 16542 SemaDiagnosticBuilder noteAmbiguous( 16543 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16544 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16545 << ConvTy->isEnumeralType() << ConvTy; 16546 } 16547 16548 SemaDiagnosticBuilder diagnoseConversion( 16549 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16550 llvm_unreachable("conversion functions are permitted"); 16551 } 16552 } ConvertDiagnoser(Diagnoser); 16553 16554 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16555 ConvertDiagnoser); 16556 if (Converted.isInvalid()) 16557 return Converted; 16558 E = Converted.get(); 16559 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16560 return ExprError(); 16561 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16562 // An ICE must be of integral or unscoped enumeration type. 16563 if (!Diagnoser.Suppress) 16564 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16565 << E->getSourceRange(); 16566 return ExprError(); 16567 } 16568 16569 ExprResult RValueExpr = DefaultLvalueConversion(E); 16570 if (RValueExpr.isInvalid()) 16571 return ExprError(); 16572 16573 E = RValueExpr.get(); 16574 16575 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16576 // in the non-ICE case. 16577 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16578 if (Result) 16579 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16580 if (!isa<ConstantExpr>(E)) 16581 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16582 : ConstantExpr::Create(Context, E); 16583 return E; 16584 } 16585 16586 Expr::EvalResult EvalResult; 16587 SmallVector<PartialDiagnosticAt, 8> Notes; 16588 EvalResult.Diag = &Notes; 16589 16590 // Try to evaluate the expression, and produce diagnostics explaining why it's 16591 // not a constant expression as a side-effect. 16592 bool Folded = 16593 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16594 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16595 16596 if (!isa<ConstantExpr>(E)) 16597 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16598 16599 // In C++11, we can rely on diagnostics being produced for any expression 16600 // which is not a constant expression. If no diagnostics were produced, then 16601 // this is a constant expression. 16602 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16603 if (Result) 16604 *Result = EvalResult.Val.getInt(); 16605 return E; 16606 } 16607 16608 // If our only note is the usual "invalid subexpression" note, just point 16609 // the caret at its location rather than producing an essentially 16610 // redundant note. 16611 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16612 diag::note_invalid_subexpr_in_const_expr) { 16613 DiagLoc = Notes[0].first; 16614 Notes.clear(); 16615 } 16616 16617 if (!Folded || !CanFold) { 16618 if (!Diagnoser.Suppress) { 16619 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16620 for (const PartialDiagnosticAt &Note : Notes) 16621 Diag(Note.first, Note.second); 16622 } 16623 16624 return ExprError(); 16625 } 16626 16627 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16628 for (const PartialDiagnosticAt &Note : Notes) 16629 Diag(Note.first, Note.second); 16630 16631 if (Result) 16632 *Result = EvalResult.Val.getInt(); 16633 return E; 16634 } 16635 16636 namespace { 16637 // Handle the case where we conclude a expression which we speculatively 16638 // considered to be unevaluated is actually evaluated. 16639 class TransformToPE : public TreeTransform<TransformToPE> { 16640 typedef TreeTransform<TransformToPE> BaseTransform; 16641 16642 public: 16643 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16644 16645 // Make sure we redo semantic analysis 16646 bool AlwaysRebuild() { return true; } 16647 bool ReplacingOriginal() { return true; } 16648 16649 // We need to special-case DeclRefExprs referring to FieldDecls which 16650 // are not part of a member pointer formation; normal TreeTransforming 16651 // doesn't catch this case because of the way we represent them in the AST. 16652 // FIXME: This is a bit ugly; is it really the best way to handle this 16653 // case? 16654 // 16655 // Error on DeclRefExprs referring to FieldDecls. 16656 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16657 if (isa<FieldDecl>(E->getDecl()) && 16658 !SemaRef.isUnevaluatedContext()) 16659 return SemaRef.Diag(E->getLocation(), 16660 diag::err_invalid_non_static_member_use) 16661 << E->getDecl() << E->getSourceRange(); 16662 16663 return BaseTransform::TransformDeclRefExpr(E); 16664 } 16665 16666 // Exception: filter out member pointer formation 16667 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16668 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16669 return E; 16670 16671 return BaseTransform::TransformUnaryOperator(E); 16672 } 16673 16674 // The body of a lambda-expression is in a separate expression evaluation 16675 // context so never needs to be transformed. 16676 // FIXME: Ideally we wouldn't transform the closure type either, and would 16677 // just recreate the capture expressions and lambda expression. 16678 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16679 return SkipLambdaBody(E, Body); 16680 } 16681 }; 16682 } 16683 16684 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16685 assert(isUnevaluatedContext() && 16686 "Should only transform unevaluated expressions"); 16687 ExprEvalContexts.back().Context = 16688 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16689 if (isUnevaluatedContext()) 16690 return E; 16691 return TransformToPE(*this).TransformExpr(E); 16692 } 16693 16694 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { 16695 assert(isUnevaluatedContext() && 16696 "Should only transform unevaluated expressions"); 16697 ExprEvalContexts.back().Context = 16698 ExprEvalContexts[ExprEvalContexts.size() - 2].Context; 16699 if (isUnevaluatedContext()) 16700 return TInfo; 16701 return TransformToPE(*this).TransformType(TInfo); 16702 } 16703 16704 void 16705 Sema::PushExpressionEvaluationContext( 16706 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16707 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16708 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16709 LambdaContextDecl, ExprContext); 16710 16711 // Discarded statements and immediate contexts nested in other 16712 // discarded statements or immediate context are themselves 16713 // a discarded statement or an immediate context, respectively. 16714 ExprEvalContexts.back().InDiscardedStatement = 16715 ExprEvalContexts[ExprEvalContexts.size() - 2] 16716 .isDiscardedStatementContext(); 16717 ExprEvalContexts.back().InImmediateFunctionContext = 16718 ExprEvalContexts[ExprEvalContexts.size() - 2] 16719 .isImmediateFunctionContext(); 16720 16721 Cleanup.reset(); 16722 if (!MaybeODRUseExprs.empty()) 16723 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16724 } 16725 16726 void 16727 Sema::PushExpressionEvaluationContext( 16728 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16729 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16730 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16731 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16732 } 16733 16734 namespace { 16735 16736 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16737 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16738 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16739 if (E->getOpcode() == UO_Deref) 16740 return CheckPossibleDeref(S, E->getSubExpr()); 16741 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16742 return CheckPossibleDeref(S, E->getBase()); 16743 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16744 return CheckPossibleDeref(S, E->getBase()); 16745 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16746 QualType Inner; 16747 QualType Ty = E->getType(); 16748 if (const auto *Ptr = Ty->getAs<PointerType>()) 16749 Inner = Ptr->getPointeeType(); 16750 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16751 Inner = Arr->getElementType(); 16752 else 16753 return nullptr; 16754 16755 if (Inner->hasAttr(attr::NoDeref)) 16756 return E; 16757 } 16758 return nullptr; 16759 } 16760 16761 } // namespace 16762 16763 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16764 for (const Expr *E : Rec.PossibleDerefs) { 16765 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16766 if (DeclRef) { 16767 const ValueDecl *Decl = DeclRef->getDecl(); 16768 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16769 << Decl->getName() << E->getSourceRange(); 16770 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16771 } else { 16772 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16773 << E->getSourceRange(); 16774 } 16775 } 16776 Rec.PossibleDerefs.clear(); 16777 } 16778 16779 /// Check whether E, which is either a discarded-value expression or an 16780 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16781 /// and if so, remove it from the list of volatile-qualified assignments that 16782 /// we are going to warn are deprecated. 16783 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16784 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16785 return; 16786 16787 // Note: ignoring parens here is not justified by the standard rules, but 16788 // ignoring parentheses seems like a more reasonable approach, and this only 16789 // drives a deprecation warning so doesn't affect conformance. 16790 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16791 if (BO->getOpcode() == BO_Assign) { 16792 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16793 llvm::erase_value(LHSs, BO->getLHS()); 16794 } 16795 } 16796 } 16797 16798 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16799 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16800 !Decl->isConsteval() || isConstantEvaluated() || 16801 RebuildingImmediateInvocation || isImmediateFunctionContext()) 16802 return E; 16803 16804 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16805 /// It's OK if this fails; we'll also remove this in 16806 /// HandleImmediateInvocations, but catching it here allows us to avoid 16807 /// walking the AST looking for it in simple cases. 16808 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16809 if (auto *DeclRef = 16810 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16811 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16812 16813 E = MaybeCreateExprWithCleanups(E); 16814 16815 ConstantExpr *Res = ConstantExpr::Create( 16816 getASTContext(), E.get(), 16817 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16818 getASTContext()), 16819 /*IsImmediateInvocation*/ true); 16820 /// Value-dependent constant expressions should not be immediately 16821 /// evaluated until they are instantiated. 16822 if (!Res->isValueDependent()) 16823 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16824 return Res; 16825 } 16826 16827 static void EvaluateAndDiagnoseImmediateInvocation( 16828 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16829 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16830 Expr::EvalResult Eval; 16831 Eval.Diag = &Notes; 16832 ConstantExpr *CE = Candidate.getPointer(); 16833 bool Result = CE->EvaluateAsConstantExpr( 16834 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16835 if (!Result || !Notes.empty()) { 16836 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16837 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16838 InnerExpr = FunctionalCast->getSubExpr(); 16839 FunctionDecl *FD = nullptr; 16840 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16841 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16842 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16843 FD = Call->getConstructor(); 16844 else 16845 llvm_unreachable("unhandled decl kind"); 16846 assert(FD->isConsteval()); 16847 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16848 for (auto &Note : Notes) 16849 SemaRef.Diag(Note.first, Note.second); 16850 return; 16851 } 16852 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16853 } 16854 16855 static void RemoveNestedImmediateInvocation( 16856 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16857 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16858 struct ComplexRemove : TreeTransform<ComplexRemove> { 16859 using Base = TreeTransform<ComplexRemove>; 16860 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16861 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16862 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16863 CurrentII; 16864 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16865 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16866 SmallVector<Sema::ImmediateInvocationCandidate, 16867 4>::reverse_iterator Current) 16868 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16869 void RemoveImmediateInvocation(ConstantExpr* E) { 16870 auto It = std::find_if(CurrentII, IISet.rend(), 16871 [E](Sema::ImmediateInvocationCandidate Elem) { 16872 return Elem.getPointer() == E; 16873 }); 16874 assert(It != IISet.rend() && 16875 "ConstantExpr marked IsImmediateInvocation should " 16876 "be present"); 16877 It->setInt(1); // Mark as deleted 16878 } 16879 ExprResult TransformConstantExpr(ConstantExpr *E) { 16880 if (!E->isImmediateInvocation()) 16881 return Base::TransformConstantExpr(E); 16882 RemoveImmediateInvocation(E); 16883 return Base::TransformExpr(E->getSubExpr()); 16884 } 16885 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16886 /// we need to remove its DeclRefExpr from the DRSet. 16887 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16888 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16889 return Base::TransformCXXOperatorCallExpr(E); 16890 } 16891 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16892 /// here. 16893 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16894 if (!Init) 16895 return Init; 16896 /// ConstantExpr are the first layer of implicit node to be removed so if 16897 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16898 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16899 if (CE->isImmediateInvocation()) 16900 RemoveImmediateInvocation(CE); 16901 return Base::TransformInitializer(Init, NotCopyInit); 16902 } 16903 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16904 DRSet.erase(E); 16905 return E; 16906 } 16907 bool AlwaysRebuild() { return false; } 16908 bool ReplacingOriginal() { return true; } 16909 bool AllowSkippingCXXConstructExpr() { 16910 bool Res = AllowSkippingFirstCXXConstructExpr; 16911 AllowSkippingFirstCXXConstructExpr = true; 16912 return Res; 16913 } 16914 bool AllowSkippingFirstCXXConstructExpr = true; 16915 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16916 Rec.ImmediateInvocationCandidates, It); 16917 16918 /// CXXConstructExpr with a single argument are getting skipped by 16919 /// TreeTransform in some situtation because they could be implicit. This 16920 /// can only occur for the top-level CXXConstructExpr because it is used 16921 /// nowhere in the expression being transformed therefore will not be rebuilt. 16922 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16923 /// skipping the first CXXConstructExpr. 16924 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16925 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16926 16927 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16928 assert(Res.isUsable()); 16929 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16930 It->getPointer()->setSubExpr(Res.get()); 16931 } 16932 16933 static void 16934 HandleImmediateInvocations(Sema &SemaRef, 16935 Sema::ExpressionEvaluationContextRecord &Rec) { 16936 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16937 Rec.ReferenceToConsteval.size() == 0) || 16938 SemaRef.RebuildingImmediateInvocation) 16939 return; 16940 16941 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16942 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16943 /// need to remove ReferenceToConsteval in the immediate invocation. 16944 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16945 16946 /// Prevent sema calls during the tree transform from adding pointers that 16947 /// are already in the sets. 16948 llvm::SaveAndRestore<bool> DisableIITracking( 16949 SemaRef.RebuildingImmediateInvocation, true); 16950 16951 /// Prevent diagnostic during tree transfrom as they are duplicates 16952 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16953 16954 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16955 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16956 if (!It->getInt()) 16957 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16958 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16959 Rec.ReferenceToConsteval.size()) { 16960 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16961 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16962 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16963 bool VisitDeclRefExpr(DeclRefExpr *E) { 16964 DRSet.erase(E); 16965 return DRSet.size(); 16966 } 16967 } Visitor(Rec.ReferenceToConsteval); 16968 Visitor.TraverseStmt( 16969 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16970 } 16971 for (auto CE : Rec.ImmediateInvocationCandidates) 16972 if (!CE.getInt()) 16973 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16974 for (auto DR : Rec.ReferenceToConsteval) { 16975 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16976 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16977 << FD; 16978 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16979 } 16980 } 16981 16982 void Sema::PopExpressionEvaluationContext() { 16983 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16984 unsigned NumTypos = Rec.NumTypos; 16985 16986 if (!Rec.Lambdas.empty()) { 16987 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16988 if (!getLangOpts().CPlusPlus20 && 16989 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16990 Rec.isUnevaluated() || 16991 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16992 unsigned D; 16993 if (Rec.isUnevaluated()) { 16994 // C++11 [expr.prim.lambda]p2: 16995 // A lambda-expression shall not appear in an unevaluated operand 16996 // (Clause 5). 16997 D = diag::err_lambda_unevaluated_operand; 16998 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16999 // C++1y [expr.const]p2: 17000 // A conditional-expression e is a core constant expression unless the 17001 // evaluation of e, following the rules of the abstract machine, would 17002 // evaluate [...] a lambda-expression. 17003 D = diag::err_lambda_in_constant_expression; 17004 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 17005 // C++17 [expr.prim.lamda]p2: 17006 // A lambda-expression shall not appear [...] in a template-argument. 17007 D = diag::err_lambda_in_invalid_context; 17008 } else 17009 llvm_unreachable("Couldn't infer lambda error message."); 17010 17011 for (const auto *L : Rec.Lambdas) 17012 Diag(L->getBeginLoc(), D); 17013 } 17014 } 17015 17016 WarnOnPendingNoDerefs(Rec); 17017 HandleImmediateInvocations(*this, Rec); 17018 17019 // Warn on any volatile-qualified simple-assignments that are not discarded- 17020 // value expressions nor unevaluated operands (those cases get removed from 17021 // this list by CheckUnusedVolatileAssignment). 17022 for (auto *BO : Rec.VolatileAssignmentLHSs) 17023 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 17024 << BO->getType(); 17025 17026 // When are coming out of an unevaluated context, clear out any 17027 // temporaries that we may have created as part of the evaluation of 17028 // the expression in that context: they aren't relevant because they 17029 // will never be constructed. 17030 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 17031 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 17032 ExprCleanupObjects.end()); 17033 Cleanup = Rec.ParentCleanup; 17034 CleanupVarDeclMarking(); 17035 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 17036 // Otherwise, merge the contexts together. 17037 } else { 17038 Cleanup.mergeFrom(Rec.ParentCleanup); 17039 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 17040 Rec.SavedMaybeODRUseExprs.end()); 17041 } 17042 17043 // Pop the current expression evaluation context off the stack. 17044 ExprEvalContexts.pop_back(); 17045 17046 // The global expression evaluation context record is never popped. 17047 ExprEvalContexts.back().NumTypos += NumTypos; 17048 } 17049 17050 void Sema::DiscardCleanupsInEvaluationContext() { 17051 ExprCleanupObjects.erase( 17052 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 17053 ExprCleanupObjects.end()); 17054 Cleanup.reset(); 17055 MaybeODRUseExprs.clear(); 17056 } 17057 17058 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 17059 ExprResult Result = CheckPlaceholderExpr(E); 17060 if (Result.isInvalid()) 17061 return ExprError(); 17062 E = Result.get(); 17063 if (!E->getType()->isVariablyModifiedType()) 17064 return E; 17065 return TransformToPotentiallyEvaluated(E); 17066 } 17067 17068 /// Are we in a context that is potentially constant evaluated per C++20 17069 /// [expr.const]p12? 17070 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 17071 /// C++2a [expr.const]p12: 17072 // An expression or conversion is potentially constant evaluated if it is 17073 switch (SemaRef.ExprEvalContexts.back().Context) { 17074 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17075 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17076 17077 // -- a manifestly constant-evaluated expression, 17078 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17079 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17080 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17081 // -- a potentially-evaluated expression, 17082 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17083 // -- an immediate subexpression of a braced-init-list, 17084 17085 // -- [FIXME] an expression of the form & cast-expression that occurs 17086 // within a templated entity 17087 // -- a subexpression of one of the above that is not a subexpression of 17088 // a nested unevaluated operand. 17089 return true; 17090 17091 case Sema::ExpressionEvaluationContext::Unevaluated: 17092 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17093 // Expressions in this context are never evaluated. 17094 return false; 17095 } 17096 llvm_unreachable("Invalid context"); 17097 } 17098 17099 /// Return true if this function has a calling convention that requires mangling 17100 /// in the size of the parameter pack. 17101 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 17102 // These manglings don't do anything on non-Windows or non-x86 platforms, so 17103 // we don't need parameter type sizes. 17104 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 17105 if (!TT.isOSWindows() || !TT.isX86()) 17106 return false; 17107 17108 // If this is C++ and this isn't an extern "C" function, parameters do not 17109 // need to be complete. In this case, C++ mangling will apply, which doesn't 17110 // use the size of the parameters. 17111 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 17112 return false; 17113 17114 // Stdcall, fastcall, and vectorcall need this special treatment. 17115 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17116 switch (CC) { 17117 case CC_X86StdCall: 17118 case CC_X86FastCall: 17119 case CC_X86VectorCall: 17120 return true; 17121 default: 17122 break; 17123 } 17124 return false; 17125 } 17126 17127 /// Require that all of the parameter types of function be complete. Normally, 17128 /// parameter types are only required to be complete when a function is called 17129 /// or defined, but to mangle functions with certain calling conventions, the 17130 /// mangler needs to know the size of the parameter list. In this situation, 17131 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 17132 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 17133 /// result in a linker error. Clang doesn't implement this behavior, and instead 17134 /// attempts to error at compile time. 17135 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 17136 SourceLocation Loc) { 17137 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 17138 FunctionDecl *FD; 17139 ParmVarDecl *Param; 17140 17141 public: 17142 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 17143 : FD(FD), Param(Param) {} 17144 17145 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17146 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17147 StringRef CCName; 17148 switch (CC) { 17149 case CC_X86StdCall: 17150 CCName = "stdcall"; 17151 break; 17152 case CC_X86FastCall: 17153 CCName = "fastcall"; 17154 break; 17155 case CC_X86VectorCall: 17156 CCName = "vectorcall"; 17157 break; 17158 default: 17159 llvm_unreachable("CC does not need mangling"); 17160 } 17161 17162 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17163 << Param->getDeclName() << FD->getDeclName() << CCName; 17164 } 17165 }; 17166 17167 for (ParmVarDecl *Param : FD->parameters()) { 17168 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17169 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17170 } 17171 } 17172 17173 namespace { 17174 enum class OdrUseContext { 17175 /// Declarations in this context are not odr-used. 17176 None, 17177 /// Declarations in this context are formally odr-used, but this is a 17178 /// dependent context. 17179 Dependent, 17180 /// Declarations in this context are odr-used but not actually used (yet). 17181 FormallyOdrUsed, 17182 /// Declarations in this context are used. 17183 Used 17184 }; 17185 } 17186 17187 /// Are we within a context in which references to resolved functions or to 17188 /// variables result in odr-use? 17189 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17190 OdrUseContext Result; 17191 17192 switch (SemaRef.ExprEvalContexts.back().Context) { 17193 case Sema::ExpressionEvaluationContext::Unevaluated: 17194 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17195 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17196 return OdrUseContext::None; 17197 17198 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17199 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17200 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17201 Result = OdrUseContext::Used; 17202 break; 17203 17204 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17205 Result = OdrUseContext::FormallyOdrUsed; 17206 break; 17207 17208 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17209 // A default argument formally results in odr-use, but doesn't actually 17210 // result in a use in any real sense until it itself is used. 17211 Result = OdrUseContext::FormallyOdrUsed; 17212 break; 17213 } 17214 17215 if (SemaRef.CurContext->isDependentContext()) 17216 return OdrUseContext::Dependent; 17217 17218 return Result; 17219 } 17220 17221 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17222 if (!Func->isConstexpr()) 17223 return false; 17224 17225 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17226 return true; 17227 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17228 return CCD && CCD->getInheritedConstructor(); 17229 } 17230 17231 /// Mark a function referenced, and check whether it is odr-used 17232 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17233 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17234 bool MightBeOdrUse) { 17235 assert(Func && "No function?"); 17236 17237 Func->setReferenced(); 17238 17239 // Recursive functions aren't really used until they're used from some other 17240 // context. 17241 bool IsRecursiveCall = CurContext == Func; 17242 17243 // C++11 [basic.def.odr]p3: 17244 // A function whose name appears as a potentially-evaluated expression is 17245 // odr-used if it is the unique lookup result or the selected member of a 17246 // set of overloaded functions [...]. 17247 // 17248 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17249 // can just check that here. 17250 OdrUseContext OdrUse = 17251 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17252 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17253 OdrUse = OdrUseContext::FormallyOdrUsed; 17254 17255 // Trivial default constructors and destructors are never actually used. 17256 // FIXME: What about other special members? 17257 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17258 OdrUse == OdrUseContext::Used) { 17259 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17260 if (Constructor->isDefaultConstructor()) 17261 OdrUse = OdrUseContext::FormallyOdrUsed; 17262 if (isa<CXXDestructorDecl>(Func)) 17263 OdrUse = OdrUseContext::FormallyOdrUsed; 17264 } 17265 17266 // C++20 [expr.const]p12: 17267 // A function [...] is needed for constant evaluation if it is [...] a 17268 // constexpr function that is named by an expression that is potentially 17269 // constant evaluated 17270 bool NeededForConstantEvaluation = 17271 isPotentiallyConstantEvaluatedContext(*this) && 17272 isImplicitlyDefinableConstexprFunction(Func); 17273 17274 // Determine whether we require a function definition to exist, per 17275 // C++11 [temp.inst]p3: 17276 // Unless a function template specialization has been explicitly 17277 // instantiated or explicitly specialized, the function template 17278 // specialization is implicitly instantiated when the specialization is 17279 // referenced in a context that requires a function definition to exist. 17280 // C++20 [temp.inst]p7: 17281 // The existence of a definition of a [...] function is considered to 17282 // affect the semantics of the program if the [...] function is needed for 17283 // constant evaluation by an expression 17284 // C++20 [basic.def.odr]p10: 17285 // Every program shall contain exactly one definition of every non-inline 17286 // function or variable that is odr-used in that program outside of a 17287 // discarded statement 17288 // C++20 [special]p1: 17289 // The implementation will implicitly define [defaulted special members] 17290 // if they are odr-used or needed for constant evaluation. 17291 // 17292 // Note that we skip the implicit instantiation of templates that are only 17293 // used in unused default arguments or by recursive calls to themselves. 17294 // This is formally non-conforming, but seems reasonable in practice. 17295 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17296 NeededForConstantEvaluation); 17297 17298 // C++14 [temp.expl.spec]p6: 17299 // If a template [...] is explicitly specialized then that specialization 17300 // shall be declared before the first use of that specialization that would 17301 // cause an implicit instantiation to take place, in every translation unit 17302 // in which such a use occurs 17303 if (NeedDefinition && 17304 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17305 Func->getMemberSpecializationInfo())) 17306 checkSpecializationVisibility(Loc, Func); 17307 17308 if (getLangOpts().CUDA) 17309 CheckCUDACall(Loc, Func); 17310 17311 if (getLangOpts().SYCLIsDevice) 17312 checkSYCLDeviceFunction(Loc, Func); 17313 17314 // If we need a definition, try to create one. 17315 if (NeedDefinition && !Func->getBody()) { 17316 runWithSufficientStackSpace(Loc, [&] { 17317 if (CXXConstructorDecl *Constructor = 17318 dyn_cast<CXXConstructorDecl>(Func)) { 17319 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17320 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17321 if (Constructor->isDefaultConstructor()) { 17322 if (Constructor->isTrivial() && 17323 !Constructor->hasAttr<DLLExportAttr>()) 17324 return; 17325 DefineImplicitDefaultConstructor(Loc, Constructor); 17326 } else if (Constructor->isCopyConstructor()) { 17327 DefineImplicitCopyConstructor(Loc, Constructor); 17328 } else if (Constructor->isMoveConstructor()) { 17329 DefineImplicitMoveConstructor(Loc, Constructor); 17330 } 17331 } else if (Constructor->getInheritedConstructor()) { 17332 DefineInheritingConstructor(Loc, Constructor); 17333 } 17334 } else if (CXXDestructorDecl *Destructor = 17335 dyn_cast<CXXDestructorDecl>(Func)) { 17336 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17337 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17338 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17339 return; 17340 DefineImplicitDestructor(Loc, Destructor); 17341 } 17342 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17343 MarkVTableUsed(Loc, Destructor->getParent()); 17344 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17345 if (MethodDecl->isOverloadedOperator() && 17346 MethodDecl->getOverloadedOperator() == OO_Equal) { 17347 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17348 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17349 if (MethodDecl->isCopyAssignmentOperator()) 17350 DefineImplicitCopyAssignment(Loc, MethodDecl); 17351 else if (MethodDecl->isMoveAssignmentOperator()) 17352 DefineImplicitMoveAssignment(Loc, MethodDecl); 17353 } 17354 } else if (isa<CXXConversionDecl>(MethodDecl) && 17355 MethodDecl->getParent()->isLambda()) { 17356 CXXConversionDecl *Conversion = 17357 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17358 if (Conversion->isLambdaToBlockPointerConversion()) 17359 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17360 else 17361 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17362 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17363 MarkVTableUsed(Loc, MethodDecl->getParent()); 17364 } 17365 17366 if (Func->isDefaulted() && !Func->isDeleted()) { 17367 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17368 if (DCK != DefaultedComparisonKind::None) 17369 DefineDefaultedComparison(Loc, Func, DCK); 17370 } 17371 17372 // Implicit instantiation of function templates and member functions of 17373 // class templates. 17374 if (Func->isImplicitlyInstantiable()) { 17375 TemplateSpecializationKind TSK = 17376 Func->getTemplateSpecializationKindForInstantiation(); 17377 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17378 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17379 if (FirstInstantiation) { 17380 PointOfInstantiation = Loc; 17381 if (auto *MSI = Func->getMemberSpecializationInfo()) 17382 MSI->setPointOfInstantiation(Loc); 17383 // FIXME: Notify listener. 17384 else 17385 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17386 } else if (TSK != TSK_ImplicitInstantiation) { 17387 // Use the point of use as the point of instantiation, instead of the 17388 // point of explicit instantiation (which we track as the actual point 17389 // of instantiation). This gives better backtraces in diagnostics. 17390 PointOfInstantiation = Loc; 17391 } 17392 17393 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17394 Func->isConstexpr()) { 17395 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17396 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17397 CodeSynthesisContexts.size()) 17398 PendingLocalImplicitInstantiations.push_back( 17399 std::make_pair(Func, PointOfInstantiation)); 17400 else if (Func->isConstexpr()) 17401 // Do not defer instantiations of constexpr functions, to avoid the 17402 // expression evaluator needing to call back into Sema if it sees a 17403 // call to such a function. 17404 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17405 else { 17406 Func->setInstantiationIsPending(true); 17407 PendingInstantiations.push_back( 17408 std::make_pair(Func, PointOfInstantiation)); 17409 // Notify the consumer that a function was implicitly instantiated. 17410 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17411 } 17412 } 17413 } else { 17414 // Walk redefinitions, as some of them may be instantiable. 17415 for (auto i : Func->redecls()) { 17416 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17417 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17418 } 17419 } 17420 }); 17421 } 17422 17423 // C++14 [except.spec]p17: 17424 // An exception-specification is considered to be needed when: 17425 // - the function is odr-used or, if it appears in an unevaluated operand, 17426 // would be odr-used if the expression were potentially-evaluated; 17427 // 17428 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17429 // function is a pure virtual function we're calling, and in that case the 17430 // function was selected by overload resolution and we need to resolve its 17431 // exception specification for a different reason. 17432 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17433 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17434 ResolveExceptionSpec(Loc, FPT); 17435 17436 // If this is the first "real" use, act on that. 17437 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17438 // Keep track of used but undefined functions. 17439 if (!Func->isDefined()) { 17440 if (mightHaveNonExternalLinkage(Func)) 17441 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17442 else if (Func->getMostRecentDecl()->isInlined() && 17443 !LangOpts.GNUInline && 17444 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17445 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17446 else if (isExternalWithNoLinkageType(Func)) 17447 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17448 } 17449 17450 // Some x86 Windows calling conventions mangle the size of the parameter 17451 // pack into the name. Computing the size of the parameters requires the 17452 // parameter types to be complete. Check that now. 17453 if (funcHasParameterSizeMangling(*this, Func)) 17454 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17455 17456 // In the MS C++ ABI, the compiler emits destructor variants where they are 17457 // used. If the destructor is used here but defined elsewhere, mark the 17458 // virtual base destructors referenced. If those virtual base destructors 17459 // are inline, this will ensure they are defined when emitting the complete 17460 // destructor variant. This checking may be redundant if the destructor is 17461 // provided later in this TU. 17462 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17463 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17464 CXXRecordDecl *Parent = Dtor->getParent(); 17465 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17466 CheckCompleteDestructorVariant(Loc, Dtor); 17467 } 17468 } 17469 17470 Func->markUsed(Context); 17471 } 17472 } 17473 17474 /// Directly mark a variable odr-used. Given a choice, prefer to use 17475 /// MarkVariableReferenced since it does additional checks and then 17476 /// calls MarkVarDeclODRUsed. 17477 /// If the variable must be captured: 17478 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17479 /// - else capture it in the DeclContext that maps to the 17480 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17481 static void 17482 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17483 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17484 // Keep track of used but undefined variables. 17485 // FIXME: We shouldn't suppress this warning for static data members. 17486 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17487 (!Var->isExternallyVisible() || Var->isInline() || 17488 SemaRef.isExternalWithNoLinkageType(Var)) && 17489 !(Var->isStaticDataMember() && Var->hasInit())) { 17490 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17491 if (old.isInvalid()) 17492 old = Loc; 17493 } 17494 QualType CaptureType, DeclRefType; 17495 if (SemaRef.LangOpts.OpenMP) 17496 SemaRef.tryCaptureOpenMPLambdas(Var); 17497 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17498 /*EllipsisLoc*/ SourceLocation(), 17499 /*BuildAndDiagnose*/ true, 17500 CaptureType, DeclRefType, 17501 FunctionScopeIndexToStopAt); 17502 17503 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { 17504 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17505 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17506 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17507 if (VarTarget == Sema::CVT_Host && 17508 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17509 UserTarget == Sema::CFT_Global)) { 17510 // Diagnose ODR-use of host global variables in device functions. 17511 // Reference of device global variables in host functions is allowed 17512 // through shadow variables therefore it is not diagnosed. 17513 if (SemaRef.LangOpts.CUDAIsDevice) { 17514 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17515 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17516 SemaRef.targetDiag(Var->getLocation(), 17517 Var->getType().isConstQualified() 17518 ? diag::note_cuda_const_var_unpromoted 17519 : diag::note_cuda_host_var); 17520 } 17521 } else if (VarTarget == Sema::CVT_Device && 17522 (UserTarget == Sema::CFT_Host || 17523 UserTarget == Sema::CFT_HostDevice) && 17524 !Var->hasExternalStorage()) { 17525 // Record a CUDA/HIP device side variable if it is ODR-used 17526 // by host code. This is done conservatively, when the variable is 17527 // referenced in any of the following contexts: 17528 // - a non-function context 17529 // - a host function 17530 // - a host device function 17531 // This makes the ODR-use of the device side variable by host code to 17532 // be visible in the device compilation for the compiler to be able to 17533 // emit template variables instantiated by host code only and to 17534 // externalize the static device side variable ODR-used by host code. 17535 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17536 } 17537 } 17538 17539 Var->markUsed(SemaRef.Context); 17540 } 17541 17542 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17543 SourceLocation Loc, 17544 unsigned CapturingScopeIndex) { 17545 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17546 } 17547 17548 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17549 ValueDecl *var) { 17550 DeclContext *VarDC = var->getDeclContext(); 17551 17552 // If the parameter still belongs to the translation unit, then 17553 // we're actually just using one parameter in the declaration of 17554 // the next. 17555 if (isa<ParmVarDecl>(var) && 17556 isa<TranslationUnitDecl>(VarDC)) 17557 return; 17558 17559 // For C code, don't diagnose about capture if we're not actually in code 17560 // right now; it's impossible to write a non-constant expression outside of 17561 // function context, so we'll get other (more useful) diagnostics later. 17562 // 17563 // For C++, things get a bit more nasty... it would be nice to suppress this 17564 // diagnostic for certain cases like using a local variable in an array bound 17565 // for a member of a local class, but the correct predicate is not obvious. 17566 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17567 return; 17568 17569 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17570 unsigned ContextKind = 3; // unknown 17571 if (isa<CXXMethodDecl>(VarDC) && 17572 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17573 ContextKind = 2; 17574 } else if (isa<FunctionDecl>(VarDC)) { 17575 ContextKind = 0; 17576 } else if (isa<BlockDecl>(VarDC)) { 17577 ContextKind = 1; 17578 } 17579 17580 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17581 << var << ValueKind << ContextKind << VarDC; 17582 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17583 << var; 17584 17585 // FIXME: Add additional diagnostic info about class etc. which prevents 17586 // capture. 17587 } 17588 17589 17590 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17591 bool &SubCapturesAreNested, 17592 QualType &CaptureType, 17593 QualType &DeclRefType) { 17594 // Check whether we've already captured it. 17595 if (CSI->CaptureMap.count(Var)) { 17596 // If we found a capture, any subcaptures are nested. 17597 SubCapturesAreNested = true; 17598 17599 // Retrieve the capture type for this variable. 17600 CaptureType = CSI->getCapture(Var).getCaptureType(); 17601 17602 // Compute the type of an expression that refers to this variable. 17603 DeclRefType = CaptureType.getNonReferenceType(); 17604 17605 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17606 // are mutable in the sense that user can change their value - they are 17607 // private instances of the captured declarations. 17608 const Capture &Cap = CSI->getCapture(Var); 17609 if (Cap.isCopyCapture() && 17610 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17611 !(isa<CapturedRegionScopeInfo>(CSI) && 17612 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17613 DeclRefType.addConst(); 17614 return true; 17615 } 17616 return false; 17617 } 17618 17619 // Only block literals, captured statements, and lambda expressions can 17620 // capture; other scopes don't work. 17621 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17622 SourceLocation Loc, 17623 const bool Diagnose, Sema &S) { 17624 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17625 return getLambdaAwareParentOfDeclContext(DC); 17626 else if (Var->hasLocalStorage()) { 17627 if (Diagnose) 17628 diagnoseUncapturableValueReference(S, Loc, Var); 17629 } 17630 return nullptr; 17631 } 17632 17633 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17634 // certain types of variables (unnamed, variably modified types etc.) 17635 // so check for eligibility. 17636 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17637 SourceLocation Loc, 17638 const bool Diagnose, Sema &S) { 17639 17640 bool IsBlock = isa<BlockScopeInfo>(CSI); 17641 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17642 17643 // Lambdas are not allowed to capture unnamed variables 17644 // (e.g. anonymous unions). 17645 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17646 // assuming that's the intent. 17647 if (IsLambda && !Var->getDeclName()) { 17648 if (Diagnose) { 17649 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17650 S.Diag(Var->getLocation(), diag::note_declared_at); 17651 } 17652 return false; 17653 } 17654 17655 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17656 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17657 if (Diagnose) { 17658 S.Diag(Loc, diag::err_ref_vm_type); 17659 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17660 } 17661 return false; 17662 } 17663 // Prohibit structs with flexible array members too. 17664 // We cannot capture what is in the tail end of the struct. 17665 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17666 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17667 if (Diagnose) { 17668 if (IsBlock) 17669 S.Diag(Loc, diag::err_ref_flexarray_type); 17670 else 17671 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17672 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17673 } 17674 return false; 17675 } 17676 } 17677 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17678 // Lambdas and captured statements are not allowed to capture __block 17679 // variables; they don't support the expected semantics. 17680 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17681 if (Diagnose) { 17682 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17683 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17684 } 17685 return false; 17686 } 17687 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17688 if (S.getLangOpts().OpenCL && IsBlock && 17689 Var->getType()->isBlockPointerType()) { 17690 if (Diagnose) 17691 S.Diag(Loc, diag::err_opencl_block_ref_block); 17692 return false; 17693 } 17694 17695 return true; 17696 } 17697 17698 // Returns true if the capture by block was successful. 17699 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17700 SourceLocation Loc, 17701 const bool BuildAndDiagnose, 17702 QualType &CaptureType, 17703 QualType &DeclRefType, 17704 const bool Nested, 17705 Sema &S, bool Invalid) { 17706 bool ByRef = false; 17707 17708 // Blocks are not allowed to capture arrays, excepting OpenCL. 17709 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17710 // (decayed to pointers). 17711 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17712 if (BuildAndDiagnose) { 17713 S.Diag(Loc, diag::err_ref_array_type); 17714 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17715 Invalid = true; 17716 } else { 17717 return false; 17718 } 17719 } 17720 17721 // Forbid the block-capture of autoreleasing variables. 17722 if (!Invalid && 17723 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17724 if (BuildAndDiagnose) { 17725 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17726 << /*block*/ 0; 17727 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17728 Invalid = true; 17729 } else { 17730 return false; 17731 } 17732 } 17733 17734 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17735 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17736 QualType PointeeTy = PT->getPointeeType(); 17737 17738 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17739 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17740 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17741 if (BuildAndDiagnose) { 17742 SourceLocation VarLoc = Var->getLocation(); 17743 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17744 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17745 } 17746 } 17747 } 17748 17749 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17750 if (HasBlocksAttr || CaptureType->isReferenceType() || 17751 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17752 // Block capture by reference does not change the capture or 17753 // declaration reference types. 17754 ByRef = true; 17755 } else { 17756 // Block capture by copy introduces 'const'. 17757 CaptureType = CaptureType.getNonReferenceType().withConst(); 17758 DeclRefType = CaptureType; 17759 } 17760 17761 // Actually capture the variable. 17762 if (BuildAndDiagnose) 17763 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17764 CaptureType, Invalid); 17765 17766 return !Invalid; 17767 } 17768 17769 17770 /// Capture the given variable in the captured region. 17771 static bool captureInCapturedRegion( 17772 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17773 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17774 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17775 bool IsTopScope, Sema &S, bool Invalid) { 17776 // By default, capture variables by reference. 17777 bool ByRef = true; 17778 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17779 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17780 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17781 // Using an LValue reference type is consistent with Lambdas (see below). 17782 if (S.isOpenMPCapturedDecl(Var)) { 17783 bool HasConst = DeclRefType.isConstQualified(); 17784 DeclRefType = DeclRefType.getUnqualifiedType(); 17785 // Don't lose diagnostics about assignments to const. 17786 if (HasConst) 17787 DeclRefType.addConst(); 17788 } 17789 // Do not capture firstprivates in tasks. 17790 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17791 OMPC_unknown) 17792 return true; 17793 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17794 RSI->OpenMPCaptureLevel); 17795 } 17796 17797 if (ByRef) 17798 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17799 else 17800 CaptureType = DeclRefType; 17801 17802 // Actually capture the variable. 17803 if (BuildAndDiagnose) 17804 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17805 Loc, SourceLocation(), CaptureType, Invalid); 17806 17807 return !Invalid; 17808 } 17809 17810 /// Capture the given variable in the lambda. 17811 static bool captureInLambda(LambdaScopeInfo *LSI, 17812 VarDecl *Var, 17813 SourceLocation Loc, 17814 const bool BuildAndDiagnose, 17815 QualType &CaptureType, 17816 QualType &DeclRefType, 17817 const bool RefersToCapturedVariable, 17818 const Sema::TryCaptureKind Kind, 17819 SourceLocation EllipsisLoc, 17820 const bool IsTopScope, 17821 Sema &S, bool Invalid) { 17822 // Determine whether we are capturing by reference or by value. 17823 bool ByRef = false; 17824 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17825 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17826 } else { 17827 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17828 } 17829 17830 // Compute the type of the field that will capture this variable. 17831 if (ByRef) { 17832 // C++11 [expr.prim.lambda]p15: 17833 // An entity is captured by reference if it is implicitly or 17834 // explicitly captured but not captured by copy. It is 17835 // unspecified whether additional unnamed non-static data 17836 // members are declared in the closure type for entities 17837 // captured by reference. 17838 // 17839 // FIXME: It is not clear whether we want to build an lvalue reference 17840 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17841 // to do the former, while EDG does the latter. Core issue 1249 will 17842 // clarify, but for now we follow GCC because it's a more permissive and 17843 // easily defensible position. 17844 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17845 } else { 17846 // C++11 [expr.prim.lambda]p14: 17847 // For each entity captured by copy, an unnamed non-static 17848 // data member is declared in the closure type. The 17849 // declaration order of these members is unspecified. The type 17850 // of such a data member is the type of the corresponding 17851 // captured entity if the entity is not a reference to an 17852 // object, or the referenced type otherwise. [Note: If the 17853 // captured entity is a reference to a function, the 17854 // corresponding data member is also a reference to a 17855 // function. - end note ] 17856 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17857 if (!RefType->getPointeeType()->isFunctionType()) 17858 CaptureType = RefType->getPointeeType(); 17859 } 17860 17861 // Forbid the lambda copy-capture of autoreleasing variables. 17862 if (!Invalid && 17863 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17864 if (BuildAndDiagnose) { 17865 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17866 S.Diag(Var->getLocation(), diag::note_previous_decl) 17867 << Var->getDeclName(); 17868 Invalid = true; 17869 } else { 17870 return false; 17871 } 17872 } 17873 17874 // Make sure that by-copy captures are of a complete and non-abstract type. 17875 if (!Invalid && BuildAndDiagnose) { 17876 if (!CaptureType->isDependentType() && 17877 S.RequireCompleteSizedType( 17878 Loc, CaptureType, 17879 diag::err_capture_of_incomplete_or_sizeless_type, 17880 Var->getDeclName())) 17881 Invalid = true; 17882 else if (S.RequireNonAbstractType(Loc, CaptureType, 17883 diag::err_capture_of_abstract_type)) 17884 Invalid = true; 17885 } 17886 } 17887 17888 // Compute the type of a reference to this captured variable. 17889 if (ByRef) 17890 DeclRefType = CaptureType.getNonReferenceType(); 17891 else { 17892 // C++ [expr.prim.lambda]p5: 17893 // The closure type for a lambda-expression has a public inline 17894 // function call operator [...]. This function call operator is 17895 // declared const (9.3.1) if and only if the lambda-expression's 17896 // parameter-declaration-clause is not followed by mutable. 17897 DeclRefType = CaptureType.getNonReferenceType(); 17898 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17899 DeclRefType.addConst(); 17900 } 17901 17902 // Add the capture. 17903 if (BuildAndDiagnose) 17904 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17905 Loc, EllipsisLoc, CaptureType, Invalid); 17906 17907 return !Invalid; 17908 } 17909 17910 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17911 // Offer a Copy fix even if the type is dependent. 17912 if (Var->getType()->isDependentType()) 17913 return true; 17914 QualType T = Var->getType().getNonReferenceType(); 17915 if (T.isTriviallyCopyableType(Context)) 17916 return true; 17917 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17918 17919 if (!(RD = RD->getDefinition())) 17920 return false; 17921 if (RD->hasSimpleCopyConstructor()) 17922 return true; 17923 if (RD->hasUserDeclaredCopyConstructor()) 17924 for (CXXConstructorDecl *Ctor : RD->ctors()) 17925 if (Ctor->isCopyConstructor()) 17926 return !Ctor->isDeleted(); 17927 } 17928 return false; 17929 } 17930 17931 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17932 /// default capture. Fixes may be omitted if they aren't allowed by the 17933 /// standard, for example we can't emit a default copy capture fix-it if we 17934 /// already explicitly copy capture capture another variable. 17935 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17936 VarDecl *Var) { 17937 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17938 // Don't offer Capture by copy of default capture by copy fixes if Var is 17939 // known not to be copy constructible. 17940 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17941 17942 SmallString<32> FixBuffer; 17943 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17944 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17945 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17946 if (ShouldOfferCopyFix) { 17947 // Offer fixes to insert an explicit capture for the variable. 17948 // [] -> [VarName] 17949 // [OtherCapture] -> [OtherCapture, VarName] 17950 FixBuffer.assign({Separator, Var->getName()}); 17951 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17952 << Var << /*value*/ 0 17953 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17954 } 17955 // As above but capture by reference. 17956 FixBuffer.assign({Separator, "&", Var->getName()}); 17957 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17958 << Var << /*reference*/ 1 17959 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17960 } 17961 17962 // Only try to offer default capture if there are no captures excluding this 17963 // and init captures. 17964 // [this]: OK. 17965 // [X = Y]: OK. 17966 // [&A, &B]: Don't offer. 17967 // [A, B]: Don't offer. 17968 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17969 return !C.isThisCapture() && !C.isInitCapture(); 17970 })) 17971 return; 17972 17973 // The default capture specifiers, '=' or '&', must appear first in the 17974 // capture body. 17975 SourceLocation DefaultInsertLoc = 17976 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17977 17978 if (ShouldOfferCopyFix) { 17979 bool CanDefaultCopyCapture = true; 17980 // [=, *this] OK since c++17 17981 // [=, this] OK since c++20 17982 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17983 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17984 ? LSI->getCXXThisCapture().isCopyCapture() 17985 : false; 17986 // We can't use default capture by copy if any captures already specified 17987 // capture by copy. 17988 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17989 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17990 })) { 17991 FixBuffer.assign({"=", Separator}); 17992 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17993 << /*value*/ 0 17994 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17995 } 17996 } 17997 17998 // We can't use default capture by reference if any captures already specified 17999 // capture by reference. 18000 if (llvm::none_of(LSI->Captures, [](Capture &C) { 18001 return !C.isInitCapture() && C.isReferenceCapture() && 18002 !C.isThisCapture(); 18003 })) { 18004 FixBuffer.assign({"&", Separator}); 18005 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 18006 << /*reference*/ 1 18007 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 18008 } 18009 } 18010 18011 bool Sema::tryCaptureVariable( 18012 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 18013 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 18014 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 18015 // An init-capture is notionally from the context surrounding its 18016 // declaration, but its parent DC is the lambda class. 18017 DeclContext *VarDC = Var->getDeclContext(); 18018 if (Var->isInitCapture()) 18019 VarDC = VarDC->getParent(); 18020 18021 DeclContext *DC = CurContext; 18022 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 18023 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 18024 // We need to sync up the Declaration Context with the 18025 // FunctionScopeIndexToStopAt 18026 if (FunctionScopeIndexToStopAt) { 18027 unsigned FSIndex = FunctionScopes.size() - 1; 18028 while (FSIndex != MaxFunctionScopesIndex) { 18029 DC = getLambdaAwareParentOfDeclContext(DC); 18030 --FSIndex; 18031 } 18032 } 18033 18034 18035 // If the variable is declared in the current context, there is no need to 18036 // capture it. 18037 if (VarDC == DC) return true; 18038 18039 // Capture global variables if it is required to use private copy of this 18040 // variable. 18041 bool IsGlobal = !Var->hasLocalStorage(); 18042 if (IsGlobal && 18043 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 18044 MaxFunctionScopesIndex))) 18045 return true; 18046 Var = Var->getCanonicalDecl(); 18047 18048 // Walk up the stack to determine whether we can capture the variable, 18049 // performing the "simple" checks that don't depend on type. We stop when 18050 // we've either hit the declared scope of the variable or find an existing 18051 // capture of that variable. We start from the innermost capturing-entity 18052 // (the DC) and ensure that all intervening capturing-entities 18053 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 18054 // declcontext can either capture the variable or have already captured 18055 // the variable. 18056 CaptureType = Var->getType(); 18057 DeclRefType = CaptureType.getNonReferenceType(); 18058 bool Nested = false; 18059 bool Explicit = (Kind != TryCapture_Implicit); 18060 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 18061 do { 18062 // Only block literals, captured statements, and lambda expressions can 18063 // capture; other scopes don't work. 18064 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 18065 ExprLoc, 18066 BuildAndDiagnose, 18067 *this); 18068 // We need to check for the parent *first* because, if we *have* 18069 // private-captured a global variable, we need to recursively capture it in 18070 // intermediate blocks, lambdas, etc. 18071 if (!ParentDC) { 18072 if (IsGlobal) { 18073 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 18074 break; 18075 } 18076 return true; 18077 } 18078 18079 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 18080 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 18081 18082 18083 // Check whether we've already captured it. 18084 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 18085 DeclRefType)) { 18086 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 18087 break; 18088 } 18089 // If we are instantiating a generic lambda call operator body, 18090 // we do not want to capture new variables. What was captured 18091 // during either a lambdas transformation or initial parsing 18092 // should be used. 18093 if (isGenericLambdaCallOperatorSpecialization(DC)) { 18094 if (BuildAndDiagnose) { 18095 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18096 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 18097 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18098 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18099 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18100 buildLambdaCaptureFixit(*this, LSI, Var); 18101 } else 18102 diagnoseUncapturableValueReference(*this, ExprLoc, Var); 18103 } 18104 return true; 18105 } 18106 18107 // Try to capture variable-length arrays types. 18108 if (Var->getType()->isVariablyModifiedType()) { 18109 // We're going to walk down into the type and look for VLA 18110 // expressions. 18111 QualType QTy = Var->getType(); 18112 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18113 QTy = PVD->getOriginalType(); 18114 captureVariablyModifiedType(Context, QTy, CSI); 18115 } 18116 18117 if (getLangOpts().OpenMP) { 18118 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18119 // OpenMP private variables should not be captured in outer scope, so 18120 // just break here. Similarly, global variables that are captured in a 18121 // target region should not be captured outside the scope of the region. 18122 if (RSI->CapRegionKind == CR_OpenMP) { 18123 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 18124 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 18125 // If the variable is private (i.e. not captured) and has variably 18126 // modified type, we still need to capture the type for correct 18127 // codegen in all regions, associated with the construct. Currently, 18128 // it is captured in the innermost captured region only. 18129 if (IsOpenMPPrivateDecl != OMPC_unknown && 18130 Var->getType()->isVariablyModifiedType()) { 18131 QualType QTy = Var->getType(); 18132 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18133 QTy = PVD->getOriginalType(); 18134 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 18135 I < E; ++I) { 18136 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 18137 FunctionScopes[FunctionScopesIndex - I]); 18138 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 18139 "Wrong number of captured regions associated with the " 18140 "OpenMP construct."); 18141 captureVariablyModifiedType(Context, QTy, OuterRSI); 18142 } 18143 } 18144 bool IsTargetCap = 18145 IsOpenMPPrivateDecl != OMPC_private && 18146 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 18147 RSI->OpenMPCaptureLevel); 18148 // Do not capture global if it is not privatized in outer regions. 18149 bool IsGlobalCap = 18150 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 18151 RSI->OpenMPCaptureLevel); 18152 18153 // When we detect target captures we are looking from inside the 18154 // target region, therefore we need to propagate the capture from the 18155 // enclosing region. Therefore, the capture is not initially nested. 18156 if (IsTargetCap) 18157 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18158 18159 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18160 (IsGlobal && !IsGlobalCap)) { 18161 Nested = !IsTargetCap; 18162 bool HasConst = DeclRefType.isConstQualified(); 18163 DeclRefType = DeclRefType.getUnqualifiedType(); 18164 // Don't lose diagnostics about assignments to const. 18165 if (HasConst) 18166 DeclRefType.addConst(); 18167 CaptureType = Context.getLValueReferenceType(DeclRefType); 18168 break; 18169 } 18170 } 18171 } 18172 } 18173 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18174 // No capture-default, and this is not an explicit capture 18175 // so cannot capture this variable. 18176 if (BuildAndDiagnose) { 18177 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18178 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18179 auto *LSI = cast<LambdaScopeInfo>(CSI); 18180 if (LSI->Lambda) { 18181 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18182 buildLambdaCaptureFixit(*this, LSI, Var); 18183 } 18184 // FIXME: If we error out because an outer lambda can not implicitly 18185 // capture a variable that an inner lambda explicitly captures, we 18186 // should have the inner lambda do the explicit capture - because 18187 // it makes for cleaner diagnostics later. This would purely be done 18188 // so that the diagnostic does not misleadingly claim that a variable 18189 // can not be captured by a lambda implicitly even though it is captured 18190 // explicitly. Suggestion: 18191 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18192 // at the function head 18193 // - cache the StartingDeclContext - this must be a lambda 18194 // - captureInLambda in the innermost lambda the variable. 18195 } 18196 return true; 18197 } 18198 18199 FunctionScopesIndex--; 18200 DC = ParentDC; 18201 Explicit = false; 18202 } while (!VarDC->Equals(DC)); 18203 18204 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18205 // computing the type of the capture at each step, checking type-specific 18206 // requirements, and adding captures if requested. 18207 // If the variable had already been captured previously, we start capturing 18208 // at the lambda nested within that one. 18209 bool Invalid = false; 18210 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18211 ++I) { 18212 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18213 18214 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18215 // certain types of variables (unnamed, variably modified types etc.) 18216 // so check for eligibility. 18217 if (!Invalid) 18218 Invalid = 18219 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18220 18221 // After encountering an error, if we're actually supposed to capture, keep 18222 // capturing in nested contexts to suppress any follow-on diagnostics. 18223 if (Invalid && !BuildAndDiagnose) 18224 return true; 18225 18226 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18227 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18228 DeclRefType, Nested, *this, Invalid); 18229 Nested = true; 18230 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18231 Invalid = !captureInCapturedRegion( 18232 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18233 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18234 Nested = true; 18235 } else { 18236 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18237 Invalid = 18238 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18239 DeclRefType, Nested, Kind, EllipsisLoc, 18240 /*IsTopScope*/ I == N - 1, *this, Invalid); 18241 Nested = true; 18242 } 18243 18244 if (Invalid && !BuildAndDiagnose) 18245 return true; 18246 } 18247 return Invalid; 18248 } 18249 18250 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18251 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18252 QualType CaptureType; 18253 QualType DeclRefType; 18254 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18255 /*BuildAndDiagnose=*/true, CaptureType, 18256 DeclRefType, nullptr); 18257 } 18258 18259 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18260 QualType CaptureType; 18261 QualType DeclRefType; 18262 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18263 /*BuildAndDiagnose=*/false, CaptureType, 18264 DeclRefType, nullptr); 18265 } 18266 18267 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18268 QualType CaptureType; 18269 QualType DeclRefType; 18270 18271 // Determine whether we can capture this variable. 18272 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18273 /*BuildAndDiagnose=*/false, CaptureType, 18274 DeclRefType, nullptr)) 18275 return QualType(); 18276 18277 return DeclRefType; 18278 } 18279 18280 namespace { 18281 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18282 // The produced TemplateArgumentListInfo* points to data stored within this 18283 // object, so should only be used in contexts where the pointer will not be 18284 // used after the CopiedTemplateArgs object is destroyed. 18285 class CopiedTemplateArgs { 18286 bool HasArgs; 18287 TemplateArgumentListInfo TemplateArgStorage; 18288 public: 18289 template<typename RefExpr> 18290 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18291 if (HasArgs) 18292 E->copyTemplateArgumentsInto(TemplateArgStorage); 18293 } 18294 operator TemplateArgumentListInfo*() 18295 #ifdef __has_cpp_attribute 18296 #if __has_cpp_attribute(clang::lifetimebound) 18297 [[clang::lifetimebound]] 18298 #endif 18299 #endif 18300 { 18301 return HasArgs ? &TemplateArgStorage : nullptr; 18302 } 18303 }; 18304 } 18305 18306 /// Walk the set of potential results of an expression and mark them all as 18307 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18308 /// 18309 /// \return A new expression if we found any potential results, ExprEmpty() if 18310 /// not, and ExprError() if we diagnosed an error. 18311 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18312 NonOdrUseReason NOUR) { 18313 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18314 // an object that satisfies the requirements for appearing in a 18315 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18316 // is immediately applied." This function handles the lvalue-to-rvalue 18317 // conversion part. 18318 // 18319 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18320 // transform it into the relevant kind of non-odr-use node and rebuild the 18321 // tree of nodes leading to it. 18322 // 18323 // This is a mini-TreeTransform that only transforms a restricted subset of 18324 // nodes (and only certain operands of them). 18325 18326 // Rebuild a subexpression. 18327 auto Rebuild = [&](Expr *Sub) { 18328 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18329 }; 18330 18331 // Check whether a potential result satisfies the requirements of NOUR. 18332 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18333 // Any entity other than a VarDecl is always odr-used whenever it's named 18334 // in a potentially-evaluated expression. 18335 auto *VD = dyn_cast<VarDecl>(D); 18336 if (!VD) 18337 return true; 18338 18339 // C++2a [basic.def.odr]p4: 18340 // A variable x whose name appears as a potentially-evalauted expression 18341 // e is odr-used by e unless 18342 // -- x is a reference that is usable in constant expressions, or 18343 // -- x is a variable of non-reference type that is usable in constant 18344 // expressions and has no mutable subobjects, and e is an element of 18345 // the set of potential results of an expression of 18346 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18347 // conversion is applied, or 18348 // -- x is a variable of non-reference type, and e is an element of the 18349 // set of potential results of a discarded-value expression to which 18350 // the lvalue-to-rvalue conversion is not applied 18351 // 18352 // We check the first bullet and the "potentially-evaluated" condition in 18353 // BuildDeclRefExpr. We check the type requirements in the second bullet 18354 // in CheckLValueToRValueConversionOperand below. 18355 switch (NOUR) { 18356 case NOUR_None: 18357 case NOUR_Unevaluated: 18358 llvm_unreachable("unexpected non-odr-use-reason"); 18359 18360 case NOUR_Constant: 18361 // Constant references were handled when they were built. 18362 if (VD->getType()->isReferenceType()) 18363 return true; 18364 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18365 if (RD->hasMutableFields()) 18366 return true; 18367 if (!VD->isUsableInConstantExpressions(S.Context)) 18368 return true; 18369 break; 18370 18371 case NOUR_Discarded: 18372 if (VD->getType()->isReferenceType()) 18373 return true; 18374 break; 18375 } 18376 return false; 18377 }; 18378 18379 // Mark that this expression does not constitute an odr-use. 18380 auto MarkNotOdrUsed = [&] { 18381 S.MaybeODRUseExprs.remove(E); 18382 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18383 LSI->markVariableExprAsNonODRUsed(E); 18384 }; 18385 18386 // C++2a [basic.def.odr]p2: 18387 // The set of potential results of an expression e is defined as follows: 18388 switch (E->getStmtClass()) { 18389 // -- If e is an id-expression, ... 18390 case Expr::DeclRefExprClass: { 18391 auto *DRE = cast<DeclRefExpr>(E); 18392 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18393 break; 18394 18395 // Rebuild as a non-odr-use DeclRefExpr. 18396 MarkNotOdrUsed(); 18397 return DeclRefExpr::Create( 18398 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18399 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18400 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18401 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18402 } 18403 18404 case Expr::FunctionParmPackExprClass: { 18405 auto *FPPE = cast<FunctionParmPackExpr>(E); 18406 // If any of the declarations in the pack is odr-used, then the expression 18407 // as a whole constitutes an odr-use. 18408 for (VarDecl *D : *FPPE) 18409 if (IsPotentialResultOdrUsed(D)) 18410 return ExprEmpty(); 18411 18412 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18413 // nothing cares about whether we marked this as an odr-use, but it might 18414 // be useful for non-compiler tools. 18415 MarkNotOdrUsed(); 18416 break; 18417 } 18418 18419 // -- If e is a subscripting operation with an array operand... 18420 case Expr::ArraySubscriptExprClass: { 18421 auto *ASE = cast<ArraySubscriptExpr>(E); 18422 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18423 if (!OldBase->getType()->isArrayType()) 18424 break; 18425 ExprResult Base = Rebuild(OldBase); 18426 if (!Base.isUsable()) 18427 return Base; 18428 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18429 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18430 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18431 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18432 ASE->getRBracketLoc()); 18433 } 18434 18435 case Expr::MemberExprClass: { 18436 auto *ME = cast<MemberExpr>(E); 18437 // -- If e is a class member access expression [...] naming a non-static 18438 // data member... 18439 if (isa<FieldDecl>(ME->getMemberDecl())) { 18440 ExprResult Base = Rebuild(ME->getBase()); 18441 if (!Base.isUsable()) 18442 return Base; 18443 return MemberExpr::Create( 18444 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18445 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18446 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18447 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18448 ME->getObjectKind(), ME->isNonOdrUse()); 18449 } 18450 18451 if (ME->getMemberDecl()->isCXXInstanceMember()) 18452 break; 18453 18454 // -- If e is a class member access expression naming a static data member, 18455 // ... 18456 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18457 break; 18458 18459 // Rebuild as a non-odr-use MemberExpr. 18460 MarkNotOdrUsed(); 18461 return MemberExpr::Create( 18462 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18463 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18464 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18465 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18466 } 18467 18468 case Expr::BinaryOperatorClass: { 18469 auto *BO = cast<BinaryOperator>(E); 18470 Expr *LHS = BO->getLHS(); 18471 Expr *RHS = BO->getRHS(); 18472 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18473 if (BO->getOpcode() == BO_PtrMemD) { 18474 ExprResult Sub = Rebuild(LHS); 18475 if (!Sub.isUsable()) 18476 return Sub; 18477 LHS = Sub.get(); 18478 // -- If e is a comma expression, ... 18479 } else if (BO->getOpcode() == BO_Comma) { 18480 ExprResult Sub = Rebuild(RHS); 18481 if (!Sub.isUsable()) 18482 return Sub; 18483 RHS = Sub.get(); 18484 } else { 18485 break; 18486 } 18487 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18488 LHS, RHS); 18489 } 18490 18491 // -- If e has the form (e1)... 18492 case Expr::ParenExprClass: { 18493 auto *PE = cast<ParenExpr>(E); 18494 ExprResult Sub = Rebuild(PE->getSubExpr()); 18495 if (!Sub.isUsable()) 18496 return Sub; 18497 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18498 } 18499 18500 // -- If e is a glvalue conditional expression, ... 18501 // We don't apply this to a binary conditional operator. FIXME: Should we? 18502 case Expr::ConditionalOperatorClass: { 18503 auto *CO = cast<ConditionalOperator>(E); 18504 ExprResult LHS = Rebuild(CO->getLHS()); 18505 if (LHS.isInvalid()) 18506 return ExprError(); 18507 ExprResult RHS = Rebuild(CO->getRHS()); 18508 if (RHS.isInvalid()) 18509 return ExprError(); 18510 if (!LHS.isUsable() && !RHS.isUsable()) 18511 return ExprEmpty(); 18512 if (!LHS.isUsable()) 18513 LHS = CO->getLHS(); 18514 if (!RHS.isUsable()) 18515 RHS = CO->getRHS(); 18516 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18517 CO->getCond(), LHS.get(), RHS.get()); 18518 } 18519 18520 // [Clang extension] 18521 // -- If e has the form __extension__ e1... 18522 case Expr::UnaryOperatorClass: { 18523 auto *UO = cast<UnaryOperator>(E); 18524 if (UO->getOpcode() != UO_Extension) 18525 break; 18526 ExprResult Sub = Rebuild(UO->getSubExpr()); 18527 if (!Sub.isUsable()) 18528 return Sub; 18529 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18530 Sub.get()); 18531 } 18532 18533 // [Clang extension] 18534 // -- If e has the form _Generic(...), the set of potential results is the 18535 // union of the sets of potential results of the associated expressions. 18536 case Expr::GenericSelectionExprClass: { 18537 auto *GSE = cast<GenericSelectionExpr>(E); 18538 18539 SmallVector<Expr *, 4> AssocExprs; 18540 bool AnyChanged = false; 18541 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18542 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18543 if (AssocExpr.isInvalid()) 18544 return ExprError(); 18545 if (AssocExpr.isUsable()) { 18546 AssocExprs.push_back(AssocExpr.get()); 18547 AnyChanged = true; 18548 } else { 18549 AssocExprs.push_back(OrigAssocExpr); 18550 } 18551 } 18552 18553 return AnyChanged ? S.CreateGenericSelectionExpr( 18554 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18555 GSE->getRParenLoc(), GSE->getControllingExpr(), 18556 GSE->getAssocTypeSourceInfos(), AssocExprs) 18557 : ExprEmpty(); 18558 } 18559 18560 // [Clang extension] 18561 // -- If e has the form __builtin_choose_expr(...), the set of potential 18562 // results is the union of the sets of potential results of the 18563 // second and third subexpressions. 18564 case Expr::ChooseExprClass: { 18565 auto *CE = cast<ChooseExpr>(E); 18566 18567 ExprResult LHS = Rebuild(CE->getLHS()); 18568 if (LHS.isInvalid()) 18569 return ExprError(); 18570 18571 ExprResult RHS = Rebuild(CE->getLHS()); 18572 if (RHS.isInvalid()) 18573 return ExprError(); 18574 18575 if (!LHS.get() && !RHS.get()) 18576 return ExprEmpty(); 18577 if (!LHS.isUsable()) 18578 LHS = CE->getLHS(); 18579 if (!RHS.isUsable()) 18580 RHS = CE->getRHS(); 18581 18582 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18583 RHS.get(), CE->getRParenLoc()); 18584 } 18585 18586 // Step through non-syntactic nodes. 18587 case Expr::ConstantExprClass: { 18588 auto *CE = cast<ConstantExpr>(E); 18589 ExprResult Sub = Rebuild(CE->getSubExpr()); 18590 if (!Sub.isUsable()) 18591 return Sub; 18592 return ConstantExpr::Create(S.Context, Sub.get()); 18593 } 18594 18595 // We could mostly rely on the recursive rebuilding to rebuild implicit 18596 // casts, but not at the top level, so rebuild them here. 18597 case Expr::ImplicitCastExprClass: { 18598 auto *ICE = cast<ImplicitCastExpr>(E); 18599 // Only step through the narrow set of cast kinds we expect to encounter. 18600 // Anything else suggests we've left the region in which potential results 18601 // can be found. 18602 switch (ICE->getCastKind()) { 18603 case CK_NoOp: 18604 case CK_DerivedToBase: 18605 case CK_UncheckedDerivedToBase: { 18606 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18607 if (!Sub.isUsable()) 18608 return Sub; 18609 CXXCastPath Path(ICE->path()); 18610 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18611 ICE->getValueKind(), &Path); 18612 } 18613 18614 default: 18615 break; 18616 } 18617 break; 18618 } 18619 18620 default: 18621 break; 18622 } 18623 18624 // Can't traverse through this node. Nothing to do. 18625 return ExprEmpty(); 18626 } 18627 18628 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18629 // Check whether the operand is or contains an object of non-trivial C union 18630 // type. 18631 if (E->getType().isVolatileQualified() && 18632 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18633 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18634 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18635 Sema::NTCUC_LValueToRValueVolatile, 18636 NTCUK_Destruct|NTCUK_Copy); 18637 18638 // C++2a [basic.def.odr]p4: 18639 // [...] an expression of non-volatile-qualified non-class type to which 18640 // the lvalue-to-rvalue conversion is applied [...] 18641 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18642 return E; 18643 18644 ExprResult Result = 18645 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18646 if (Result.isInvalid()) 18647 return ExprError(); 18648 return Result.get() ? Result : E; 18649 } 18650 18651 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18652 Res = CorrectDelayedTyposInExpr(Res); 18653 18654 if (!Res.isUsable()) 18655 return Res; 18656 18657 // If a constant-expression is a reference to a variable where we delay 18658 // deciding whether it is an odr-use, just assume we will apply the 18659 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18660 // (a non-type template argument), we have special handling anyway. 18661 return CheckLValueToRValueConversionOperand(Res.get()); 18662 } 18663 18664 void Sema::CleanupVarDeclMarking() { 18665 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18666 // call. 18667 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18668 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18669 18670 for (Expr *E : LocalMaybeODRUseExprs) { 18671 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18672 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18673 DRE->getLocation(), *this); 18674 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18675 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18676 *this); 18677 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18678 for (VarDecl *VD : *FP) 18679 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18680 } else { 18681 llvm_unreachable("Unexpected expression"); 18682 } 18683 } 18684 18685 assert(MaybeODRUseExprs.empty() && 18686 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18687 } 18688 18689 static void DoMarkVarDeclReferenced( 18690 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18691 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18692 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18693 isa<FunctionParmPackExpr>(E)) && 18694 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18695 Var->setReferenced(); 18696 18697 if (Var->isInvalidDecl()) 18698 return; 18699 18700 auto *MSI = Var->getMemberSpecializationInfo(); 18701 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18702 : Var->getTemplateSpecializationKind(); 18703 18704 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18705 bool UsableInConstantExpr = 18706 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18707 18708 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18709 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18710 } 18711 18712 // C++20 [expr.const]p12: 18713 // A variable [...] is needed for constant evaluation if it is [...] a 18714 // variable whose name appears as a potentially constant evaluated 18715 // expression that is either a contexpr variable or is of non-volatile 18716 // const-qualified integral type or of reference type 18717 bool NeededForConstantEvaluation = 18718 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18719 18720 bool NeedDefinition = 18721 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18722 18723 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18724 "Can't instantiate a partial template specialization."); 18725 18726 // If this might be a member specialization of a static data member, check 18727 // the specialization is visible. We already did the checks for variable 18728 // template specializations when we created them. 18729 if (NeedDefinition && TSK != TSK_Undeclared && 18730 !isa<VarTemplateSpecializationDecl>(Var)) 18731 SemaRef.checkSpecializationVisibility(Loc, Var); 18732 18733 // Perform implicit instantiation of static data members, static data member 18734 // templates of class templates, and variable template specializations. Delay 18735 // instantiations of variable templates, except for those that could be used 18736 // in a constant expression. 18737 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18738 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18739 // instantiation declaration if a variable is usable in a constant 18740 // expression (among other cases). 18741 bool TryInstantiating = 18742 TSK == TSK_ImplicitInstantiation || 18743 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18744 18745 if (TryInstantiating) { 18746 SourceLocation PointOfInstantiation = 18747 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18748 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18749 if (FirstInstantiation) { 18750 PointOfInstantiation = Loc; 18751 if (MSI) 18752 MSI->setPointOfInstantiation(PointOfInstantiation); 18753 // FIXME: Notify listener. 18754 else 18755 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18756 } 18757 18758 if (UsableInConstantExpr) { 18759 // Do not defer instantiations of variables that could be used in a 18760 // constant expression. 18761 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18762 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18763 }); 18764 18765 // Re-set the member to trigger a recomputation of the dependence bits 18766 // for the expression. 18767 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18768 DRE->setDecl(DRE->getDecl()); 18769 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18770 ME->setMemberDecl(ME->getMemberDecl()); 18771 } else if (FirstInstantiation || 18772 isa<VarTemplateSpecializationDecl>(Var)) { 18773 // FIXME: For a specialization of a variable template, we don't 18774 // distinguish between "declaration and type implicitly instantiated" 18775 // and "implicit instantiation of definition requested", so we have 18776 // no direct way to avoid enqueueing the pending instantiation 18777 // multiple times. 18778 SemaRef.PendingInstantiations 18779 .push_back(std::make_pair(Var, PointOfInstantiation)); 18780 } 18781 } 18782 } 18783 18784 // C++2a [basic.def.odr]p4: 18785 // A variable x whose name appears as a potentially-evaluated expression e 18786 // is odr-used by e unless 18787 // -- x is a reference that is usable in constant expressions 18788 // -- x is a variable of non-reference type that is usable in constant 18789 // expressions and has no mutable subobjects [FIXME], and e is an 18790 // element of the set of potential results of an expression of 18791 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18792 // conversion is applied 18793 // -- x is a variable of non-reference type, and e is an element of the set 18794 // of potential results of a discarded-value expression to which the 18795 // lvalue-to-rvalue conversion is not applied [FIXME] 18796 // 18797 // We check the first part of the second bullet here, and 18798 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18799 // FIXME: To get the third bullet right, we need to delay this even for 18800 // variables that are not usable in constant expressions. 18801 18802 // If we already know this isn't an odr-use, there's nothing more to do. 18803 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18804 if (DRE->isNonOdrUse()) 18805 return; 18806 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18807 if (ME->isNonOdrUse()) 18808 return; 18809 18810 switch (OdrUse) { 18811 case OdrUseContext::None: 18812 assert((!E || isa<FunctionParmPackExpr>(E)) && 18813 "missing non-odr-use marking for unevaluated decl ref"); 18814 break; 18815 18816 case OdrUseContext::FormallyOdrUsed: 18817 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18818 // behavior. 18819 break; 18820 18821 case OdrUseContext::Used: 18822 // If we might later find that this expression isn't actually an odr-use, 18823 // delay the marking. 18824 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18825 SemaRef.MaybeODRUseExprs.insert(E); 18826 else 18827 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18828 break; 18829 18830 case OdrUseContext::Dependent: 18831 // If this is a dependent context, we don't need to mark variables as 18832 // odr-used, but we may still need to track them for lambda capture. 18833 // FIXME: Do we also need to do this inside dependent typeid expressions 18834 // (which are modeled as unevaluated at this point)? 18835 const bool RefersToEnclosingScope = 18836 (SemaRef.CurContext != Var->getDeclContext() && 18837 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18838 if (RefersToEnclosingScope) { 18839 LambdaScopeInfo *const LSI = 18840 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18841 if (LSI && (!LSI->CallOperator || 18842 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18843 // If a variable could potentially be odr-used, defer marking it so 18844 // until we finish analyzing the full expression for any 18845 // lvalue-to-rvalue 18846 // or discarded value conversions that would obviate odr-use. 18847 // Add it to the list of potential captures that will be analyzed 18848 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18849 // unless the variable is a reference that was initialized by a constant 18850 // expression (this will never need to be captured or odr-used). 18851 // 18852 // FIXME: We can simplify this a lot after implementing P0588R1. 18853 assert(E && "Capture variable should be used in an expression."); 18854 if (!Var->getType()->isReferenceType() || 18855 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18856 LSI->addPotentialCapture(E->IgnoreParens()); 18857 } 18858 } 18859 break; 18860 } 18861 } 18862 18863 /// Mark a variable referenced, and check whether it is odr-used 18864 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18865 /// used directly for normal expressions referring to VarDecl. 18866 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18867 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18868 } 18869 18870 static void 18871 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18872 bool MightBeOdrUse, 18873 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18874 if (SemaRef.isInOpenMPDeclareTargetContext()) 18875 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18876 18877 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18878 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18879 return; 18880 } 18881 18882 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18883 18884 // If this is a call to a method via a cast, also mark the method in the 18885 // derived class used in case codegen can devirtualize the call. 18886 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18887 if (!ME) 18888 return; 18889 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18890 if (!MD) 18891 return; 18892 // Only attempt to devirtualize if this is truly a virtual call. 18893 bool IsVirtualCall = MD->isVirtual() && 18894 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18895 if (!IsVirtualCall) 18896 return; 18897 18898 // If it's possible to devirtualize the call, mark the called function 18899 // referenced. 18900 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18901 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18902 if (DM) 18903 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18904 } 18905 18906 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18907 /// 18908 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18909 /// handled with care if the DeclRefExpr is not newly-created. 18910 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18911 // TODO: update this with DR# once a defect report is filed. 18912 // C++11 defect. The address of a pure member should not be an ODR use, even 18913 // if it's a qualified reference. 18914 bool OdrUse = true; 18915 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18916 if (Method->isVirtual() && 18917 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18918 OdrUse = false; 18919 18920 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18921 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18922 FD->isConsteval() && !RebuildingImmediateInvocation) 18923 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18924 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18925 RefsMinusAssignments); 18926 } 18927 18928 /// Perform reference-marking and odr-use handling for a MemberExpr. 18929 void Sema::MarkMemberReferenced(MemberExpr *E) { 18930 // C++11 [basic.def.odr]p2: 18931 // A non-overloaded function whose name appears as a potentially-evaluated 18932 // expression or a member of a set of candidate functions, if selected by 18933 // overload resolution when referred to from a potentially-evaluated 18934 // expression, is odr-used, unless it is a pure virtual function and its 18935 // name is not explicitly qualified. 18936 bool MightBeOdrUse = true; 18937 if (E->performsVirtualDispatch(getLangOpts())) { 18938 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18939 if (Method->isPure()) 18940 MightBeOdrUse = false; 18941 } 18942 SourceLocation Loc = 18943 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18944 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18945 RefsMinusAssignments); 18946 } 18947 18948 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18949 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18950 for (VarDecl *VD : *E) 18951 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18952 RefsMinusAssignments); 18953 } 18954 18955 /// Perform marking for a reference to an arbitrary declaration. It 18956 /// marks the declaration referenced, and performs odr-use checking for 18957 /// functions and variables. This method should not be used when building a 18958 /// normal expression which refers to a variable. 18959 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18960 bool MightBeOdrUse) { 18961 if (MightBeOdrUse) { 18962 if (auto *VD = dyn_cast<VarDecl>(D)) { 18963 MarkVariableReferenced(Loc, VD); 18964 return; 18965 } 18966 } 18967 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18968 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18969 return; 18970 } 18971 D->setReferenced(); 18972 } 18973 18974 namespace { 18975 // Mark all of the declarations used by a type as referenced. 18976 // FIXME: Not fully implemented yet! We need to have a better understanding 18977 // of when we're entering a context we should not recurse into. 18978 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18979 // TreeTransforms rebuilding the type in a new context. Rather than 18980 // duplicating the TreeTransform logic, we should consider reusing it here. 18981 // Currently that causes problems when rebuilding LambdaExprs. 18982 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18983 Sema &S; 18984 SourceLocation Loc; 18985 18986 public: 18987 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18988 18989 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18990 18991 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18992 }; 18993 } 18994 18995 bool MarkReferencedDecls::TraverseTemplateArgument( 18996 const TemplateArgument &Arg) { 18997 { 18998 // A non-type template argument is a constant-evaluated context. 18999 EnterExpressionEvaluationContext Evaluated( 19000 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 19001 if (Arg.getKind() == TemplateArgument::Declaration) { 19002 if (Decl *D = Arg.getAsDecl()) 19003 S.MarkAnyDeclReferenced(Loc, D, true); 19004 } else if (Arg.getKind() == TemplateArgument::Expression) { 19005 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 19006 } 19007 } 19008 19009 return Inherited::TraverseTemplateArgument(Arg); 19010 } 19011 19012 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 19013 MarkReferencedDecls Marker(*this, Loc); 19014 Marker.TraverseType(T); 19015 } 19016 19017 namespace { 19018 /// Helper class that marks all of the declarations referenced by 19019 /// potentially-evaluated subexpressions as "referenced". 19020 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 19021 public: 19022 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 19023 bool SkipLocalVariables; 19024 ArrayRef<const Expr *> StopAt; 19025 19026 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 19027 ArrayRef<const Expr *> StopAt) 19028 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 19029 19030 void visitUsedDecl(SourceLocation Loc, Decl *D) { 19031 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 19032 } 19033 19034 void Visit(Expr *E) { 19035 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end()) 19036 return; 19037 Inherited::Visit(E); 19038 } 19039 19040 void VisitDeclRefExpr(DeclRefExpr *E) { 19041 // If we were asked not to visit local variables, don't. 19042 if (SkipLocalVariables) { 19043 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 19044 if (VD->hasLocalStorage()) 19045 return; 19046 } 19047 19048 // FIXME: This can trigger the instantiation of the initializer of a 19049 // variable, which can cause the expression to become value-dependent 19050 // or error-dependent. Do we need to propagate the new dependence bits? 19051 S.MarkDeclRefReferenced(E); 19052 } 19053 19054 void VisitMemberExpr(MemberExpr *E) { 19055 S.MarkMemberReferenced(E); 19056 Visit(E->getBase()); 19057 } 19058 }; 19059 } // namespace 19060 19061 /// Mark any declarations that appear within this expression or any 19062 /// potentially-evaluated subexpressions as "referenced". 19063 /// 19064 /// \param SkipLocalVariables If true, don't mark local variables as 19065 /// 'referenced'. 19066 /// \param StopAt Subexpressions that we shouldn't recurse into. 19067 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 19068 bool SkipLocalVariables, 19069 ArrayRef<const Expr*> StopAt) { 19070 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 19071 } 19072 19073 /// Emit a diagnostic when statements are reachable. 19074 /// FIXME: check for reachability even in expressions for which we don't build a 19075 /// CFG (eg, in the initializer of a global or in a constant expression). 19076 /// For example, 19077 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 19078 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 19079 const PartialDiagnostic &PD) { 19080 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 19081 if (!FunctionScopes.empty()) 19082 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 19083 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 19084 return true; 19085 } 19086 19087 // The initializer of a constexpr variable or of the first declaration of a 19088 // static data member is not syntactically a constant evaluated constant, 19089 // but nonetheless is always required to be a constant expression, so we 19090 // can skip diagnosing. 19091 // FIXME: Using the mangling context here is a hack. 19092 if (auto *VD = dyn_cast_or_null<VarDecl>( 19093 ExprEvalContexts.back().ManglingContextDecl)) { 19094 if (VD->isConstexpr() || 19095 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 19096 return false; 19097 // FIXME: For any other kind of variable, we should build a CFG for its 19098 // initializer and check whether the context in question is reachable. 19099 } 19100 19101 Diag(Loc, PD); 19102 return true; 19103 } 19104 19105 /// Emit a diagnostic that describes an effect on the run-time behavior 19106 /// of the program being compiled. 19107 /// 19108 /// This routine emits the given diagnostic when the code currently being 19109 /// type-checked is "potentially evaluated", meaning that there is a 19110 /// possibility that the code will actually be executable. Code in sizeof() 19111 /// expressions, code used only during overload resolution, etc., are not 19112 /// potentially evaluated. This routine will suppress such diagnostics or, 19113 /// in the absolutely nutty case of potentially potentially evaluated 19114 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 19115 /// later. 19116 /// 19117 /// This routine should be used for all diagnostics that describe the run-time 19118 /// behavior of a program, such as passing a non-POD value through an ellipsis. 19119 /// Failure to do so will likely result in spurious diagnostics or failures 19120 /// during overload resolution or within sizeof/alignof/typeof/typeid. 19121 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 19122 const PartialDiagnostic &PD) { 19123 19124 if (ExprEvalContexts.back().isDiscardedStatementContext()) 19125 return false; 19126 19127 switch (ExprEvalContexts.back().Context) { 19128 case ExpressionEvaluationContext::Unevaluated: 19129 case ExpressionEvaluationContext::UnevaluatedList: 19130 case ExpressionEvaluationContext::UnevaluatedAbstract: 19131 case ExpressionEvaluationContext::DiscardedStatement: 19132 // The argument will never be evaluated, so don't complain. 19133 break; 19134 19135 case ExpressionEvaluationContext::ConstantEvaluated: 19136 case ExpressionEvaluationContext::ImmediateFunctionContext: 19137 // Relevant diagnostics should be produced by constant evaluation. 19138 break; 19139 19140 case ExpressionEvaluationContext::PotentiallyEvaluated: 19141 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 19142 return DiagIfReachable(Loc, Stmts, PD); 19143 } 19144 19145 return false; 19146 } 19147 19148 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 19149 const PartialDiagnostic &PD) { 19150 return DiagRuntimeBehavior( 19151 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 19152 } 19153 19154 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 19155 CallExpr *CE, FunctionDecl *FD) { 19156 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 19157 return false; 19158 19159 // If we're inside a decltype's expression, don't check for a valid return 19160 // type or construct temporaries until we know whether this is the last call. 19161 if (ExprEvalContexts.back().ExprContext == 19162 ExpressionEvaluationContextRecord::EK_Decltype) { 19163 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 19164 return false; 19165 } 19166 19167 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19168 FunctionDecl *FD; 19169 CallExpr *CE; 19170 19171 public: 19172 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19173 : FD(FD), CE(CE) { } 19174 19175 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19176 if (!FD) { 19177 S.Diag(Loc, diag::err_call_incomplete_return) 19178 << T << CE->getSourceRange(); 19179 return; 19180 } 19181 19182 S.Diag(Loc, diag::err_call_function_incomplete_return) 19183 << CE->getSourceRange() << FD << T; 19184 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19185 << FD->getDeclName(); 19186 } 19187 } Diagnoser(FD, CE); 19188 19189 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19190 return true; 19191 19192 return false; 19193 } 19194 19195 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19196 // will prevent this condition from triggering, which is what we want. 19197 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19198 SourceLocation Loc; 19199 19200 unsigned diagnostic = diag::warn_condition_is_assignment; 19201 bool IsOrAssign = false; 19202 19203 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19204 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19205 return; 19206 19207 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19208 19209 // Greylist some idioms by putting them into a warning subcategory. 19210 if (ObjCMessageExpr *ME 19211 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19212 Selector Sel = ME->getSelector(); 19213 19214 // self = [<foo> init...] 19215 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19216 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19217 19218 // <foo> = [<bar> nextObject] 19219 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19220 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19221 } 19222 19223 Loc = Op->getOperatorLoc(); 19224 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19225 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19226 return; 19227 19228 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19229 Loc = Op->getOperatorLoc(); 19230 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19231 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19232 else { 19233 // Not an assignment. 19234 return; 19235 } 19236 19237 Diag(Loc, diagnostic) << E->getSourceRange(); 19238 19239 SourceLocation Open = E->getBeginLoc(); 19240 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19241 Diag(Loc, diag::note_condition_assign_silence) 19242 << FixItHint::CreateInsertion(Open, "(") 19243 << FixItHint::CreateInsertion(Close, ")"); 19244 19245 if (IsOrAssign) 19246 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19247 << FixItHint::CreateReplacement(Loc, "!="); 19248 else 19249 Diag(Loc, diag::note_condition_assign_to_comparison) 19250 << FixItHint::CreateReplacement(Loc, "=="); 19251 } 19252 19253 /// Redundant parentheses over an equality comparison can indicate 19254 /// that the user intended an assignment used as condition. 19255 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19256 // Don't warn if the parens came from a macro. 19257 SourceLocation parenLoc = ParenE->getBeginLoc(); 19258 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19259 return; 19260 // Don't warn for dependent expressions. 19261 if (ParenE->isTypeDependent()) 19262 return; 19263 19264 Expr *E = ParenE->IgnoreParens(); 19265 19266 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19267 if (opE->getOpcode() == BO_EQ && 19268 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19269 == Expr::MLV_Valid) { 19270 SourceLocation Loc = opE->getOperatorLoc(); 19271 19272 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19273 SourceRange ParenERange = ParenE->getSourceRange(); 19274 Diag(Loc, diag::note_equality_comparison_silence) 19275 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19276 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19277 Diag(Loc, diag::note_equality_comparison_to_assign) 19278 << FixItHint::CreateReplacement(Loc, "="); 19279 } 19280 } 19281 19282 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19283 bool IsConstexpr) { 19284 DiagnoseAssignmentAsCondition(E); 19285 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19286 DiagnoseEqualityWithExtraParens(parenE); 19287 19288 ExprResult result = CheckPlaceholderExpr(E); 19289 if (result.isInvalid()) return ExprError(); 19290 E = result.get(); 19291 19292 if (!E->isTypeDependent()) { 19293 if (getLangOpts().CPlusPlus) 19294 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19295 19296 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19297 if (ERes.isInvalid()) 19298 return ExprError(); 19299 E = ERes.get(); 19300 19301 QualType T = E->getType(); 19302 if (!T->isScalarType()) { // C99 6.8.4.1p1 19303 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19304 << T << E->getSourceRange(); 19305 return ExprError(); 19306 } 19307 CheckBoolLikeConversion(E, Loc); 19308 } 19309 19310 return E; 19311 } 19312 19313 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19314 Expr *SubExpr, ConditionKind CK, 19315 bool MissingOK) { 19316 // MissingOK indicates whether having no condition expression is valid 19317 // (for loop) or invalid (e.g. while loop). 19318 if (!SubExpr) 19319 return MissingOK ? ConditionResult() : ConditionError(); 19320 19321 ExprResult Cond; 19322 switch (CK) { 19323 case ConditionKind::Boolean: 19324 Cond = CheckBooleanCondition(Loc, SubExpr); 19325 break; 19326 19327 case ConditionKind::ConstexprIf: 19328 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19329 break; 19330 19331 case ConditionKind::Switch: 19332 Cond = CheckSwitchCondition(Loc, SubExpr); 19333 break; 19334 } 19335 if (Cond.isInvalid()) { 19336 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19337 {SubExpr}, PreferredConditionType(CK)); 19338 if (!Cond.get()) 19339 return ConditionError(); 19340 } 19341 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19342 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19343 if (!FullExpr.get()) 19344 return ConditionError(); 19345 19346 return ConditionResult(*this, nullptr, FullExpr, 19347 CK == ConditionKind::ConstexprIf); 19348 } 19349 19350 namespace { 19351 /// A visitor for rebuilding a call to an __unknown_any expression 19352 /// to have an appropriate type. 19353 struct RebuildUnknownAnyFunction 19354 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19355 19356 Sema &S; 19357 19358 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19359 19360 ExprResult VisitStmt(Stmt *S) { 19361 llvm_unreachable("unexpected statement!"); 19362 } 19363 19364 ExprResult VisitExpr(Expr *E) { 19365 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19366 << E->getSourceRange(); 19367 return ExprError(); 19368 } 19369 19370 /// Rebuild an expression which simply semantically wraps another 19371 /// expression which it shares the type and value kind of. 19372 template <class T> ExprResult rebuildSugarExpr(T *E) { 19373 ExprResult SubResult = Visit(E->getSubExpr()); 19374 if (SubResult.isInvalid()) return ExprError(); 19375 19376 Expr *SubExpr = SubResult.get(); 19377 E->setSubExpr(SubExpr); 19378 E->setType(SubExpr->getType()); 19379 E->setValueKind(SubExpr->getValueKind()); 19380 assert(E->getObjectKind() == OK_Ordinary); 19381 return E; 19382 } 19383 19384 ExprResult VisitParenExpr(ParenExpr *E) { 19385 return rebuildSugarExpr(E); 19386 } 19387 19388 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19389 return rebuildSugarExpr(E); 19390 } 19391 19392 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19393 ExprResult SubResult = Visit(E->getSubExpr()); 19394 if (SubResult.isInvalid()) return ExprError(); 19395 19396 Expr *SubExpr = SubResult.get(); 19397 E->setSubExpr(SubExpr); 19398 E->setType(S.Context.getPointerType(SubExpr->getType())); 19399 assert(E->isPRValue()); 19400 assert(E->getObjectKind() == OK_Ordinary); 19401 return E; 19402 } 19403 19404 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19405 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19406 19407 E->setType(VD->getType()); 19408 19409 assert(E->isPRValue()); 19410 if (S.getLangOpts().CPlusPlus && 19411 !(isa<CXXMethodDecl>(VD) && 19412 cast<CXXMethodDecl>(VD)->isInstance())) 19413 E->setValueKind(VK_LValue); 19414 19415 return E; 19416 } 19417 19418 ExprResult VisitMemberExpr(MemberExpr *E) { 19419 return resolveDecl(E, E->getMemberDecl()); 19420 } 19421 19422 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19423 return resolveDecl(E, E->getDecl()); 19424 } 19425 }; 19426 } 19427 19428 /// Given a function expression of unknown-any type, try to rebuild it 19429 /// to have a function type. 19430 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19431 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19432 if (Result.isInvalid()) return ExprError(); 19433 return S.DefaultFunctionArrayConversion(Result.get()); 19434 } 19435 19436 namespace { 19437 /// A visitor for rebuilding an expression of type __unknown_anytype 19438 /// into one which resolves the type directly on the referring 19439 /// expression. Strict preservation of the original source 19440 /// structure is not a goal. 19441 struct RebuildUnknownAnyExpr 19442 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19443 19444 Sema &S; 19445 19446 /// The current destination type. 19447 QualType DestType; 19448 19449 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19450 : S(S), DestType(CastType) {} 19451 19452 ExprResult VisitStmt(Stmt *S) { 19453 llvm_unreachable("unexpected statement!"); 19454 } 19455 19456 ExprResult VisitExpr(Expr *E) { 19457 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19458 << E->getSourceRange(); 19459 return ExprError(); 19460 } 19461 19462 ExprResult VisitCallExpr(CallExpr *E); 19463 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19464 19465 /// Rebuild an expression which simply semantically wraps another 19466 /// expression which it shares the type and value kind of. 19467 template <class T> ExprResult rebuildSugarExpr(T *E) { 19468 ExprResult SubResult = Visit(E->getSubExpr()); 19469 if (SubResult.isInvalid()) return ExprError(); 19470 Expr *SubExpr = SubResult.get(); 19471 E->setSubExpr(SubExpr); 19472 E->setType(SubExpr->getType()); 19473 E->setValueKind(SubExpr->getValueKind()); 19474 assert(E->getObjectKind() == OK_Ordinary); 19475 return E; 19476 } 19477 19478 ExprResult VisitParenExpr(ParenExpr *E) { 19479 return rebuildSugarExpr(E); 19480 } 19481 19482 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19483 return rebuildSugarExpr(E); 19484 } 19485 19486 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19487 const PointerType *Ptr = DestType->getAs<PointerType>(); 19488 if (!Ptr) { 19489 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19490 << E->getSourceRange(); 19491 return ExprError(); 19492 } 19493 19494 if (isa<CallExpr>(E->getSubExpr())) { 19495 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19496 << E->getSourceRange(); 19497 return ExprError(); 19498 } 19499 19500 assert(E->isPRValue()); 19501 assert(E->getObjectKind() == OK_Ordinary); 19502 E->setType(DestType); 19503 19504 // Build the sub-expression as if it were an object of the pointee type. 19505 DestType = Ptr->getPointeeType(); 19506 ExprResult SubResult = Visit(E->getSubExpr()); 19507 if (SubResult.isInvalid()) return ExprError(); 19508 E->setSubExpr(SubResult.get()); 19509 return E; 19510 } 19511 19512 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19513 19514 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19515 19516 ExprResult VisitMemberExpr(MemberExpr *E) { 19517 return resolveDecl(E, E->getMemberDecl()); 19518 } 19519 19520 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19521 return resolveDecl(E, E->getDecl()); 19522 } 19523 }; 19524 } 19525 19526 /// Rebuilds a call expression which yielded __unknown_anytype. 19527 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19528 Expr *CalleeExpr = E->getCallee(); 19529 19530 enum FnKind { 19531 FK_MemberFunction, 19532 FK_FunctionPointer, 19533 FK_BlockPointer 19534 }; 19535 19536 FnKind Kind; 19537 QualType CalleeType = CalleeExpr->getType(); 19538 if (CalleeType == S.Context.BoundMemberTy) { 19539 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19540 Kind = FK_MemberFunction; 19541 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19542 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19543 CalleeType = Ptr->getPointeeType(); 19544 Kind = FK_FunctionPointer; 19545 } else { 19546 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19547 Kind = FK_BlockPointer; 19548 } 19549 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19550 19551 // Verify that this is a legal result type of a function. 19552 if (DestType->isArrayType() || DestType->isFunctionType()) { 19553 unsigned diagID = diag::err_func_returning_array_function; 19554 if (Kind == FK_BlockPointer) 19555 diagID = diag::err_block_returning_array_function; 19556 19557 S.Diag(E->getExprLoc(), diagID) 19558 << DestType->isFunctionType() << DestType; 19559 return ExprError(); 19560 } 19561 19562 // Otherwise, go ahead and set DestType as the call's result. 19563 E->setType(DestType.getNonLValueExprType(S.Context)); 19564 E->setValueKind(Expr::getValueKindForType(DestType)); 19565 assert(E->getObjectKind() == OK_Ordinary); 19566 19567 // Rebuild the function type, replacing the result type with DestType. 19568 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19569 if (Proto) { 19570 // __unknown_anytype(...) is a special case used by the debugger when 19571 // it has no idea what a function's signature is. 19572 // 19573 // We want to build this call essentially under the K&R 19574 // unprototyped rules, but making a FunctionNoProtoType in C++ 19575 // would foul up all sorts of assumptions. However, we cannot 19576 // simply pass all arguments as variadic arguments, nor can we 19577 // portably just call the function under a non-variadic type; see 19578 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19579 // However, it turns out that in practice it is generally safe to 19580 // call a function declared as "A foo(B,C,D);" under the prototype 19581 // "A foo(B,C,D,...);". The only known exception is with the 19582 // Windows ABI, where any variadic function is implicitly cdecl 19583 // regardless of its normal CC. Therefore we change the parameter 19584 // types to match the types of the arguments. 19585 // 19586 // This is a hack, but it is far superior to moving the 19587 // corresponding target-specific code from IR-gen to Sema/AST. 19588 19589 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19590 SmallVector<QualType, 8> ArgTypes; 19591 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19592 ArgTypes.reserve(E->getNumArgs()); 19593 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19594 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19595 } 19596 ParamTypes = ArgTypes; 19597 } 19598 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19599 Proto->getExtProtoInfo()); 19600 } else { 19601 DestType = S.Context.getFunctionNoProtoType(DestType, 19602 FnType->getExtInfo()); 19603 } 19604 19605 // Rebuild the appropriate pointer-to-function type. 19606 switch (Kind) { 19607 case FK_MemberFunction: 19608 // Nothing to do. 19609 break; 19610 19611 case FK_FunctionPointer: 19612 DestType = S.Context.getPointerType(DestType); 19613 break; 19614 19615 case FK_BlockPointer: 19616 DestType = S.Context.getBlockPointerType(DestType); 19617 break; 19618 } 19619 19620 // Finally, we can recurse. 19621 ExprResult CalleeResult = Visit(CalleeExpr); 19622 if (!CalleeResult.isUsable()) return ExprError(); 19623 E->setCallee(CalleeResult.get()); 19624 19625 // Bind a temporary if necessary. 19626 return S.MaybeBindToTemporary(E); 19627 } 19628 19629 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19630 // Verify that this is a legal result type of a call. 19631 if (DestType->isArrayType() || DestType->isFunctionType()) { 19632 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19633 << DestType->isFunctionType() << DestType; 19634 return ExprError(); 19635 } 19636 19637 // Rewrite the method result type if available. 19638 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19639 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19640 Method->setReturnType(DestType); 19641 } 19642 19643 // Change the type of the message. 19644 E->setType(DestType.getNonReferenceType()); 19645 E->setValueKind(Expr::getValueKindForType(DestType)); 19646 19647 return S.MaybeBindToTemporary(E); 19648 } 19649 19650 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19651 // The only case we should ever see here is a function-to-pointer decay. 19652 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19653 assert(E->isPRValue()); 19654 assert(E->getObjectKind() == OK_Ordinary); 19655 19656 E->setType(DestType); 19657 19658 // Rebuild the sub-expression as the pointee (function) type. 19659 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19660 19661 ExprResult Result = Visit(E->getSubExpr()); 19662 if (!Result.isUsable()) return ExprError(); 19663 19664 E->setSubExpr(Result.get()); 19665 return E; 19666 } else if (E->getCastKind() == CK_LValueToRValue) { 19667 assert(E->isPRValue()); 19668 assert(E->getObjectKind() == OK_Ordinary); 19669 19670 assert(isa<BlockPointerType>(E->getType())); 19671 19672 E->setType(DestType); 19673 19674 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19675 DestType = S.Context.getLValueReferenceType(DestType); 19676 19677 ExprResult Result = Visit(E->getSubExpr()); 19678 if (!Result.isUsable()) return ExprError(); 19679 19680 E->setSubExpr(Result.get()); 19681 return E; 19682 } else { 19683 llvm_unreachable("Unhandled cast type!"); 19684 } 19685 } 19686 19687 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19688 ExprValueKind ValueKind = VK_LValue; 19689 QualType Type = DestType; 19690 19691 // We know how to make this work for certain kinds of decls: 19692 19693 // - functions 19694 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19695 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19696 DestType = Ptr->getPointeeType(); 19697 ExprResult Result = resolveDecl(E, VD); 19698 if (Result.isInvalid()) return ExprError(); 19699 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19700 VK_PRValue); 19701 } 19702 19703 if (!Type->isFunctionType()) { 19704 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19705 << VD << E->getSourceRange(); 19706 return ExprError(); 19707 } 19708 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19709 // We must match the FunctionDecl's type to the hack introduced in 19710 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19711 // type. See the lengthy commentary in that routine. 19712 QualType FDT = FD->getType(); 19713 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19714 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19715 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19716 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19717 SourceLocation Loc = FD->getLocation(); 19718 FunctionDecl *NewFD = FunctionDecl::Create( 19719 S.Context, FD->getDeclContext(), Loc, Loc, 19720 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19721 SC_None, S.getCurFPFeatures().isFPConstrained(), 19722 false /*isInlineSpecified*/, FD->hasPrototype(), 19723 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19724 19725 if (FD->getQualifier()) 19726 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19727 19728 SmallVector<ParmVarDecl*, 16> Params; 19729 for (const auto &AI : FT->param_types()) { 19730 ParmVarDecl *Param = 19731 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19732 Param->setScopeInfo(0, Params.size()); 19733 Params.push_back(Param); 19734 } 19735 NewFD->setParams(Params); 19736 DRE->setDecl(NewFD); 19737 VD = DRE->getDecl(); 19738 } 19739 } 19740 19741 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19742 if (MD->isInstance()) { 19743 ValueKind = VK_PRValue; 19744 Type = S.Context.BoundMemberTy; 19745 } 19746 19747 // Function references aren't l-values in C. 19748 if (!S.getLangOpts().CPlusPlus) 19749 ValueKind = VK_PRValue; 19750 19751 // - variables 19752 } else if (isa<VarDecl>(VD)) { 19753 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19754 Type = RefTy->getPointeeType(); 19755 } else if (Type->isFunctionType()) { 19756 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19757 << VD << E->getSourceRange(); 19758 return ExprError(); 19759 } 19760 19761 // - nothing else 19762 } else { 19763 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19764 << VD << E->getSourceRange(); 19765 return ExprError(); 19766 } 19767 19768 // Modifying the declaration like this is friendly to IR-gen but 19769 // also really dangerous. 19770 VD->setType(DestType); 19771 E->setType(Type); 19772 E->setValueKind(ValueKind); 19773 return E; 19774 } 19775 19776 /// Check a cast of an unknown-any type. We intentionally only 19777 /// trigger this for C-style casts. 19778 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19779 Expr *CastExpr, CastKind &CastKind, 19780 ExprValueKind &VK, CXXCastPath &Path) { 19781 // The type we're casting to must be either void or complete. 19782 if (!CastType->isVoidType() && 19783 RequireCompleteType(TypeRange.getBegin(), CastType, 19784 diag::err_typecheck_cast_to_incomplete)) 19785 return ExprError(); 19786 19787 // Rewrite the casted expression from scratch. 19788 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19789 if (!result.isUsable()) return ExprError(); 19790 19791 CastExpr = result.get(); 19792 VK = CastExpr->getValueKind(); 19793 CastKind = CK_NoOp; 19794 19795 return CastExpr; 19796 } 19797 19798 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19799 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19800 } 19801 19802 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19803 Expr *arg, QualType ¶mType) { 19804 // If the syntactic form of the argument is not an explicit cast of 19805 // any sort, just do default argument promotion. 19806 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19807 if (!castArg) { 19808 ExprResult result = DefaultArgumentPromotion(arg); 19809 if (result.isInvalid()) return ExprError(); 19810 paramType = result.get()->getType(); 19811 return result; 19812 } 19813 19814 // Otherwise, use the type that was written in the explicit cast. 19815 assert(!arg->hasPlaceholderType()); 19816 paramType = castArg->getTypeAsWritten(); 19817 19818 // Copy-initialize a parameter of that type. 19819 InitializedEntity entity = 19820 InitializedEntity::InitializeParameter(Context, paramType, 19821 /*consumed*/ false); 19822 return PerformCopyInitialization(entity, callLoc, arg); 19823 } 19824 19825 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19826 Expr *orig = E; 19827 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19828 while (true) { 19829 E = E->IgnoreParenImpCasts(); 19830 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19831 E = call->getCallee(); 19832 diagID = diag::err_uncasted_call_of_unknown_any; 19833 } else { 19834 break; 19835 } 19836 } 19837 19838 SourceLocation loc; 19839 NamedDecl *d; 19840 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19841 loc = ref->getLocation(); 19842 d = ref->getDecl(); 19843 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19844 loc = mem->getMemberLoc(); 19845 d = mem->getMemberDecl(); 19846 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19847 diagID = diag::err_uncasted_call_of_unknown_any; 19848 loc = msg->getSelectorStartLoc(); 19849 d = msg->getMethodDecl(); 19850 if (!d) { 19851 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19852 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19853 << orig->getSourceRange(); 19854 return ExprError(); 19855 } 19856 } else { 19857 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19858 << E->getSourceRange(); 19859 return ExprError(); 19860 } 19861 19862 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19863 19864 // Never recoverable. 19865 return ExprError(); 19866 } 19867 19868 /// Check for operands with placeholder types and complain if found. 19869 /// Returns ExprError() if there was an error and no recovery was possible. 19870 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19871 if (!Context.isDependenceAllowed()) { 19872 // C cannot handle TypoExpr nodes on either side of a binop because it 19873 // doesn't handle dependent types properly, so make sure any TypoExprs have 19874 // been dealt with before checking the operands. 19875 ExprResult Result = CorrectDelayedTyposInExpr(E); 19876 if (!Result.isUsable()) return ExprError(); 19877 E = Result.get(); 19878 } 19879 19880 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19881 if (!placeholderType) return E; 19882 19883 switch (placeholderType->getKind()) { 19884 19885 // Overloaded expressions. 19886 case BuiltinType::Overload: { 19887 // Try to resolve a single function template specialization. 19888 // This is obligatory. 19889 ExprResult Result = E; 19890 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19891 return Result; 19892 19893 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19894 // leaves Result unchanged on failure. 19895 Result = E; 19896 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19897 return Result; 19898 19899 // If that failed, try to recover with a call. 19900 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19901 /*complain*/ true); 19902 return Result; 19903 } 19904 19905 // Bound member functions. 19906 case BuiltinType::BoundMember: { 19907 ExprResult result = E; 19908 const Expr *BME = E->IgnoreParens(); 19909 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19910 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19911 if (isa<CXXPseudoDestructorExpr>(BME)) { 19912 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19913 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19914 if (ME->getMemberNameInfo().getName().getNameKind() == 19915 DeclarationName::CXXDestructorName) 19916 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19917 } 19918 tryToRecoverWithCall(result, PD, 19919 /*complain*/ true); 19920 return result; 19921 } 19922 19923 // ARC unbridged casts. 19924 case BuiltinType::ARCUnbridgedCast: { 19925 Expr *realCast = stripARCUnbridgedCast(E); 19926 diagnoseARCUnbridgedCast(realCast); 19927 return realCast; 19928 } 19929 19930 // Expressions of unknown type. 19931 case BuiltinType::UnknownAny: 19932 return diagnoseUnknownAnyExpr(*this, E); 19933 19934 // Pseudo-objects. 19935 case BuiltinType::PseudoObject: 19936 return checkPseudoObjectRValue(E); 19937 19938 case BuiltinType::BuiltinFn: { 19939 // Accept __noop without parens by implicitly converting it to a call expr. 19940 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19941 if (DRE) { 19942 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19943 if (FD->getBuiltinID() == Builtin::BI__noop) { 19944 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19945 CK_BuiltinFnToFnPtr) 19946 .get(); 19947 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19948 VK_PRValue, SourceLocation(), 19949 FPOptionsOverride()); 19950 } 19951 } 19952 19953 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19954 return ExprError(); 19955 } 19956 19957 case BuiltinType::IncompleteMatrixIdx: 19958 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19959 ->getRowIdx() 19960 ->getBeginLoc(), 19961 diag::err_matrix_incomplete_index); 19962 return ExprError(); 19963 19964 // Expressions of unknown type. 19965 case BuiltinType::OMPArraySection: 19966 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19967 return ExprError(); 19968 19969 // Expressions of unknown type. 19970 case BuiltinType::OMPArrayShaping: 19971 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19972 19973 case BuiltinType::OMPIterator: 19974 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19975 19976 // Everything else should be impossible. 19977 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19978 case BuiltinType::Id: 19979 #include "clang/Basic/OpenCLImageTypes.def" 19980 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19981 case BuiltinType::Id: 19982 #include "clang/Basic/OpenCLExtensionTypes.def" 19983 #define SVE_TYPE(Name, Id, SingletonId) \ 19984 case BuiltinType::Id: 19985 #include "clang/Basic/AArch64SVEACLETypes.def" 19986 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19987 case BuiltinType::Id: 19988 #include "clang/Basic/PPCTypes.def" 19989 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19990 #include "clang/Basic/RISCVVTypes.def" 19991 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19992 #define PLACEHOLDER_TYPE(Id, SingletonId) 19993 #include "clang/AST/BuiltinTypes.def" 19994 break; 19995 } 19996 19997 llvm_unreachable("invalid placeholder type!"); 19998 } 19999 20000 bool Sema::CheckCaseExpression(Expr *E) { 20001 if (E->isTypeDependent()) 20002 return true; 20003 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 20004 return E->getType()->isIntegralOrEnumerationType(); 20005 return false; 20006 } 20007 20008 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 20009 ExprResult 20010 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 20011 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 20012 "Unknown Objective-C Boolean value!"); 20013 QualType BoolT = Context.ObjCBuiltinBoolTy; 20014 if (!Context.getBOOLDecl()) { 20015 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 20016 Sema::LookupOrdinaryName); 20017 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 20018 NamedDecl *ND = Result.getFoundDecl(); 20019 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 20020 Context.setBOOLDecl(TD); 20021 } 20022 } 20023 if (Context.getBOOLDecl()) 20024 BoolT = Context.getBOOLType(); 20025 return new (Context) 20026 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 20027 } 20028 20029 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 20030 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 20031 SourceLocation RParen) { 20032 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 20033 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20034 return Spec.getPlatform() == Platform; 20035 }); 20036 // Transcribe the "ios" availability check to "maccatalyst" when compiling 20037 // for "maccatalyst" if "maccatalyst" is not specified. 20038 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 20039 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20040 return Spec.getPlatform() == "ios"; 20041 }); 20042 } 20043 if (Spec == AvailSpecs.end()) 20044 return None; 20045 return Spec->getVersion(); 20046 }; 20047 20048 VersionTuple Version; 20049 if (auto MaybeVersion = 20050 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 20051 Version = *MaybeVersion; 20052 20053 // The use of `@available` in the enclosing context should be analyzed to 20054 // warn when it's used inappropriately (i.e. not if(@available)). 20055 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 20056 Context->HasPotentialAvailabilityViolations = true; 20057 20058 return new (Context) 20059 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 20060 } 20061 20062 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 20063 ArrayRef<Expr *> SubExprs, QualType T) { 20064 if (!Context.getLangOpts().RecoveryAST) 20065 return ExprError(); 20066 20067 if (isSFINAEContext()) 20068 return ExprError(); 20069 20070 if (T.isNull() || T->isUndeducedType() || 20071 !Context.getLangOpts().RecoveryASTType) 20072 // We don't know the concrete type, fallback to dependent type. 20073 T = Context.DependentTy; 20074 20075 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 20076 } 20077