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 using llvm::RoundingMode; 59 60 /// Determine whether the use of this declaration is valid, without 61 /// emitting diagnostics. 62 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 63 // See if this is an auto-typed variable whose initializer we are parsing. 64 if (ParsingInitForAutoVars.count(D)) 65 return false; 66 67 // See if this is a deleted function. 68 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 69 if (FD->isDeleted()) 70 return false; 71 72 // If the function has a deduced return type, and we can't deduce it, 73 // then we can't use it either. 74 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 75 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 76 return false; 77 78 // See if this is an aligned allocation/deallocation function that is 79 // unavailable. 80 if (TreatUnavailableAsInvalid && 81 isUnavailableAlignedAllocationFunction(*FD)) 82 return false; 83 } 84 85 // See if this function is unavailable. 86 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 87 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 88 return false; 89 90 if (isa<UnresolvedUsingIfExistsDecl>(D)) 91 return false; 92 93 return true; 94 } 95 96 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 97 // Warn if this is used but marked unused. 98 if (const auto *A = D->getAttr<UnusedAttr>()) { 99 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 100 // should diagnose them. 101 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 102 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 103 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 104 if (DC && !DC->hasAttr<UnusedAttr>()) 105 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 106 } 107 } 108 } 109 110 /// Emit a note explaining that this function is deleted. 111 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 112 assert(Decl && Decl->isDeleted()); 113 114 if (Decl->isDefaulted()) { 115 // If the method was explicitly defaulted, point at that declaration. 116 if (!Decl->isImplicit()) 117 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 118 119 // Try to diagnose why this special member function was implicitly 120 // deleted. This might fail, if that reason no longer applies. 121 DiagnoseDeletedDefaultedFunction(Decl); 122 return; 123 } 124 125 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 126 if (Ctor && Ctor->isInheritingConstructor()) 127 return NoteDeletedInheritingConstructor(Ctor); 128 129 Diag(Decl->getLocation(), diag::note_availability_specified_here) 130 << Decl << 1; 131 } 132 133 /// Determine whether a FunctionDecl was ever declared with an 134 /// explicit storage class. 135 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 136 for (auto I : D->redecls()) { 137 if (I->getStorageClass() != SC_None) 138 return true; 139 } 140 return false; 141 } 142 143 /// Check whether we're in an extern inline function and referring to a 144 /// variable or function with internal linkage (C11 6.7.4p3). 145 /// 146 /// This is only a warning because we used to silently accept this code, but 147 /// in many cases it will not behave correctly. This is not enabled in C++ mode 148 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 149 /// and so while there may still be user mistakes, most of the time we can't 150 /// prove that there are errors. 151 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 152 const NamedDecl *D, 153 SourceLocation Loc) { 154 // This is disabled under C++; there are too many ways for this to fire in 155 // contexts where the warning is a false positive, or where it is technically 156 // correct but benign. 157 if (S.getLangOpts().CPlusPlus) 158 return; 159 160 // Check if this is an inlined function or method. 161 FunctionDecl *Current = S.getCurFunctionDecl(); 162 if (!Current) 163 return; 164 if (!Current->isInlined()) 165 return; 166 if (!Current->isExternallyVisible()) 167 return; 168 169 // Check if the decl has internal linkage. 170 if (D->getFormalLinkage() != InternalLinkage) 171 return; 172 173 // Downgrade from ExtWarn to Extension if 174 // (1) the supposedly external inline function is in the main file, 175 // and probably won't be included anywhere else. 176 // (2) the thing we're referencing is a pure function. 177 // (3) the thing we're referencing is another inline function. 178 // This last can give us false negatives, but it's better than warning on 179 // wrappers for simple C library functions. 180 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 181 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 182 if (!DowngradeWarning && UsedFn) 183 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 184 185 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 186 : diag::ext_internal_in_extern_inline) 187 << /*IsVar=*/!UsedFn << D; 188 189 S.MaybeSuggestAddingStaticToDecl(Current); 190 191 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 192 << D; 193 } 194 195 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 196 const FunctionDecl *First = Cur->getFirstDecl(); 197 198 // Suggest "static" on the function, if possible. 199 if (!hasAnyExplicitStorageClass(First)) { 200 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 201 Diag(DeclBegin, diag::note_convert_inline_to_static) 202 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 203 } 204 } 205 206 /// Determine whether the use of this declaration is valid, and 207 /// emit any corresponding diagnostics. 208 /// 209 /// This routine diagnoses various problems with referencing 210 /// declarations that can occur when using a declaration. For example, 211 /// it might warn if a deprecated or unavailable declaration is being 212 /// used, or produce an error (and return true) if a C++0x deleted 213 /// function is being used. 214 /// 215 /// \returns true if there was an error (this declaration cannot be 216 /// referenced), false otherwise. 217 /// 218 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 219 const ObjCInterfaceDecl *UnknownObjCClass, 220 bool ObjCPropertyAccess, 221 bool AvoidPartialAvailabilityChecks, 222 ObjCInterfaceDecl *ClassReceiver) { 223 SourceLocation Loc = Locs.front(); 224 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 225 // If there were any diagnostics suppressed by template argument deduction, 226 // emit them now. 227 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 228 if (Pos != SuppressedDiagnostics.end()) { 229 for (const PartialDiagnosticAt &Suppressed : Pos->second) 230 Diag(Suppressed.first, Suppressed.second); 231 232 // Clear out the list of suppressed diagnostics, so that we don't emit 233 // them again for this specialization. However, we don't obsolete this 234 // entry from the table, because we want to avoid ever emitting these 235 // diagnostics again. 236 Pos->second.clear(); 237 } 238 239 // C++ [basic.start.main]p3: 240 // The function 'main' shall not be used within a program. 241 if (cast<FunctionDecl>(D)->isMain()) 242 Diag(Loc, diag::ext_main_used); 243 244 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 245 } 246 247 // See if this is an auto-typed variable whose initializer we are parsing. 248 if (ParsingInitForAutoVars.count(D)) { 249 if (isa<BindingDecl>(D)) { 250 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 251 << D->getDeclName(); 252 } else { 253 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 254 << D->getDeclName() << cast<VarDecl>(D)->getType(); 255 } 256 return true; 257 } 258 259 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 260 // See if this is a deleted function. 261 if (FD->isDeleted()) { 262 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 263 if (Ctor && Ctor->isInheritingConstructor()) 264 Diag(Loc, diag::err_deleted_inherited_ctor_use) 265 << Ctor->getParent() 266 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 267 else 268 Diag(Loc, diag::err_deleted_function_use); 269 NoteDeletedFunction(FD); 270 return true; 271 } 272 273 // [expr.prim.id]p4 274 // A program that refers explicitly or implicitly to a function with a 275 // trailing requires-clause whose constraint-expression is not satisfied, 276 // other than to declare it, is ill-formed. [...] 277 // 278 // See if this is a function with constraints that need to be satisfied. 279 // Check this before deducing the return type, as it might instantiate the 280 // definition. 281 if (FD->getTrailingRequiresClause()) { 282 ConstraintSatisfaction Satisfaction; 283 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 284 // A diagnostic will have already been generated (non-constant 285 // constraint expression, for example) 286 return true; 287 if (!Satisfaction.IsSatisfied) { 288 Diag(Loc, 289 diag::err_reference_to_function_with_unsatisfied_constraints) 290 << D; 291 DiagnoseUnsatisfiedConstraint(Satisfaction); 292 return true; 293 } 294 } 295 296 // If the function has a deduced return type, and we can't deduce it, 297 // then we can't use it either. 298 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 299 DeduceReturnType(FD, Loc)) 300 return true; 301 302 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 303 return true; 304 305 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 306 return true; 307 } 308 309 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 310 // Lambdas are only default-constructible or assignable in C++2a onwards. 311 if (MD->getParent()->isLambda() && 312 ((isa<CXXConstructorDecl>(MD) && 313 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 314 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 315 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 316 << !isa<CXXConstructorDecl>(MD); 317 } 318 } 319 320 auto getReferencedObjCProp = [](const NamedDecl *D) -> 321 const ObjCPropertyDecl * { 322 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 323 return MD->findPropertyDecl(); 324 return nullptr; 325 }; 326 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 327 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 328 return true; 329 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 330 return true; 331 } 332 333 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 334 // Only the variables omp_in and omp_out are allowed in the combiner. 335 // Only the variables omp_priv and omp_orig are allowed in the 336 // initializer-clause. 337 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 338 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 339 isa<VarDecl>(D)) { 340 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 341 << getCurFunction()->HasOMPDeclareReductionCombiner; 342 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 343 return true; 344 } 345 346 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 347 // List-items in map clauses on this construct may only refer to the declared 348 // variable var and entities that could be referenced by a procedure defined 349 // at the same location 350 if (LangOpts.OpenMP && isa<VarDecl>(D) && 351 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 352 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 353 << getOpenMPDeclareMapperVarName(); 354 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 355 return true; 356 } 357 358 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 359 Diag(Loc, diag::err_use_of_empty_using_if_exists); 360 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 361 return true; 362 } 363 364 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 365 AvoidPartialAvailabilityChecks, ClassReceiver); 366 367 DiagnoseUnusedOfDecl(*this, D, Loc); 368 369 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 370 371 if (auto *VD = dyn_cast<ValueDecl>(D)) 372 checkTypeSupport(VD->getType(), Loc, VD); 373 374 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 375 if (!Context.getTargetInfo().isTLSSupported()) 376 if (const auto *VD = dyn_cast<VarDecl>(D)) 377 if (VD->getTLSKind() != VarDecl::TLS_None) 378 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 379 } 380 381 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 382 !isUnevaluatedContext()) { 383 // C++ [expr.prim.req.nested] p3 384 // A local parameter shall only appear as an unevaluated operand 385 // (Clause 8) within the constraint-expression. 386 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 387 << D; 388 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 389 return true; 390 } 391 392 return false; 393 } 394 395 /// DiagnoseSentinelCalls - This routine checks whether a call or 396 /// message-send is to a declaration with the sentinel attribute, and 397 /// if so, it checks that the requirements of the sentinel are 398 /// satisfied. 399 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 400 ArrayRef<Expr *> Args) { 401 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 402 if (!attr) 403 return; 404 405 // The number of formal parameters of the declaration. 406 unsigned numFormalParams; 407 408 // The kind of declaration. This is also an index into a %select in 409 // the diagnostic. 410 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 411 412 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 413 numFormalParams = MD->param_size(); 414 calleeType = CT_Method; 415 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 416 numFormalParams = FD->param_size(); 417 calleeType = CT_Function; 418 } else if (isa<VarDecl>(D)) { 419 QualType type = cast<ValueDecl>(D)->getType(); 420 const FunctionType *fn = nullptr; 421 if (const PointerType *ptr = type->getAs<PointerType>()) { 422 fn = ptr->getPointeeType()->getAs<FunctionType>(); 423 if (!fn) return; 424 calleeType = CT_Function; 425 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 426 fn = ptr->getPointeeType()->castAs<FunctionType>(); 427 calleeType = CT_Block; 428 } else { 429 return; 430 } 431 432 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 433 numFormalParams = proto->getNumParams(); 434 } else { 435 numFormalParams = 0; 436 } 437 } else { 438 return; 439 } 440 441 // "nullPos" is the number of formal parameters at the end which 442 // effectively count as part of the variadic arguments. This is 443 // useful if you would prefer to not have *any* formal parameters, 444 // but the language forces you to have at least one. 445 unsigned nullPos = attr->getNullPos(); 446 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 447 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 448 449 // The number of arguments which should follow the sentinel. 450 unsigned numArgsAfterSentinel = attr->getSentinel(); 451 452 // If there aren't enough arguments for all the formal parameters, 453 // the sentinel, and the args after the sentinel, complain. 454 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 455 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 456 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 457 return; 458 } 459 460 // Otherwise, find the sentinel expression. 461 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 462 if (!sentinelExpr) return; 463 if (sentinelExpr->isValueDependent()) return; 464 if (Context.isSentinelNullExpr(sentinelExpr)) return; 465 466 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 467 // or 'NULL' if those are actually defined in the context. Only use 468 // 'nil' for ObjC methods, where it's much more likely that the 469 // variadic arguments form a list of object pointers. 470 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 471 std::string NullValue; 472 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 473 NullValue = "nil"; 474 else if (getLangOpts().CPlusPlus11) 475 NullValue = "nullptr"; 476 else if (PP.isMacroDefined("NULL")) 477 NullValue = "NULL"; 478 else 479 NullValue = "(void*) 0"; 480 481 if (MissingNilLoc.isInvalid()) 482 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 483 else 484 Diag(MissingNilLoc, diag::warn_missing_sentinel) 485 << int(calleeType) 486 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 487 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 488 } 489 490 SourceRange Sema::getExprRange(Expr *E) const { 491 return E ? E->getSourceRange() : SourceRange(); 492 } 493 494 //===----------------------------------------------------------------------===// 495 // Standard Promotions and Conversions 496 //===----------------------------------------------------------------------===// 497 498 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 499 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 500 // Handle any placeholder expressions which made it here. 501 if (E->getType()->isPlaceholderType()) { 502 ExprResult result = CheckPlaceholderExpr(E); 503 if (result.isInvalid()) return ExprError(); 504 E = result.get(); 505 } 506 507 QualType Ty = E->getType(); 508 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 509 510 if (Ty->isFunctionType()) { 511 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 512 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 513 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 514 return ExprError(); 515 516 E = ImpCastExprToType(E, Context.getPointerType(Ty), 517 CK_FunctionToPointerDecay).get(); 518 } else if (Ty->isArrayType()) { 519 // In C90 mode, arrays only promote to pointers if the array expression is 520 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 521 // type 'array of type' is converted to an expression that has type 'pointer 522 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 523 // that has type 'array of type' ...". The relevant change is "an lvalue" 524 // (C90) to "an expression" (C99). 525 // 526 // C++ 4.2p1: 527 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 528 // T" can be converted to an rvalue of type "pointer to T". 529 // 530 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 531 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 532 CK_ArrayToPointerDecay); 533 if (Res.isInvalid()) 534 return ExprError(); 535 E = Res.get(); 536 } 537 } 538 return E; 539 } 540 541 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 542 // Check to see if we are dereferencing a null pointer. If so, 543 // and if not volatile-qualified, this is undefined behavior that the 544 // optimizer will delete, so warn about it. People sometimes try to use this 545 // to get a deterministic trap and are surprised by clang's behavior. This 546 // only handles the pattern "*null", which is a very syntactic check. 547 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 548 if (UO && UO->getOpcode() == UO_Deref && 549 UO->getSubExpr()->getType()->isPointerType()) { 550 const LangAS AS = 551 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 552 if ((!isTargetAddressSpace(AS) || 553 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 554 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 555 S.Context, Expr::NPC_ValueDependentIsNotNull) && 556 !UO->getType().isVolatileQualified()) { 557 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 558 S.PDiag(diag::warn_indirection_through_null) 559 << UO->getSubExpr()->getSourceRange()); 560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 561 S.PDiag(diag::note_indirection_through_null)); 562 } 563 } 564 } 565 566 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 567 SourceLocation AssignLoc, 568 const Expr* RHS) { 569 const ObjCIvarDecl *IV = OIRE->getDecl(); 570 if (!IV) 571 return; 572 573 DeclarationName MemberName = IV->getDeclName(); 574 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 575 if (!Member || !Member->isStr("isa")) 576 return; 577 578 const Expr *Base = OIRE->getBase(); 579 QualType BaseType = Base->getType(); 580 if (OIRE->isArrow()) 581 BaseType = BaseType->getPointeeType(); 582 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 583 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 584 ObjCInterfaceDecl *ClassDeclared = nullptr; 585 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 586 if (!ClassDeclared->getSuperClass() 587 && (*ClassDeclared->ivar_begin()) == IV) { 588 if (RHS) { 589 NamedDecl *ObjectSetClass = 590 S.LookupSingleName(S.TUScope, 591 &S.Context.Idents.get("object_setClass"), 592 SourceLocation(), S.LookupOrdinaryName); 593 if (ObjectSetClass) { 594 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 595 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 596 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 597 "object_setClass(") 598 << FixItHint::CreateReplacement( 599 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 600 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 601 } 602 else 603 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 604 } else { 605 NamedDecl *ObjectGetClass = 606 S.LookupSingleName(S.TUScope, 607 &S.Context.Idents.get("object_getClass"), 608 SourceLocation(), S.LookupOrdinaryName); 609 if (ObjectGetClass) 610 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 611 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 612 "object_getClass(") 613 << FixItHint::CreateReplacement( 614 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 615 else 616 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 617 } 618 S.Diag(IV->getLocation(), diag::note_ivar_decl); 619 } 620 } 621 } 622 623 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 624 // Handle any placeholder expressions which made it here. 625 if (E->getType()->isPlaceholderType()) { 626 ExprResult result = CheckPlaceholderExpr(E); 627 if (result.isInvalid()) return ExprError(); 628 E = result.get(); 629 } 630 631 // C++ [conv.lval]p1: 632 // A glvalue of a non-function, non-array type T can be 633 // converted to a prvalue. 634 if (!E->isGLValue()) return E; 635 636 QualType T = E->getType(); 637 assert(!T.isNull() && "r-value conversion on typeless expression?"); 638 639 // lvalue-to-rvalue conversion cannot be applied to function or array types. 640 if (T->isFunctionType() || T->isArrayType()) 641 return E; 642 643 // We don't want to throw lvalue-to-rvalue casts on top of 644 // expressions of certain types in C++. 645 if (getLangOpts().CPlusPlus && 646 (E->getType() == Context.OverloadTy || 647 T->isDependentType() || 648 T->isRecordType())) 649 return E; 650 651 // The C standard is actually really unclear on this point, and 652 // DR106 tells us what the result should be but not why. It's 653 // generally best to say that void types just doesn't undergo 654 // lvalue-to-rvalue at all. Note that expressions of unqualified 655 // 'void' type are never l-values, but qualified void can be. 656 if (T->isVoidType()) 657 return E; 658 659 // OpenCL usually rejects direct accesses to values of 'half' type. 660 if (getLangOpts().OpenCL && 661 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 662 T->isHalfType()) { 663 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 664 << 0 << T; 665 return ExprError(); 666 } 667 668 CheckForNullPointerDereference(*this, E); 669 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 670 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 671 &Context.Idents.get("object_getClass"), 672 SourceLocation(), LookupOrdinaryName); 673 if (ObjectGetClass) 674 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 675 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 676 << FixItHint::CreateReplacement( 677 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 678 else 679 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 680 } 681 else if (const ObjCIvarRefExpr *OIRE = 682 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 683 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 684 685 // C++ [conv.lval]p1: 686 // [...] If T is a non-class type, the type of the prvalue is the 687 // cv-unqualified version of T. Otherwise, the type of the 688 // rvalue is T. 689 // 690 // C99 6.3.2.1p2: 691 // If the lvalue has qualified type, the value has the unqualified 692 // version of the type of the lvalue; otherwise, the value has the 693 // type of the lvalue. 694 if (T.hasQualifiers()) 695 T = T.getUnqualifiedType(); 696 697 // Under the MS ABI, lock down the inheritance model now. 698 if (T->isMemberPointerType() && 699 Context.getTargetInfo().getCXXABI().isMicrosoft()) 700 (void)isCompleteType(E->getExprLoc(), T); 701 702 ExprResult Res = CheckLValueToRValueConversionOperand(E); 703 if (Res.isInvalid()) 704 return Res; 705 E = Res.get(); 706 707 // Loading a __weak object implicitly retains the value, so we need a cleanup to 708 // balance that. 709 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 710 Cleanup.setExprNeedsCleanups(true); 711 712 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 713 Cleanup.setExprNeedsCleanups(true); 714 715 // C++ [conv.lval]p3: 716 // If T is cv std::nullptr_t, the result is a null pointer constant. 717 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 718 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 719 CurFPFeatureOverrides()); 720 721 // C11 6.3.2.1p2: 722 // ... if the lvalue has atomic type, the value has the non-atomic version 723 // of the type of the lvalue ... 724 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 725 T = Atomic->getValueType().getUnqualifiedType(); 726 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 727 nullptr, VK_PRValue, FPOptionsOverride()); 728 } 729 730 return Res; 731 } 732 733 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 734 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 735 if (Res.isInvalid()) 736 return ExprError(); 737 Res = DefaultLvalueConversion(Res.get()); 738 if (Res.isInvalid()) 739 return ExprError(); 740 return Res; 741 } 742 743 /// CallExprUnaryConversions - a special case of an unary conversion 744 /// performed on a function designator of a call expression. 745 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 746 QualType Ty = E->getType(); 747 ExprResult Res = E; 748 // Only do implicit cast for a function type, but not for a pointer 749 // to function type. 750 if (Ty->isFunctionType()) { 751 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 752 CK_FunctionToPointerDecay); 753 if (Res.isInvalid()) 754 return ExprError(); 755 } 756 Res = DefaultLvalueConversion(Res.get()); 757 if (Res.isInvalid()) 758 return ExprError(); 759 return Res.get(); 760 } 761 762 /// UsualUnaryConversions - Performs various conversions that are common to most 763 /// operators (C99 6.3). The conversions of array and function types are 764 /// sometimes suppressed. For example, the array->pointer conversion doesn't 765 /// apply if the array is an argument to the sizeof or address (&) operators. 766 /// In these instances, this routine should *not* be called. 767 ExprResult Sema::UsualUnaryConversions(Expr *E) { 768 // First, convert to an r-value. 769 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 770 if (Res.isInvalid()) 771 return ExprError(); 772 E = Res.get(); 773 774 QualType Ty = E->getType(); 775 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 776 777 // Half FP have to be promoted to float unless it is natively supported 778 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 779 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 780 781 // Try to perform integral promotions if the object has a theoretically 782 // promotable type. 783 if (Ty->isIntegralOrUnscopedEnumerationType()) { 784 // C99 6.3.1.1p2: 785 // 786 // The following may be used in an expression wherever an int or 787 // unsigned int may be used: 788 // - an object or expression with an integer type whose integer 789 // conversion rank is less than or equal to the rank of int 790 // and unsigned int. 791 // - A bit-field of type _Bool, int, signed int, or unsigned int. 792 // 793 // If an int can represent all values of the original type, the 794 // value is converted to an int; otherwise, it is converted to an 795 // unsigned int. These are called the integer promotions. All 796 // other types are unchanged by the integer promotions. 797 798 QualType PTy = Context.isPromotableBitField(E); 799 if (!PTy.isNull()) { 800 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 801 return E; 802 } 803 if (Ty->isPromotableIntegerType()) { 804 QualType PT = Context.getPromotedIntegerType(Ty); 805 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 806 return E; 807 } 808 } 809 return E; 810 } 811 812 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 813 /// do not have a prototype. Arguments that have type float or __fp16 814 /// are promoted to double. All other argument types are converted by 815 /// UsualUnaryConversions(). 816 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 817 QualType Ty = E->getType(); 818 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 819 820 ExprResult Res = UsualUnaryConversions(E); 821 if (Res.isInvalid()) 822 return ExprError(); 823 E = Res.get(); 824 825 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 826 // promote to double. 827 // Note that default argument promotion applies only to float (and 828 // half/fp16); it does not apply to _Float16. 829 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 830 if (BTy && (BTy->getKind() == BuiltinType::Half || 831 BTy->getKind() == BuiltinType::Float)) { 832 if (getLangOpts().OpenCL && 833 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 834 if (BTy->getKind() == BuiltinType::Half) { 835 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 836 } 837 } else { 838 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 839 } 840 } 841 if (BTy && 842 getLangOpts().getExtendIntArgs() == 843 LangOptions::ExtendArgsKind::ExtendTo64 && 844 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 845 Context.getTypeSizeInChars(BTy) < 846 Context.getTypeSizeInChars(Context.LongLongTy)) { 847 E = (Ty->isUnsignedIntegerType()) 848 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 849 .get() 850 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 851 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 852 "Unexpected typesize for LongLongTy"); 853 } 854 855 // C++ performs lvalue-to-rvalue conversion as a default argument 856 // promotion, even on class types, but note: 857 // C++11 [conv.lval]p2: 858 // When an lvalue-to-rvalue conversion occurs in an unevaluated 859 // operand or a subexpression thereof the value contained in the 860 // referenced object is not accessed. Otherwise, if the glvalue 861 // has a class type, the conversion copy-initializes a temporary 862 // of type T from the glvalue and the result of the conversion 863 // is a prvalue for the temporary. 864 // FIXME: add some way to gate this entire thing for correctness in 865 // potentially potentially evaluated contexts. 866 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 867 ExprResult Temp = PerformCopyInitialization( 868 InitializedEntity::InitializeTemporary(E->getType()), 869 E->getExprLoc(), E); 870 if (Temp.isInvalid()) 871 return ExprError(); 872 E = Temp.get(); 873 } 874 875 return E; 876 } 877 878 /// Determine the degree of POD-ness for an expression. 879 /// Incomplete types are considered POD, since this check can be performed 880 /// when we're in an unevaluated context. 881 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 882 if (Ty->isIncompleteType()) { 883 // C++11 [expr.call]p7: 884 // After these conversions, if the argument does not have arithmetic, 885 // enumeration, pointer, pointer to member, or class type, the program 886 // is ill-formed. 887 // 888 // Since we've already performed array-to-pointer and function-to-pointer 889 // decay, the only such type in C++ is cv void. This also handles 890 // initializer lists as variadic arguments. 891 if (Ty->isVoidType()) 892 return VAK_Invalid; 893 894 if (Ty->isObjCObjectType()) 895 return VAK_Invalid; 896 return VAK_Valid; 897 } 898 899 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 900 return VAK_Invalid; 901 902 if (Ty.isCXX98PODType(Context)) 903 return VAK_Valid; 904 905 // C++11 [expr.call]p7: 906 // Passing a potentially-evaluated argument of class type (Clause 9) 907 // having a non-trivial copy constructor, a non-trivial move constructor, 908 // or a non-trivial destructor, with no corresponding parameter, 909 // is conditionally-supported with implementation-defined semantics. 910 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 911 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 912 if (!Record->hasNonTrivialCopyConstructor() && 913 !Record->hasNonTrivialMoveConstructor() && 914 !Record->hasNonTrivialDestructor()) 915 return VAK_ValidInCXX11; 916 917 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 918 return VAK_Valid; 919 920 if (Ty->isObjCObjectType()) 921 return VAK_Invalid; 922 923 if (getLangOpts().MSVCCompat) 924 return VAK_MSVCUndefined; 925 926 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 927 // permitted to reject them. We should consider doing so. 928 return VAK_Undefined; 929 } 930 931 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 932 // Don't allow one to pass an Objective-C interface to a vararg. 933 const QualType &Ty = E->getType(); 934 VarArgKind VAK = isValidVarArgType(Ty); 935 936 // Complain about passing non-POD types through varargs. 937 switch (VAK) { 938 case VAK_ValidInCXX11: 939 DiagRuntimeBehavior( 940 E->getBeginLoc(), nullptr, 941 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 942 LLVM_FALLTHROUGH; 943 case VAK_Valid: 944 if (Ty->isRecordType()) { 945 // This is unlikely to be what the user intended. If the class has a 946 // 'c_str' member function, the user probably meant to call that. 947 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 948 PDiag(diag::warn_pass_class_arg_to_vararg) 949 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 950 } 951 break; 952 953 case VAK_Undefined: 954 case VAK_MSVCUndefined: 955 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 956 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 957 << getLangOpts().CPlusPlus11 << Ty << CT); 958 break; 959 960 case VAK_Invalid: 961 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 962 Diag(E->getBeginLoc(), 963 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 964 << Ty << CT; 965 else if (Ty->isObjCObjectType()) 966 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 967 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 968 << Ty << CT); 969 else 970 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 971 << isa<InitListExpr>(E) << Ty << CT; 972 break; 973 } 974 } 975 976 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 977 /// will create a trap if the resulting type is not a POD type. 978 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 979 FunctionDecl *FDecl) { 980 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 981 // Strip the unbridged-cast placeholder expression off, if applicable. 982 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 983 (CT == VariadicMethod || 984 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 985 E = stripARCUnbridgedCast(E); 986 987 // Otherwise, do normal placeholder checking. 988 } else { 989 ExprResult ExprRes = CheckPlaceholderExpr(E); 990 if (ExprRes.isInvalid()) 991 return ExprError(); 992 E = ExprRes.get(); 993 } 994 } 995 996 ExprResult ExprRes = DefaultArgumentPromotion(E); 997 if (ExprRes.isInvalid()) 998 return ExprError(); 999 1000 // Copy blocks to the heap. 1001 if (ExprRes.get()->getType()->isBlockPointerType()) 1002 maybeExtendBlockObject(ExprRes); 1003 1004 E = ExprRes.get(); 1005 1006 // Diagnostics regarding non-POD argument types are 1007 // emitted along with format string checking in Sema::CheckFunctionCall(). 1008 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1009 // Turn this into a trap. 1010 CXXScopeSpec SS; 1011 SourceLocation TemplateKWLoc; 1012 UnqualifiedId Name; 1013 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1014 E->getBeginLoc()); 1015 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1016 /*HasTrailingLParen=*/true, 1017 /*IsAddressOfOperand=*/false); 1018 if (TrapFn.isInvalid()) 1019 return ExprError(); 1020 1021 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1022 None, E->getEndLoc()); 1023 if (Call.isInvalid()) 1024 return ExprError(); 1025 1026 ExprResult Comma = 1027 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1028 if (Comma.isInvalid()) 1029 return ExprError(); 1030 return Comma.get(); 1031 } 1032 1033 if (!getLangOpts().CPlusPlus && 1034 RequireCompleteType(E->getExprLoc(), E->getType(), 1035 diag::err_call_incomplete_argument)) 1036 return ExprError(); 1037 1038 return E; 1039 } 1040 1041 /// Converts an integer to complex float type. Helper function of 1042 /// UsualArithmeticConversions() 1043 /// 1044 /// \return false if the integer expression is an integer type and is 1045 /// successfully converted to the complex type. 1046 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1047 ExprResult &ComplexExpr, 1048 QualType IntTy, 1049 QualType ComplexTy, 1050 bool SkipCast) { 1051 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1052 if (SkipCast) return false; 1053 if (IntTy->isIntegerType()) { 1054 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1055 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1056 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1057 CK_FloatingRealToComplex); 1058 } else { 1059 assert(IntTy->isComplexIntegerType()); 1060 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1061 CK_IntegralComplexToFloatingComplex); 1062 } 1063 return false; 1064 } 1065 1066 /// Handle arithmetic conversion with complex types. Helper function of 1067 /// UsualArithmeticConversions() 1068 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1069 ExprResult &RHS, QualType LHSType, 1070 QualType RHSType, 1071 bool IsCompAssign) { 1072 // if we have an integer operand, the result is the complex type. 1073 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1074 /*skipCast*/false)) 1075 return LHSType; 1076 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1077 /*skipCast*/IsCompAssign)) 1078 return RHSType; 1079 1080 // This handles complex/complex, complex/float, or float/complex. 1081 // When both operands are complex, the shorter operand is converted to the 1082 // type of the longer, and that is the type of the result. This corresponds 1083 // to what is done when combining two real floating-point operands. 1084 // The fun begins when size promotion occur across type domains. 1085 // From H&S 6.3.4: When one operand is complex and the other is a real 1086 // floating-point type, the less precise type is converted, within it's 1087 // real or complex domain, to the precision of the other type. For example, 1088 // when combining a "long double" with a "double _Complex", the 1089 // "double _Complex" is promoted to "long double _Complex". 1090 1091 // Compute the rank of the two types, regardless of whether they are complex. 1092 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1093 1094 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1095 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1096 QualType LHSElementType = 1097 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1098 QualType RHSElementType = 1099 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1100 1101 QualType ResultType = S.Context.getComplexType(LHSElementType); 1102 if (Order < 0) { 1103 // Promote the precision of the LHS if not an assignment. 1104 ResultType = S.Context.getComplexType(RHSElementType); 1105 if (!IsCompAssign) { 1106 if (LHSComplexType) 1107 LHS = 1108 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1109 else 1110 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1111 } 1112 } else if (Order > 0) { 1113 // Promote the precision of the RHS. 1114 if (RHSComplexType) 1115 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1116 else 1117 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1118 } 1119 return ResultType; 1120 } 1121 1122 /// Handle arithmetic conversion from integer to float. Helper function 1123 /// of UsualArithmeticConversions() 1124 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1125 ExprResult &IntExpr, 1126 QualType FloatTy, QualType IntTy, 1127 bool ConvertFloat, bool ConvertInt) { 1128 if (IntTy->isIntegerType()) { 1129 if (ConvertInt) 1130 // Convert intExpr to the lhs floating point type. 1131 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1132 CK_IntegralToFloating); 1133 return FloatTy; 1134 } 1135 1136 // Convert both sides to the appropriate complex float. 1137 assert(IntTy->isComplexIntegerType()); 1138 QualType result = S.Context.getComplexType(FloatTy); 1139 1140 // _Complex int -> _Complex float 1141 if (ConvertInt) 1142 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1143 CK_IntegralComplexToFloatingComplex); 1144 1145 // float -> _Complex float 1146 if (ConvertFloat) 1147 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1148 CK_FloatingRealToComplex); 1149 1150 return result; 1151 } 1152 1153 /// Handle arithmethic conversion with floating point types. Helper 1154 /// function of UsualArithmeticConversions() 1155 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1156 ExprResult &RHS, QualType LHSType, 1157 QualType RHSType, bool IsCompAssign) { 1158 bool LHSFloat = LHSType->isRealFloatingType(); 1159 bool RHSFloat = RHSType->isRealFloatingType(); 1160 1161 // N1169 4.1.4: If one of the operands has a floating type and the other 1162 // operand has a fixed-point type, the fixed-point operand 1163 // is converted to the floating type [...] 1164 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1165 if (LHSFloat) 1166 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1167 else if (!IsCompAssign) 1168 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1169 return LHSFloat ? LHSType : RHSType; 1170 } 1171 1172 // If we have two real floating types, convert the smaller operand 1173 // to the bigger result. 1174 if (LHSFloat && RHSFloat) { 1175 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1176 if (order > 0) { 1177 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1178 return LHSType; 1179 } 1180 1181 assert(order < 0 && "illegal float comparison"); 1182 if (!IsCompAssign) 1183 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1184 return RHSType; 1185 } 1186 1187 if (LHSFloat) { 1188 // Half FP has to be promoted to float unless it is natively supported 1189 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1190 LHSType = S.Context.FloatTy; 1191 1192 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1193 /*ConvertFloat=*/!IsCompAssign, 1194 /*ConvertInt=*/ true); 1195 } 1196 assert(RHSFloat); 1197 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1198 /*ConvertFloat=*/ true, 1199 /*ConvertInt=*/!IsCompAssign); 1200 } 1201 1202 /// Diagnose attempts to convert between __float128, __ibm128 and 1203 /// long double if there is no support for such conversion. 1204 /// Helper function of UsualArithmeticConversions(). 1205 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1206 QualType RHSType) { 1207 // No issue if either is not a floating point type. 1208 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1209 return false; 1210 1211 // No issue if both have the same 128-bit float semantics. 1212 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1213 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1214 1215 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1216 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1217 1218 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1219 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1220 1221 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1222 &RHSSem != &llvm::APFloat::IEEEquad()) && 1223 (&LHSSem != &llvm::APFloat::IEEEquad() || 1224 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1225 return false; 1226 1227 return true; 1228 } 1229 1230 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1231 1232 namespace { 1233 /// These helper callbacks are placed in an anonymous namespace to 1234 /// permit their use as function template parameters. 1235 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1236 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1237 } 1238 1239 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1240 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1241 CK_IntegralComplexCast); 1242 } 1243 } 1244 1245 /// Handle integer arithmetic conversions. Helper function of 1246 /// UsualArithmeticConversions() 1247 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1248 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1249 ExprResult &RHS, QualType LHSType, 1250 QualType RHSType, bool IsCompAssign) { 1251 // The rules for this case are in C99 6.3.1.8 1252 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1253 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1254 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1255 if (LHSSigned == RHSSigned) { 1256 // Same signedness; use the higher-ranked type 1257 if (order >= 0) { 1258 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1259 return LHSType; 1260 } else if (!IsCompAssign) 1261 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1262 return RHSType; 1263 } else if (order != (LHSSigned ? 1 : -1)) { 1264 // The unsigned type has greater than or equal rank to the 1265 // signed type, so use the unsigned type 1266 if (RHSSigned) { 1267 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1268 return LHSType; 1269 } else if (!IsCompAssign) 1270 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1271 return RHSType; 1272 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1273 // The two types are different widths; if we are here, that 1274 // means the signed type is larger than the unsigned type, so 1275 // use the signed type. 1276 if (LHSSigned) { 1277 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1278 return LHSType; 1279 } else if (!IsCompAssign) 1280 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1281 return RHSType; 1282 } else { 1283 // The signed type is higher-ranked than the unsigned type, 1284 // but isn't actually any bigger (like unsigned int and long 1285 // on most 32-bit systems). Use the unsigned type corresponding 1286 // to the signed type. 1287 QualType result = 1288 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1289 RHS = (*doRHSCast)(S, RHS.get(), result); 1290 if (!IsCompAssign) 1291 LHS = (*doLHSCast)(S, LHS.get(), result); 1292 return result; 1293 } 1294 } 1295 1296 /// Handle conversions with GCC complex int extension. Helper function 1297 /// of UsualArithmeticConversions() 1298 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1299 ExprResult &RHS, QualType LHSType, 1300 QualType RHSType, 1301 bool IsCompAssign) { 1302 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1303 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1304 1305 if (LHSComplexInt && RHSComplexInt) { 1306 QualType LHSEltType = LHSComplexInt->getElementType(); 1307 QualType RHSEltType = RHSComplexInt->getElementType(); 1308 QualType ScalarType = 1309 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1310 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1311 1312 return S.Context.getComplexType(ScalarType); 1313 } 1314 1315 if (LHSComplexInt) { 1316 QualType LHSEltType = LHSComplexInt->getElementType(); 1317 QualType ScalarType = 1318 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1319 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1320 QualType ComplexType = S.Context.getComplexType(ScalarType); 1321 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1322 CK_IntegralRealToComplex); 1323 1324 return ComplexType; 1325 } 1326 1327 assert(RHSComplexInt); 1328 1329 QualType RHSEltType = RHSComplexInt->getElementType(); 1330 QualType ScalarType = 1331 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1332 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1333 QualType ComplexType = S.Context.getComplexType(ScalarType); 1334 1335 if (!IsCompAssign) 1336 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1337 CK_IntegralRealToComplex); 1338 return ComplexType; 1339 } 1340 1341 /// Return the rank of a given fixed point or integer type. The value itself 1342 /// doesn't matter, but the values must be increasing with proper increasing 1343 /// rank as described in N1169 4.1.1. 1344 static unsigned GetFixedPointRank(QualType Ty) { 1345 const auto *BTy = Ty->getAs<BuiltinType>(); 1346 assert(BTy && "Expected a builtin type."); 1347 1348 switch (BTy->getKind()) { 1349 case BuiltinType::ShortFract: 1350 case BuiltinType::UShortFract: 1351 case BuiltinType::SatShortFract: 1352 case BuiltinType::SatUShortFract: 1353 return 1; 1354 case BuiltinType::Fract: 1355 case BuiltinType::UFract: 1356 case BuiltinType::SatFract: 1357 case BuiltinType::SatUFract: 1358 return 2; 1359 case BuiltinType::LongFract: 1360 case BuiltinType::ULongFract: 1361 case BuiltinType::SatLongFract: 1362 case BuiltinType::SatULongFract: 1363 return 3; 1364 case BuiltinType::ShortAccum: 1365 case BuiltinType::UShortAccum: 1366 case BuiltinType::SatShortAccum: 1367 case BuiltinType::SatUShortAccum: 1368 return 4; 1369 case BuiltinType::Accum: 1370 case BuiltinType::UAccum: 1371 case BuiltinType::SatAccum: 1372 case BuiltinType::SatUAccum: 1373 return 5; 1374 case BuiltinType::LongAccum: 1375 case BuiltinType::ULongAccum: 1376 case BuiltinType::SatLongAccum: 1377 case BuiltinType::SatULongAccum: 1378 return 6; 1379 default: 1380 if (BTy->isInteger()) 1381 return 0; 1382 llvm_unreachable("Unexpected fixed point or integer type"); 1383 } 1384 } 1385 1386 /// handleFixedPointConversion - Fixed point operations between fixed 1387 /// point types and integers or other fixed point types do not fall under 1388 /// usual arithmetic conversion since these conversions could result in loss 1389 /// of precsision (N1169 4.1.4). These operations should be calculated with 1390 /// the full precision of their result type (N1169 4.1.6.2.1). 1391 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1392 QualType RHSTy) { 1393 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1394 "Expected at least one of the operands to be a fixed point type"); 1395 assert((LHSTy->isFixedPointOrIntegerType() || 1396 RHSTy->isFixedPointOrIntegerType()) && 1397 "Special fixed point arithmetic operation conversions are only " 1398 "applied to ints or other fixed point types"); 1399 1400 // If one operand has signed fixed-point type and the other operand has 1401 // unsigned fixed-point type, then the unsigned fixed-point operand is 1402 // converted to its corresponding signed fixed-point type and the resulting 1403 // type is the type of the converted operand. 1404 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1405 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1406 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1407 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1408 1409 // The result type is the type with the highest rank, whereby a fixed-point 1410 // conversion rank is always greater than an integer conversion rank; if the 1411 // type of either of the operands is a saturating fixedpoint type, the result 1412 // type shall be the saturating fixed-point type corresponding to the type 1413 // with the highest rank; the resulting value is converted (taking into 1414 // account rounding and overflow) to the precision of the resulting type. 1415 // Same ranks between signed and unsigned types are resolved earlier, so both 1416 // types are either signed or both unsigned at this point. 1417 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1418 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1419 1420 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1421 1422 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1423 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1424 1425 return ResultTy; 1426 } 1427 1428 /// Check that the usual arithmetic conversions can be performed on this pair of 1429 /// expressions that might be of enumeration type. 1430 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1431 SourceLocation Loc, 1432 Sema::ArithConvKind ACK) { 1433 // C++2a [expr.arith.conv]p1: 1434 // If one operand is of enumeration type and the other operand is of a 1435 // different enumeration type or a floating-point type, this behavior is 1436 // deprecated ([depr.arith.conv.enum]). 1437 // 1438 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1439 // Eventually we will presumably reject these cases (in C++23 onwards?). 1440 QualType L = LHS->getType(), R = RHS->getType(); 1441 bool LEnum = L->isUnscopedEnumerationType(), 1442 REnum = R->isUnscopedEnumerationType(); 1443 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1444 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1445 (REnum && L->isFloatingType())) { 1446 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1447 ? diag::warn_arith_conv_enum_float_cxx20 1448 : diag::warn_arith_conv_enum_float) 1449 << LHS->getSourceRange() << RHS->getSourceRange() 1450 << (int)ACK << LEnum << L << R; 1451 } else if (!IsCompAssign && LEnum && REnum && 1452 !S.Context.hasSameUnqualifiedType(L, R)) { 1453 unsigned DiagID; 1454 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1455 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1456 // If either enumeration type is unnamed, it's less likely that the 1457 // user cares about this, but this situation is still deprecated in 1458 // C++2a. Use a different warning group. 1459 DiagID = S.getLangOpts().CPlusPlus20 1460 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1461 : diag::warn_arith_conv_mixed_anon_enum_types; 1462 } else if (ACK == Sema::ACK_Conditional) { 1463 // Conditional expressions are separated out because they have 1464 // historically had a different warning flag. 1465 DiagID = S.getLangOpts().CPlusPlus20 1466 ? diag::warn_conditional_mixed_enum_types_cxx20 1467 : diag::warn_conditional_mixed_enum_types; 1468 } else if (ACK == Sema::ACK_Comparison) { 1469 // Comparison expressions are separated out because they have 1470 // historically had a different warning flag. 1471 DiagID = S.getLangOpts().CPlusPlus20 1472 ? diag::warn_comparison_mixed_enum_types_cxx20 1473 : diag::warn_comparison_mixed_enum_types; 1474 } else { 1475 DiagID = S.getLangOpts().CPlusPlus20 1476 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1477 : diag::warn_arith_conv_mixed_enum_types; 1478 } 1479 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1480 << (int)ACK << L << R; 1481 } 1482 } 1483 1484 /// UsualArithmeticConversions - Performs various conversions that are common to 1485 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1486 /// routine returns the first non-arithmetic type found. The client is 1487 /// responsible for emitting appropriate error diagnostics. 1488 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1489 SourceLocation Loc, 1490 ArithConvKind ACK) { 1491 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1492 1493 if (ACK != ACK_CompAssign) { 1494 LHS = UsualUnaryConversions(LHS.get()); 1495 if (LHS.isInvalid()) 1496 return QualType(); 1497 } 1498 1499 RHS = UsualUnaryConversions(RHS.get()); 1500 if (RHS.isInvalid()) 1501 return QualType(); 1502 1503 // For conversion purposes, we ignore any qualifiers. 1504 // For example, "const float" and "float" are equivalent. 1505 QualType LHSType = 1506 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1507 QualType RHSType = 1508 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1509 1510 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1511 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1512 LHSType = AtomicLHS->getValueType(); 1513 1514 // If both types are identical, no conversion is needed. 1515 if (LHSType == RHSType) 1516 return LHSType; 1517 1518 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1519 // The caller can deal with this (e.g. pointer + int). 1520 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1521 return QualType(); 1522 1523 // Apply unary and bitfield promotions to the LHS's type. 1524 QualType LHSUnpromotedType = LHSType; 1525 if (LHSType->isPromotableIntegerType()) 1526 LHSType = Context.getPromotedIntegerType(LHSType); 1527 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1528 if (!LHSBitfieldPromoteTy.isNull()) 1529 LHSType = LHSBitfieldPromoteTy; 1530 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1531 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1532 1533 // If both types are identical, no conversion is needed. 1534 if (LHSType == RHSType) 1535 return LHSType; 1536 1537 // At this point, we have two different arithmetic types. 1538 1539 // Diagnose attempts to convert between __ibm128, __float128 and long double 1540 // where such conversions currently can't be handled. 1541 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1542 return QualType(); 1543 1544 // Handle complex types first (C99 6.3.1.8p1). 1545 if (LHSType->isComplexType() || RHSType->isComplexType()) 1546 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1547 ACK == ACK_CompAssign); 1548 1549 // Now handle "real" floating types (i.e. float, double, long double). 1550 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1551 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1552 ACK == ACK_CompAssign); 1553 1554 // Handle GCC complex int extension. 1555 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1556 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1557 ACK == ACK_CompAssign); 1558 1559 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1560 return handleFixedPointConversion(*this, LHSType, RHSType); 1561 1562 // Finally, we have two differing integer types. 1563 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1564 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1565 } 1566 1567 //===----------------------------------------------------------------------===// 1568 // Semantic Analysis for various Expression Types 1569 //===----------------------------------------------------------------------===// 1570 1571 1572 ExprResult 1573 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1574 SourceLocation DefaultLoc, 1575 SourceLocation RParenLoc, 1576 Expr *ControllingExpr, 1577 ArrayRef<ParsedType> ArgTypes, 1578 ArrayRef<Expr *> ArgExprs) { 1579 unsigned NumAssocs = ArgTypes.size(); 1580 assert(NumAssocs == ArgExprs.size()); 1581 1582 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1583 for (unsigned i = 0; i < NumAssocs; ++i) { 1584 if (ArgTypes[i]) 1585 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1586 else 1587 Types[i] = nullptr; 1588 } 1589 1590 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1591 ControllingExpr, 1592 llvm::makeArrayRef(Types, NumAssocs), 1593 ArgExprs); 1594 delete [] Types; 1595 return ER; 1596 } 1597 1598 ExprResult 1599 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1600 SourceLocation DefaultLoc, 1601 SourceLocation RParenLoc, 1602 Expr *ControllingExpr, 1603 ArrayRef<TypeSourceInfo *> Types, 1604 ArrayRef<Expr *> Exprs) { 1605 unsigned NumAssocs = Types.size(); 1606 assert(NumAssocs == Exprs.size()); 1607 1608 // Decay and strip qualifiers for the controlling expression type, and handle 1609 // placeholder type replacement. See committee discussion from WG14 DR423. 1610 { 1611 EnterExpressionEvaluationContext Unevaluated( 1612 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1613 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1614 if (R.isInvalid()) 1615 return ExprError(); 1616 ControllingExpr = R.get(); 1617 } 1618 1619 // The controlling expression is an unevaluated operand, so side effects are 1620 // likely unintended. 1621 if (!inTemplateInstantiation() && 1622 ControllingExpr->HasSideEffects(Context, false)) 1623 Diag(ControllingExpr->getExprLoc(), 1624 diag::warn_side_effects_unevaluated_context); 1625 1626 bool TypeErrorFound = false, 1627 IsResultDependent = ControllingExpr->isTypeDependent(), 1628 ContainsUnexpandedParameterPack 1629 = ControllingExpr->containsUnexpandedParameterPack(); 1630 1631 for (unsigned i = 0; i < NumAssocs; ++i) { 1632 if (Exprs[i]->containsUnexpandedParameterPack()) 1633 ContainsUnexpandedParameterPack = true; 1634 1635 if (Types[i]) { 1636 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1637 ContainsUnexpandedParameterPack = true; 1638 1639 if (Types[i]->getType()->isDependentType()) { 1640 IsResultDependent = true; 1641 } else { 1642 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1643 // complete object type other than a variably modified type." 1644 unsigned D = 0; 1645 if (Types[i]->getType()->isIncompleteType()) 1646 D = diag::err_assoc_type_incomplete; 1647 else if (!Types[i]->getType()->isObjectType()) 1648 D = diag::err_assoc_type_nonobject; 1649 else if (Types[i]->getType()->isVariablyModifiedType()) 1650 D = diag::err_assoc_type_variably_modified; 1651 1652 if (D != 0) { 1653 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1654 << Types[i]->getTypeLoc().getSourceRange() 1655 << Types[i]->getType(); 1656 TypeErrorFound = true; 1657 } 1658 1659 // C11 6.5.1.1p2 "No two generic associations in the same generic 1660 // selection shall specify compatible types." 1661 for (unsigned j = i+1; j < NumAssocs; ++j) 1662 if (Types[j] && !Types[j]->getType()->isDependentType() && 1663 Context.typesAreCompatible(Types[i]->getType(), 1664 Types[j]->getType())) { 1665 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1666 diag::err_assoc_compatible_types) 1667 << Types[j]->getTypeLoc().getSourceRange() 1668 << Types[j]->getType() 1669 << Types[i]->getType(); 1670 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1671 diag::note_compat_assoc) 1672 << Types[i]->getTypeLoc().getSourceRange() 1673 << Types[i]->getType(); 1674 TypeErrorFound = true; 1675 } 1676 } 1677 } 1678 } 1679 if (TypeErrorFound) 1680 return ExprError(); 1681 1682 // If we determined that the generic selection is result-dependent, don't 1683 // try to compute the result expression. 1684 if (IsResultDependent) 1685 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1686 Exprs, DefaultLoc, RParenLoc, 1687 ContainsUnexpandedParameterPack); 1688 1689 SmallVector<unsigned, 1> CompatIndices; 1690 unsigned DefaultIndex = -1U; 1691 for (unsigned i = 0; i < NumAssocs; ++i) { 1692 if (!Types[i]) 1693 DefaultIndex = i; 1694 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1695 Types[i]->getType())) 1696 CompatIndices.push_back(i); 1697 } 1698 1699 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1700 // type compatible with at most one of the types named in its generic 1701 // association list." 1702 if (CompatIndices.size() > 1) { 1703 // We strip parens here because the controlling expression is typically 1704 // parenthesized in macro definitions. 1705 ControllingExpr = ControllingExpr->IgnoreParens(); 1706 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1707 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1708 << (unsigned)CompatIndices.size(); 1709 for (unsigned I : CompatIndices) { 1710 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1711 diag::note_compat_assoc) 1712 << Types[I]->getTypeLoc().getSourceRange() 1713 << Types[I]->getType(); 1714 } 1715 return ExprError(); 1716 } 1717 1718 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1719 // its controlling expression shall have type compatible with exactly one of 1720 // the types named in its generic association list." 1721 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1722 // We strip parens here because the controlling expression is typically 1723 // parenthesized in macro definitions. 1724 ControllingExpr = ControllingExpr->IgnoreParens(); 1725 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1726 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1727 return ExprError(); 1728 } 1729 1730 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1731 // type name that is compatible with the type of the controlling expression, 1732 // then the result expression of the generic selection is the expression 1733 // in that generic association. Otherwise, the result expression of the 1734 // generic selection is the expression in the default generic association." 1735 unsigned ResultIndex = 1736 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1737 1738 return GenericSelectionExpr::Create( 1739 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1740 ContainsUnexpandedParameterPack, ResultIndex); 1741 } 1742 1743 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1744 /// location of the token and the offset of the ud-suffix within it. 1745 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1746 unsigned Offset) { 1747 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1748 S.getLangOpts()); 1749 } 1750 1751 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1752 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1753 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1754 IdentifierInfo *UDSuffix, 1755 SourceLocation UDSuffixLoc, 1756 ArrayRef<Expr*> Args, 1757 SourceLocation LitEndLoc) { 1758 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1759 1760 QualType ArgTy[2]; 1761 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1762 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1763 if (ArgTy[ArgIdx]->isArrayType()) 1764 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1765 } 1766 1767 DeclarationName OpName = 1768 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1769 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1770 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1771 1772 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1773 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1774 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1775 /*AllowStringTemplatePack*/ false, 1776 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1777 return ExprError(); 1778 1779 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1780 } 1781 1782 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1783 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1784 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1785 /// multiple tokens. However, the common case is that StringToks points to one 1786 /// string. 1787 /// 1788 ExprResult 1789 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1790 assert(!StringToks.empty() && "Must have at least one string!"); 1791 1792 StringLiteralParser Literal(StringToks, PP); 1793 if (Literal.hadError) 1794 return ExprError(); 1795 1796 SmallVector<SourceLocation, 4> StringTokLocs; 1797 for (const Token &Tok : StringToks) 1798 StringTokLocs.push_back(Tok.getLocation()); 1799 1800 QualType CharTy = Context.CharTy; 1801 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1802 if (Literal.isWide()) { 1803 CharTy = Context.getWideCharType(); 1804 Kind = StringLiteral::Wide; 1805 } else if (Literal.isUTF8()) { 1806 if (getLangOpts().Char8) 1807 CharTy = Context.Char8Ty; 1808 Kind = StringLiteral::UTF8; 1809 } else if (Literal.isUTF16()) { 1810 CharTy = Context.Char16Ty; 1811 Kind = StringLiteral::UTF16; 1812 } else if (Literal.isUTF32()) { 1813 CharTy = Context.Char32Ty; 1814 Kind = StringLiteral::UTF32; 1815 } else if (Literal.isPascal()) { 1816 CharTy = Context.UnsignedCharTy; 1817 } 1818 1819 // Warn on initializing an array of char from a u8 string literal; this 1820 // becomes ill-formed in C++2a. 1821 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1822 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1823 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1824 1825 // Create removals for all 'u8' prefixes in the string literal(s). This 1826 // ensures C++2a compatibility (but may change the program behavior when 1827 // built by non-Clang compilers for which the execution character set is 1828 // not always UTF-8). 1829 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1830 SourceLocation RemovalDiagLoc; 1831 for (const Token &Tok : StringToks) { 1832 if (Tok.getKind() == tok::utf8_string_literal) { 1833 if (RemovalDiagLoc.isInvalid()) 1834 RemovalDiagLoc = Tok.getLocation(); 1835 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1836 Tok.getLocation(), 1837 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1838 getSourceManager(), getLangOpts()))); 1839 } 1840 } 1841 Diag(RemovalDiagLoc, RemovalDiag); 1842 } 1843 1844 QualType StrTy = 1845 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1846 1847 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1848 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1849 Kind, Literal.Pascal, StrTy, 1850 &StringTokLocs[0], 1851 StringTokLocs.size()); 1852 if (Literal.getUDSuffix().empty()) 1853 return Lit; 1854 1855 // We're building a user-defined literal. 1856 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1857 SourceLocation UDSuffixLoc = 1858 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1859 Literal.getUDSuffixOffset()); 1860 1861 // Make sure we're allowed user-defined literals here. 1862 if (!UDLScope) 1863 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1864 1865 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1866 // operator "" X (str, len) 1867 QualType SizeType = Context.getSizeType(); 1868 1869 DeclarationName OpName = 1870 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1871 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1872 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1873 1874 QualType ArgTy[] = { 1875 Context.getArrayDecayedType(StrTy), SizeType 1876 }; 1877 1878 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1879 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1880 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1881 /*AllowStringTemplatePack*/ true, 1882 /*DiagnoseMissing*/ true, Lit)) { 1883 1884 case LOLR_Cooked: { 1885 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1886 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1887 StringTokLocs[0]); 1888 Expr *Args[] = { Lit, LenArg }; 1889 1890 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1891 } 1892 1893 case LOLR_Template: { 1894 TemplateArgumentListInfo ExplicitArgs; 1895 TemplateArgument Arg(Lit); 1896 TemplateArgumentLocInfo ArgInfo(Lit); 1897 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1898 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1899 &ExplicitArgs); 1900 } 1901 1902 case LOLR_StringTemplatePack: { 1903 TemplateArgumentListInfo ExplicitArgs; 1904 1905 unsigned CharBits = Context.getIntWidth(CharTy); 1906 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1907 llvm::APSInt Value(CharBits, CharIsUnsigned); 1908 1909 TemplateArgument TypeArg(CharTy); 1910 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1911 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1912 1913 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1914 Value = Lit->getCodeUnit(I); 1915 TemplateArgument Arg(Context, Value, CharTy); 1916 TemplateArgumentLocInfo ArgInfo; 1917 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1918 } 1919 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1920 &ExplicitArgs); 1921 } 1922 case LOLR_Raw: 1923 case LOLR_ErrorNoDiagnostic: 1924 llvm_unreachable("unexpected literal operator lookup result"); 1925 case LOLR_Error: 1926 return ExprError(); 1927 } 1928 llvm_unreachable("unexpected literal operator lookup result"); 1929 } 1930 1931 DeclRefExpr * 1932 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1933 SourceLocation Loc, 1934 const CXXScopeSpec *SS) { 1935 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1936 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1937 } 1938 1939 DeclRefExpr * 1940 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1941 const DeclarationNameInfo &NameInfo, 1942 const CXXScopeSpec *SS, NamedDecl *FoundD, 1943 SourceLocation TemplateKWLoc, 1944 const TemplateArgumentListInfo *TemplateArgs) { 1945 NestedNameSpecifierLoc NNS = 1946 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1947 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1948 TemplateArgs); 1949 } 1950 1951 // CUDA/HIP: Check whether a captured reference variable is referencing a 1952 // host variable in a device or host device lambda. 1953 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1954 VarDecl *VD) { 1955 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1956 return false; 1957 assert(VD->getType()->isReferenceType()); 1958 1959 // Check whether the reference variable is referencing a host variable. 1960 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1961 if (!DRE) 1962 return false; 1963 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1964 if (!Referee || !Referee->hasGlobalStorage() || 1965 Referee->hasAttr<CUDADeviceAttr>()) 1966 return false; 1967 1968 // Check whether the current function is a device or host device lambda. 1969 // Check whether the reference variable is a capture by getDeclContext() 1970 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1971 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1972 if (MD && MD->getParent()->isLambda() && 1973 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1974 VD->getDeclContext() != MD) 1975 return true; 1976 1977 return false; 1978 } 1979 1980 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1981 // A declaration named in an unevaluated operand never constitutes an odr-use. 1982 if (isUnevaluatedContext()) 1983 return NOUR_Unevaluated; 1984 1985 // C++2a [basic.def.odr]p4: 1986 // A variable x whose name appears as a potentially-evaluated expression e 1987 // is odr-used by e unless [...] x is a reference that is usable in 1988 // constant expressions. 1989 // CUDA/HIP: 1990 // If a reference variable referencing a host variable is captured in a 1991 // device or host device lambda, the value of the referee must be copied 1992 // to the capture and the reference variable must be treated as odr-use 1993 // since the value of the referee is not known at compile time and must 1994 // be loaded from the captured. 1995 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1996 if (VD->getType()->isReferenceType() && 1997 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1998 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 1999 VD->isUsableInConstantExpressions(Context)) 2000 return NOUR_Constant; 2001 } 2002 2003 // All remaining non-variable cases constitute an odr-use. For variables, we 2004 // need to wait and see how the expression is used. 2005 return NOUR_None; 2006 } 2007 2008 /// BuildDeclRefExpr - Build an expression that references a 2009 /// declaration that does not require a closure capture. 2010 DeclRefExpr * 2011 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2012 const DeclarationNameInfo &NameInfo, 2013 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2014 SourceLocation TemplateKWLoc, 2015 const TemplateArgumentListInfo *TemplateArgs) { 2016 bool RefersToCapturedVariable = 2017 isa<VarDecl>(D) && 2018 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2019 2020 DeclRefExpr *E = DeclRefExpr::Create( 2021 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2022 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2023 MarkDeclRefReferenced(E); 2024 2025 // C++ [except.spec]p17: 2026 // An exception-specification is considered to be needed when: 2027 // - in an expression, the function is the unique lookup result or 2028 // the selected member of a set of overloaded functions. 2029 // 2030 // We delay doing this until after we've built the function reference and 2031 // marked it as used so that: 2032 // a) if the function is defaulted, we get errors from defining it before / 2033 // instead of errors from computing its exception specification, and 2034 // b) if the function is a defaulted comparison, we can use the body we 2035 // build when defining it as input to the exception specification 2036 // computation rather than computing a new body. 2037 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2038 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2039 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2040 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2041 } 2042 } 2043 2044 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2045 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2046 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2047 getCurFunction()->recordUseOfWeak(E); 2048 2049 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2050 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2051 FD = IFD->getAnonField(); 2052 if (FD) { 2053 UnusedPrivateFields.remove(FD); 2054 // Just in case we're building an illegal pointer-to-member. 2055 if (FD->isBitField()) 2056 E->setObjectKind(OK_BitField); 2057 } 2058 2059 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2060 // designates a bit-field. 2061 if (auto *BD = dyn_cast<BindingDecl>(D)) 2062 if (auto *BE = BD->getBinding()) 2063 E->setObjectKind(BE->getObjectKind()); 2064 2065 return E; 2066 } 2067 2068 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2069 /// possibly a list of template arguments. 2070 /// 2071 /// If this produces template arguments, it is permitted to call 2072 /// DecomposeTemplateName. 2073 /// 2074 /// This actually loses a lot of source location information for 2075 /// non-standard name kinds; we should consider preserving that in 2076 /// some way. 2077 void 2078 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2079 TemplateArgumentListInfo &Buffer, 2080 DeclarationNameInfo &NameInfo, 2081 const TemplateArgumentListInfo *&TemplateArgs) { 2082 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2083 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2084 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2085 2086 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2087 Id.TemplateId->NumArgs); 2088 translateTemplateArguments(TemplateArgsPtr, Buffer); 2089 2090 TemplateName TName = Id.TemplateId->Template.get(); 2091 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2092 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2093 TemplateArgs = &Buffer; 2094 } else { 2095 NameInfo = GetNameFromUnqualifiedId(Id); 2096 TemplateArgs = nullptr; 2097 } 2098 } 2099 2100 static void emitEmptyLookupTypoDiagnostic( 2101 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2102 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2103 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2104 DeclContext *Ctx = 2105 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2106 if (!TC) { 2107 // Emit a special diagnostic for failed member lookups. 2108 // FIXME: computing the declaration context might fail here (?) 2109 if (Ctx) 2110 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2111 << SS.getRange(); 2112 else 2113 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2114 return; 2115 } 2116 2117 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2118 bool DroppedSpecifier = 2119 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2120 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2121 ? diag::note_implicit_param_decl 2122 : diag::note_previous_decl; 2123 if (!Ctx) 2124 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2125 SemaRef.PDiag(NoteID)); 2126 else 2127 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2128 << Typo << Ctx << DroppedSpecifier 2129 << SS.getRange(), 2130 SemaRef.PDiag(NoteID)); 2131 } 2132 2133 /// Diagnose a lookup that found results in an enclosing class during error 2134 /// recovery. This usually indicates that the results were found in a dependent 2135 /// base class that could not be searched as part of a template definition. 2136 /// Always issues a diagnostic (though this may be only a warning in MS 2137 /// compatibility mode). 2138 /// 2139 /// Return \c true if the error is unrecoverable, or \c false if the caller 2140 /// should attempt to recover using these lookup results. 2141 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2142 // During a default argument instantiation the CurContext points 2143 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2144 // function parameter list, hence add an explicit check. 2145 bool isDefaultArgument = 2146 !CodeSynthesisContexts.empty() && 2147 CodeSynthesisContexts.back().Kind == 2148 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2149 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2150 bool isInstance = CurMethod && CurMethod->isInstance() && 2151 R.getNamingClass() == CurMethod->getParent() && 2152 !isDefaultArgument; 2153 2154 // There are two ways we can find a class-scope declaration during template 2155 // instantiation that we did not find in the template definition: if it is a 2156 // member of a dependent base class, or if it is declared after the point of 2157 // use in the same class. Distinguish these by comparing the class in which 2158 // the member was found to the naming class of the lookup. 2159 unsigned DiagID = diag::err_found_in_dependent_base; 2160 unsigned NoteID = diag::note_member_declared_at; 2161 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2162 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2163 : diag::err_found_later_in_class; 2164 } else if (getLangOpts().MSVCCompat) { 2165 DiagID = diag::ext_found_in_dependent_base; 2166 NoteID = diag::note_dependent_member_use; 2167 } 2168 2169 if (isInstance) { 2170 // Give a code modification hint to insert 'this->'. 2171 Diag(R.getNameLoc(), DiagID) 2172 << R.getLookupName() 2173 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2174 CheckCXXThisCapture(R.getNameLoc()); 2175 } else { 2176 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2177 // they're not shadowed). 2178 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2179 } 2180 2181 for (NamedDecl *D : R) 2182 Diag(D->getLocation(), NoteID); 2183 2184 // Return true if we are inside a default argument instantiation 2185 // and the found name refers to an instance member function, otherwise 2186 // the caller will try to create an implicit member call and this is wrong 2187 // for default arguments. 2188 // 2189 // FIXME: Is this special case necessary? We could allow the caller to 2190 // diagnose this. 2191 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2192 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2193 return true; 2194 } 2195 2196 // Tell the callee to try to recover. 2197 return false; 2198 } 2199 2200 /// Diagnose an empty lookup. 2201 /// 2202 /// \return false if new lookup candidates were found 2203 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2204 CorrectionCandidateCallback &CCC, 2205 TemplateArgumentListInfo *ExplicitTemplateArgs, 2206 ArrayRef<Expr *> Args, TypoExpr **Out) { 2207 DeclarationName Name = R.getLookupName(); 2208 2209 unsigned diagnostic = diag::err_undeclared_var_use; 2210 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2211 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2212 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2213 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2214 diagnostic = diag::err_undeclared_use; 2215 diagnostic_suggest = diag::err_undeclared_use_suggest; 2216 } 2217 2218 // If the original lookup was an unqualified lookup, fake an 2219 // unqualified lookup. This is useful when (for example) the 2220 // original lookup would not have found something because it was a 2221 // dependent name. 2222 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2223 while (DC) { 2224 if (isa<CXXRecordDecl>(DC)) { 2225 LookupQualifiedName(R, DC); 2226 2227 if (!R.empty()) { 2228 // Don't give errors about ambiguities in this lookup. 2229 R.suppressDiagnostics(); 2230 2231 // If there's a best viable function among the results, only mention 2232 // that one in the notes. 2233 OverloadCandidateSet Candidates(R.getNameLoc(), 2234 OverloadCandidateSet::CSK_Normal); 2235 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2236 OverloadCandidateSet::iterator Best; 2237 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2238 OR_Success) { 2239 R.clear(); 2240 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2241 R.resolveKind(); 2242 } 2243 2244 return DiagnoseDependentMemberLookup(R); 2245 } 2246 2247 R.clear(); 2248 } 2249 2250 DC = DC->getLookupParent(); 2251 } 2252 2253 // We didn't find anything, so try to correct for a typo. 2254 TypoCorrection Corrected; 2255 if (S && Out) { 2256 SourceLocation TypoLoc = R.getNameLoc(); 2257 assert(!ExplicitTemplateArgs && 2258 "Diagnosing an empty lookup with explicit template args!"); 2259 *Out = CorrectTypoDelayed( 2260 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2261 [=](const TypoCorrection &TC) { 2262 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2263 diagnostic, diagnostic_suggest); 2264 }, 2265 nullptr, CTK_ErrorRecovery); 2266 if (*Out) 2267 return true; 2268 } else if (S && 2269 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2270 S, &SS, CCC, CTK_ErrorRecovery))) { 2271 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2272 bool DroppedSpecifier = 2273 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2274 R.setLookupName(Corrected.getCorrection()); 2275 2276 bool AcceptableWithRecovery = false; 2277 bool AcceptableWithoutRecovery = false; 2278 NamedDecl *ND = Corrected.getFoundDecl(); 2279 if (ND) { 2280 if (Corrected.isOverloaded()) { 2281 OverloadCandidateSet OCS(R.getNameLoc(), 2282 OverloadCandidateSet::CSK_Normal); 2283 OverloadCandidateSet::iterator Best; 2284 for (NamedDecl *CD : Corrected) { 2285 if (FunctionTemplateDecl *FTD = 2286 dyn_cast<FunctionTemplateDecl>(CD)) 2287 AddTemplateOverloadCandidate( 2288 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2289 Args, OCS); 2290 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2291 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2292 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2293 Args, OCS); 2294 } 2295 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2296 case OR_Success: 2297 ND = Best->FoundDecl; 2298 Corrected.setCorrectionDecl(ND); 2299 break; 2300 default: 2301 // FIXME: Arbitrarily pick the first declaration for the note. 2302 Corrected.setCorrectionDecl(ND); 2303 break; 2304 } 2305 } 2306 R.addDecl(ND); 2307 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2308 CXXRecordDecl *Record = nullptr; 2309 if (Corrected.getCorrectionSpecifier()) { 2310 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2311 Record = Ty->getAsCXXRecordDecl(); 2312 } 2313 if (!Record) 2314 Record = cast<CXXRecordDecl>( 2315 ND->getDeclContext()->getRedeclContext()); 2316 R.setNamingClass(Record); 2317 } 2318 2319 auto *UnderlyingND = ND->getUnderlyingDecl(); 2320 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2321 isa<FunctionTemplateDecl>(UnderlyingND); 2322 // FIXME: If we ended up with a typo for a type name or 2323 // Objective-C class name, we're in trouble because the parser 2324 // is in the wrong place to recover. Suggest the typo 2325 // correction, but don't make it a fix-it since we're not going 2326 // to recover well anyway. 2327 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2328 getAsTypeTemplateDecl(UnderlyingND) || 2329 isa<ObjCInterfaceDecl>(UnderlyingND); 2330 } else { 2331 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2332 // because we aren't able to recover. 2333 AcceptableWithoutRecovery = true; 2334 } 2335 2336 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2337 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2338 ? diag::note_implicit_param_decl 2339 : diag::note_previous_decl; 2340 if (SS.isEmpty()) 2341 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2342 PDiag(NoteID), AcceptableWithRecovery); 2343 else 2344 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2345 << Name << computeDeclContext(SS, false) 2346 << DroppedSpecifier << SS.getRange(), 2347 PDiag(NoteID), AcceptableWithRecovery); 2348 2349 // Tell the callee whether to try to recover. 2350 return !AcceptableWithRecovery; 2351 } 2352 } 2353 R.clear(); 2354 2355 // Emit a special diagnostic for failed member lookups. 2356 // FIXME: computing the declaration context might fail here (?) 2357 if (!SS.isEmpty()) { 2358 Diag(R.getNameLoc(), diag::err_no_member) 2359 << Name << computeDeclContext(SS, false) 2360 << SS.getRange(); 2361 return true; 2362 } 2363 2364 // Give up, we can't recover. 2365 Diag(R.getNameLoc(), diagnostic) << Name; 2366 return true; 2367 } 2368 2369 /// In Microsoft mode, if we are inside a template class whose parent class has 2370 /// dependent base classes, and we can't resolve an unqualified identifier, then 2371 /// assume the identifier is a member of a dependent base class. We can only 2372 /// recover successfully in static methods, instance methods, and other contexts 2373 /// where 'this' is available. This doesn't precisely match MSVC's 2374 /// instantiation model, but it's close enough. 2375 static Expr * 2376 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2377 DeclarationNameInfo &NameInfo, 2378 SourceLocation TemplateKWLoc, 2379 const TemplateArgumentListInfo *TemplateArgs) { 2380 // Only try to recover from lookup into dependent bases in static methods or 2381 // contexts where 'this' is available. 2382 QualType ThisType = S.getCurrentThisType(); 2383 const CXXRecordDecl *RD = nullptr; 2384 if (!ThisType.isNull()) 2385 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2386 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2387 RD = MD->getParent(); 2388 if (!RD || !RD->hasAnyDependentBases()) 2389 return nullptr; 2390 2391 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2392 // is available, suggest inserting 'this->' as a fixit. 2393 SourceLocation Loc = NameInfo.getLoc(); 2394 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2395 DB << NameInfo.getName() << RD; 2396 2397 if (!ThisType.isNull()) { 2398 DB << FixItHint::CreateInsertion(Loc, "this->"); 2399 return CXXDependentScopeMemberExpr::Create( 2400 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2401 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2402 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2403 } 2404 2405 // Synthesize a fake NNS that points to the derived class. This will 2406 // perform name lookup during template instantiation. 2407 CXXScopeSpec SS; 2408 auto *NNS = 2409 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2410 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2411 return DependentScopeDeclRefExpr::Create( 2412 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2413 TemplateArgs); 2414 } 2415 2416 ExprResult 2417 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2418 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2419 bool HasTrailingLParen, bool IsAddressOfOperand, 2420 CorrectionCandidateCallback *CCC, 2421 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2422 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2423 "cannot be direct & operand and have a trailing lparen"); 2424 if (SS.isInvalid()) 2425 return ExprError(); 2426 2427 TemplateArgumentListInfo TemplateArgsBuffer; 2428 2429 // Decompose the UnqualifiedId into the following data. 2430 DeclarationNameInfo NameInfo; 2431 const TemplateArgumentListInfo *TemplateArgs; 2432 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2433 2434 DeclarationName Name = NameInfo.getName(); 2435 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2436 SourceLocation NameLoc = NameInfo.getLoc(); 2437 2438 if (II && II->isEditorPlaceholder()) { 2439 // FIXME: When typed placeholders are supported we can create a typed 2440 // placeholder expression node. 2441 return ExprError(); 2442 } 2443 2444 // C++ [temp.dep.expr]p3: 2445 // An id-expression is type-dependent if it contains: 2446 // -- an identifier that was declared with a dependent type, 2447 // (note: handled after lookup) 2448 // -- a template-id that is dependent, 2449 // (note: handled in BuildTemplateIdExpr) 2450 // -- a conversion-function-id that specifies a dependent type, 2451 // -- a nested-name-specifier that contains a class-name that 2452 // names a dependent type. 2453 // Determine whether this is a member of an unknown specialization; 2454 // we need to handle these differently. 2455 bool DependentID = false; 2456 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2457 Name.getCXXNameType()->isDependentType()) { 2458 DependentID = true; 2459 } else if (SS.isSet()) { 2460 if (DeclContext *DC = computeDeclContext(SS, false)) { 2461 if (RequireCompleteDeclContext(SS, DC)) 2462 return ExprError(); 2463 } else { 2464 DependentID = true; 2465 } 2466 } 2467 2468 if (DependentID) 2469 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2470 IsAddressOfOperand, TemplateArgs); 2471 2472 // Perform the required lookup. 2473 LookupResult R(*this, NameInfo, 2474 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2475 ? LookupObjCImplicitSelfParam 2476 : LookupOrdinaryName); 2477 if (TemplateKWLoc.isValid() || TemplateArgs) { 2478 // Lookup the template name again to correctly establish the context in 2479 // which it was found. This is really unfortunate as we already did the 2480 // lookup to determine that it was a template name in the first place. If 2481 // this becomes a performance hit, we can work harder to preserve those 2482 // results until we get here but it's likely not worth it. 2483 bool MemberOfUnknownSpecialization; 2484 AssumedTemplateKind AssumedTemplate; 2485 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2486 MemberOfUnknownSpecialization, TemplateKWLoc, 2487 &AssumedTemplate)) 2488 return ExprError(); 2489 2490 if (MemberOfUnknownSpecialization || 2491 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2492 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2493 IsAddressOfOperand, TemplateArgs); 2494 } else { 2495 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2496 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2497 2498 // If the result might be in a dependent base class, this is a dependent 2499 // id-expression. 2500 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2501 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2502 IsAddressOfOperand, TemplateArgs); 2503 2504 // If this reference is in an Objective-C method, then we need to do 2505 // some special Objective-C lookup, too. 2506 if (IvarLookupFollowUp) { 2507 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2508 if (E.isInvalid()) 2509 return ExprError(); 2510 2511 if (Expr *Ex = E.getAs<Expr>()) 2512 return Ex; 2513 } 2514 } 2515 2516 if (R.isAmbiguous()) 2517 return ExprError(); 2518 2519 // This could be an implicitly declared function reference (legal in C90, 2520 // extension in C99, forbidden in C++). 2521 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2522 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2523 if (D) R.addDecl(D); 2524 } 2525 2526 // Determine whether this name might be a candidate for 2527 // argument-dependent lookup. 2528 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2529 2530 if (R.empty() && !ADL) { 2531 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2532 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2533 TemplateKWLoc, TemplateArgs)) 2534 return E; 2535 } 2536 2537 // Don't diagnose an empty lookup for inline assembly. 2538 if (IsInlineAsmIdentifier) 2539 return ExprError(); 2540 2541 // If this name wasn't predeclared and if this is not a function 2542 // call, diagnose the problem. 2543 TypoExpr *TE = nullptr; 2544 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2545 : nullptr); 2546 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2547 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2548 "Typo correction callback misconfigured"); 2549 if (CCC) { 2550 // Make sure the callback knows what the typo being diagnosed is. 2551 CCC->setTypoName(II); 2552 if (SS.isValid()) 2553 CCC->setTypoNNS(SS.getScopeRep()); 2554 } 2555 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2556 // a template name, but we happen to have always already looked up the name 2557 // before we get here if it must be a template name. 2558 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2559 None, &TE)) { 2560 if (TE && KeywordReplacement) { 2561 auto &State = getTypoExprState(TE); 2562 auto BestTC = State.Consumer->getNextCorrection(); 2563 if (BestTC.isKeyword()) { 2564 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2565 if (State.DiagHandler) 2566 State.DiagHandler(BestTC); 2567 KeywordReplacement->startToken(); 2568 KeywordReplacement->setKind(II->getTokenID()); 2569 KeywordReplacement->setIdentifierInfo(II); 2570 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2571 // Clean up the state associated with the TypoExpr, since it has 2572 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2573 clearDelayedTypo(TE); 2574 // Signal that a correction to a keyword was performed by returning a 2575 // valid-but-null ExprResult. 2576 return (Expr*)nullptr; 2577 } 2578 State.Consumer->resetCorrectionStream(); 2579 } 2580 return TE ? TE : ExprError(); 2581 } 2582 2583 assert(!R.empty() && 2584 "DiagnoseEmptyLookup returned false but added no results"); 2585 2586 // If we found an Objective-C instance variable, let 2587 // LookupInObjCMethod build the appropriate expression to 2588 // reference the ivar. 2589 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2590 R.clear(); 2591 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2592 // In a hopelessly buggy code, Objective-C instance variable 2593 // lookup fails and no expression will be built to reference it. 2594 if (!E.isInvalid() && !E.get()) 2595 return ExprError(); 2596 return E; 2597 } 2598 } 2599 2600 // This is guaranteed from this point on. 2601 assert(!R.empty() || ADL); 2602 2603 // Check whether this might be a C++ implicit instance member access. 2604 // C++ [class.mfct.non-static]p3: 2605 // When an id-expression that is not part of a class member access 2606 // syntax and not used to form a pointer to member is used in the 2607 // body of a non-static member function of class X, if name lookup 2608 // resolves the name in the id-expression to a non-static non-type 2609 // member of some class C, the id-expression is transformed into a 2610 // class member access expression using (*this) as the 2611 // postfix-expression to the left of the . operator. 2612 // 2613 // But we don't actually need to do this for '&' operands if R 2614 // resolved to a function or overloaded function set, because the 2615 // expression is ill-formed if it actually works out to be a 2616 // non-static member function: 2617 // 2618 // C++ [expr.ref]p4: 2619 // Otherwise, if E1.E2 refers to a non-static member function. . . 2620 // [t]he expression can be used only as the left-hand operand of a 2621 // member function call. 2622 // 2623 // There are other safeguards against such uses, but it's important 2624 // to get this right here so that we don't end up making a 2625 // spuriously dependent expression if we're inside a dependent 2626 // instance method. 2627 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2628 bool MightBeImplicitMember; 2629 if (!IsAddressOfOperand) 2630 MightBeImplicitMember = true; 2631 else if (!SS.isEmpty()) 2632 MightBeImplicitMember = false; 2633 else if (R.isOverloadedResult()) 2634 MightBeImplicitMember = false; 2635 else if (R.isUnresolvableResult()) 2636 MightBeImplicitMember = true; 2637 else 2638 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2639 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2640 isa<MSPropertyDecl>(R.getFoundDecl()); 2641 2642 if (MightBeImplicitMember) 2643 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2644 R, TemplateArgs, S); 2645 } 2646 2647 if (TemplateArgs || TemplateKWLoc.isValid()) { 2648 2649 // In C++1y, if this is a variable template id, then check it 2650 // in BuildTemplateIdExpr(). 2651 // The single lookup result must be a variable template declaration. 2652 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2653 Id.TemplateId->Kind == TNK_Var_template) { 2654 assert(R.getAsSingle<VarTemplateDecl>() && 2655 "There should only be one declaration found."); 2656 } 2657 2658 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2659 } 2660 2661 return BuildDeclarationNameExpr(SS, R, ADL); 2662 } 2663 2664 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2665 /// declaration name, generally during template instantiation. 2666 /// There's a large number of things which don't need to be done along 2667 /// this path. 2668 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2669 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2670 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2671 DeclContext *DC = computeDeclContext(SS, false); 2672 if (!DC) 2673 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2674 NameInfo, /*TemplateArgs=*/nullptr); 2675 2676 if (RequireCompleteDeclContext(SS, DC)) 2677 return ExprError(); 2678 2679 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2680 LookupQualifiedName(R, DC); 2681 2682 if (R.isAmbiguous()) 2683 return ExprError(); 2684 2685 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2686 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2687 NameInfo, /*TemplateArgs=*/nullptr); 2688 2689 if (R.empty()) { 2690 // Don't diagnose problems with invalid record decl, the secondary no_member 2691 // diagnostic during template instantiation is likely bogus, e.g. if a class 2692 // is invalid because it's derived from an invalid base class, then missing 2693 // members were likely supposed to be inherited. 2694 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2695 if (CD->isInvalidDecl()) 2696 return ExprError(); 2697 Diag(NameInfo.getLoc(), diag::err_no_member) 2698 << NameInfo.getName() << DC << SS.getRange(); 2699 return ExprError(); 2700 } 2701 2702 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2703 // Diagnose a missing typename if this resolved unambiguously to a type in 2704 // a dependent context. If we can recover with a type, downgrade this to 2705 // a warning in Microsoft compatibility mode. 2706 unsigned DiagID = diag::err_typename_missing; 2707 if (RecoveryTSI && getLangOpts().MSVCCompat) 2708 DiagID = diag::ext_typename_missing; 2709 SourceLocation Loc = SS.getBeginLoc(); 2710 auto D = Diag(Loc, DiagID); 2711 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2712 << SourceRange(Loc, NameInfo.getEndLoc()); 2713 2714 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2715 // context. 2716 if (!RecoveryTSI) 2717 return ExprError(); 2718 2719 // Only issue the fixit if we're prepared to recover. 2720 D << FixItHint::CreateInsertion(Loc, "typename "); 2721 2722 // Recover by pretending this was an elaborated type. 2723 QualType Ty = Context.getTypeDeclType(TD); 2724 TypeLocBuilder TLB; 2725 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2726 2727 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2728 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2729 QTL.setElaboratedKeywordLoc(SourceLocation()); 2730 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2731 2732 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2733 2734 return ExprEmpty(); 2735 } 2736 2737 // Defend against this resolving to an implicit member access. We usually 2738 // won't get here if this might be a legitimate a class member (we end up in 2739 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2740 // a pointer-to-member or in an unevaluated context in C++11. 2741 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2742 return BuildPossibleImplicitMemberExpr(SS, 2743 /*TemplateKWLoc=*/SourceLocation(), 2744 R, /*TemplateArgs=*/nullptr, S); 2745 2746 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2747 } 2748 2749 /// The parser has read a name in, and Sema has detected that we're currently 2750 /// inside an ObjC method. Perform some additional checks and determine if we 2751 /// should form a reference to an ivar. 2752 /// 2753 /// Ideally, most of this would be done by lookup, but there's 2754 /// actually quite a lot of extra work involved. 2755 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2756 IdentifierInfo *II) { 2757 SourceLocation Loc = Lookup.getNameLoc(); 2758 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2759 2760 // Check for error condition which is already reported. 2761 if (!CurMethod) 2762 return DeclResult(true); 2763 2764 // There are two cases to handle here. 1) scoped lookup could have failed, 2765 // in which case we should look for an ivar. 2) scoped lookup could have 2766 // found a decl, but that decl is outside the current instance method (i.e. 2767 // a global variable). In these two cases, we do a lookup for an ivar with 2768 // this name, if the lookup sucedes, we replace it our current decl. 2769 2770 // If we're in a class method, we don't normally want to look for 2771 // ivars. But if we don't find anything else, and there's an 2772 // ivar, that's an error. 2773 bool IsClassMethod = CurMethod->isClassMethod(); 2774 2775 bool LookForIvars; 2776 if (Lookup.empty()) 2777 LookForIvars = true; 2778 else if (IsClassMethod) 2779 LookForIvars = false; 2780 else 2781 LookForIvars = (Lookup.isSingleResult() && 2782 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2783 ObjCInterfaceDecl *IFace = nullptr; 2784 if (LookForIvars) { 2785 IFace = CurMethod->getClassInterface(); 2786 ObjCInterfaceDecl *ClassDeclared; 2787 ObjCIvarDecl *IV = nullptr; 2788 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2789 // Diagnose using an ivar in a class method. 2790 if (IsClassMethod) { 2791 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2792 return DeclResult(true); 2793 } 2794 2795 // Diagnose the use of an ivar outside of the declaring class. 2796 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2797 !declaresSameEntity(ClassDeclared, IFace) && 2798 !getLangOpts().DebuggerSupport) 2799 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2800 2801 // Success. 2802 return IV; 2803 } 2804 } else if (CurMethod->isInstanceMethod()) { 2805 // We should warn if a local variable hides an ivar. 2806 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2807 ObjCInterfaceDecl *ClassDeclared; 2808 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2809 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2810 declaresSameEntity(IFace, ClassDeclared)) 2811 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2812 } 2813 } 2814 } else if (Lookup.isSingleResult() && 2815 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2816 // If accessing a stand-alone ivar in a class method, this is an error. 2817 if (const ObjCIvarDecl *IV = 2818 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2819 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2820 return DeclResult(true); 2821 } 2822 } 2823 2824 // Didn't encounter an error, didn't find an ivar. 2825 return DeclResult(false); 2826 } 2827 2828 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2829 ObjCIvarDecl *IV) { 2830 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2831 assert(CurMethod && CurMethod->isInstanceMethod() && 2832 "should not reference ivar from this context"); 2833 2834 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2835 assert(IFace && "should not reference ivar from this context"); 2836 2837 // If we're referencing an invalid decl, just return this as a silent 2838 // error node. The error diagnostic was already emitted on the decl. 2839 if (IV->isInvalidDecl()) 2840 return ExprError(); 2841 2842 // Check if referencing a field with __attribute__((deprecated)). 2843 if (DiagnoseUseOfDecl(IV, Loc)) 2844 return ExprError(); 2845 2846 // FIXME: This should use a new expr for a direct reference, don't 2847 // turn this into Self->ivar, just return a BareIVarExpr or something. 2848 IdentifierInfo &II = Context.Idents.get("self"); 2849 UnqualifiedId SelfName; 2850 SelfName.setImplicitSelfParam(&II); 2851 CXXScopeSpec SelfScopeSpec; 2852 SourceLocation TemplateKWLoc; 2853 ExprResult SelfExpr = 2854 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2855 /*HasTrailingLParen=*/false, 2856 /*IsAddressOfOperand=*/false); 2857 if (SelfExpr.isInvalid()) 2858 return ExprError(); 2859 2860 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2861 if (SelfExpr.isInvalid()) 2862 return ExprError(); 2863 2864 MarkAnyDeclReferenced(Loc, IV, true); 2865 2866 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2867 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2868 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2869 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2870 2871 ObjCIvarRefExpr *Result = new (Context) 2872 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2873 IV->getLocation(), SelfExpr.get(), true, true); 2874 2875 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2876 if (!isUnevaluatedContext() && 2877 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2878 getCurFunction()->recordUseOfWeak(Result); 2879 } 2880 if (getLangOpts().ObjCAutoRefCount) 2881 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2882 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2883 2884 return Result; 2885 } 2886 2887 /// The parser has read a name in, and Sema has detected that we're currently 2888 /// inside an ObjC method. Perform some additional checks and determine if we 2889 /// should form a reference to an ivar. If so, build an expression referencing 2890 /// that ivar. 2891 ExprResult 2892 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2893 IdentifierInfo *II, bool AllowBuiltinCreation) { 2894 // FIXME: Integrate this lookup step into LookupParsedName. 2895 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2896 if (Ivar.isInvalid()) 2897 return ExprError(); 2898 if (Ivar.isUsable()) 2899 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2900 cast<ObjCIvarDecl>(Ivar.get())); 2901 2902 if (Lookup.empty() && II && AllowBuiltinCreation) 2903 LookupBuiltin(Lookup); 2904 2905 // Sentinel value saying that we didn't do anything special. 2906 return ExprResult(false); 2907 } 2908 2909 /// Cast a base object to a member's actual type. 2910 /// 2911 /// There are two relevant checks: 2912 /// 2913 /// C++ [class.access.base]p7: 2914 /// 2915 /// If a class member access operator [...] is used to access a non-static 2916 /// data member or non-static member function, the reference is ill-formed if 2917 /// the left operand [...] cannot be implicitly converted to a pointer to the 2918 /// naming class of the right operand. 2919 /// 2920 /// C++ [expr.ref]p7: 2921 /// 2922 /// If E2 is a non-static data member or a non-static member function, the 2923 /// program is ill-formed if the class of which E2 is directly a member is an 2924 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2925 /// 2926 /// Note that the latter check does not consider access; the access of the 2927 /// "real" base class is checked as appropriate when checking the access of the 2928 /// member name. 2929 ExprResult 2930 Sema::PerformObjectMemberConversion(Expr *From, 2931 NestedNameSpecifier *Qualifier, 2932 NamedDecl *FoundDecl, 2933 NamedDecl *Member) { 2934 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2935 if (!RD) 2936 return From; 2937 2938 QualType DestRecordType; 2939 QualType DestType; 2940 QualType FromRecordType; 2941 QualType FromType = From->getType(); 2942 bool PointerConversions = false; 2943 if (isa<FieldDecl>(Member)) { 2944 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2945 auto FromPtrType = FromType->getAs<PointerType>(); 2946 DestRecordType = Context.getAddrSpaceQualType( 2947 DestRecordType, FromPtrType 2948 ? FromType->getPointeeType().getAddressSpace() 2949 : FromType.getAddressSpace()); 2950 2951 if (FromPtrType) { 2952 DestType = Context.getPointerType(DestRecordType); 2953 FromRecordType = FromPtrType->getPointeeType(); 2954 PointerConversions = true; 2955 } else { 2956 DestType = DestRecordType; 2957 FromRecordType = FromType; 2958 } 2959 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2960 if (Method->isStatic()) 2961 return From; 2962 2963 DestType = Method->getThisType(); 2964 DestRecordType = DestType->getPointeeType(); 2965 2966 if (FromType->getAs<PointerType>()) { 2967 FromRecordType = FromType->getPointeeType(); 2968 PointerConversions = true; 2969 } else { 2970 FromRecordType = FromType; 2971 DestType = DestRecordType; 2972 } 2973 2974 LangAS FromAS = FromRecordType.getAddressSpace(); 2975 LangAS DestAS = DestRecordType.getAddressSpace(); 2976 if (FromAS != DestAS) { 2977 QualType FromRecordTypeWithoutAS = 2978 Context.removeAddrSpaceQualType(FromRecordType); 2979 QualType FromTypeWithDestAS = 2980 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2981 if (PointerConversions) 2982 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2983 From = ImpCastExprToType(From, FromTypeWithDestAS, 2984 CK_AddressSpaceConversion, From->getValueKind()) 2985 .get(); 2986 } 2987 } else { 2988 // No conversion necessary. 2989 return From; 2990 } 2991 2992 if (DestType->isDependentType() || FromType->isDependentType()) 2993 return From; 2994 2995 // If the unqualified types are the same, no conversion is necessary. 2996 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2997 return From; 2998 2999 SourceRange FromRange = From->getSourceRange(); 3000 SourceLocation FromLoc = FromRange.getBegin(); 3001 3002 ExprValueKind VK = From->getValueKind(); 3003 3004 // C++ [class.member.lookup]p8: 3005 // [...] Ambiguities can often be resolved by qualifying a name with its 3006 // class name. 3007 // 3008 // If the member was a qualified name and the qualified referred to a 3009 // specific base subobject type, we'll cast to that intermediate type 3010 // first and then to the object in which the member is declared. That allows 3011 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3012 // 3013 // class Base { public: int x; }; 3014 // class Derived1 : public Base { }; 3015 // class Derived2 : public Base { }; 3016 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3017 // 3018 // void VeryDerived::f() { 3019 // x = 17; // error: ambiguous base subobjects 3020 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3021 // } 3022 if (Qualifier && Qualifier->getAsType()) { 3023 QualType QType = QualType(Qualifier->getAsType(), 0); 3024 assert(QType->isRecordType() && "lookup done with non-record type"); 3025 3026 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3027 3028 // In C++98, the qualifier type doesn't actually have to be a base 3029 // type of the object type, in which case we just ignore it. 3030 // Otherwise build the appropriate casts. 3031 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3032 CXXCastPath BasePath; 3033 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3034 FromLoc, FromRange, &BasePath)) 3035 return ExprError(); 3036 3037 if (PointerConversions) 3038 QType = Context.getPointerType(QType); 3039 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3040 VK, &BasePath).get(); 3041 3042 FromType = QType; 3043 FromRecordType = QRecordType; 3044 3045 // If the qualifier type was the same as the destination type, 3046 // we're done. 3047 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3048 return From; 3049 } 3050 } 3051 3052 CXXCastPath BasePath; 3053 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3054 FromLoc, FromRange, &BasePath, 3055 /*IgnoreAccess=*/true)) 3056 return ExprError(); 3057 3058 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3059 VK, &BasePath); 3060 } 3061 3062 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3063 const LookupResult &R, 3064 bool HasTrailingLParen) { 3065 // Only when used directly as the postfix-expression of a call. 3066 if (!HasTrailingLParen) 3067 return false; 3068 3069 // Never if a scope specifier was provided. 3070 if (SS.isSet()) 3071 return false; 3072 3073 // Only in C++ or ObjC++. 3074 if (!getLangOpts().CPlusPlus) 3075 return false; 3076 3077 // Turn off ADL when we find certain kinds of declarations during 3078 // normal lookup: 3079 for (NamedDecl *D : R) { 3080 // C++0x [basic.lookup.argdep]p3: 3081 // -- a declaration of a class member 3082 // Since using decls preserve this property, we check this on the 3083 // original decl. 3084 if (D->isCXXClassMember()) 3085 return false; 3086 3087 // C++0x [basic.lookup.argdep]p3: 3088 // -- a block-scope function declaration that is not a 3089 // using-declaration 3090 // NOTE: we also trigger this for function templates (in fact, we 3091 // don't check the decl type at all, since all other decl types 3092 // turn off ADL anyway). 3093 if (isa<UsingShadowDecl>(D)) 3094 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3095 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3096 return false; 3097 3098 // C++0x [basic.lookup.argdep]p3: 3099 // -- a declaration that is neither a function or a function 3100 // template 3101 // And also for builtin functions. 3102 if (isa<FunctionDecl>(D)) { 3103 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3104 3105 // But also builtin functions. 3106 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3107 return false; 3108 } else if (!isa<FunctionTemplateDecl>(D)) 3109 return false; 3110 } 3111 3112 return true; 3113 } 3114 3115 3116 /// Diagnoses obvious problems with the use of the given declaration 3117 /// as an expression. This is only actually called for lookups that 3118 /// were not overloaded, and it doesn't promise that the declaration 3119 /// will in fact be used. 3120 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3121 if (D->isInvalidDecl()) 3122 return true; 3123 3124 if (isa<TypedefNameDecl>(D)) { 3125 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3126 return true; 3127 } 3128 3129 if (isa<ObjCInterfaceDecl>(D)) { 3130 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3131 return true; 3132 } 3133 3134 if (isa<NamespaceDecl>(D)) { 3135 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3136 return true; 3137 } 3138 3139 return false; 3140 } 3141 3142 // Certain multiversion types should be treated as overloaded even when there is 3143 // only one result. 3144 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3145 assert(R.isSingleResult() && "Expected only a single result"); 3146 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3147 return FD && 3148 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3149 } 3150 3151 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3152 LookupResult &R, bool NeedsADL, 3153 bool AcceptInvalidDecl) { 3154 // If this is a single, fully-resolved result and we don't need ADL, 3155 // just build an ordinary singleton decl ref. 3156 if (!NeedsADL && R.isSingleResult() && 3157 !R.getAsSingle<FunctionTemplateDecl>() && 3158 !ShouldLookupResultBeMultiVersionOverload(R)) 3159 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3160 R.getRepresentativeDecl(), nullptr, 3161 AcceptInvalidDecl); 3162 3163 // We only need to check the declaration if there's exactly one 3164 // result, because in the overloaded case the results can only be 3165 // functions and function templates. 3166 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3167 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3168 return ExprError(); 3169 3170 // Otherwise, just build an unresolved lookup expression. Suppress 3171 // any lookup-related diagnostics; we'll hash these out later, when 3172 // we've picked a target. 3173 R.suppressDiagnostics(); 3174 3175 UnresolvedLookupExpr *ULE 3176 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3177 SS.getWithLocInContext(Context), 3178 R.getLookupNameInfo(), 3179 NeedsADL, R.isOverloadedResult(), 3180 R.begin(), R.end()); 3181 3182 return ULE; 3183 } 3184 3185 static void 3186 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3187 ValueDecl *var, DeclContext *DC); 3188 3189 /// Complete semantic analysis for a reference to the given declaration. 3190 ExprResult Sema::BuildDeclarationNameExpr( 3191 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3192 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3193 bool AcceptInvalidDecl) { 3194 assert(D && "Cannot refer to a NULL declaration"); 3195 assert(!isa<FunctionTemplateDecl>(D) && 3196 "Cannot refer unambiguously to a function template"); 3197 3198 SourceLocation Loc = NameInfo.getLoc(); 3199 if (CheckDeclInExpr(*this, Loc, D)) 3200 return ExprError(); 3201 3202 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3203 // Specifically diagnose references to class templates that are missing 3204 // a template argument list. 3205 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3206 return ExprError(); 3207 } 3208 3209 // Make sure that we're referring to a value. 3210 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3211 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3212 Diag(D->getLocation(), diag::note_declared_at); 3213 return ExprError(); 3214 } 3215 3216 // Check whether this declaration can be used. Note that we suppress 3217 // this check when we're going to perform argument-dependent lookup 3218 // on this function name, because this might not be the function 3219 // that overload resolution actually selects. 3220 if (DiagnoseUseOfDecl(D, Loc)) 3221 return ExprError(); 3222 3223 auto *VD = cast<ValueDecl>(D); 3224 3225 // Only create DeclRefExpr's for valid Decl's. 3226 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3227 return ExprError(); 3228 3229 // Handle members of anonymous structs and unions. If we got here, 3230 // and the reference is to a class member indirect field, then this 3231 // must be the subject of a pointer-to-member expression. 3232 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3233 if (!indirectField->isCXXClassMember()) 3234 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3235 indirectField); 3236 3237 QualType type = VD->getType(); 3238 if (type.isNull()) 3239 return ExprError(); 3240 ExprValueKind valueKind = VK_PRValue; 3241 3242 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3243 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3244 // is expanded by some outer '...' in the context of the use. 3245 type = type.getNonPackExpansionType(); 3246 3247 switch (D->getKind()) { 3248 // Ignore all the non-ValueDecl kinds. 3249 #define ABSTRACT_DECL(kind) 3250 #define VALUE(type, base) 3251 #define DECL(type, base) case Decl::type: 3252 #include "clang/AST/DeclNodes.inc" 3253 llvm_unreachable("invalid value decl kind"); 3254 3255 // These shouldn't make it here. 3256 case Decl::ObjCAtDefsField: 3257 llvm_unreachable("forming non-member reference to ivar?"); 3258 3259 // Enum constants are always r-values and never references. 3260 // Unresolved using declarations are dependent. 3261 case Decl::EnumConstant: 3262 case Decl::UnresolvedUsingValue: 3263 case Decl::OMPDeclareReduction: 3264 case Decl::OMPDeclareMapper: 3265 valueKind = VK_PRValue; 3266 break; 3267 3268 // Fields and indirect fields that got here must be for 3269 // pointer-to-member expressions; we just call them l-values for 3270 // internal consistency, because this subexpression doesn't really 3271 // exist in the high-level semantics. 3272 case Decl::Field: 3273 case Decl::IndirectField: 3274 case Decl::ObjCIvar: 3275 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3276 3277 // These can't have reference type in well-formed programs, but 3278 // for internal consistency we do this anyway. 3279 type = type.getNonReferenceType(); 3280 valueKind = VK_LValue; 3281 break; 3282 3283 // Non-type template parameters are either l-values or r-values 3284 // depending on the type. 3285 case Decl::NonTypeTemplateParm: { 3286 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3287 type = reftype->getPointeeType(); 3288 valueKind = VK_LValue; // even if the parameter is an r-value reference 3289 break; 3290 } 3291 3292 // [expr.prim.id.unqual]p2: 3293 // If the entity is a template parameter object for a template 3294 // parameter of type T, the type of the expression is const T. 3295 // [...] The expression is an lvalue if the entity is a [...] template 3296 // parameter object. 3297 if (type->isRecordType()) { 3298 type = type.getUnqualifiedType().withConst(); 3299 valueKind = VK_LValue; 3300 break; 3301 } 3302 3303 // For non-references, we need to strip qualifiers just in case 3304 // the template parameter was declared as 'const int' or whatever. 3305 valueKind = VK_PRValue; 3306 type = type.getUnqualifiedType(); 3307 break; 3308 } 3309 3310 case Decl::Var: 3311 case Decl::VarTemplateSpecialization: 3312 case Decl::VarTemplatePartialSpecialization: 3313 case Decl::Decomposition: 3314 case Decl::OMPCapturedExpr: 3315 // In C, "extern void blah;" is valid and is an r-value. 3316 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3317 type->isVoidType()) { 3318 valueKind = VK_PRValue; 3319 break; 3320 } 3321 LLVM_FALLTHROUGH; 3322 3323 case Decl::ImplicitParam: 3324 case Decl::ParmVar: { 3325 // These are always l-values. 3326 valueKind = VK_LValue; 3327 type = type.getNonReferenceType(); 3328 3329 // FIXME: Does the addition of const really only apply in 3330 // potentially-evaluated contexts? Since the variable isn't actually 3331 // captured in an unevaluated context, it seems that the answer is no. 3332 if (!isUnevaluatedContext()) { 3333 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3334 if (!CapturedType.isNull()) 3335 type = CapturedType; 3336 } 3337 3338 break; 3339 } 3340 3341 case Decl::Binding: { 3342 // These are always lvalues. 3343 valueKind = VK_LValue; 3344 type = type.getNonReferenceType(); 3345 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3346 // decides how that's supposed to work. 3347 auto *BD = cast<BindingDecl>(VD); 3348 if (BD->getDeclContext() != CurContext) { 3349 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3350 if (DD && DD->hasLocalStorage()) 3351 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3352 } 3353 break; 3354 } 3355 3356 case Decl::Function: { 3357 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3358 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3359 type = Context.BuiltinFnTy; 3360 valueKind = VK_PRValue; 3361 break; 3362 } 3363 } 3364 3365 const FunctionType *fty = type->castAs<FunctionType>(); 3366 3367 // If we're referring to a function with an __unknown_anytype 3368 // result type, make the entire expression __unknown_anytype. 3369 if (fty->getReturnType() == Context.UnknownAnyTy) { 3370 type = Context.UnknownAnyTy; 3371 valueKind = VK_PRValue; 3372 break; 3373 } 3374 3375 // Functions are l-values in C++. 3376 if (getLangOpts().CPlusPlus) { 3377 valueKind = VK_LValue; 3378 break; 3379 } 3380 3381 // C99 DR 316 says that, if a function type comes from a 3382 // function definition (without a prototype), that type is only 3383 // used for checking compatibility. Therefore, when referencing 3384 // the function, we pretend that we don't have the full function 3385 // type. 3386 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3387 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3388 fty->getExtInfo()); 3389 3390 // Functions are r-values in C. 3391 valueKind = VK_PRValue; 3392 break; 3393 } 3394 3395 case Decl::CXXDeductionGuide: 3396 llvm_unreachable("building reference to deduction guide"); 3397 3398 case Decl::MSProperty: 3399 case Decl::MSGuid: 3400 case Decl::TemplateParamObject: 3401 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3402 // capture in OpenMP, or duplicated between host and device? 3403 valueKind = VK_LValue; 3404 break; 3405 3406 case Decl::CXXMethod: 3407 // If we're referring to a method with an __unknown_anytype 3408 // result type, make the entire expression __unknown_anytype. 3409 // This should only be possible with a type written directly. 3410 if (const FunctionProtoType *proto = 3411 dyn_cast<FunctionProtoType>(VD->getType())) 3412 if (proto->getReturnType() == Context.UnknownAnyTy) { 3413 type = Context.UnknownAnyTy; 3414 valueKind = VK_PRValue; 3415 break; 3416 } 3417 3418 // C++ methods are l-values if static, r-values if non-static. 3419 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3420 valueKind = VK_LValue; 3421 break; 3422 } 3423 LLVM_FALLTHROUGH; 3424 3425 case Decl::CXXConversion: 3426 case Decl::CXXDestructor: 3427 case Decl::CXXConstructor: 3428 valueKind = VK_PRValue; 3429 break; 3430 } 3431 3432 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3433 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3434 TemplateArgs); 3435 } 3436 3437 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3438 SmallString<32> &Target) { 3439 Target.resize(CharByteWidth * (Source.size() + 1)); 3440 char *ResultPtr = &Target[0]; 3441 const llvm::UTF8 *ErrorPtr; 3442 bool success = 3443 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3444 (void)success; 3445 assert(success); 3446 Target.resize(ResultPtr - &Target[0]); 3447 } 3448 3449 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3450 PredefinedExpr::IdentKind IK) { 3451 // Pick the current block, lambda, captured statement or function. 3452 Decl *currentDecl = nullptr; 3453 if (const BlockScopeInfo *BSI = getCurBlock()) 3454 currentDecl = BSI->TheDecl; 3455 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3456 currentDecl = LSI->CallOperator; 3457 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3458 currentDecl = CSI->TheCapturedDecl; 3459 else 3460 currentDecl = getCurFunctionOrMethodDecl(); 3461 3462 if (!currentDecl) { 3463 Diag(Loc, diag::ext_predef_outside_function); 3464 currentDecl = Context.getTranslationUnitDecl(); 3465 } 3466 3467 QualType ResTy; 3468 StringLiteral *SL = nullptr; 3469 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3470 ResTy = Context.DependentTy; 3471 else { 3472 // Pre-defined identifiers are of type char[x], where x is the length of 3473 // the string. 3474 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3475 unsigned Length = Str.length(); 3476 3477 llvm::APInt LengthI(32, Length + 1); 3478 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3479 ResTy = 3480 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3481 SmallString<32> RawChars; 3482 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3483 Str, RawChars); 3484 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3485 ArrayType::Normal, 3486 /*IndexTypeQuals*/ 0); 3487 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3488 /*Pascal*/ false, ResTy, Loc); 3489 } else { 3490 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3491 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3492 ArrayType::Normal, 3493 /*IndexTypeQuals*/ 0); 3494 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3495 /*Pascal*/ false, ResTy, Loc); 3496 } 3497 } 3498 3499 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3500 } 3501 3502 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3503 SourceLocation LParen, 3504 SourceLocation RParen, 3505 TypeSourceInfo *TSI) { 3506 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3507 } 3508 3509 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3510 SourceLocation LParen, 3511 SourceLocation RParen, 3512 ParsedType ParsedTy) { 3513 TypeSourceInfo *TSI = nullptr; 3514 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3515 3516 if (Ty.isNull()) 3517 return ExprError(); 3518 if (!TSI) 3519 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3520 3521 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3522 } 3523 3524 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3525 PredefinedExpr::IdentKind IK; 3526 3527 switch (Kind) { 3528 default: llvm_unreachable("Unknown simple primary expr!"); 3529 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3530 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3531 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3532 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3533 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3534 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3535 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3536 } 3537 3538 return BuildPredefinedExpr(Loc, IK); 3539 } 3540 3541 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3542 SmallString<16> CharBuffer; 3543 bool Invalid = false; 3544 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3545 if (Invalid) 3546 return ExprError(); 3547 3548 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3549 PP, Tok.getKind()); 3550 if (Literal.hadError()) 3551 return ExprError(); 3552 3553 QualType Ty; 3554 if (Literal.isWide()) 3555 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3556 else if (Literal.isUTF8() && getLangOpts().Char8) 3557 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3558 else if (Literal.isUTF16()) 3559 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3560 else if (Literal.isUTF32()) 3561 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3562 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3563 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3564 else 3565 Ty = Context.CharTy; // 'x' -> char in C++ 3566 3567 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3568 if (Literal.isWide()) 3569 Kind = CharacterLiteral::Wide; 3570 else if (Literal.isUTF16()) 3571 Kind = CharacterLiteral::UTF16; 3572 else if (Literal.isUTF32()) 3573 Kind = CharacterLiteral::UTF32; 3574 else if (Literal.isUTF8()) 3575 Kind = CharacterLiteral::UTF8; 3576 3577 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3578 Tok.getLocation()); 3579 3580 if (Literal.getUDSuffix().empty()) 3581 return Lit; 3582 3583 // We're building a user-defined literal. 3584 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3585 SourceLocation UDSuffixLoc = 3586 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3587 3588 // Make sure we're allowed user-defined literals here. 3589 if (!UDLScope) 3590 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3591 3592 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3593 // operator "" X (ch) 3594 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3595 Lit, Tok.getLocation()); 3596 } 3597 3598 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3599 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3600 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3601 Context.IntTy, Loc); 3602 } 3603 3604 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3605 QualType Ty, SourceLocation Loc) { 3606 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3607 3608 using llvm::APFloat; 3609 APFloat Val(Format); 3610 3611 APFloat::opStatus result = Literal.GetFloatValue(Val); 3612 3613 // Overflow is always an error, but underflow is only an error if 3614 // we underflowed to zero (APFloat reports denormals as underflow). 3615 if ((result & APFloat::opOverflow) || 3616 ((result & APFloat::opUnderflow) && Val.isZero())) { 3617 unsigned diagnostic; 3618 SmallString<20> buffer; 3619 if (result & APFloat::opOverflow) { 3620 diagnostic = diag::warn_float_overflow; 3621 APFloat::getLargest(Format).toString(buffer); 3622 } else { 3623 diagnostic = diag::warn_float_underflow; 3624 APFloat::getSmallest(Format).toString(buffer); 3625 } 3626 3627 S.Diag(Loc, diagnostic) 3628 << Ty 3629 << StringRef(buffer.data(), buffer.size()); 3630 } 3631 3632 bool isExact = (result == APFloat::opOK); 3633 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3634 } 3635 3636 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3637 assert(E && "Invalid expression"); 3638 3639 if (E->isValueDependent()) 3640 return false; 3641 3642 QualType QT = E->getType(); 3643 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3644 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3645 return true; 3646 } 3647 3648 llvm::APSInt ValueAPS; 3649 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3650 3651 if (R.isInvalid()) 3652 return true; 3653 3654 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3655 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3656 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3657 << toString(ValueAPS, 10) << ValueIsPositive; 3658 return true; 3659 } 3660 3661 return false; 3662 } 3663 3664 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3665 // Fast path for a single digit (which is quite common). A single digit 3666 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3667 if (Tok.getLength() == 1) { 3668 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3669 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3670 } 3671 3672 SmallString<128> SpellingBuffer; 3673 // NumericLiteralParser wants to overread by one character. Add padding to 3674 // the buffer in case the token is copied to the buffer. If getSpelling() 3675 // returns a StringRef to the memory buffer, it should have a null char at 3676 // the EOF, so it is also safe. 3677 SpellingBuffer.resize(Tok.getLength() + 1); 3678 3679 // Get the spelling of the token, which eliminates trigraphs, etc. 3680 bool Invalid = false; 3681 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3682 if (Invalid) 3683 return ExprError(); 3684 3685 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3686 PP.getSourceManager(), PP.getLangOpts(), 3687 PP.getTargetInfo(), PP.getDiagnostics()); 3688 if (Literal.hadError) 3689 return ExprError(); 3690 3691 if (Literal.hasUDSuffix()) { 3692 // We're building a user-defined literal. 3693 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3694 SourceLocation UDSuffixLoc = 3695 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3696 3697 // Make sure we're allowed user-defined literals here. 3698 if (!UDLScope) 3699 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3700 3701 QualType CookedTy; 3702 if (Literal.isFloatingLiteral()) { 3703 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3704 // long double, the literal is treated as a call of the form 3705 // operator "" X (f L) 3706 CookedTy = Context.LongDoubleTy; 3707 } else { 3708 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3709 // unsigned long long, the literal is treated as a call of the form 3710 // operator "" X (n ULL) 3711 CookedTy = Context.UnsignedLongLongTy; 3712 } 3713 3714 DeclarationName OpName = 3715 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3716 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3717 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3718 3719 SourceLocation TokLoc = Tok.getLocation(); 3720 3721 // Perform literal operator lookup to determine if we're building a raw 3722 // literal or a cooked one. 3723 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3724 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3725 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3726 /*AllowStringTemplatePack*/ false, 3727 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3728 case LOLR_ErrorNoDiagnostic: 3729 // Lookup failure for imaginary constants isn't fatal, there's still the 3730 // GNU extension producing _Complex types. 3731 break; 3732 case LOLR_Error: 3733 return ExprError(); 3734 case LOLR_Cooked: { 3735 Expr *Lit; 3736 if (Literal.isFloatingLiteral()) { 3737 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3738 } else { 3739 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3740 if (Literal.GetIntegerValue(ResultVal)) 3741 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3742 << /* Unsigned */ 1; 3743 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3744 Tok.getLocation()); 3745 } 3746 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3747 } 3748 3749 case LOLR_Raw: { 3750 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3751 // literal is treated as a call of the form 3752 // operator "" X ("n") 3753 unsigned Length = Literal.getUDSuffixOffset(); 3754 QualType StrTy = Context.getConstantArrayType( 3755 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3756 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3757 Expr *Lit = StringLiteral::Create( 3758 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3759 /*Pascal*/false, StrTy, &TokLoc, 1); 3760 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3761 } 3762 3763 case LOLR_Template: { 3764 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3765 // template), L is treated as a call fo the form 3766 // operator "" X <'c1', 'c2', ... 'ck'>() 3767 // where n is the source character sequence c1 c2 ... ck. 3768 TemplateArgumentListInfo ExplicitArgs; 3769 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3770 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3771 llvm::APSInt Value(CharBits, CharIsUnsigned); 3772 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3773 Value = TokSpelling[I]; 3774 TemplateArgument Arg(Context, Value, Context.CharTy); 3775 TemplateArgumentLocInfo ArgInfo; 3776 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3777 } 3778 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3779 &ExplicitArgs); 3780 } 3781 case LOLR_StringTemplatePack: 3782 llvm_unreachable("unexpected literal operator lookup result"); 3783 } 3784 } 3785 3786 Expr *Res; 3787 3788 if (Literal.isFixedPointLiteral()) { 3789 QualType Ty; 3790 3791 if (Literal.isAccum) { 3792 if (Literal.isHalf) { 3793 Ty = Context.ShortAccumTy; 3794 } else if (Literal.isLong) { 3795 Ty = Context.LongAccumTy; 3796 } else { 3797 Ty = Context.AccumTy; 3798 } 3799 } else if (Literal.isFract) { 3800 if (Literal.isHalf) { 3801 Ty = Context.ShortFractTy; 3802 } else if (Literal.isLong) { 3803 Ty = Context.LongFractTy; 3804 } else { 3805 Ty = Context.FractTy; 3806 } 3807 } 3808 3809 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3810 3811 bool isSigned = !Literal.isUnsigned; 3812 unsigned scale = Context.getFixedPointScale(Ty); 3813 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3814 3815 llvm::APInt Val(bit_width, 0, isSigned); 3816 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3817 bool ValIsZero = Val.isZero() && !Overflowed; 3818 3819 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3820 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3821 // Clause 6.4.4 - The value of a constant shall be in the range of 3822 // representable values for its type, with exception for constants of a 3823 // fract type with a value of exactly 1; such a constant shall denote 3824 // the maximal value for the type. 3825 --Val; 3826 else if (Val.ugt(MaxVal) || Overflowed) 3827 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3828 3829 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3830 Tok.getLocation(), scale); 3831 } else if (Literal.isFloatingLiteral()) { 3832 QualType Ty; 3833 if (Literal.isHalf){ 3834 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3835 Ty = Context.HalfTy; 3836 else { 3837 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3838 return ExprError(); 3839 } 3840 } else if (Literal.isFloat) 3841 Ty = Context.FloatTy; 3842 else if (Literal.isLong) 3843 Ty = Context.LongDoubleTy; 3844 else if (Literal.isFloat16) 3845 Ty = Context.Float16Ty; 3846 else if (Literal.isFloat128) 3847 Ty = Context.Float128Ty; 3848 else 3849 Ty = Context.DoubleTy; 3850 3851 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3852 3853 if (Ty == Context.DoubleTy) { 3854 if (getLangOpts().SinglePrecisionConstants) { 3855 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3856 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3857 } 3858 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3859 "cl_khr_fp64", getLangOpts())) { 3860 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3861 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3862 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3863 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3864 } 3865 } 3866 } else if (!Literal.isIntegerLiteral()) { 3867 return ExprError(); 3868 } else { 3869 QualType Ty; 3870 3871 // 'long long' is a C99 or C++11 feature. 3872 if (!getLangOpts().C99 && Literal.isLongLong) { 3873 if (getLangOpts().CPlusPlus) 3874 Diag(Tok.getLocation(), 3875 getLangOpts().CPlusPlus11 ? 3876 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3877 else 3878 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3879 } 3880 3881 // 'z/uz' literals are a C++2b feature. 3882 if (Literal.isSizeT) 3883 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3884 ? getLangOpts().CPlusPlus2b 3885 ? diag::warn_cxx20_compat_size_t_suffix 3886 : diag::ext_cxx2b_size_t_suffix 3887 : diag::err_cxx2b_size_t_suffix); 3888 3889 // Get the value in the widest-possible width. 3890 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3891 llvm::APInt ResultVal(MaxWidth, 0); 3892 3893 if (Literal.GetIntegerValue(ResultVal)) { 3894 // If this value didn't fit into uintmax_t, error and force to ull. 3895 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3896 << /* Unsigned */ 1; 3897 Ty = Context.UnsignedLongLongTy; 3898 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3899 "long long is not intmax_t?"); 3900 } else { 3901 // If this value fits into a ULL, try to figure out what else it fits into 3902 // according to the rules of C99 6.4.4.1p5. 3903 3904 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3905 // be an unsigned int. 3906 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3907 3908 // Check from smallest to largest, picking the smallest type we can. 3909 unsigned Width = 0; 3910 3911 // Microsoft specific integer suffixes are explicitly sized. 3912 if (Literal.MicrosoftInteger) { 3913 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3914 Width = 8; 3915 Ty = Context.CharTy; 3916 } else { 3917 Width = Literal.MicrosoftInteger; 3918 Ty = Context.getIntTypeForBitwidth(Width, 3919 /*Signed=*/!Literal.isUnsigned); 3920 } 3921 } 3922 3923 // Check C++2b size_t literals. 3924 if (Literal.isSizeT) { 3925 assert(!Literal.MicrosoftInteger && 3926 "size_t literals can't be Microsoft literals"); 3927 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3928 Context.getTargetInfo().getSizeType()); 3929 3930 // Does it fit in size_t? 3931 if (ResultVal.isIntN(SizeTSize)) { 3932 // Does it fit in ssize_t? 3933 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3934 Ty = Context.getSignedSizeType(); 3935 else if (AllowUnsigned) 3936 Ty = Context.getSizeType(); 3937 Width = SizeTSize; 3938 } 3939 } 3940 3941 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3942 !Literal.isSizeT) { 3943 // Are int/unsigned possibilities? 3944 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3945 3946 // Does it fit in a unsigned int? 3947 if (ResultVal.isIntN(IntSize)) { 3948 // Does it fit in a signed int? 3949 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3950 Ty = Context.IntTy; 3951 else if (AllowUnsigned) 3952 Ty = Context.UnsignedIntTy; 3953 Width = IntSize; 3954 } 3955 } 3956 3957 // Are long/unsigned long possibilities? 3958 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3959 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3960 3961 // Does it fit in a unsigned long? 3962 if (ResultVal.isIntN(LongSize)) { 3963 // Does it fit in a signed long? 3964 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3965 Ty = Context.LongTy; 3966 else if (AllowUnsigned) 3967 Ty = Context.UnsignedLongTy; 3968 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3969 // is compatible. 3970 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3971 const unsigned LongLongSize = 3972 Context.getTargetInfo().getLongLongWidth(); 3973 Diag(Tok.getLocation(), 3974 getLangOpts().CPlusPlus 3975 ? Literal.isLong 3976 ? diag::warn_old_implicitly_unsigned_long_cxx 3977 : /*C++98 UB*/ diag:: 3978 ext_old_implicitly_unsigned_long_cxx 3979 : diag::warn_old_implicitly_unsigned_long) 3980 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3981 : /*will be ill-formed*/ 1); 3982 Ty = Context.UnsignedLongTy; 3983 } 3984 Width = LongSize; 3985 } 3986 } 3987 3988 // Check long long if needed. 3989 if (Ty.isNull() && !Literal.isSizeT) { 3990 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3991 3992 // Does it fit in a unsigned long long? 3993 if (ResultVal.isIntN(LongLongSize)) { 3994 // Does it fit in a signed long long? 3995 // To be compatible with MSVC, hex integer literals ending with the 3996 // LL or i64 suffix are always signed in Microsoft mode. 3997 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3998 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3999 Ty = Context.LongLongTy; 4000 else if (AllowUnsigned) 4001 Ty = Context.UnsignedLongLongTy; 4002 Width = LongLongSize; 4003 } 4004 } 4005 4006 // If we still couldn't decide a type, we either have 'size_t' literal 4007 // that is out of range, or a decimal literal that does not fit in a 4008 // signed long long and has no U suffix. 4009 if (Ty.isNull()) { 4010 if (Literal.isSizeT) 4011 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4012 << Literal.isUnsigned; 4013 else 4014 Diag(Tok.getLocation(), 4015 diag::ext_integer_literal_too_large_for_signed); 4016 Ty = Context.UnsignedLongLongTy; 4017 Width = Context.getTargetInfo().getLongLongWidth(); 4018 } 4019 4020 if (ResultVal.getBitWidth() != Width) 4021 ResultVal = ResultVal.trunc(Width); 4022 } 4023 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4024 } 4025 4026 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4027 if (Literal.isImaginary) { 4028 Res = new (Context) ImaginaryLiteral(Res, 4029 Context.getComplexType(Res->getType())); 4030 4031 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4032 } 4033 return Res; 4034 } 4035 4036 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4037 assert(E && "ActOnParenExpr() missing expr"); 4038 QualType ExprTy = E->getType(); 4039 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4040 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4041 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4042 return new (Context) ParenExpr(L, R, E); 4043 } 4044 4045 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4046 SourceLocation Loc, 4047 SourceRange ArgRange) { 4048 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4049 // scalar or vector data type argument..." 4050 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4051 // type (C99 6.2.5p18) or void. 4052 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4053 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4054 << T << ArgRange; 4055 return true; 4056 } 4057 4058 assert((T->isVoidType() || !T->isIncompleteType()) && 4059 "Scalar types should always be complete"); 4060 return false; 4061 } 4062 4063 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4064 SourceLocation Loc, 4065 SourceRange ArgRange, 4066 UnaryExprOrTypeTrait TraitKind) { 4067 // Invalid types must be hard errors for SFINAE in C++. 4068 if (S.LangOpts.CPlusPlus) 4069 return true; 4070 4071 // C99 6.5.3.4p1: 4072 if (T->isFunctionType() && 4073 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4074 TraitKind == UETT_PreferredAlignOf)) { 4075 // sizeof(function)/alignof(function) is allowed as an extension. 4076 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4077 << getTraitSpelling(TraitKind) << ArgRange; 4078 return false; 4079 } 4080 4081 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4082 // this is an error (OpenCL v1.1 s6.3.k) 4083 if (T->isVoidType()) { 4084 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4085 : diag::ext_sizeof_alignof_void_type; 4086 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4087 return false; 4088 } 4089 4090 return true; 4091 } 4092 4093 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4094 SourceLocation Loc, 4095 SourceRange ArgRange, 4096 UnaryExprOrTypeTrait TraitKind) { 4097 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4098 // runtime doesn't allow it. 4099 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4100 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4101 << T << (TraitKind == UETT_SizeOf) 4102 << ArgRange; 4103 return true; 4104 } 4105 4106 return false; 4107 } 4108 4109 /// Check whether E is a pointer from a decayed array type (the decayed 4110 /// pointer type is equal to T) and emit a warning if it is. 4111 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4112 Expr *E) { 4113 // Don't warn if the operation changed the type. 4114 if (T != E->getType()) 4115 return; 4116 4117 // Now look for array decays. 4118 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4119 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4120 return; 4121 4122 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4123 << ICE->getType() 4124 << ICE->getSubExpr()->getType(); 4125 } 4126 4127 /// Check the constraints on expression operands to unary type expression 4128 /// and type traits. 4129 /// 4130 /// Completes any types necessary and validates the constraints on the operand 4131 /// expression. The logic mostly mirrors the type-based overload, but may modify 4132 /// the expression as it completes the type for that expression through template 4133 /// instantiation, etc. 4134 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4135 UnaryExprOrTypeTrait ExprKind) { 4136 QualType ExprTy = E->getType(); 4137 assert(!ExprTy->isReferenceType()); 4138 4139 bool IsUnevaluatedOperand = 4140 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4141 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4142 if (IsUnevaluatedOperand) { 4143 ExprResult Result = CheckUnevaluatedOperand(E); 4144 if (Result.isInvalid()) 4145 return true; 4146 E = Result.get(); 4147 } 4148 4149 // The operand for sizeof and alignof is in an unevaluated expression context, 4150 // so side effects could result in unintended consequences. 4151 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4152 // used to build SFINAE gadgets. 4153 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4154 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4155 !E->isInstantiationDependent() && 4156 E->HasSideEffects(Context, false)) 4157 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4158 4159 if (ExprKind == UETT_VecStep) 4160 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4161 E->getSourceRange()); 4162 4163 // Explicitly list some types as extensions. 4164 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4165 E->getSourceRange(), ExprKind)) 4166 return false; 4167 4168 // 'alignof' applied to an expression only requires the base element type of 4169 // the expression to be complete. 'sizeof' requires the expression's type to 4170 // be complete (and will attempt to complete it if it's an array of unknown 4171 // bound). 4172 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4173 if (RequireCompleteSizedType( 4174 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4175 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4176 getTraitSpelling(ExprKind), E->getSourceRange())) 4177 return true; 4178 } else { 4179 if (RequireCompleteSizedExprType( 4180 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4181 getTraitSpelling(ExprKind), E->getSourceRange())) 4182 return true; 4183 } 4184 4185 // Completing the expression's type may have changed it. 4186 ExprTy = E->getType(); 4187 assert(!ExprTy->isReferenceType()); 4188 4189 if (ExprTy->isFunctionType()) { 4190 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4191 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4192 return true; 4193 } 4194 4195 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4196 E->getSourceRange(), ExprKind)) 4197 return true; 4198 4199 if (ExprKind == UETT_SizeOf) { 4200 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4201 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4202 QualType OType = PVD->getOriginalType(); 4203 QualType Type = PVD->getType(); 4204 if (Type->isPointerType() && OType->isArrayType()) { 4205 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4206 << Type << OType; 4207 Diag(PVD->getLocation(), diag::note_declared_at); 4208 } 4209 } 4210 } 4211 4212 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4213 // decays into a pointer and returns an unintended result. This is most 4214 // likely a typo for "sizeof(array) op x". 4215 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4216 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4217 BO->getLHS()); 4218 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4219 BO->getRHS()); 4220 } 4221 } 4222 4223 return false; 4224 } 4225 4226 /// Check the constraints on operands to unary expression and type 4227 /// traits. 4228 /// 4229 /// This will complete any types necessary, and validate the various constraints 4230 /// on those operands. 4231 /// 4232 /// The UsualUnaryConversions() function is *not* called by this routine. 4233 /// C99 6.3.2.1p[2-4] all state: 4234 /// Except when it is the operand of the sizeof operator ... 4235 /// 4236 /// C++ [expr.sizeof]p4 4237 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4238 /// standard conversions are not applied to the operand of sizeof. 4239 /// 4240 /// This policy is followed for all of the unary trait expressions. 4241 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4242 SourceLocation OpLoc, 4243 SourceRange ExprRange, 4244 UnaryExprOrTypeTrait ExprKind) { 4245 if (ExprType->isDependentType()) 4246 return false; 4247 4248 // C++ [expr.sizeof]p2: 4249 // When applied to a reference or a reference type, the result 4250 // is the size of the referenced type. 4251 // C++11 [expr.alignof]p3: 4252 // When alignof is applied to a reference type, the result 4253 // shall be the alignment of the referenced type. 4254 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4255 ExprType = Ref->getPointeeType(); 4256 4257 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4258 // When alignof or _Alignof is applied to an array type, the result 4259 // is the alignment of the element type. 4260 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4261 ExprKind == UETT_OpenMPRequiredSimdAlign) 4262 ExprType = Context.getBaseElementType(ExprType); 4263 4264 if (ExprKind == UETT_VecStep) 4265 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4266 4267 // Explicitly list some types as extensions. 4268 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4269 ExprKind)) 4270 return false; 4271 4272 if (RequireCompleteSizedType( 4273 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4274 getTraitSpelling(ExprKind), ExprRange)) 4275 return true; 4276 4277 if (ExprType->isFunctionType()) { 4278 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4279 << getTraitSpelling(ExprKind) << ExprRange; 4280 return true; 4281 } 4282 4283 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4284 ExprKind)) 4285 return true; 4286 4287 return false; 4288 } 4289 4290 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4291 // Cannot know anything else if the expression is dependent. 4292 if (E->isTypeDependent()) 4293 return false; 4294 4295 if (E->getObjectKind() == OK_BitField) { 4296 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4297 << 1 << E->getSourceRange(); 4298 return true; 4299 } 4300 4301 ValueDecl *D = nullptr; 4302 Expr *Inner = E->IgnoreParens(); 4303 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4304 D = DRE->getDecl(); 4305 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4306 D = ME->getMemberDecl(); 4307 } 4308 4309 // If it's a field, require the containing struct to have a 4310 // complete definition so that we can compute the layout. 4311 // 4312 // This can happen in C++11 onwards, either by naming the member 4313 // in a way that is not transformed into a member access expression 4314 // (in an unevaluated operand, for instance), or by naming the member 4315 // in a trailing-return-type. 4316 // 4317 // For the record, since __alignof__ on expressions is a GCC 4318 // extension, GCC seems to permit this but always gives the 4319 // nonsensical answer 0. 4320 // 4321 // We don't really need the layout here --- we could instead just 4322 // directly check for all the appropriate alignment-lowing 4323 // attributes --- but that would require duplicating a lot of 4324 // logic that just isn't worth duplicating for such a marginal 4325 // use-case. 4326 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4327 // Fast path this check, since we at least know the record has a 4328 // definition if we can find a member of it. 4329 if (!FD->getParent()->isCompleteDefinition()) { 4330 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4331 << E->getSourceRange(); 4332 return true; 4333 } 4334 4335 // Otherwise, if it's a field, and the field doesn't have 4336 // reference type, then it must have a complete type (or be a 4337 // flexible array member, which we explicitly want to 4338 // white-list anyway), which makes the following checks trivial. 4339 if (!FD->getType()->isReferenceType()) 4340 return false; 4341 } 4342 4343 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4344 } 4345 4346 bool Sema::CheckVecStepExpr(Expr *E) { 4347 E = E->IgnoreParens(); 4348 4349 // Cannot know anything else if the expression is dependent. 4350 if (E->isTypeDependent()) 4351 return false; 4352 4353 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4354 } 4355 4356 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4357 CapturingScopeInfo *CSI) { 4358 assert(T->isVariablyModifiedType()); 4359 assert(CSI != nullptr); 4360 4361 // We're going to walk down into the type and look for VLA expressions. 4362 do { 4363 const Type *Ty = T.getTypePtr(); 4364 switch (Ty->getTypeClass()) { 4365 #define TYPE(Class, Base) 4366 #define ABSTRACT_TYPE(Class, Base) 4367 #define NON_CANONICAL_TYPE(Class, Base) 4368 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4369 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4370 #include "clang/AST/TypeNodes.inc" 4371 T = QualType(); 4372 break; 4373 // These types are never variably-modified. 4374 case Type::Builtin: 4375 case Type::Complex: 4376 case Type::Vector: 4377 case Type::ExtVector: 4378 case Type::ConstantMatrix: 4379 case Type::Record: 4380 case Type::Enum: 4381 case Type::Elaborated: 4382 case Type::TemplateSpecialization: 4383 case Type::ObjCObject: 4384 case Type::ObjCInterface: 4385 case Type::ObjCObjectPointer: 4386 case Type::ObjCTypeParam: 4387 case Type::Pipe: 4388 case Type::ExtInt: 4389 llvm_unreachable("type class is never variably-modified!"); 4390 case Type::Adjusted: 4391 T = cast<AdjustedType>(Ty)->getOriginalType(); 4392 break; 4393 case Type::Decayed: 4394 T = cast<DecayedType>(Ty)->getPointeeType(); 4395 break; 4396 case Type::Pointer: 4397 T = cast<PointerType>(Ty)->getPointeeType(); 4398 break; 4399 case Type::BlockPointer: 4400 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4401 break; 4402 case Type::LValueReference: 4403 case Type::RValueReference: 4404 T = cast<ReferenceType>(Ty)->getPointeeType(); 4405 break; 4406 case Type::MemberPointer: 4407 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4408 break; 4409 case Type::ConstantArray: 4410 case Type::IncompleteArray: 4411 // Losing element qualification here is fine. 4412 T = cast<ArrayType>(Ty)->getElementType(); 4413 break; 4414 case Type::VariableArray: { 4415 // Losing element qualification here is fine. 4416 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4417 4418 // Unknown size indication requires no size computation. 4419 // Otherwise, evaluate and record it. 4420 auto Size = VAT->getSizeExpr(); 4421 if (Size && !CSI->isVLATypeCaptured(VAT) && 4422 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4423 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4424 4425 T = VAT->getElementType(); 4426 break; 4427 } 4428 case Type::FunctionProto: 4429 case Type::FunctionNoProto: 4430 T = cast<FunctionType>(Ty)->getReturnType(); 4431 break; 4432 case Type::Paren: 4433 case Type::TypeOf: 4434 case Type::UnaryTransform: 4435 case Type::Attributed: 4436 case Type::SubstTemplateTypeParm: 4437 case Type::MacroQualified: 4438 // Keep walking after single level desugaring. 4439 T = T.getSingleStepDesugaredType(Context); 4440 break; 4441 case Type::Typedef: 4442 T = cast<TypedefType>(Ty)->desugar(); 4443 break; 4444 case Type::Decltype: 4445 T = cast<DecltypeType>(Ty)->desugar(); 4446 break; 4447 case Type::Auto: 4448 case Type::DeducedTemplateSpecialization: 4449 T = cast<DeducedType>(Ty)->getDeducedType(); 4450 break; 4451 case Type::TypeOfExpr: 4452 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4453 break; 4454 case Type::Atomic: 4455 T = cast<AtomicType>(Ty)->getValueType(); 4456 break; 4457 } 4458 } while (!T.isNull() && T->isVariablyModifiedType()); 4459 } 4460 4461 /// Build a sizeof or alignof expression given a type operand. 4462 ExprResult 4463 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4464 SourceLocation OpLoc, 4465 UnaryExprOrTypeTrait ExprKind, 4466 SourceRange R) { 4467 if (!TInfo) 4468 return ExprError(); 4469 4470 QualType T = TInfo->getType(); 4471 4472 if (!T->isDependentType() && 4473 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4474 return ExprError(); 4475 4476 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4477 if (auto *TT = T->getAs<TypedefType>()) { 4478 for (auto I = FunctionScopes.rbegin(), 4479 E = std::prev(FunctionScopes.rend()); 4480 I != E; ++I) { 4481 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4482 if (CSI == nullptr) 4483 break; 4484 DeclContext *DC = nullptr; 4485 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4486 DC = LSI->CallOperator; 4487 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4488 DC = CRSI->TheCapturedDecl; 4489 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4490 DC = BSI->TheDecl; 4491 if (DC) { 4492 if (DC->containsDecl(TT->getDecl())) 4493 break; 4494 captureVariablyModifiedType(Context, T, CSI); 4495 } 4496 } 4497 } 4498 } 4499 4500 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4501 return new (Context) UnaryExprOrTypeTraitExpr( 4502 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4503 } 4504 4505 /// Build a sizeof or alignof expression given an expression 4506 /// operand. 4507 ExprResult 4508 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4509 UnaryExprOrTypeTrait ExprKind) { 4510 ExprResult PE = CheckPlaceholderExpr(E); 4511 if (PE.isInvalid()) 4512 return ExprError(); 4513 4514 E = PE.get(); 4515 4516 // Verify that the operand is valid. 4517 bool isInvalid = false; 4518 if (E->isTypeDependent()) { 4519 // Delay type-checking for type-dependent expressions. 4520 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4521 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4522 } else if (ExprKind == UETT_VecStep) { 4523 isInvalid = CheckVecStepExpr(E); 4524 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4525 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4526 isInvalid = true; 4527 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4528 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4529 isInvalid = true; 4530 } else { 4531 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4532 } 4533 4534 if (isInvalid) 4535 return ExprError(); 4536 4537 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4538 PE = TransformToPotentiallyEvaluated(E); 4539 if (PE.isInvalid()) return ExprError(); 4540 E = PE.get(); 4541 } 4542 4543 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4544 return new (Context) UnaryExprOrTypeTraitExpr( 4545 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4546 } 4547 4548 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4549 /// expr and the same for @c alignof and @c __alignof 4550 /// Note that the ArgRange is invalid if isType is false. 4551 ExprResult 4552 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4553 UnaryExprOrTypeTrait ExprKind, bool IsType, 4554 void *TyOrEx, SourceRange ArgRange) { 4555 // If error parsing type, ignore. 4556 if (!TyOrEx) return ExprError(); 4557 4558 if (IsType) { 4559 TypeSourceInfo *TInfo; 4560 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4561 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4562 } 4563 4564 Expr *ArgEx = (Expr *)TyOrEx; 4565 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4566 return Result; 4567 } 4568 4569 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4570 bool IsReal) { 4571 if (V.get()->isTypeDependent()) 4572 return S.Context.DependentTy; 4573 4574 // _Real and _Imag are only l-values for normal l-values. 4575 if (V.get()->getObjectKind() != OK_Ordinary) { 4576 V = S.DefaultLvalueConversion(V.get()); 4577 if (V.isInvalid()) 4578 return QualType(); 4579 } 4580 4581 // These operators return the element type of a complex type. 4582 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4583 return CT->getElementType(); 4584 4585 // Otherwise they pass through real integer and floating point types here. 4586 if (V.get()->getType()->isArithmeticType()) 4587 return V.get()->getType(); 4588 4589 // Test for placeholders. 4590 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4591 if (PR.isInvalid()) return QualType(); 4592 if (PR.get() != V.get()) { 4593 V = PR; 4594 return CheckRealImagOperand(S, V, Loc, IsReal); 4595 } 4596 4597 // Reject anything else. 4598 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4599 << (IsReal ? "__real" : "__imag"); 4600 return QualType(); 4601 } 4602 4603 4604 4605 ExprResult 4606 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4607 tok::TokenKind Kind, Expr *Input) { 4608 UnaryOperatorKind Opc; 4609 switch (Kind) { 4610 default: llvm_unreachable("Unknown unary op!"); 4611 case tok::plusplus: Opc = UO_PostInc; break; 4612 case tok::minusminus: Opc = UO_PostDec; break; 4613 } 4614 4615 // Since this might is a postfix expression, get rid of ParenListExprs. 4616 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4617 if (Result.isInvalid()) return ExprError(); 4618 Input = Result.get(); 4619 4620 return BuildUnaryOp(S, OpLoc, Opc, Input); 4621 } 4622 4623 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4624 /// 4625 /// \return true on error 4626 static bool checkArithmeticOnObjCPointer(Sema &S, 4627 SourceLocation opLoc, 4628 Expr *op) { 4629 assert(op->getType()->isObjCObjectPointerType()); 4630 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4631 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4632 return false; 4633 4634 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4635 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4636 << op->getSourceRange(); 4637 return true; 4638 } 4639 4640 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4641 auto *BaseNoParens = Base->IgnoreParens(); 4642 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4643 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4644 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4645 } 4646 4647 ExprResult 4648 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4649 Expr *idx, SourceLocation rbLoc) { 4650 if (base && !base->getType().isNull() && 4651 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4652 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4653 SourceLocation(), /*Length*/ nullptr, 4654 /*Stride=*/nullptr, rbLoc); 4655 4656 // Since this might be a postfix expression, get rid of ParenListExprs. 4657 if (isa<ParenListExpr>(base)) { 4658 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4659 if (result.isInvalid()) return ExprError(); 4660 base = result.get(); 4661 } 4662 4663 // Check if base and idx form a MatrixSubscriptExpr. 4664 // 4665 // Helper to check for comma expressions, which are not allowed as indices for 4666 // matrix subscript expressions. 4667 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4668 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4669 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4670 << SourceRange(base->getBeginLoc(), rbLoc); 4671 return true; 4672 } 4673 return false; 4674 }; 4675 // The matrix subscript operator ([][])is considered a single operator. 4676 // Separating the index expressions by parenthesis is not allowed. 4677 if (base->getType()->isSpecificPlaceholderType( 4678 BuiltinType::IncompleteMatrixIdx) && 4679 !isa<MatrixSubscriptExpr>(base)) { 4680 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4681 << SourceRange(base->getBeginLoc(), rbLoc); 4682 return ExprError(); 4683 } 4684 // If the base is a MatrixSubscriptExpr, try to create a new 4685 // MatrixSubscriptExpr. 4686 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4687 if (matSubscriptE) { 4688 if (CheckAndReportCommaError(idx)) 4689 return ExprError(); 4690 4691 assert(matSubscriptE->isIncomplete() && 4692 "base has to be an incomplete matrix subscript"); 4693 return CreateBuiltinMatrixSubscriptExpr( 4694 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4695 } 4696 4697 // Handle any non-overload placeholder types in the base and index 4698 // expressions. We can't handle overloads here because the other 4699 // operand might be an overloadable type, in which case the overload 4700 // resolution for the operator overload should get the first crack 4701 // at the overload. 4702 bool IsMSPropertySubscript = false; 4703 if (base->getType()->isNonOverloadPlaceholderType()) { 4704 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4705 if (!IsMSPropertySubscript) { 4706 ExprResult result = CheckPlaceholderExpr(base); 4707 if (result.isInvalid()) 4708 return ExprError(); 4709 base = result.get(); 4710 } 4711 } 4712 4713 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4714 if (base->getType()->isMatrixType()) { 4715 if (CheckAndReportCommaError(idx)) 4716 return ExprError(); 4717 4718 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4719 } 4720 4721 // A comma-expression as the index is deprecated in C++2a onwards. 4722 if (getLangOpts().CPlusPlus20 && 4723 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4724 (isa<CXXOperatorCallExpr>(idx) && 4725 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4726 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4727 << SourceRange(base->getBeginLoc(), rbLoc); 4728 } 4729 4730 if (idx->getType()->isNonOverloadPlaceholderType()) { 4731 ExprResult result = CheckPlaceholderExpr(idx); 4732 if (result.isInvalid()) return ExprError(); 4733 idx = result.get(); 4734 } 4735 4736 // Build an unanalyzed expression if either operand is type-dependent. 4737 if (getLangOpts().CPlusPlus && 4738 (base->isTypeDependent() || idx->isTypeDependent())) { 4739 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4740 VK_LValue, OK_Ordinary, rbLoc); 4741 } 4742 4743 // MSDN, property (C++) 4744 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4745 // This attribute can also be used in the declaration of an empty array in a 4746 // class or structure definition. For example: 4747 // __declspec(property(get=GetX, put=PutX)) int x[]; 4748 // The above statement indicates that x[] can be used with one or more array 4749 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4750 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4751 if (IsMSPropertySubscript) { 4752 // Build MS property subscript expression if base is MS property reference 4753 // or MS property subscript. 4754 return new (Context) MSPropertySubscriptExpr( 4755 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4756 } 4757 4758 // Use C++ overloaded-operator rules if either operand has record 4759 // type. The spec says to do this if either type is *overloadable*, 4760 // but enum types can't declare subscript operators or conversion 4761 // operators, so there's nothing interesting for overload resolution 4762 // to do if there aren't any record types involved. 4763 // 4764 // ObjC pointers have their own subscripting logic that is not tied 4765 // to overload resolution and so should not take this path. 4766 if (getLangOpts().CPlusPlus && 4767 (base->getType()->isRecordType() || 4768 (!base->getType()->isObjCObjectPointerType() && 4769 idx->getType()->isRecordType()))) { 4770 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4771 } 4772 4773 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4774 4775 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4776 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4777 4778 return Res; 4779 } 4780 4781 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4782 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4783 InitializationKind Kind = 4784 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4785 InitializationSequence InitSeq(*this, Entity, Kind, E); 4786 return InitSeq.Perform(*this, Entity, Kind, E); 4787 } 4788 4789 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4790 Expr *ColumnIdx, 4791 SourceLocation RBLoc) { 4792 ExprResult BaseR = CheckPlaceholderExpr(Base); 4793 if (BaseR.isInvalid()) 4794 return BaseR; 4795 Base = BaseR.get(); 4796 4797 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4798 if (RowR.isInvalid()) 4799 return RowR; 4800 RowIdx = RowR.get(); 4801 4802 if (!ColumnIdx) 4803 return new (Context) MatrixSubscriptExpr( 4804 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4805 4806 // Build an unanalyzed expression if any of the operands is type-dependent. 4807 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4808 ColumnIdx->isTypeDependent()) 4809 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4810 Context.DependentTy, RBLoc); 4811 4812 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4813 if (ColumnR.isInvalid()) 4814 return ColumnR; 4815 ColumnIdx = ColumnR.get(); 4816 4817 // Check that IndexExpr is an integer expression. If it is a constant 4818 // expression, check that it is less than Dim (= the number of elements in the 4819 // corresponding dimension). 4820 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4821 bool IsColumnIdx) -> Expr * { 4822 if (!IndexExpr->getType()->isIntegerType() && 4823 !IndexExpr->isTypeDependent()) { 4824 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4825 << IsColumnIdx; 4826 return nullptr; 4827 } 4828 4829 if (Optional<llvm::APSInt> Idx = 4830 IndexExpr->getIntegerConstantExpr(Context)) { 4831 if ((*Idx < 0 || *Idx >= Dim)) { 4832 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4833 << IsColumnIdx << Dim; 4834 return nullptr; 4835 } 4836 } 4837 4838 ExprResult ConvExpr = 4839 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4840 assert(!ConvExpr.isInvalid() && 4841 "should be able to convert any integer type to size type"); 4842 return ConvExpr.get(); 4843 }; 4844 4845 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4846 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4847 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4848 if (!RowIdx || !ColumnIdx) 4849 return ExprError(); 4850 4851 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4852 MTy->getElementType(), RBLoc); 4853 } 4854 4855 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4856 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4857 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4858 4859 // For expressions like `&(*s).b`, the base is recorded and what should be 4860 // checked. 4861 const MemberExpr *Member = nullptr; 4862 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4863 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4864 4865 LastRecord.PossibleDerefs.erase(StrippedExpr); 4866 } 4867 4868 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4869 if (isUnevaluatedContext()) 4870 return; 4871 4872 QualType ResultTy = E->getType(); 4873 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4874 4875 // Bail if the element is an array since it is not memory access. 4876 if (isa<ArrayType>(ResultTy)) 4877 return; 4878 4879 if (ResultTy->hasAttr(attr::NoDeref)) { 4880 LastRecord.PossibleDerefs.insert(E); 4881 return; 4882 } 4883 4884 // Check if the base type is a pointer to a member access of a struct 4885 // marked with noderef. 4886 const Expr *Base = E->getBase(); 4887 QualType BaseTy = Base->getType(); 4888 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4889 // Not a pointer access 4890 return; 4891 4892 const MemberExpr *Member = nullptr; 4893 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4894 Member->isArrow()) 4895 Base = Member->getBase(); 4896 4897 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4898 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4899 LastRecord.PossibleDerefs.insert(E); 4900 } 4901 } 4902 4903 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4904 Expr *LowerBound, 4905 SourceLocation ColonLocFirst, 4906 SourceLocation ColonLocSecond, 4907 Expr *Length, Expr *Stride, 4908 SourceLocation RBLoc) { 4909 if (Base->getType()->isPlaceholderType() && 4910 !Base->getType()->isSpecificPlaceholderType( 4911 BuiltinType::OMPArraySection)) { 4912 ExprResult Result = CheckPlaceholderExpr(Base); 4913 if (Result.isInvalid()) 4914 return ExprError(); 4915 Base = Result.get(); 4916 } 4917 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4918 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4919 if (Result.isInvalid()) 4920 return ExprError(); 4921 Result = DefaultLvalueConversion(Result.get()); 4922 if (Result.isInvalid()) 4923 return ExprError(); 4924 LowerBound = Result.get(); 4925 } 4926 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4927 ExprResult Result = CheckPlaceholderExpr(Length); 4928 if (Result.isInvalid()) 4929 return ExprError(); 4930 Result = DefaultLvalueConversion(Result.get()); 4931 if (Result.isInvalid()) 4932 return ExprError(); 4933 Length = Result.get(); 4934 } 4935 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4936 ExprResult Result = CheckPlaceholderExpr(Stride); 4937 if (Result.isInvalid()) 4938 return ExprError(); 4939 Result = DefaultLvalueConversion(Result.get()); 4940 if (Result.isInvalid()) 4941 return ExprError(); 4942 Stride = Result.get(); 4943 } 4944 4945 // Build an unanalyzed expression if either operand is type-dependent. 4946 if (Base->isTypeDependent() || 4947 (LowerBound && 4948 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4949 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4950 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4951 return new (Context) OMPArraySectionExpr( 4952 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4953 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4954 } 4955 4956 // Perform default conversions. 4957 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4958 QualType ResultTy; 4959 if (OriginalTy->isAnyPointerType()) { 4960 ResultTy = OriginalTy->getPointeeType(); 4961 } else if (OriginalTy->isArrayType()) { 4962 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4963 } else { 4964 return ExprError( 4965 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4966 << Base->getSourceRange()); 4967 } 4968 // C99 6.5.2.1p1 4969 if (LowerBound) { 4970 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4971 LowerBound); 4972 if (Res.isInvalid()) 4973 return ExprError(Diag(LowerBound->getExprLoc(), 4974 diag::err_omp_typecheck_section_not_integer) 4975 << 0 << LowerBound->getSourceRange()); 4976 LowerBound = Res.get(); 4977 4978 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4979 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4980 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4981 << 0 << LowerBound->getSourceRange(); 4982 } 4983 if (Length) { 4984 auto Res = 4985 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4986 if (Res.isInvalid()) 4987 return ExprError(Diag(Length->getExprLoc(), 4988 diag::err_omp_typecheck_section_not_integer) 4989 << 1 << Length->getSourceRange()); 4990 Length = Res.get(); 4991 4992 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4993 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4994 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4995 << 1 << Length->getSourceRange(); 4996 } 4997 if (Stride) { 4998 ExprResult Res = 4999 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5000 if (Res.isInvalid()) 5001 return ExprError(Diag(Stride->getExprLoc(), 5002 diag::err_omp_typecheck_section_not_integer) 5003 << 1 << Stride->getSourceRange()); 5004 Stride = Res.get(); 5005 5006 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5007 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5008 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5009 << 1 << Stride->getSourceRange(); 5010 } 5011 5012 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5013 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5014 // type. Note that functions are not objects, and that (in C99 parlance) 5015 // incomplete types are not object types. 5016 if (ResultTy->isFunctionType()) { 5017 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5018 << ResultTy << Base->getSourceRange(); 5019 return ExprError(); 5020 } 5021 5022 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5023 diag::err_omp_section_incomplete_type, Base)) 5024 return ExprError(); 5025 5026 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5027 Expr::EvalResult Result; 5028 if (LowerBound->EvaluateAsInt(Result, Context)) { 5029 // OpenMP 5.0, [2.1.5 Array Sections] 5030 // The array section must be a subset of the original array. 5031 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5032 if (LowerBoundValue.isNegative()) { 5033 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5034 << LowerBound->getSourceRange(); 5035 return ExprError(); 5036 } 5037 } 5038 } 5039 5040 if (Length) { 5041 Expr::EvalResult Result; 5042 if (Length->EvaluateAsInt(Result, Context)) { 5043 // OpenMP 5.0, [2.1.5 Array Sections] 5044 // The length must evaluate to non-negative integers. 5045 llvm::APSInt LengthValue = Result.Val.getInt(); 5046 if (LengthValue.isNegative()) { 5047 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5048 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5049 << Length->getSourceRange(); 5050 return ExprError(); 5051 } 5052 } 5053 } else if (ColonLocFirst.isValid() && 5054 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5055 !OriginalTy->isVariableArrayType()))) { 5056 // OpenMP 5.0, [2.1.5 Array Sections] 5057 // When the size of the array dimension is not known, the length must be 5058 // specified explicitly. 5059 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5060 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5061 return ExprError(); 5062 } 5063 5064 if (Stride) { 5065 Expr::EvalResult Result; 5066 if (Stride->EvaluateAsInt(Result, Context)) { 5067 // OpenMP 5.0, [2.1.5 Array Sections] 5068 // The stride must evaluate to a positive integer. 5069 llvm::APSInt StrideValue = Result.Val.getInt(); 5070 if (!StrideValue.isStrictlyPositive()) { 5071 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5072 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5073 << Stride->getSourceRange(); 5074 return ExprError(); 5075 } 5076 } 5077 } 5078 5079 if (!Base->getType()->isSpecificPlaceholderType( 5080 BuiltinType::OMPArraySection)) { 5081 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5082 if (Result.isInvalid()) 5083 return ExprError(); 5084 Base = Result.get(); 5085 } 5086 return new (Context) OMPArraySectionExpr( 5087 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5088 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5089 } 5090 5091 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5092 SourceLocation RParenLoc, 5093 ArrayRef<Expr *> Dims, 5094 ArrayRef<SourceRange> Brackets) { 5095 if (Base->getType()->isPlaceholderType()) { 5096 ExprResult Result = CheckPlaceholderExpr(Base); 5097 if (Result.isInvalid()) 5098 return ExprError(); 5099 Result = DefaultLvalueConversion(Result.get()); 5100 if (Result.isInvalid()) 5101 return ExprError(); 5102 Base = Result.get(); 5103 } 5104 QualType BaseTy = Base->getType(); 5105 // Delay analysis of the types/expressions if instantiation/specialization is 5106 // required. 5107 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5108 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5109 LParenLoc, RParenLoc, Dims, Brackets); 5110 if (!BaseTy->isPointerType() || 5111 (!Base->isTypeDependent() && 5112 BaseTy->getPointeeType()->isIncompleteType())) 5113 return ExprError(Diag(Base->getExprLoc(), 5114 diag::err_omp_non_pointer_type_array_shaping_base) 5115 << Base->getSourceRange()); 5116 5117 SmallVector<Expr *, 4> NewDims; 5118 bool ErrorFound = false; 5119 for (Expr *Dim : Dims) { 5120 if (Dim->getType()->isPlaceholderType()) { 5121 ExprResult Result = CheckPlaceholderExpr(Dim); 5122 if (Result.isInvalid()) { 5123 ErrorFound = true; 5124 continue; 5125 } 5126 Result = DefaultLvalueConversion(Result.get()); 5127 if (Result.isInvalid()) { 5128 ErrorFound = true; 5129 continue; 5130 } 5131 Dim = Result.get(); 5132 } 5133 if (!Dim->isTypeDependent()) { 5134 ExprResult Result = 5135 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5136 if (Result.isInvalid()) { 5137 ErrorFound = true; 5138 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5139 << Dim->getSourceRange(); 5140 continue; 5141 } 5142 Dim = Result.get(); 5143 Expr::EvalResult EvResult; 5144 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5145 // OpenMP 5.0, [2.1.4 Array Shaping] 5146 // Each si is an integral type expression that must evaluate to a 5147 // positive integer. 5148 llvm::APSInt Value = EvResult.Val.getInt(); 5149 if (!Value.isStrictlyPositive()) { 5150 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5151 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5152 << Dim->getSourceRange(); 5153 ErrorFound = true; 5154 continue; 5155 } 5156 } 5157 } 5158 NewDims.push_back(Dim); 5159 } 5160 if (ErrorFound) 5161 return ExprError(); 5162 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5163 LParenLoc, RParenLoc, NewDims, Brackets); 5164 } 5165 5166 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5167 SourceLocation LLoc, SourceLocation RLoc, 5168 ArrayRef<OMPIteratorData> Data) { 5169 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5170 bool IsCorrect = true; 5171 for (const OMPIteratorData &D : Data) { 5172 TypeSourceInfo *TInfo = nullptr; 5173 SourceLocation StartLoc; 5174 QualType DeclTy; 5175 if (!D.Type.getAsOpaquePtr()) { 5176 // OpenMP 5.0, 2.1.6 Iterators 5177 // In an iterator-specifier, if the iterator-type is not specified then 5178 // the type of that iterator is of int type. 5179 DeclTy = Context.IntTy; 5180 StartLoc = D.DeclIdentLoc; 5181 } else { 5182 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5183 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5184 } 5185 5186 bool IsDeclTyDependent = DeclTy->isDependentType() || 5187 DeclTy->containsUnexpandedParameterPack() || 5188 DeclTy->isInstantiationDependentType(); 5189 if (!IsDeclTyDependent) { 5190 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5191 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5192 // The iterator-type must be an integral or pointer type. 5193 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5194 << DeclTy; 5195 IsCorrect = false; 5196 continue; 5197 } 5198 if (DeclTy.isConstant(Context)) { 5199 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5200 // The iterator-type must not be const qualified. 5201 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5202 << DeclTy; 5203 IsCorrect = false; 5204 continue; 5205 } 5206 } 5207 5208 // Iterator declaration. 5209 assert(D.DeclIdent && "Identifier expected."); 5210 // Always try to create iterator declarator to avoid extra error messages 5211 // about unknown declarations use. 5212 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5213 D.DeclIdent, DeclTy, TInfo, SC_None); 5214 VD->setImplicit(); 5215 if (S) { 5216 // Check for conflicting previous declaration. 5217 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5218 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5219 ForVisibleRedeclaration); 5220 Previous.suppressDiagnostics(); 5221 LookupName(Previous, S); 5222 5223 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5224 /*AllowInlineNamespace=*/false); 5225 if (!Previous.empty()) { 5226 NamedDecl *Old = Previous.getRepresentativeDecl(); 5227 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5228 Diag(Old->getLocation(), diag::note_previous_definition); 5229 } else { 5230 PushOnScopeChains(VD, S); 5231 } 5232 } else { 5233 CurContext->addDecl(VD); 5234 } 5235 Expr *Begin = D.Range.Begin; 5236 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5237 ExprResult BeginRes = 5238 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5239 Begin = BeginRes.get(); 5240 } 5241 Expr *End = D.Range.End; 5242 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5243 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5244 End = EndRes.get(); 5245 } 5246 Expr *Step = D.Range.Step; 5247 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5248 if (!Step->getType()->isIntegralType(Context)) { 5249 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5250 << Step << Step->getSourceRange(); 5251 IsCorrect = false; 5252 continue; 5253 } 5254 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5255 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5256 // If the step expression of a range-specification equals zero, the 5257 // behavior is unspecified. 5258 if (Result && Result->isZero()) { 5259 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5260 << Step << Step->getSourceRange(); 5261 IsCorrect = false; 5262 continue; 5263 } 5264 } 5265 if (!Begin || !End || !IsCorrect) { 5266 IsCorrect = false; 5267 continue; 5268 } 5269 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5270 IDElem.IteratorDecl = VD; 5271 IDElem.AssignmentLoc = D.AssignLoc; 5272 IDElem.Range.Begin = Begin; 5273 IDElem.Range.End = End; 5274 IDElem.Range.Step = Step; 5275 IDElem.ColonLoc = D.ColonLoc; 5276 IDElem.SecondColonLoc = D.SecColonLoc; 5277 } 5278 if (!IsCorrect) { 5279 // Invalidate all created iterator declarations if error is found. 5280 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5281 if (Decl *ID = D.IteratorDecl) 5282 ID->setInvalidDecl(); 5283 } 5284 return ExprError(); 5285 } 5286 SmallVector<OMPIteratorHelperData, 4> Helpers; 5287 if (!CurContext->isDependentContext()) { 5288 // Build number of ityeration for each iteration range. 5289 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5290 // ((Begini-Stepi-1-Endi) / -Stepi); 5291 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5292 // (Endi - Begini) 5293 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5294 D.Range.Begin); 5295 if(!Res.isUsable()) { 5296 IsCorrect = false; 5297 continue; 5298 } 5299 ExprResult St, St1; 5300 if (D.Range.Step) { 5301 St = D.Range.Step; 5302 // (Endi - Begini) + Stepi 5303 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5304 if (!Res.isUsable()) { 5305 IsCorrect = false; 5306 continue; 5307 } 5308 // (Endi - Begini) + Stepi - 1 5309 Res = 5310 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5311 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5312 if (!Res.isUsable()) { 5313 IsCorrect = false; 5314 continue; 5315 } 5316 // ((Endi - Begini) + Stepi - 1) / Stepi 5317 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5318 if (!Res.isUsable()) { 5319 IsCorrect = false; 5320 continue; 5321 } 5322 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5323 // (Begini - Endi) 5324 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5325 D.Range.Begin, D.Range.End); 5326 if (!Res1.isUsable()) { 5327 IsCorrect = false; 5328 continue; 5329 } 5330 // (Begini - Endi) - Stepi 5331 Res1 = 5332 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5333 if (!Res1.isUsable()) { 5334 IsCorrect = false; 5335 continue; 5336 } 5337 // (Begini - Endi) - Stepi - 1 5338 Res1 = 5339 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5340 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5341 if (!Res1.isUsable()) { 5342 IsCorrect = false; 5343 continue; 5344 } 5345 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5346 Res1 = 5347 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5348 if (!Res1.isUsable()) { 5349 IsCorrect = false; 5350 continue; 5351 } 5352 // Stepi > 0. 5353 ExprResult CmpRes = 5354 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5355 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5356 if (!CmpRes.isUsable()) { 5357 IsCorrect = false; 5358 continue; 5359 } 5360 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5361 Res.get(), Res1.get()); 5362 if (!Res.isUsable()) { 5363 IsCorrect = false; 5364 continue; 5365 } 5366 } 5367 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5368 if (!Res.isUsable()) { 5369 IsCorrect = false; 5370 continue; 5371 } 5372 5373 // Build counter update. 5374 // Build counter. 5375 auto *CounterVD = 5376 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5377 D.IteratorDecl->getBeginLoc(), nullptr, 5378 Res.get()->getType(), nullptr, SC_None); 5379 CounterVD->setImplicit(); 5380 ExprResult RefRes = 5381 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5382 D.IteratorDecl->getBeginLoc()); 5383 // Build counter update. 5384 // I = Begini + counter * Stepi; 5385 ExprResult UpdateRes; 5386 if (D.Range.Step) { 5387 UpdateRes = CreateBuiltinBinOp( 5388 D.AssignmentLoc, BO_Mul, 5389 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5390 } else { 5391 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5392 } 5393 if (!UpdateRes.isUsable()) { 5394 IsCorrect = false; 5395 continue; 5396 } 5397 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5398 UpdateRes.get()); 5399 if (!UpdateRes.isUsable()) { 5400 IsCorrect = false; 5401 continue; 5402 } 5403 ExprResult VDRes = 5404 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5405 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5406 D.IteratorDecl->getBeginLoc()); 5407 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5408 UpdateRes.get()); 5409 if (!UpdateRes.isUsable()) { 5410 IsCorrect = false; 5411 continue; 5412 } 5413 UpdateRes = 5414 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5415 if (!UpdateRes.isUsable()) { 5416 IsCorrect = false; 5417 continue; 5418 } 5419 ExprResult CounterUpdateRes = 5420 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5421 if (!CounterUpdateRes.isUsable()) { 5422 IsCorrect = false; 5423 continue; 5424 } 5425 CounterUpdateRes = 5426 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5427 if (!CounterUpdateRes.isUsable()) { 5428 IsCorrect = false; 5429 continue; 5430 } 5431 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5432 HD.CounterVD = CounterVD; 5433 HD.Upper = Res.get(); 5434 HD.Update = UpdateRes.get(); 5435 HD.CounterUpdate = CounterUpdateRes.get(); 5436 } 5437 } else { 5438 Helpers.assign(ID.size(), {}); 5439 } 5440 if (!IsCorrect) { 5441 // Invalidate all created iterator declarations if error is found. 5442 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5443 if (Decl *ID = D.IteratorDecl) 5444 ID->setInvalidDecl(); 5445 } 5446 return ExprError(); 5447 } 5448 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5449 LLoc, RLoc, ID, Helpers); 5450 } 5451 5452 ExprResult 5453 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5454 Expr *Idx, SourceLocation RLoc) { 5455 Expr *LHSExp = Base; 5456 Expr *RHSExp = Idx; 5457 5458 ExprValueKind VK = VK_LValue; 5459 ExprObjectKind OK = OK_Ordinary; 5460 5461 // Per C++ core issue 1213, the result is an xvalue if either operand is 5462 // a non-lvalue array, and an lvalue otherwise. 5463 if (getLangOpts().CPlusPlus11) { 5464 for (auto *Op : {LHSExp, RHSExp}) { 5465 Op = Op->IgnoreImplicit(); 5466 if (Op->getType()->isArrayType() && !Op->isLValue()) 5467 VK = VK_XValue; 5468 } 5469 } 5470 5471 // Perform default conversions. 5472 if (!LHSExp->getType()->getAs<VectorType>()) { 5473 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5474 if (Result.isInvalid()) 5475 return ExprError(); 5476 LHSExp = Result.get(); 5477 } 5478 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5479 if (Result.isInvalid()) 5480 return ExprError(); 5481 RHSExp = Result.get(); 5482 5483 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5484 5485 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5486 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5487 // in the subscript position. As a result, we need to derive the array base 5488 // and index from the expression types. 5489 Expr *BaseExpr, *IndexExpr; 5490 QualType ResultType; 5491 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5492 BaseExpr = LHSExp; 5493 IndexExpr = RHSExp; 5494 ResultType = Context.DependentTy; 5495 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5496 BaseExpr = LHSExp; 5497 IndexExpr = RHSExp; 5498 ResultType = PTy->getPointeeType(); 5499 } else if (const ObjCObjectPointerType *PTy = 5500 LHSTy->getAs<ObjCObjectPointerType>()) { 5501 BaseExpr = LHSExp; 5502 IndexExpr = RHSExp; 5503 5504 // Use custom logic if this should be the pseudo-object subscript 5505 // expression. 5506 if (!LangOpts.isSubscriptPointerArithmetic()) 5507 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5508 nullptr); 5509 5510 ResultType = PTy->getPointeeType(); 5511 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5512 // Handle the uncommon case of "123[Ptr]". 5513 BaseExpr = RHSExp; 5514 IndexExpr = LHSExp; 5515 ResultType = PTy->getPointeeType(); 5516 } else if (const ObjCObjectPointerType *PTy = 5517 RHSTy->getAs<ObjCObjectPointerType>()) { 5518 // Handle the uncommon case of "123[Ptr]". 5519 BaseExpr = RHSExp; 5520 IndexExpr = LHSExp; 5521 ResultType = PTy->getPointeeType(); 5522 if (!LangOpts.isSubscriptPointerArithmetic()) { 5523 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5524 << ResultType << BaseExpr->getSourceRange(); 5525 return ExprError(); 5526 } 5527 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5528 BaseExpr = LHSExp; // vectors: V[123] 5529 IndexExpr = RHSExp; 5530 // We apply C++ DR1213 to vector subscripting too. 5531 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5532 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5533 if (Materialized.isInvalid()) 5534 return ExprError(); 5535 LHSExp = Materialized.get(); 5536 } 5537 VK = LHSExp->getValueKind(); 5538 if (VK != VK_PRValue) 5539 OK = OK_VectorComponent; 5540 5541 ResultType = VTy->getElementType(); 5542 QualType BaseType = BaseExpr->getType(); 5543 Qualifiers BaseQuals = BaseType.getQualifiers(); 5544 Qualifiers MemberQuals = ResultType.getQualifiers(); 5545 Qualifiers Combined = BaseQuals + MemberQuals; 5546 if (Combined != MemberQuals) 5547 ResultType = Context.getQualifiedType(ResultType, Combined); 5548 } else if (LHSTy->isArrayType()) { 5549 // If we see an array that wasn't promoted by 5550 // DefaultFunctionArrayLvalueConversion, it must be an array that 5551 // wasn't promoted because of the C90 rule that doesn't 5552 // allow promoting non-lvalue arrays. Warn, then 5553 // force the promotion here. 5554 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5555 << LHSExp->getSourceRange(); 5556 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5557 CK_ArrayToPointerDecay).get(); 5558 LHSTy = LHSExp->getType(); 5559 5560 BaseExpr = LHSExp; 5561 IndexExpr = RHSExp; 5562 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5563 } else if (RHSTy->isArrayType()) { 5564 // Same as previous, except for 123[f().a] case 5565 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5566 << RHSExp->getSourceRange(); 5567 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5568 CK_ArrayToPointerDecay).get(); 5569 RHSTy = RHSExp->getType(); 5570 5571 BaseExpr = RHSExp; 5572 IndexExpr = LHSExp; 5573 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5574 } else { 5575 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5576 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5577 } 5578 // C99 6.5.2.1p1 5579 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5580 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5581 << IndexExpr->getSourceRange()); 5582 5583 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5584 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5585 && !IndexExpr->isTypeDependent()) 5586 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5587 5588 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5589 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5590 // type. Note that Functions are not objects, and that (in C99 parlance) 5591 // incomplete types are not object types. 5592 if (ResultType->isFunctionType()) { 5593 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5594 << ResultType << BaseExpr->getSourceRange(); 5595 return ExprError(); 5596 } 5597 5598 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5599 // GNU extension: subscripting on pointer to void 5600 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5601 << BaseExpr->getSourceRange(); 5602 5603 // C forbids expressions of unqualified void type from being l-values. 5604 // See IsCForbiddenLValueType. 5605 if (!ResultType.hasQualifiers()) 5606 VK = VK_PRValue; 5607 } else if (!ResultType->isDependentType() && 5608 RequireCompleteSizedType( 5609 LLoc, ResultType, 5610 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5611 return ExprError(); 5612 5613 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5614 !ResultType.isCForbiddenLValueType()); 5615 5616 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5617 FunctionScopes.size() > 1) { 5618 if (auto *TT = 5619 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5620 for (auto I = FunctionScopes.rbegin(), 5621 E = std::prev(FunctionScopes.rend()); 5622 I != E; ++I) { 5623 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5624 if (CSI == nullptr) 5625 break; 5626 DeclContext *DC = nullptr; 5627 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5628 DC = LSI->CallOperator; 5629 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5630 DC = CRSI->TheCapturedDecl; 5631 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5632 DC = BSI->TheDecl; 5633 if (DC) { 5634 if (DC->containsDecl(TT->getDecl())) 5635 break; 5636 captureVariablyModifiedType( 5637 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5638 } 5639 } 5640 } 5641 } 5642 5643 return new (Context) 5644 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5645 } 5646 5647 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5648 ParmVarDecl *Param) { 5649 if (Param->hasUnparsedDefaultArg()) { 5650 // If we've already cleared out the location for the default argument, 5651 // that means we're parsing it right now. 5652 if (!UnparsedDefaultArgLocs.count(Param)) { 5653 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5654 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5655 Param->setInvalidDecl(); 5656 return true; 5657 } 5658 5659 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5660 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5661 Diag(UnparsedDefaultArgLocs[Param], 5662 diag::note_default_argument_declared_here); 5663 return true; 5664 } 5665 5666 if (Param->hasUninstantiatedDefaultArg() && 5667 InstantiateDefaultArgument(CallLoc, FD, Param)) 5668 return true; 5669 5670 assert(Param->hasInit() && "default argument but no initializer?"); 5671 5672 // If the default expression creates temporaries, we need to 5673 // push them to the current stack of expression temporaries so they'll 5674 // be properly destroyed. 5675 // FIXME: We should really be rebuilding the default argument with new 5676 // bound temporaries; see the comment in PR5810. 5677 // We don't need to do that with block decls, though, because 5678 // blocks in default argument expression can never capture anything. 5679 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5680 // Set the "needs cleanups" bit regardless of whether there are 5681 // any explicit objects. 5682 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5683 5684 // Append all the objects to the cleanup list. Right now, this 5685 // should always be a no-op, because blocks in default argument 5686 // expressions should never be able to capture anything. 5687 assert(!Init->getNumObjects() && 5688 "default argument expression has capturing blocks?"); 5689 } 5690 5691 // We already type-checked the argument, so we know it works. 5692 // Just mark all of the declarations in this potentially-evaluated expression 5693 // as being "referenced". 5694 EnterExpressionEvaluationContext EvalContext( 5695 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5696 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5697 /*SkipLocalVariables=*/true); 5698 return false; 5699 } 5700 5701 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5702 FunctionDecl *FD, ParmVarDecl *Param) { 5703 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5704 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5705 return ExprError(); 5706 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5707 } 5708 5709 Sema::VariadicCallType 5710 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5711 Expr *Fn) { 5712 if (Proto && Proto->isVariadic()) { 5713 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5714 return VariadicConstructor; 5715 else if (Fn && Fn->getType()->isBlockPointerType()) 5716 return VariadicBlock; 5717 else if (FDecl) { 5718 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5719 if (Method->isInstance()) 5720 return VariadicMethod; 5721 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5722 return VariadicMethod; 5723 return VariadicFunction; 5724 } 5725 return VariadicDoesNotApply; 5726 } 5727 5728 namespace { 5729 class FunctionCallCCC final : public FunctionCallFilterCCC { 5730 public: 5731 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5732 unsigned NumArgs, MemberExpr *ME) 5733 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5734 FunctionName(FuncName) {} 5735 5736 bool ValidateCandidate(const TypoCorrection &candidate) override { 5737 if (!candidate.getCorrectionSpecifier() || 5738 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5739 return false; 5740 } 5741 5742 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5743 } 5744 5745 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5746 return std::make_unique<FunctionCallCCC>(*this); 5747 } 5748 5749 private: 5750 const IdentifierInfo *const FunctionName; 5751 }; 5752 } 5753 5754 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5755 FunctionDecl *FDecl, 5756 ArrayRef<Expr *> Args) { 5757 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5758 DeclarationName FuncName = FDecl->getDeclName(); 5759 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5760 5761 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5762 if (TypoCorrection Corrected = S.CorrectTypo( 5763 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5764 S.getScopeForContext(S.CurContext), nullptr, CCC, 5765 Sema::CTK_ErrorRecovery)) { 5766 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5767 if (Corrected.isOverloaded()) { 5768 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5769 OverloadCandidateSet::iterator Best; 5770 for (NamedDecl *CD : Corrected) { 5771 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5772 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5773 OCS); 5774 } 5775 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5776 case OR_Success: 5777 ND = Best->FoundDecl; 5778 Corrected.setCorrectionDecl(ND); 5779 break; 5780 default: 5781 break; 5782 } 5783 } 5784 ND = ND->getUnderlyingDecl(); 5785 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5786 return Corrected; 5787 } 5788 } 5789 return TypoCorrection(); 5790 } 5791 5792 /// ConvertArgumentsForCall - Converts the arguments specified in 5793 /// Args/NumArgs to the parameter types of the function FDecl with 5794 /// function prototype Proto. Call is the call expression itself, and 5795 /// Fn is the function expression. For a C++ member function, this 5796 /// routine does not attempt to convert the object argument. Returns 5797 /// true if the call is ill-formed. 5798 bool 5799 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5800 FunctionDecl *FDecl, 5801 const FunctionProtoType *Proto, 5802 ArrayRef<Expr *> Args, 5803 SourceLocation RParenLoc, 5804 bool IsExecConfig) { 5805 // Bail out early if calling a builtin with custom typechecking. 5806 if (FDecl) 5807 if (unsigned ID = FDecl->getBuiltinID()) 5808 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5809 return false; 5810 5811 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5812 // assignment, to the types of the corresponding parameter, ... 5813 unsigned NumParams = Proto->getNumParams(); 5814 bool Invalid = false; 5815 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5816 unsigned FnKind = Fn->getType()->isBlockPointerType() 5817 ? 1 /* block */ 5818 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5819 : 0 /* function */); 5820 5821 // If too few arguments are available (and we don't have default 5822 // arguments for the remaining parameters), don't make the call. 5823 if (Args.size() < NumParams) { 5824 if (Args.size() < MinArgs) { 5825 TypoCorrection TC; 5826 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5827 unsigned diag_id = 5828 MinArgs == NumParams && !Proto->isVariadic() 5829 ? diag::err_typecheck_call_too_few_args_suggest 5830 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5831 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5832 << static_cast<unsigned>(Args.size()) 5833 << TC.getCorrectionRange()); 5834 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5835 Diag(RParenLoc, 5836 MinArgs == NumParams && !Proto->isVariadic() 5837 ? diag::err_typecheck_call_too_few_args_one 5838 : diag::err_typecheck_call_too_few_args_at_least_one) 5839 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5840 else 5841 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5842 ? diag::err_typecheck_call_too_few_args 5843 : diag::err_typecheck_call_too_few_args_at_least) 5844 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5845 << Fn->getSourceRange(); 5846 5847 // Emit the location of the prototype. 5848 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5849 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5850 5851 return true; 5852 } 5853 // We reserve space for the default arguments when we create 5854 // the call expression, before calling ConvertArgumentsForCall. 5855 assert((Call->getNumArgs() == NumParams) && 5856 "We should have reserved space for the default arguments before!"); 5857 } 5858 5859 // If too many are passed and not variadic, error on the extras and drop 5860 // them. 5861 if (Args.size() > NumParams) { 5862 if (!Proto->isVariadic()) { 5863 TypoCorrection TC; 5864 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5865 unsigned diag_id = 5866 MinArgs == NumParams && !Proto->isVariadic() 5867 ? diag::err_typecheck_call_too_many_args_suggest 5868 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5869 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5870 << static_cast<unsigned>(Args.size()) 5871 << TC.getCorrectionRange()); 5872 } else if (NumParams == 1 && FDecl && 5873 FDecl->getParamDecl(0)->getDeclName()) 5874 Diag(Args[NumParams]->getBeginLoc(), 5875 MinArgs == NumParams 5876 ? diag::err_typecheck_call_too_many_args_one 5877 : diag::err_typecheck_call_too_many_args_at_most_one) 5878 << FnKind << FDecl->getParamDecl(0) 5879 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5880 << SourceRange(Args[NumParams]->getBeginLoc(), 5881 Args.back()->getEndLoc()); 5882 else 5883 Diag(Args[NumParams]->getBeginLoc(), 5884 MinArgs == NumParams 5885 ? diag::err_typecheck_call_too_many_args 5886 : diag::err_typecheck_call_too_many_args_at_most) 5887 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5888 << Fn->getSourceRange() 5889 << SourceRange(Args[NumParams]->getBeginLoc(), 5890 Args.back()->getEndLoc()); 5891 5892 // Emit the location of the prototype. 5893 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5894 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5895 5896 // This deletes the extra arguments. 5897 Call->shrinkNumArgs(NumParams); 5898 return true; 5899 } 5900 } 5901 SmallVector<Expr *, 8> AllArgs; 5902 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5903 5904 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5905 AllArgs, CallType); 5906 if (Invalid) 5907 return true; 5908 unsigned TotalNumArgs = AllArgs.size(); 5909 for (unsigned i = 0; i < TotalNumArgs; ++i) 5910 Call->setArg(i, AllArgs[i]); 5911 5912 Call->computeDependence(); 5913 return false; 5914 } 5915 5916 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5917 const FunctionProtoType *Proto, 5918 unsigned FirstParam, ArrayRef<Expr *> Args, 5919 SmallVectorImpl<Expr *> &AllArgs, 5920 VariadicCallType CallType, bool AllowExplicit, 5921 bool IsListInitialization) { 5922 unsigned NumParams = Proto->getNumParams(); 5923 bool Invalid = false; 5924 size_t ArgIx = 0; 5925 // Continue to check argument types (even if we have too few/many args). 5926 for (unsigned i = FirstParam; i < NumParams; i++) { 5927 QualType ProtoArgType = Proto->getParamType(i); 5928 5929 Expr *Arg; 5930 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5931 if (ArgIx < Args.size()) { 5932 Arg = Args[ArgIx++]; 5933 5934 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5935 diag::err_call_incomplete_argument, Arg)) 5936 return true; 5937 5938 // Strip the unbridged-cast placeholder expression off, if applicable. 5939 bool CFAudited = false; 5940 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5941 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5942 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5943 Arg = stripARCUnbridgedCast(Arg); 5944 else if (getLangOpts().ObjCAutoRefCount && 5945 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5946 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5947 CFAudited = true; 5948 5949 if (Proto->getExtParameterInfo(i).isNoEscape() && 5950 ProtoArgType->isBlockPointerType()) 5951 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5952 BE->getBlockDecl()->setDoesNotEscape(); 5953 5954 InitializedEntity Entity = 5955 Param ? InitializedEntity::InitializeParameter(Context, Param, 5956 ProtoArgType) 5957 : InitializedEntity::InitializeParameter( 5958 Context, ProtoArgType, Proto->isParamConsumed(i)); 5959 5960 // Remember that parameter belongs to a CF audited API. 5961 if (CFAudited) 5962 Entity.setParameterCFAudited(); 5963 5964 ExprResult ArgE = PerformCopyInitialization( 5965 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5966 if (ArgE.isInvalid()) 5967 return true; 5968 5969 Arg = ArgE.getAs<Expr>(); 5970 } else { 5971 assert(Param && "can't use default arguments without a known callee"); 5972 5973 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5974 if (ArgExpr.isInvalid()) 5975 return true; 5976 5977 Arg = ArgExpr.getAs<Expr>(); 5978 } 5979 5980 // Check for array bounds violations for each argument to the call. This 5981 // check only triggers warnings when the argument isn't a more complex Expr 5982 // with its own checking, such as a BinaryOperator. 5983 CheckArrayAccess(Arg); 5984 5985 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5986 CheckStaticArrayArgument(CallLoc, Param, Arg); 5987 5988 AllArgs.push_back(Arg); 5989 } 5990 5991 // If this is a variadic call, handle args passed through "...". 5992 if (CallType != VariadicDoesNotApply) { 5993 // Assume that extern "C" functions with variadic arguments that 5994 // return __unknown_anytype aren't *really* variadic. 5995 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5996 FDecl->isExternC()) { 5997 for (Expr *A : Args.slice(ArgIx)) { 5998 QualType paramType; // ignored 5999 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6000 Invalid |= arg.isInvalid(); 6001 AllArgs.push_back(arg.get()); 6002 } 6003 6004 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6005 } else { 6006 for (Expr *A : Args.slice(ArgIx)) { 6007 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6008 Invalid |= Arg.isInvalid(); 6009 AllArgs.push_back(Arg.get()); 6010 } 6011 } 6012 6013 // Check for array bounds violations. 6014 for (Expr *A : Args.slice(ArgIx)) 6015 CheckArrayAccess(A); 6016 } 6017 return Invalid; 6018 } 6019 6020 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6021 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6022 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6023 TL = DTL.getOriginalLoc(); 6024 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6025 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6026 << ATL.getLocalSourceRange(); 6027 } 6028 6029 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6030 /// array parameter, check that it is non-null, and that if it is formed by 6031 /// array-to-pointer decay, the underlying array is sufficiently large. 6032 /// 6033 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6034 /// array type derivation, then for each call to the function, the value of the 6035 /// corresponding actual argument shall provide access to the first element of 6036 /// an array with at least as many elements as specified by the size expression. 6037 void 6038 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6039 ParmVarDecl *Param, 6040 const Expr *ArgExpr) { 6041 // Static array parameters are not supported in C++. 6042 if (!Param || getLangOpts().CPlusPlus) 6043 return; 6044 6045 QualType OrigTy = Param->getOriginalType(); 6046 6047 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6048 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6049 return; 6050 6051 if (ArgExpr->isNullPointerConstant(Context, 6052 Expr::NPC_NeverValueDependent)) { 6053 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6054 DiagnoseCalleeStaticArrayParam(*this, Param); 6055 return; 6056 } 6057 6058 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6059 if (!CAT) 6060 return; 6061 6062 const ConstantArrayType *ArgCAT = 6063 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6064 if (!ArgCAT) 6065 return; 6066 6067 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6068 ArgCAT->getElementType())) { 6069 if (ArgCAT->getSize().ult(CAT->getSize())) { 6070 Diag(CallLoc, diag::warn_static_array_too_small) 6071 << ArgExpr->getSourceRange() 6072 << (unsigned)ArgCAT->getSize().getZExtValue() 6073 << (unsigned)CAT->getSize().getZExtValue() << 0; 6074 DiagnoseCalleeStaticArrayParam(*this, Param); 6075 } 6076 return; 6077 } 6078 6079 Optional<CharUnits> ArgSize = 6080 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6081 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6082 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6083 Diag(CallLoc, diag::warn_static_array_too_small) 6084 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6085 << (unsigned)ParmSize->getQuantity() << 1; 6086 DiagnoseCalleeStaticArrayParam(*this, Param); 6087 } 6088 } 6089 6090 /// Given a function expression of unknown-any type, try to rebuild it 6091 /// to have a function type. 6092 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6093 6094 /// Is the given type a placeholder that we need to lower out 6095 /// immediately during argument processing? 6096 static bool isPlaceholderToRemoveAsArg(QualType type) { 6097 // Placeholders are never sugared. 6098 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6099 if (!placeholder) return false; 6100 6101 switch (placeholder->getKind()) { 6102 // Ignore all the non-placeholder types. 6103 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6104 case BuiltinType::Id: 6105 #include "clang/Basic/OpenCLImageTypes.def" 6106 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6107 case BuiltinType::Id: 6108 #include "clang/Basic/OpenCLExtensionTypes.def" 6109 // In practice we'll never use this, since all SVE types are sugared 6110 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6111 #define SVE_TYPE(Name, Id, SingletonId) \ 6112 case BuiltinType::Id: 6113 #include "clang/Basic/AArch64SVEACLETypes.def" 6114 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6115 case BuiltinType::Id: 6116 #include "clang/Basic/PPCTypes.def" 6117 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6118 #include "clang/Basic/RISCVVTypes.def" 6119 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6120 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6121 #include "clang/AST/BuiltinTypes.def" 6122 return false; 6123 6124 // We cannot lower out overload sets; they might validly be resolved 6125 // by the call machinery. 6126 case BuiltinType::Overload: 6127 return false; 6128 6129 // Unbridged casts in ARC can be handled in some call positions and 6130 // should be left in place. 6131 case BuiltinType::ARCUnbridgedCast: 6132 return false; 6133 6134 // Pseudo-objects should be converted as soon as possible. 6135 case BuiltinType::PseudoObject: 6136 return true; 6137 6138 // The debugger mode could theoretically but currently does not try 6139 // to resolve unknown-typed arguments based on known parameter types. 6140 case BuiltinType::UnknownAny: 6141 return true; 6142 6143 // These are always invalid as call arguments and should be reported. 6144 case BuiltinType::BoundMember: 6145 case BuiltinType::BuiltinFn: 6146 case BuiltinType::IncompleteMatrixIdx: 6147 case BuiltinType::OMPArraySection: 6148 case BuiltinType::OMPArrayShaping: 6149 case BuiltinType::OMPIterator: 6150 return true; 6151 6152 } 6153 llvm_unreachable("bad builtin type kind"); 6154 } 6155 6156 /// Check an argument list for placeholders that we won't try to 6157 /// handle later. 6158 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6159 // Apply this processing to all the arguments at once instead of 6160 // dying at the first failure. 6161 bool hasInvalid = false; 6162 for (size_t i = 0, e = args.size(); i != e; i++) { 6163 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6164 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6165 if (result.isInvalid()) hasInvalid = true; 6166 else args[i] = result.get(); 6167 } 6168 } 6169 return hasInvalid; 6170 } 6171 6172 /// If a builtin function has a pointer argument with no explicit address 6173 /// space, then it should be able to accept a pointer to any address 6174 /// space as input. In order to do this, we need to replace the 6175 /// standard builtin declaration with one that uses the same address space 6176 /// as the call. 6177 /// 6178 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6179 /// it does not contain any pointer arguments without 6180 /// an address space qualifer. Otherwise the rewritten 6181 /// FunctionDecl is returned. 6182 /// TODO: Handle pointer return types. 6183 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6184 FunctionDecl *FDecl, 6185 MultiExprArg ArgExprs) { 6186 6187 QualType DeclType = FDecl->getType(); 6188 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6189 6190 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6191 ArgExprs.size() < FT->getNumParams()) 6192 return nullptr; 6193 6194 bool NeedsNewDecl = false; 6195 unsigned i = 0; 6196 SmallVector<QualType, 8> OverloadParams; 6197 6198 for (QualType ParamType : FT->param_types()) { 6199 6200 // Convert array arguments to pointer to simplify type lookup. 6201 ExprResult ArgRes = 6202 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6203 if (ArgRes.isInvalid()) 6204 return nullptr; 6205 Expr *Arg = ArgRes.get(); 6206 QualType ArgType = Arg->getType(); 6207 if (!ParamType->isPointerType() || 6208 ParamType.hasAddressSpace() || 6209 !ArgType->isPointerType() || 6210 !ArgType->getPointeeType().hasAddressSpace()) { 6211 OverloadParams.push_back(ParamType); 6212 continue; 6213 } 6214 6215 QualType PointeeType = ParamType->getPointeeType(); 6216 if (PointeeType.hasAddressSpace()) 6217 continue; 6218 6219 NeedsNewDecl = true; 6220 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6221 6222 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6223 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6224 } 6225 6226 if (!NeedsNewDecl) 6227 return nullptr; 6228 6229 FunctionProtoType::ExtProtoInfo EPI; 6230 EPI.Variadic = FT->isVariadic(); 6231 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6232 OverloadParams, EPI); 6233 DeclContext *Parent = FDecl->getParent(); 6234 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6235 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6236 FDecl->getIdentifier(), OverloadTy, 6237 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6238 false, 6239 /*hasPrototype=*/true); 6240 SmallVector<ParmVarDecl*, 16> Params; 6241 FT = cast<FunctionProtoType>(OverloadTy); 6242 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6243 QualType ParamType = FT->getParamType(i); 6244 ParmVarDecl *Parm = 6245 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6246 SourceLocation(), nullptr, ParamType, 6247 /*TInfo=*/nullptr, SC_None, nullptr); 6248 Parm->setScopeInfo(0, i); 6249 Params.push_back(Parm); 6250 } 6251 OverloadDecl->setParams(Params); 6252 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6253 return OverloadDecl; 6254 } 6255 6256 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6257 FunctionDecl *Callee, 6258 MultiExprArg ArgExprs) { 6259 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6260 // similar attributes) really don't like it when functions are called with an 6261 // invalid number of args. 6262 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6263 /*PartialOverloading=*/false) && 6264 !Callee->isVariadic()) 6265 return; 6266 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6267 return; 6268 6269 if (const EnableIfAttr *Attr = 6270 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6271 S.Diag(Fn->getBeginLoc(), 6272 isa<CXXMethodDecl>(Callee) 6273 ? diag::err_ovl_no_viable_member_function_in_call 6274 : diag::err_ovl_no_viable_function_in_call) 6275 << Callee << Callee->getSourceRange(); 6276 S.Diag(Callee->getLocation(), 6277 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6278 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6279 return; 6280 } 6281 } 6282 6283 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6284 const UnresolvedMemberExpr *const UME, Sema &S) { 6285 6286 const auto GetFunctionLevelDCIfCXXClass = 6287 [](Sema &S) -> const CXXRecordDecl * { 6288 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6289 if (!DC || !DC->getParent()) 6290 return nullptr; 6291 6292 // If the call to some member function was made from within a member 6293 // function body 'M' return return 'M's parent. 6294 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6295 return MD->getParent()->getCanonicalDecl(); 6296 // else the call was made from within a default member initializer of a 6297 // class, so return the class. 6298 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6299 return RD->getCanonicalDecl(); 6300 return nullptr; 6301 }; 6302 // If our DeclContext is neither a member function nor a class (in the 6303 // case of a lambda in a default member initializer), we can't have an 6304 // enclosing 'this'. 6305 6306 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6307 if (!CurParentClass) 6308 return false; 6309 6310 // The naming class for implicit member functions call is the class in which 6311 // name lookup starts. 6312 const CXXRecordDecl *const NamingClass = 6313 UME->getNamingClass()->getCanonicalDecl(); 6314 assert(NamingClass && "Must have naming class even for implicit access"); 6315 6316 // If the unresolved member functions were found in a 'naming class' that is 6317 // related (either the same or derived from) to the class that contains the 6318 // member function that itself contained the implicit member access. 6319 6320 return CurParentClass == NamingClass || 6321 CurParentClass->isDerivedFrom(NamingClass); 6322 } 6323 6324 static void 6325 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6326 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6327 6328 if (!UME) 6329 return; 6330 6331 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6332 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6333 // already been captured, or if this is an implicit member function call (if 6334 // it isn't, an attempt to capture 'this' should already have been made). 6335 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6336 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6337 return; 6338 6339 // Check if the naming class in which the unresolved members were found is 6340 // related (same as or is a base of) to the enclosing class. 6341 6342 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6343 return; 6344 6345 6346 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6347 // If the enclosing function is not dependent, then this lambda is 6348 // capture ready, so if we can capture this, do so. 6349 if (!EnclosingFunctionCtx->isDependentContext()) { 6350 // If the current lambda and all enclosing lambdas can capture 'this' - 6351 // then go ahead and capture 'this' (since our unresolved overload set 6352 // contains at least one non-static member function). 6353 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6354 S.CheckCXXThisCapture(CallLoc); 6355 } else if (S.CurContext->isDependentContext()) { 6356 // ... since this is an implicit member reference, that might potentially 6357 // involve a 'this' capture, mark 'this' for potential capture in 6358 // enclosing lambdas. 6359 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6360 CurLSI->addPotentialThisCapture(CallLoc); 6361 } 6362 } 6363 6364 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6365 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6366 Expr *ExecConfig) { 6367 ExprResult Call = 6368 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6369 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6370 if (Call.isInvalid()) 6371 return Call; 6372 6373 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6374 // language modes. 6375 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6376 if (ULE->hasExplicitTemplateArgs() && 6377 ULE->decls_begin() == ULE->decls_end()) { 6378 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6379 ? diag::warn_cxx17_compat_adl_only_template_id 6380 : diag::ext_adl_only_template_id) 6381 << ULE->getName(); 6382 } 6383 } 6384 6385 if (LangOpts.OpenMP) 6386 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6387 ExecConfig); 6388 6389 return Call; 6390 } 6391 6392 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6393 /// This provides the location of the left/right parens and a list of comma 6394 /// locations. 6395 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6396 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6397 Expr *ExecConfig, bool IsExecConfig, 6398 bool AllowRecovery) { 6399 // Since this might be a postfix expression, get rid of ParenListExprs. 6400 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6401 if (Result.isInvalid()) return ExprError(); 6402 Fn = Result.get(); 6403 6404 if (checkArgsForPlaceholders(*this, ArgExprs)) 6405 return ExprError(); 6406 6407 if (getLangOpts().CPlusPlus) { 6408 // If this is a pseudo-destructor expression, build the call immediately. 6409 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6410 if (!ArgExprs.empty()) { 6411 // Pseudo-destructor calls should not have any arguments. 6412 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6413 << FixItHint::CreateRemoval( 6414 SourceRange(ArgExprs.front()->getBeginLoc(), 6415 ArgExprs.back()->getEndLoc())); 6416 } 6417 6418 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6419 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6420 } 6421 if (Fn->getType() == Context.PseudoObjectTy) { 6422 ExprResult result = CheckPlaceholderExpr(Fn); 6423 if (result.isInvalid()) return ExprError(); 6424 Fn = result.get(); 6425 } 6426 6427 // Determine whether this is a dependent call inside a C++ template, 6428 // in which case we won't do any semantic analysis now. 6429 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6430 if (ExecConfig) { 6431 return CUDAKernelCallExpr::Create(Context, Fn, 6432 cast<CallExpr>(ExecConfig), ArgExprs, 6433 Context.DependentTy, VK_PRValue, 6434 RParenLoc, CurFPFeatureOverrides()); 6435 } else { 6436 6437 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6438 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6439 Fn->getBeginLoc()); 6440 6441 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6442 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6443 } 6444 } 6445 6446 // Determine whether this is a call to an object (C++ [over.call.object]). 6447 if (Fn->getType()->isRecordType()) 6448 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6449 RParenLoc); 6450 6451 if (Fn->getType() == Context.UnknownAnyTy) { 6452 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6453 if (result.isInvalid()) return ExprError(); 6454 Fn = result.get(); 6455 } 6456 6457 if (Fn->getType() == Context.BoundMemberTy) { 6458 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6459 RParenLoc, ExecConfig, IsExecConfig, 6460 AllowRecovery); 6461 } 6462 } 6463 6464 // Check for overloaded calls. This can happen even in C due to extensions. 6465 if (Fn->getType() == Context.OverloadTy) { 6466 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6467 6468 // We aren't supposed to apply this logic if there's an '&' involved. 6469 if (!find.HasFormOfMemberPointer) { 6470 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6471 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6472 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6473 OverloadExpr *ovl = find.Expression; 6474 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6475 return BuildOverloadedCallExpr( 6476 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6477 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6478 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6479 RParenLoc, ExecConfig, IsExecConfig, 6480 AllowRecovery); 6481 } 6482 } 6483 6484 // If we're directly calling a function, get the appropriate declaration. 6485 if (Fn->getType() == Context.UnknownAnyTy) { 6486 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6487 if (result.isInvalid()) return ExprError(); 6488 Fn = result.get(); 6489 } 6490 6491 Expr *NakedFn = Fn->IgnoreParens(); 6492 6493 bool CallingNDeclIndirectly = false; 6494 NamedDecl *NDecl = nullptr; 6495 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6496 if (UnOp->getOpcode() == UO_AddrOf) { 6497 CallingNDeclIndirectly = true; 6498 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6499 } 6500 } 6501 6502 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6503 NDecl = DRE->getDecl(); 6504 6505 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6506 if (FDecl && FDecl->getBuiltinID()) { 6507 // Rewrite the function decl for this builtin by replacing parameters 6508 // with no explicit address space with the address space of the arguments 6509 // in ArgExprs. 6510 if ((FDecl = 6511 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6512 NDecl = FDecl; 6513 Fn = DeclRefExpr::Create( 6514 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6515 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6516 nullptr, DRE->isNonOdrUse()); 6517 } 6518 } 6519 } else if (isa<MemberExpr>(NakedFn)) 6520 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6521 6522 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6523 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6524 FD, /*Complain=*/true, Fn->getBeginLoc())) 6525 return ExprError(); 6526 6527 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6528 6529 // If this expression is a call to a builtin function in HIP device 6530 // compilation, allow a pointer-type argument to default address space to be 6531 // passed as a pointer-type parameter to a non-default address space. 6532 // If Arg is declared in the default address space and Param is declared 6533 // in a non-default address space, perform an implicit address space cast to 6534 // the parameter type. 6535 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6536 FD->getBuiltinID()) { 6537 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6538 ParmVarDecl *Param = FD->getParamDecl(Idx); 6539 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6540 !ArgExprs[Idx]->getType()->isPointerType()) 6541 continue; 6542 6543 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6544 auto ArgTy = ArgExprs[Idx]->getType(); 6545 auto ArgPtTy = ArgTy->getPointeeType(); 6546 auto ArgAS = ArgPtTy.getAddressSpace(); 6547 6548 // Add address space cast if target address spaces are different 6549 bool NeedImplicitASC = 6550 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6551 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6552 // or from specific AS which has target AS matching that of Param. 6553 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6554 if (!NeedImplicitASC) 6555 continue; 6556 6557 // First, ensure that the Arg is an RValue. 6558 if (ArgExprs[Idx]->isGLValue()) { 6559 ArgExprs[Idx] = ImplicitCastExpr::Create( 6560 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6561 nullptr, VK_PRValue, FPOptionsOverride()); 6562 } 6563 6564 // Construct a new arg type with address space of Param 6565 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6566 ArgPtQuals.setAddressSpace(ParamAS); 6567 auto NewArgPtTy = 6568 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6569 auto NewArgTy = 6570 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6571 ArgTy.getQualifiers()); 6572 6573 // Finally perform an implicit address space cast 6574 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6575 CK_AddressSpaceConversion) 6576 .get(); 6577 } 6578 } 6579 } 6580 6581 if (Context.isDependenceAllowed() && 6582 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6583 assert(!getLangOpts().CPlusPlus); 6584 assert((Fn->containsErrors() || 6585 llvm::any_of(ArgExprs, 6586 [](clang::Expr *E) { return E->containsErrors(); })) && 6587 "should only occur in error-recovery path."); 6588 QualType ReturnType = 6589 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6590 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6591 : Context.DependentTy; 6592 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6593 Expr::getValueKindForType(ReturnType), RParenLoc, 6594 CurFPFeatureOverrides()); 6595 } 6596 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6597 ExecConfig, IsExecConfig); 6598 } 6599 6600 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6601 // with the specified CallArgs 6602 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6603 MultiExprArg CallArgs) { 6604 StringRef Name = Context.BuiltinInfo.getName(Id); 6605 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6606 Sema::LookupOrdinaryName); 6607 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6608 6609 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6610 assert(BuiltInDecl && "failed to find builtin declaration"); 6611 6612 ExprResult DeclRef = 6613 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6614 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6615 6616 ExprResult Call = 6617 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6618 6619 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6620 return Call.get(); 6621 } 6622 6623 /// Parse a __builtin_astype expression. 6624 /// 6625 /// __builtin_astype( value, dst type ) 6626 /// 6627 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6628 SourceLocation BuiltinLoc, 6629 SourceLocation RParenLoc) { 6630 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6631 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6632 } 6633 6634 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6635 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6636 SourceLocation BuiltinLoc, 6637 SourceLocation RParenLoc) { 6638 ExprValueKind VK = VK_PRValue; 6639 ExprObjectKind OK = OK_Ordinary; 6640 QualType SrcTy = E->getType(); 6641 if (!SrcTy->isDependentType() && 6642 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6643 return ExprError( 6644 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6645 << DestTy << SrcTy << E->getSourceRange()); 6646 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6647 } 6648 6649 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6650 /// provided arguments. 6651 /// 6652 /// __builtin_convertvector( value, dst type ) 6653 /// 6654 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6655 SourceLocation BuiltinLoc, 6656 SourceLocation RParenLoc) { 6657 TypeSourceInfo *TInfo; 6658 GetTypeFromParser(ParsedDestTy, &TInfo); 6659 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6660 } 6661 6662 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6663 /// i.e. an expression not of \p OverloadTy. The expression should 6664 /// unary-convert to an expression of function-pointer or 6665 /// block-pointer type. 6666 /// 6667 /// \param NDecl the declaration being called, if available 6668 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6669 SourceLocation LParenLoc, 6670 ArrayRef<Expr *> Args, 6671 SourceLocation RParenLoc, Expr *Config, 6672 bool IsExecConfig, ADLCallKind UsesADL) { 6673 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6674 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6675 6676 // Functions with 'interrupt' attribute cannot be called directly. 6677 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6678 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6679 return ExprError(); 6680 } 6681 6682 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6683 // so there's some risk when calling out to non-interrupt handler functions 6684 // that the callee might not preserve them. This is easy to diagnose here, 6685 // but can be very challenging to debug. 6686 // Likewise, X86 interrupt handlers may only call routines with attribute 6687 // no_caller_saved_registers since there is no efficient way to 6688 // save and restore the non-GPR state. 6689 if (auto *Caller = getCurFunctionDecl()) { 6690 if (Caller->hasAttr<ARMInterruptAttr>()) { 6691 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6692 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6693 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6694 if (FDecl) 6695 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6696 } 6697 } 6698 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6699 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6700 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6701 if (FDecl) 6702 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6703 } 6704 } 6705 6706 // Promote the function operand. 6707 // We special-case function promotion here because we only allow promoting 6708 // builtin functions to function pointers in the callee of a call. 6709 ExprResult Result; 6710 QualType ResultTy; 6711 if (BuiltinID && 6712 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6713 // Extract the return type from the (builtin) function pointer type. 6714 // FIXME Several builtins still have setType in 6715 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6716 // Builtins.def to ensure they are correct before removing setType calls. 6717 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6718 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6719 ResultTy = FDecl->getCallResultType(); 6720 } else { 6721 Result = CallExprUnaryConversions(Fn); 6722 ResultTy = Context.BoolTy; 6723 } 6724 if (Result.isInvalid()) 6725 return ExprError(); 6726 Fn = Result.get(); 6727 6728 // Check for a valid function type, but only if it is not a builtin which 6729 // requires custom type checking. These will be handled by 6730 // CheckBuiltinFunctionCall below just after creation of the call expression. 6731 const FunctionType *FuncT = nullptr; 6732 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6733 retry: 6734 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6735 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6736 // have type pointer to function". 6737 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6738 if (!FuncT) 6739 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6740 << Fn->getType() << Fn->getSourceRange()); 6741 } else if (const BlockPointerType *BPT = 6742 Fn->getType()->getAs<BlockPointerType>()) { 6743 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6744 } else { 6745 // Handle calls to expressions of unknown-any type. 6746 if (Fn->getType() == Context.UnknownAnyTy) { 6747 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6748 if (rewrite.isInvalid()) 6749 return ExprError(); 6750 Fn = rewrite.get(); 6751 goto retry; 6752 } 6753 6754 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6755 << Fn->getType() << Fn->getSourceRange()); 6756 } 6757 } 6758 6759 // Get the number of parameters in the function prototype, if any. 6760 // We will allocate space for max(Args.size(), NumParams) arguments 6761 // in the call expression. 6762 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6763 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6764 6765 CallExpr *TheCall; 6766 if (Config) { 6767 assert(UsesADL == ADLCallKind::NotADL && 6768 "CUDAKernelCallExpr should not use ADL"); 6769 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6770 Args, ResultTy, VK_PRValue, RParenLoc, 6771 CurFPFeatureOverrides(), NumParams); 6772 } else { 6773 TheCall = 6774 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6775 CurFPFeatureOverrides(), NumParams, UsesADL); 6776 } 6777 6778 if (!Context.isDependenceAllowed()) { 6779 // Forget about the nulled arguments since typo correction 6780 // do not handle them well. 6781 TheCall->shrinkNumArgs(Args.size()); 6782 // C cannot always handle TypoExpr nodes in builtin calls and direct 6783 // function calls as their argument checking don't necessarily handle 6784 // dependent types properly, so make sure any TypoExprs have been 6785 // dealt with. 6786 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6787 if (!Result.isUsable()) return ExprError(); 6788 CallExpr *TheOldCall = TheCall; 6789 TheCall = dyn_cast<CallExpr>(Result.get()); 6790 bool CorrectedTypos = TheCall != TheOldCall; 6791 if (!TheCall) return Result; 6792 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6793 6794 // A new call expression node was created if some typos were corrected. 6795 // However it may not have been constructed with enough storage. In this 6796 // case, rebuild the node with enough storage. The waste of space is 6797 // immaterial since this only happens when some typos were corrected. 6798 if (CorrectedTypos && Args.size() < NumParams) { 6799 if (Config) 6800 TheCall = CUDAKernelCallExpr::Create( 6801 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6802 RParenLoc, CurFPFeatureOverrides(), NumParams); 6803 else 6804 TheCall = 6805 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6806 CurFPFeatureOverrides(), NumParams, UsesADL); 6807 } 6808 // We can now handle the nulled arguments for the default arguments. 6809 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6810 } 6811 6812 // Bail out early if calling a builtin with custom type checking. 6813 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6814 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6815 6816 if (getLangOpts().CUDA) { 6817 if (Config) { 6818 // CUDA: Kernel calls must be to global functions 6819 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6820 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6821 << FDecl << Fn->getSourceRange()); 6822 6823 // CUDA: Kernel function must have 'void' return type 6824 if (!FuncT->getReturnType()->isVoidType() && 6825 !FuncT->getReturnType()->getAs<AutoType>() && 6826 !FuncT->getReturnType()->isInstantiationDependentType()) 6827 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6828 << Fn->getType() << Fn->getSourceRange()); 6829 } else { 6830 // CUDA: Calls to global functions must be configured 6831 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6832 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6833 << FDecl << Fn->getSourceRange()); 6834 } 6835 } 6836 6837 // Check for a valid return type 6838 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6839 FDecl)) 6840 return ExprError(); 6841 6842 // We know the result type of the call, set it. 6843 TheCall->setType(FuncT->getCallResultType(Context)); 6844 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6845 6846 if (Proto) { 6847 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6848 IsExecConfig)) 6849 return ExprError(); 6850 } else { 6851 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6852 6853 if (FDecl) { 6854 // Check if we have too few/too many template arguments, based 6855 // on our knowledge of the function definition. 6856 const FunctionDecl *Def = nullptr; 6857 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6858 Proto = Def->getType()->getAs<FunctionProtoType>(); 6859 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6860 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6861 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6862 } 6863 6864 // If the function we're calling isn't a function prototype, but we have 6865 // a function prototype from a prior declaratiom, use that prototype. 6866 if (!FDecl->hasPrototype()) 6867 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6868 } 6869 6870 // Promote the arguments (C99 6.5.2.2p6). 6871 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6872 Expr *Arg = Args[i]; 6873 6874 if (Proto && i < Proto->getNumParams()) { 6875 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6876 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6877 ExprResult ArgE = 6878 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6879 if (ArgE.isInvalid()) 6880 return true; 6881 6882 Arg = ArgE.getAs<Expr>(); 6883 6884 } else { 6885 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6886 6887 if (ArgE.isInvalid()) 6888 return true; 6889 6890 Arg = ArgE.getAs<Expr>(); 6891 } 6892 6893 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6894 diag::err_call_incomplete_argument, Arg)) 6895 return ExprError(); 6896 6897 TheCall->setArg(i, Arg); 6898 } 6899 TheCall->computeDependence(); 6900 } 6901 6902 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6903 if (!Method->isStatic()) 6904 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6905 << Fn->getSourceRange()); 6906 6907 // Check for sentinels 6908 if (NDecl) 6909 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6910 6911 // Warn for unions passing across security boundary (CMSE). 6912 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6913 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6914 if (const auto *RT = 6915 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6916 if (RT->getDecl()->isOrContainsUnion()) 6917 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6918 << 0 << i; 6919 } 6920 } 6921 } 6922 6923 // Do special checking on direct calls to functions. 6924 if (FDecl) { 6925 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6926 return ExprError(); 6927 6928 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6929 6930 if (BuiltinID) 6931 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6932 } else if (NDecl) { 6933 if (CheckPointerCall(NDecl, TheCall, Proto)) 6934 return ExprError(); 6935 } else { 6936 if (CheckOtherCall(TheCall, Proto)) 6937 return ExprError(); 6938 } 6939 6940 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6941 } 6942 6943 ExprResult 6944 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6945 SourceLocation RParenLoc, Expr *InitExpr) { 6946 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6947 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6948 6949 TypeSourceInfo *TInfo; 6950 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6951 if (!TInfo) 6952 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6953 6954 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6955 } 6956 6957 ExprResult 6958 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6959 SourceLocation RParenLoc, Expr *LiteralExpr) { 6960 QualType literalType = TInfo->getType(); 6961 6962 if (literalType->isArrayType()) { 6963 if (RequireCompleteSizedType( 6964 LParenLoc, Context.getBaseElementType(literalType), 6965 diag::err_array_incomplete_or_sizeless_type, 6966 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6967 return ExprError(); 6968 if (literalType->isVariableArrayType()) { 6969 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6970 diag::err_variable_object_no_init)) { 6971 return ExprError(); 6972 } 6973 } 6974 } else if (!literalType->isDependentType() && 6975 RequireCompleteType(LParenLoc, literalType, 6976 diag::err_typecheck_decl_incomplete_type, 6977 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6978 return ExprError(); 6979 6980 InitializedEntity Entity 6981 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6982 InitializationKind Kind 6983 = InitializationKind::CreateCStyleCast(LParenLoc, 6984 SourceRange(LParenLoc, RParenLoc), 6985 /*InitList=*/true); 6986 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6987 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6988 &literalType); 6989 if (Result.isInvalid()) 6990 return ExprError(); 6991 LiteralExpr = Result.get(); 6992 6993 bool isFileScope = !CurContext->isFunctionOrMethod(); 6994 6995 // In C, compound literals are l-values for some reason. 6996 // For GCC compatibility, in C++, file-scope array compound literals with 6997 // constant initializers are also l-values, and compound literals are 6998 // otherwise prvalues. 6999 // 7000 // (GCC also treats C++ list-initialized file-scope array prvalues with 7001 // constant initializers as l-values, but that's non-conforming, so we don't 7002 // follow it there.) 7003 // 7004 // FIXME: It would be better to handle the lvalue cases as materializing and 7005 // lifetime-extending a temporary object, but our materialized temporaries 7006 // representation only supports lifetime extension from a variable, not "out 7007 // of thin air". 7008 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7009 // is bound to the result of applying array-to-pointer decay to the compound 7010 // literal. 7011 // FIXME: GCC supports compound literals of reference type, which should 7012 // obviously have a value kind derived from the kind of reference involved. 7013 ExprValueKind VK = 7014 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7015 ? VK_PRValue 7016 : VK_LValue; 7017 7018 if (isFileScope) 7019 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7020 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7021 Expr *Init = ILE->getInit(i); 7022 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7023 } 7024 7025 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7026 VK, LiteralExpr, isFileScope); 7027 if (isFileScope) { 7028 if (!LiteralExpr->isTypeDependent() && 7029 !LiteralExpr->isValueDependent() && 7030 !literalType->isDependentType()) // C99 6.5.2.5p3 7031 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7032 return ExprError(); 7033 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7034 literalType.getAddressSpace() != LangAS::Default) { 7035 // Embedded-C extensions to C99 6.5.2.5: 7036 // "If the compound literal occurs inside the body of a function, the 7037 // type name shall not be qualified by an address-space qualifier." 7038 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7039 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7040 return ExprError(); 7041 } 7042 7043 if (!isFileScope && !getLangOpts().CPlusPlus) { 7044 // Compound literals that have automatic storage duration are destroyed at 7045 // the end of the scope in C; in C++, they're just temporaries. 7046 7047 // Emit diagnostics if it is or contains a C union type that is non-trivial 7048 // to destruct. 7049 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7050 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7051 NTCUC_CompoundLiteral, NTCUK_Destruct); 7052 7053 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7054 if (literalType.isDestructedType()) { 7055 Cleanup.setExprNeedsCleanups(true); 7056 ExprCleanupObjects.push_back(E); 7057 getCurFunction()->setHasBranchProtectedScope(); 7058 } 7059 } 7060 7061 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7062 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7063 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7064 E->getInitializer()->getExprLoc()); 7065 7066 return MaybeBindToTemporary(E); 7067 } 7068 7069 ExprResult 7070 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7071 SourceLocation RBraceLoc) { 7072 // Only produce each kind of designated initialization diagnostic once. 7073 SourceLocation FirstDesignator; 7074 bool DiagnosedArrayDesignator = false; 7075 bool DiagnosedNestedDesignator = false; 7076 bool DiagnosedMixedDesignator = false; 7077 7078 // Check that any designated initializers are syntactically valid in the 7079 // current language mode. 7080 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7081 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7082 if (FirstDesignator.isInvalid()) 7083 FirstDesignator = DIE->getBeginLoc(); 7084 7085 if (!getLangOpts().CPlusPlus) 7086 break; 7087 7088 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7089 DiagnosedNestedDesignator = true; 7090 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7091 << DIE->getDesignatorsSourceRange(); 7092 } 7093 7094 for (auto &Desig : DIE->designators()) { 7095 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7096 DiagnosedArrayDesignator = true; 7097 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7098 << Desig.getSourceRange(); 7099 } 7100 } 7101 7102 if (!DiagnosedMixedDesignator && 7103 !isa<DesignatedInitExpr>(InitArgList[0])) { 7104 DiagnosedMixedDesignator = true; 7105 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7106 << DIE->getSourceRange(); 7107 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7108 << InitArgList[0]->getSourceRange(); 7109 } 7110 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7111 isa<DesignatedInitExpr>(InitArgList[0])) { 7112 DiagnosedMixedDesignator = true; 7113 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7114 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7115 << DIE->getSourceRange(); 7116 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7117 << InitArgList[I]->getSourceRange(); 7118 } 7119 } 7120 7121 if (FirstDesignator.isValid()) { 7122 // Only diagnose designated initiaization as a C++20 extension if we didn't 7123 // already diagnose use of (non-C++20) C99 designator syntax. 7124 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7125 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7126 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7127 ? diag::warn_cxx17_compat_designated_init 7128 : diag::ext_cxx_designated_init); 7129 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7130 Diag(FirstDesignator, diag::ext_designated_init); 7131 } 7132 } 7133 7134 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7135 } 7136 7137 ExprResult 7138 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7139 SourceLocation RBraceLoc) { 7140 // Semantic analysis for initializers is done by ActOnDeclarator() and 7141 // CheckInitializer() - it requires knowledge of the object being initialized. 7142 7143 // Immediately handle non-overload placeholders. Overloads can be 7144 // resolved contextually, but everything else here can't. 7145 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7146 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7147 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7148 7149 // Ignore failures; dropping the entire initializer list because 7150 // of one failure would be terrible for indexing/etc. 7151 if (result.isInvalid()) continue; 7152 7153 InitArgList[I] = result.get(); 7154 } 7155 } 7156 7157 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7158 RBraceLoc); 7159 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7160 return E; 7161 } 7162 7163 /// Do an explicit extend of the given block pointer if we're in ARC. 7164 void Sema::maybeExtendBlockObject(ExprResult &E) { 7165 assert(E.get()->getType()->isBlockPointerType()); 7166 assert(E.get()->isPRValue()); 7167 7168 // Only do this in an r-value context. 7169 if (!getLangOpts().ObjCAutoRefCount) return; 7170 7171 E = ImplicitCastExpr::Create( 7172 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7173 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7174 Cleanup.setExprNeedsCleanups(true); 7175 } 7176 7177 /// Prepare a conversion of the given expression to an ObjC object 7178 /// pointer type. 7179 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7180 QualType type = E.get()->getType(); 7181 if (type->isObjCObjectPointerType()) { 7182 return CK_BitCast; 7183 } else if (type->isBlockPointerType()) { 7184 maybeExtendBlockObject(E); 7185 return CK_BlockPointerToObjCPointerCast; 7186 } else { 7187 assert(type->isPointerType()); 7188 return CK_CPointerToObjCPointerCast; 7189 } 7190 } 7191 7192 /// Prepares for a scalar cast, performing all the necessary stages 7193 /// except the final cast and returning the kind required. 7194 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7195 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7196 // Also, callers should have filtered out the invalid cases with 7197 // pointers. Everything else should be possible. 7198 7199 QualType SrcTy = Src.get()->getType(); 7200 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7201 return CK_NoOp; 7202 7203 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7204 case Type::STK_MemberPointer: 7205 llvm_unreachable("member pointer type in C"); 7206 7207 case Type::STK_CPointer: 7208 case Type::STK_BlockPointer: 7209 case Type::STK_ObjCObjectPointer: 7210 switch (DestTy->getScalarTypeKind()) { 7211 case Type::STK_CPointer: { 7212 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7213 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7214 if (SrcAS != DestAS) 7215 return CK_AddressSpaceConversion; 7216 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7217 return CK_NoOp; 7218 return CK_BitCast; 7219 } 7220 case Type::STK_BlockPointer: 7221 return (SrcKind == Type::STK_BlockPointer 7222 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7223 case Type::STK_ObjCObjectPointer: 7224 if (SrcKind == Type::STK_ObjCObjectPointer) 7225 return CK_BitCast; 7226 if (SrcKind == Type::STK_CPointer) 7227 return CK_CPointerToObjCPointerCast; 7228 maybeExtendBlockObject(Src); 7229 return CK_BlockPointerToObjCPointerCast; 7230 case Type::STK_Bool: 7231 return CK_PointerToBoolean; 7232 case Type::STK_Integral: 7233 return CK_PointerToIntegral; 7234 case Type::STK_Floating: 7235 case Type::STK_FloatingComplex: 7236 case Type::STK_IntegralComplex: 7237 case Type::STK_MemberPointer: 7238 case Type::STK_FixedPoint: 7239 llvm_unreachable("illegal cast from pointer"); 7240 } 7241 llvm_unreachable("Should have returned before this"); 7242 7243 case Type::STK_FixedPoint: 7244 switch (DestTy->getScalarTypeKind()) { 7245 case Type::STK_FixedPoint: 7246 return CK_FixedPointCast; 7247 case Type::STK_Bool: 7248 return CK_FixedPointToBoolean; 7249 case Type::STK_Integral: 7250 return CK_FixedPointToIntegral; 7251 case Type::STK_Floating: 7252 return CK_FixedPointToFloating; 7253 case Type::STK_IntegralComplex: 7254 case Type::STK_FloatingComplex: 7255 Diag(Src.get()->getExprLoc(), 7256 diag::err_unimplemented_conversion_with_fixed_point_type) 7257 << DestTy; 7258 return CK_IntegralCast; 7259 case Type::STK_CPointer: 7260 case Type::STK_ObjCObjectPointer: 7261 case Type::STK_BlockPointer: 7262 case Type::STK_MemberPointer: 7263 llvm_unreachable("illegal cast to pointer type"); 7264 } 7265 llvm_unreachable("Should have returned before this"); 7266 7267 case Type::STK_Bool: // casting from bool is like casting from an integer 7268 case Type::STK_Integral: 7269 switch (DestTy->getScalarTypeKind()) { 7270 case Type::STK_CPointer: 7271 case Type::STK_ObjCObjectPointer: 7272 case Type::STK_BlockPointer: 7273 if (Src.get()->isNullPointerConstant(Context, 7274 Expr::NPC_ValueDependentIsNull)) 7275 return CK_NullToPointer; 7276 return CK_IntegralToPointer; 7277 case Type::STK_Bool: 7278 return CK_IntegralToBoolean; 7279 case Type::STK_Integral: 7280 return CK_IntegralCast; 7281 case Type::STK_Floating: 7282 return CK_IntegralToFloating; 7283 case Type::STK_IntegralComplex: 7284 Src = ImpCastExprToType(Src.get(), 7285 DestTy->castAs<ComplexType>()->getElementType(), 7286 CK_IntegralCast); 7287 return CK_IntegralRealToComplex; 7288 case Type::STK_FloatingComplex: 7289 Src = ImpCastExprToType(Src.get(), 7290 DestTy->castAs<ComplexType>()->getElementType(), 7291 CK_IntegralToFloating); 7292 return CK_FloatingRealToComplex; 7293 case Type::STK_MemberPointer: 7294 llvm_unreachable("member pointer type in C"); 7295 case Type::STK_FixedPoint: 7296 return CK_IntegralToFixedPoint; 7297 } 7298 llvm_unreachable("Should have returned before this"); 7299 7300 case Type::STK_Floating: 7301 switch (DestTy->getScalarTypeKind()) { 7302 case Type::STK_Floating: 7303 return CK_FloatingCast; 7304 case Type::STK_Bool: 7305 return CK_FloatingToBoolean; 7306 case Type::STK_Integral: 7307 return CK_FloatingToIntegral; 7308 case Type::STK_FloatingComplex: 7309 Src = ImpCastExprToType(Src.get(), 7310 DestTy->castAs<ComplexType>()->getElementType(), 7311 CK_FloatingCast); 7312 return CK_FloatingRealToComplex; 7313 case Type::STK_IntegralComplex: 7314 Src = ImpCastExprToType(Src.get(), 7315 DestTy->castAs<ComplexType>()->getElementType(), 7316 CK_FloatingToIntegral); 7317 return CK_IntegralRealToComplex; 7318 case Type::STK_CPointer: 7319 case Type::STK_ObjCObjectPointer: 7320 case Type::STK_BlockPointer: 7321 llvm_unreachable("valid float->pointer cast?"); 7322 case Type::STK_MemberPointer: 7323 llvm_unreachable("member pointer type in C"); 7324 case Type::STK_FixedPoint: 7325 return CK_FloatingToFixedPoint; 7326 } 7327 llvm_unreachable("Should have returned before this"); 7328 7329 case Type::STK_FloatingComplex: 7330 switch (DestTy->getScalarTypeKind()) { 7331 case Type::STK_FloatingComplex: 7332 return CK_FloatingComplexCast; 7333 case Type::STK_IntegralComplex: 7334 return CK_FloatingComplexToIntegralComplex; 7335 case Type::STK_Floating: { 7336 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7337 if (Context.hasSameType(ET, DestTy)) 7338 return CK_FloatingComplexToReal; 7339 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7340 return CK_FloatingCast; 7341 } 7342 case Type::STK_Bool: 7343 return CK_FloatingComplexToBoolean; 7344 case Type::STK_Integral: 7345 Src = ImpCastExprToType(Src.get(), 7346 SrcTy->castAs<ComplexType>()->getElementType(), 7347 CK_FloatingComplexToReal); 7348 return CK_FloatingToIntegral; 7349 case Type::STK_CPointer: 7350 case Type::STK_ObjCObjectPointer: 7351 case Type::STK_BlockPointer: 7352 llvm_unreachable("valid complex float->pointer cast?"); 7353 case Type::STK_MemberPointer: 7354 llvm_unreachable("member pointer type in C"); 7355 case Type::STK_FixedPoint: 7356 Diag(Src.get()->getExprLoc(), 7357 diag::err_unimplemented_conversion_with_fixed_point_type) 7358 << SrcTy; 7359 return CK_IntegralCast; 7360 } 7361 llvm_unreachable("Should have returned before this"); 7362 7363 case Type::STK_IntegralComplex: 7364 switch (DestTy->getScalarTypeKind()) { 7365 case Type::STK_FloatingComplex: 7366 return CK_IntegralComplexToFloatingComplex; 7367 case Type::STK_IntegralComplex: 7368 return CK_IntegralComplexCast; 7369 case Type::STK_Integral: { 7370 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7371 if (Context.hasSameType(ET, DestTy)) 7372 return CK_IntegralComplexToReal; 7373 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7374 return CK_IntegralCast; 7375 } 7376 case Type::STK_Bool: 7377 return CK_IntegralComplexToBoolean; 7378 case Type::STK_Floating: 7379 Src = ImpCastExprToType(Src.get(), 7380 SrcTy->castAs<ComplexType>()->getElementType(), 7381 CK_IntegralComplexToReal); 7382 return CK_IntegralToFloating; 7383 case Type::STK_CPointer: 7384 case Type::STK_ObjCObjectPointer: 7385 case Type::STK_BlockPointer: 7386 llvm_unreachable("valid complex int->pointer cast?"); 7387 case Type::STK_MemberPointer: 7388 llvm_unreachable("member pointer type in C"); 7389 case Type::STK_FixedPoint: 7390 Diag(Src.get()->getExprLoc(), 7391 diag::err_unimplemented_conversion_with_fixed_point_type) 7392 << SrcTy; 7393 return CK_IntegralCast; 7394 } 7395 llvm_unreachable("Should have returned before this"); 7396 } 7397 7398 llvm_unreachable("Unhandled scalar cast"); 7399 } 7400 7401 static bool breakDownVectorType(QualType type, uint64_t &len, 7402 QualType &eltType) { 7403 // Vectors are simple. 7404 if (const VectorType *vecType = type->getAs<VectorType>()) { 7405 len = vecType->getNumElements(); 7406 eltType = vecType->getElementType(); 7407 assert(eltType->isScalarType()); 7408 return true; 7409 } 7410 7411 // We allow lax conversion to and from non-vector types, but only if 7412 // they're real types (i.e. non-complex, non-pointer scalar types). 7413 if (!type->isRealType()) return false; 7414 7415 len = 1; 7416 eltType = type; 7417 return true; 7418 } 7419 7420 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7421 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7422 /// allowed? 7423 /// 7424 /// This will also return false if the two given types do not make sense from 7425 /// the perspective of SVE bitcasts. 7426 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7427 assert(srcTy->isVectorType() || destTy->isVectorType()); 7428 7429 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7430 if (!FirstType->isSizelessBuiltinType()) 7431 return false; 7432 7433 const auto *VecTy = SecondType->getAs<VectorType>(); 7434 return VecTy && 7435 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7436 }; 7437 7438 return ValidScalableConversion(srcTy, destTy) || 7439 ValidScalableConversion(destTy, srcTy); 7440 } 7441 7442 /// Are the two types matrix types and do they have the same dimensions i.e. 7443 /// do they have the same number of rows and the same number of columns? 7444 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7445 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7446 return false; 7447 7448 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7449 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7450 7451 return matSrcType->getNumRows() == matDestType->getNumRows() && 7452 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7453 } 7454 7455 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7456 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7457 7458 uint64_t SrcLen, DestLen; 7459 QualType SrcEltTy, DestEltTy; 7460 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7461 return false; 7462 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7463 return false; 7464 7465 // ASTContext::getTypeSize will return the size rounded up to a 7466 // power of 2, so instead of using that, we need to use the raw 7467 // element size multiplied by the element count. 7468 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7469 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7470 7471 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7472 } 7473 7474 /// Are the two types lax-compatible vector types? That is, given 7475 /// that one of them is a vector, do they have equal storage sizes, 7476 /// where the storage size is the number of elements times the element 7477 /// size? 7478 /// 7479 /// This will also return false if either of the types is neither a 7480 /// vector nor a real type. 7481 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7482 assert(destTy->isVectorType() || srcTy->isVectorType()); 7483 7484 // Disallow lax conversions between scalars and ExtVectors (these 7485 // conversions are allowed for other vector types because common headers 7486 // depend on them). Most scalar OP ExtVector cases are handled by the 7487 // splat path anyway, which does what we want (convert, not bitcast). 7488 // What this rules out for ExtVectors is crazy things like char4*float. 7489 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7490 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7491 7492 return areVectorTypesSameSize(srcTy, destTy); 7493 } 7494 7495 /// Is this a legal conversion between two types, one of which is 7496 /// known to be a vector type? 7497 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7498 assert(destTy->isVectorType() || srcTy->isVectorType()); 7499 7500 switch (Context.getLangOpts().getLaxVectorConversions()) { 7501 case LangOptions::LaxVectorConversionKind::None: 7502 return false; 7503 7504 case LangOptions::LaxVectorConversionKind::Integer: 7505 if (!srcTy->isIntegralOrEnumerationType()) { 7506 auto *Vec = srcTy->getAs<VectorType>(); 7507 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7508 return false; 7509 } 7510 if (!destTy->isIntegralOrEnumerationType()) { 7511 auto *Vec = destTy->getAs<VectorType>(); 7512 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7513 return false; 7514 } 7515 // OK, integer (vector) -> integer (vector) bitcast. 7516 break; 7517 7518 case LangOptions::LaxVectorConversionKind::All: 7519 break; 7520 } 7521 7522 return areLaxCompatibleVectorTypes(srcTy, destTy); 7523 } 7524 7525 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7526 CastKind &Kind) { 7527 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7528 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7529 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7530 << DestTy << SrcTy << R; 7531 } 7532 } else if (SrcTy->isMatrixType()) { 7533 return Diag(R.getBegin(), 7534 diag::err_invalid_conversion_between_matrix_and_type) 7535 << SrcTy << DestTy << R; 7536 } else if (DestTy->isMatrixType()) { 7537 return Diag(R.getBegin(), 7538 diag::err_invalid_conversion_between_matrix_and_type) 7539 << DestTy << SrcTy << R; 7540 } 7541 7542 Kind = CK_MatrixCast; 7543 return false; 7544 } 7545 7546 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7547 CastKind &Kind) { 7548 assert(VectorTy->isVectorType() && "Not a vector type!"); 7549 7550 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7551 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7552 return Diag(R.getBegin(), 7553 Ty->isVectorType() ? 7554 diag::err_invalid_conversion_between_vectors : 7555 diag::err_invalid_conversion_between_vector_and_integer) 7556 << VectorTy << Ty << R; 7557 } else 7558 return Diag(R.getBegin(), 7559 diag::err_invalid_conversion_between_vector_and_scalar) 7560 << VectorTy << Ty << R; 7561 7562 Kind = CK_BitCast; 7563 return false; 7564 } 7565 7566 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7567 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7568 7569 if (DestElemTy == SplattedExpr->getType()) 7570 return SplattedExpr; 7571 7572 assert(DestElemTy->isFloatingType() || 7573 DestElemTy->isIntegralOrEnumerationType()); 7574 7575 CastKind CK; 7576 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7577 // OpenCL requires that we convert `true` boolean expressions to -1, but 7578 // only when splatting vectors. 7579 if (DestElemTy->isFloatingType()) { 7580 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7581 // in two steps: boolean to signed integral, then to floating. 7582 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7583 CK_BooleanToSignedIntegral); 7584 SplattedExpr = CastExprRes.get(); 7585 CK = CK_IntegralToFloating; 7586 } else { 7587 CK = CK_BooleanToSignedIntegral; 7588 } 7589 } else { 7590 ExprResult CastExprRes = SplattedExpr; 7591 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7592 if (CastExprRes.isInvalid()) 7593 return ExprError(); 7594 SplattedExpr = CastExprRes.get(); 7595 } 7596 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7597 } 7598 7599 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7600 Expr *CastExpr, CastKind &Kind) { 7601 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7602 7603 QualType SrcTy = CastExpr->getType(); 7604 7605 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7606 // an ExtVectorType. 7607 // In OpenCL, casts between vectors of different types are not allowed. 7608 // (See OpenCL 6.2). 7609 if (SrcTy->isVectorType()) { 7610 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7611 (getLangOpts().OpenCL && 7612 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7613 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7614 << DestTy << SrcTy << R; 7615 return ExprError(); 7616 } 7617 Kind = CK_BitCast; 7618 return CastExpr; 7619 } 7620 7621 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7622 // conversion will take place first from scalar to elt type, and then 7623 // splat from elt type to vector. 7624 if (SrcTy->isPointerType()) 7625 return Diag(R.getBegin(), 7626 diag::err_invalid_conversion_between_vector_and_scalar) 7627 << DestTy << SrcTy << R; 7628 7629 Kind = CK_VectorSplat; 7630 return prepareVectorSplat(DestTy, CastExpr); 7631 } 7632 7633 ExprResult 7634 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7635 Declarator &D, ParsedType &Ty, 7636 SourceLocation RParenLoc, Expr *CastExpr) { 7637 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7638 "ActOnCastExpr(): missing type or expr"); 7639 7640 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7641 if (D.isInvalidType()) 7642 return ExprError(); 7643 7644 if (getLangOpts().CPlusPlus) { 7645 // Check that there are no default arguments (C++ only). 7646 CheckExtraCXXDefaultArguments(D); 7647 } else { 7648 // Make sure any TypoExprs have been dealt with. 7649 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7650 if (!Res.isUsable()) 7651 return ExprError(); 7652 CastExpr = Res.get(); 7653 } 7654 7655 checkUnusedDeclAttributes(D); 7656 7657 QualType castType = castTInfo->getType(); 7658 Ty = CreateParsedType(castType, castTInfo); 7659 7660 bool isVectorLiteral = false; 7661 7662 // Check for an altivec or OpenCL literal, 7663 // i.e. all the elements are integer constants. 7664 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7665 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7666 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7667 && castType->isVectorType() && (PE || PLE)) { 7668 if (PLE && PLE->getNumExprs() == 0) { 7669 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7670 return ExprError(); 7671 } 7672 if (PE || PLE->getNumExprs() == 1) { 7673 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7674 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7675 isVectorLiteral = true; 7676 } 7677 else 7678 isVectorLiteral = true; 7679 } 7680 7681 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7682 // then handle it as such. 7683 if (isVectorLiteral) 7684 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7685 7686 // If the Expr being casted is a ParenListExpr, handle it specially. 7687 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7688 // sequence of BinOp comma operators. 7689 if (isa<ParenListExpr>(CastExpr)) { 7690 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7691 if (Result.isInvalid()) return ExprError(); 7692 CastExpr = Result.get(); 7693 } 7694 7695 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7696 !getSourceManager().isInSystemMacro(LParenLoc)) 7697 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7698 7699 CheckTollFreeBridgeCast(castType, CastExpr); 7700 7701 CheckObjCBridgeRelatedCast(castType, CastExpr); 7702 7703 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7704 7705 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7706 } 7707 7708 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7709 SourceLocation RParenLoc, Expr *E, 7710 TypeSourceInfo *TInfo) { 7711 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7712 "Expected paren or paren list expression"); 7713 7714 Expr **exprs; 7715 unsigned numExprs; 7716 Expr *subExpr; 7717 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7718 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7719 LiteralLParenLoc = PE->getLParenLoc(); 7720 LiteralRParenLoc = PE->getRParenLoc(); 7721 exprs = PE->getExprs(); 7722 numExprs = PE->getNumExprs(); 7723 } else { // isa<ParenExpr> by assertion at function entrance 7724 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7725 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7726 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7727 exprs = &subExpr; 7728 numExprs = 1; 7729 } 7730 7731 QualType Ty = TInfo->getType(); 7732 assert(Ty->isVectorType() && "Expected vector type"); 7733 7734 SmallVector<Expr *, 8> initExprs; 7735 const VectorType *VTy = Ty->castAs<VectorType>(); 7736 unsigned numElems = VTy->getNumElements(); 7737 7738 // '(...)' form of vector initialization in AltiVec: the number of 7739 // initializers must be one or must match the size of the vector. 7740 // If a single value is specified in the initializer then it will be 7741 // replicated to all the components of the vector 7742 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7743 VTy->getElementType())) 7744 return ExprError(); 7745 if (ShouldSplatAltivecScalarInCast(VTy)) { 7746 // The number of initializers must be one or must match the size of the 7747 // vector. If a single value is specified in the initializer then it will 7748 // be replicated to all the components of the vector 7749 if (numExprs == 1) { 7750 QualType ElemTy = VTy->getElementType(); 7751 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7752 if (Literal.isInvalid()) 7753 return ExprError(); 7754 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7755 PrepareScalarCast(Literal, ElemTy)); 7756 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7757 } 7758 else if (numExprs < numElems) { 7759 Diag(E->getExprLoc(), 7760 diag::err_incorrect_number_of_vector_initializers); 7761 return ExprError(); 7762 } 7763 else 7764 initExprs.append(exprs, exprs + numExprs); 7765 } 7766 else { 7767 // For OpenCL, when the number of initializers is a single value, 7768 // it will be replicated to all components of the vector. 7769 if (getLangOpts().OpenCL && 7770 VTy->getVectorKind() == VectorType::GenericVector && 7771 numExprs == 1) { 7772 QualType ElemTy = VTy->getElementType(); 7773 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7774 if (Literal.isInvalid()) 7775 return ExprError(); 7776 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7777 PrepareScalarCast(Literal, ElemTy)); 7778 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7779 } 7780 7781 initExprs.append(exprs, exprs + numExprs); 7782 } 7783 // FIXME: This means that pretty-printing the final AST will produce curly 7784 // braces instead of the original commas. 7785 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7786 initExprs, LiteralRParenLoc); 7787 initE->setType(Ty); 7788 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7789 } 7790 7791 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7792 /// the ParenListExpr into a sequence of comma binary operators. 7793 ExprResult 7794 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7795 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7796 if (!E) 7797 return OrigExpr; 7798 7799 ExprResult Result(E->getExpr(0)); 7800 7801 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7802 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7803 E->getExpr(i)); 7804 7805 if (Result.isInvalid()) return ExprError(); 7806 7807 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7808 } 7809 7810 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7811 SourceLocation R, 7812 MultiExprArg Val) { 7813 return ParenListExpr::Create(Context, L, Val, R); 7814 } 7815 7816 /// Emit a specialized diagnostic when one expression is a null pointer 7817 /// constant and the other is not a pointer. Returns true if a diagnostic is 7818 /// emitted. 7819 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7820 SourceLocation QuestionLoc) { 7821 Expr *NullExpr = LHSExpr; 7822 Expr *NonPointerExpr = RHSExpr; 7823 Expr::NullPointerConstantKind NullKind = 7824 NullExpr->isNullPointerConstant(Context, 7825 Expr::NPC_ValueDependentIsNotNull); 7826 7827 if (NullKind == Expr::NPCK_NotNull) { 7828 NullExpr = RHSExpr; 7829 NonPointerExpr = LHSExpr; 7830 NullKind = 7831 NullExpr->isNullPointerConstant(Context, 7832 Expr::NPC_ValueDependentIsNotNull); 7833 } 7834 7835 if (NullKind == Expr::NPCK_NotNull) 7836 return false; 7837 7838 if (NullKind == Expr::NPCK_ZeroExpression) 7839 return false; 7840 7841 if (NullKind == Expr::NPCK_ZeroLiteral) { 7842 // In this case, check to make sure that we got here from a "NULL" 7843 // string in the source code. 7844 NullExpr = NullExpr->IgnoreParenImpCasts(); 7845 SourceLocation loc = NullExpr->getExprLoc(); 7846 if (!findMacroSpelling(loc, "NULL")) 7847 return false; 7848 } 7849 7850 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7851 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7852 << NonPointerExpr->getType() << DiagType 7853 << NonPointerExpr->getSourceRange(); 7854 return true; 7855 } 7856 7857 /// Return false if the condition expression is valid, true otherwise. 7858 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7859 QualType CondTy = Cond->getType(); 7860 7861 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7862 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7863 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7864 << CondTy << Cond->getSourceRange(); 7865 return true; 7866 } 7867 7868 // C99 6.5.15p2 7869 if (CondTy->isScalarType()) return false; 7870 7871 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7872 << CondTy << Cond->getSourceRange(); 7873 return true; 7874 } 7875 7876 /// Handle when one or both operands are void type. 7877 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7878 ExprResult &RHS) { 7879 Expr *LHSExpr = LHS.get(); 7880 Expr *RHSExpr = RHS.get(); 7881 7882 if (!LHSExpr->getType()->isVoidType()) 7883 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7884 << RHSExpr->getSourceRange(); 7885 if (!RHSExpr->getType()->isVoidType()) 7886 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7887 << LHSExpr->getSourceRange(); 7888 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7889 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7890 return S.Context.VoidTy; 7891 } 7892 7893 /// Return false if the NullExpr can be promoted to PointerTy, 7894 /// true otherwise. 7895 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7896 QualType PointerTy) { 7897 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7898 !NullExpr.get()->isNullPointerConstant(S.Context, 7899 Expr::NPC_ValueDependentIsNull)) 7900 return true; 7901 7902 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7903 return false; 7904 } 7905 7906 /// Checks compatibility between two pointers and return the resulting 7907 /// type. 7908 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7909 ExprResult &RHS, 7910 SourceLocation Loc) { 7911 QualType LHSTy = LHS.get()->getType(); 7912 QualType RHSTy = RHS.get()->getType(); 7913 7914 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7915 // Two identical pointers types are always compatible. 7916 return LHSTy; 7917 } 7918 7919 QualType lhptee, rhptee; 7920 7921 // Get the pointee types. 7922 bool IsBlockPointer = false; 7923 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7924 lhptee = LHSBTy->getPointeeType(); 7925 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7926 IsBlockPointer = true; 7927 } else { 7928 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7929 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7930 } 7931 7932 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7933 // differently qualified versions of compatible types, the result type is 7934 // a pointer to an appropriately qualified version of the composite 7935 // type. 7936 7937 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7938 // clause doesn't make sense for our extensions. E.g. address space 2 should 7939 // be incompatible with address space 3: they may live on different devices or 7940 // anything. 7941 Qualifiers lhQual = lhptee.getQualifiers(); 7942 Qualifiers rhQual = rhptee.getQualifiers(); 7943 7944 LangAS ResultAddrSpace = LangAS::Default; 7945 LangAS LAddrSpace = lhQual.getAddressSpace(); 7946 LangAS RAddrSpace = rhQual.getAddressSpace(); 7947 7948 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7949 // spaces is disallowed. 7950 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7951 ResultAddrSpace = LAddrSpace; 7952 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7953 ResultAddrSpace = RAddrSpace; 7954 else { 7955 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7956 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7957 << RHS.get()->getSourceRange(); 7958 return QualType(); 7959 } 7960 7961 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7962 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7963 lhQual.removeCVRQualifiers(); 7964 rhQual.removeCVRQualifiers(); 7965 7966 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7967 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7968 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7969 // qual types are compatible iff 7970 // * corresponded types are compatible 7971 // * CVR qualifiers are equal 7972 // * address spaces are equal 7973 // Thus for conditional operator we merge CVR and address space unqualified 7974 // pointees and if there is a composite type we return a pointer to it with 7975 // merged qualifiers. 7976 LHSCastKind = 7977 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7978 RHSCastKind = 7979 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7980 lhQual.removeAddressSpace(); 7981 rhQual.removeAddressSpace(); 7982 7983 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7984 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7985 7986 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7987 7988 if (CompositeTy.isNull()) { 7989 // In this situation, we assume void* type. No especially good 7990 // reason, but this is what gcc does, and we do have to pick 7991 // to get a consistent AST. 7992 QualType incompatTy; 7993 incompatTy = S.Context.getPointerType( 7994 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7995 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7996 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7997 7998 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7999 // for casts between types with incompatible address space qualifiers. 8000 // For the following code the compiler produces casts between global and 8001 // local address spaces of the corresponded innermost pointees: 8002 // local int *global *a; 8003 // global int *global *b; 8004 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8005 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8006 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8007 << RHS.get()->getSourceRange(); 8008 8009 return incompatTy; 8010 } 8011 8012 // The pointer types are compatible. 8013 // In case of OpenCL ResultTy should have the address space qualifier 8014 // which is a superset of address spaces of both the 2nd and the 3rd 8015 // operands of the conditional operator. 8016 QualType ResultTy = [&, ResultAddrSpace]() { 8017 if (S.getLangOpts().OpenCL) { 8018 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8019 CompositeQuals.setAddressSpace(ResultAddrSpace); 8020 return S.Context 8021 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8022 .withCVRQualifiers(MergedCVRQual); 8023 } 8024 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8025 }(); 8026 if (IsBlockPointer) 8027 ResultTy = S.Context.getBlockPointerType(ResultTy); 8028 else 8029 ResultTy = S.Context.getPointerType(ResultTy); 8030 8031 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8032 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8033 return ResultTy; 8034 } 8035 8036 /// Return the resulting type when the operands are both block pointers. 8037 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8038 ExprResult &LHS, 8039 ExprResult &RHS, 8040 SourceLocation Loc) { 8041 QualType LHSTy = LHS.get()->getType(); 8042 QualType RHSTy = RHS.get()->getType(); 8043 8044 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8045 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8046 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8047 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8048 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8049 return destType; 8050 } 8051 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8052 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8053 << RHS.get()->getSourceRange(); 8054 return QualType(); 8055 } 8056 8057 // We have 2 block pointer types. 8058 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8059 } 8060 8061 /// Return the resulting type when the operands are both pointers. 8062 static QualType 8063 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8064 ExprResult &RHS, 8065 SourceLocation Loc) { 8066 // get the pointer types 8067 QualType LHSTy = LHS.get()->getType(); 8068 QualType RHSTy = RHS.get()->getType(); 8069 8070 // get the "pointed to" types 8071 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8072 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8073 8074 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8075 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8076 // Figure out necessary qualifiers (C99 6.5.15p6) 8077 QualType destPointee 8078 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8079 QualType destType = S.Context.getPointerType(destPointee); 8080 // Add qualifiers if necessary. 8081 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8082 // Promote to void*. 8083 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8084 return destType; 8085 } 8086 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8087 QualType destPointee 8088 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8089 QualType destType = S.Context.getPointerType(destPointee); 8090 // Add qualifiers if necessary. 8091 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8092 // Promote to void*. 8093 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8094 return destType; 8095 } 8096 8097 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8098 } 8099 8100 /// Return false if the first expression is not an integer and the second 8101 /// expression is not a pointer, true otherwise. 8102 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8103 Expr* PointerExpr, SourceLocation Loc, 8104 bool IsIntFirstExpr) { 8105 if (!PointerExpr->getType()->isPointerType() || 8106 !Int.get()->getType()->isIntegerType()) 8107 return false; 8108 8109 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8110 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8111 8112 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8113 << Expr1->getType() << Expr2->getType() 8114 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8115 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8116 CK_IntegralToPointer); 8117 return true; 8118 } 8119 8120 /// Simple conversion between integer and floating point types. 8121 /// 8122 /// Used when handling the OpenCL conditional operator where the 8123 /// condition is a vector while the other operands are scalar. 8124 /// 8125 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8126 /// types are either integer or floating type. Between the two 8127 /// operands, the type with the higher rank is defined as the "result 8128 /// type". The other operand needs to be promoted to the same type. No 8129 /// other type promotion is allowed. We cannot use 8130 /// UsualArithmeticConversions() for this purpose, since it always 8131 /// promotes promotable types. 8132 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8133 ExprResult &RHS, 8134 SourceLocation QuestionLoc) { 8135 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8136 if (LHS.isInvalid()) 8137 return QualType(); 8138 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8139 if (RHS.isInvalid()) 8140 return QualType(); 8141 8142 // For conversion purposes, we ignore any qualifiers. 8143 // For example, "const float" and "float" are equivalent. 8144 QualType LHSType = 8145 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8146 QualType RHSType = 8147 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8148 8149 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8150 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8151 << LHSType << LHS.get()->getSourceRange(); 8152 return QualType(); 8153 } 8154 8155 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8156 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8157 << RHSType << RHS.get()->getSourceRange(); 8158 return QualType(); 8159 } 8160 8161 // If both types are identical, no conversion is needed. 8162 if (LHSType == RHSType) 8163 return LHSType; 8164 8165 // Now handle "real" floating types (i.e. float, double, long double). 8166 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8167 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8168 /*IsCompAssign = */ false); 8169 8170 // Finally, we have two differing integer types. 8171 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8172 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8173 } 8174 8175 /// Convert scalar operands to a vector that matches the 8176 /// condition in length. 8177 /// 8178 /// Used when handling the OpenCL conditional operator where the 8179 /// condition is a vector while the other operands are scalar. 8180 /// 8181 /// We first compute the "result type" for the scalar operands 8182 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8183 /// into a vector of that type where the length matches the condition 8184 /// vector type. s6.11.6 requires that the element types of the result 8185 /// and the condition must have the same number of bits. 8186 static QualType 8187 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8188 QualType CondTy, SourceLocation QuestionLoc) { 8189 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8190 if (ResTy.isNull()) return QualType(); 8191 8192 const VectorType *CV = CondTy->getAs<VectorType>(); 8193 assert(CV); 8194 8195 // Determine the vector result type 8196 unsigned NumElements = CV->getNumElements(); 8197 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8198 8199 // Ensure that all types have the same number of bits 8200 if (S.Context.getTypeSize(CV->getElementType()) 8201 != S.Context.getTypeSize(ResTy)) { 8202 // Since VectorTy is created internally, it does not pretty print 8203 // with an OpenCL name. Instead, we just print a description. 8204 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8205 SmallString<64> Str; 8206 llvm::raw_svector_ostream OS(Str); 8207 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8208 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8209 << CondTy << OS.str(); 8210 return QualType(); 8211 } 8212 8213 // Convert operands to the vector result type 8214 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8215 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8216 8217 return VectorTy; 8218 } 8219 8220 /// Return false if this is a valid OpenCL condition vector 8221 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8222 SourceLocation QuestionLoc) { 8223 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8224 // integral type. 8225 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8226 assert(CondTy); 8227 QualType EleTy = CondTy->getElementType(); 8228 if (EleTy->isIntegerType()) return false; 8229 8230 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8231 << Cond->getType() << Cond->getSourceRange(); 8232 return true; 8233 } 8234 8235 /// Return false if the vector condition type and the vector 8236 /// result type are compatible. 8237 /// 8238 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8239 /// number of elements, and their element types have the same number 8240 /// of bits. 8241 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8242 SourceLocation QuestionLoc) { 8243 const VectorType *CV = CondTy->getAs<VectorType>(); 8244 const VectorType *RV = VecResTy->getAs<VectorType>(); 8245 assert(CV && RV); 8246 8247 if (CV->getNumElements() != RV->getNumElements()) { 8248 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8249 << CondTy << VecResTy; 8250 return true; 8251 } 8252 8253 QualType CVE = CV->getElementType(); 8254 QualType RVE = RV->getElementType(); 8255 8256 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8257 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8258 << CondTy << VecResTy; 8259 return true; 8260 } 8261 8262 return false; 8263 } 8264 8265 /// Return the resulting type for the conditional operator in 8266 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8267 /// s6.3.i) when the condition is a vector type. 8268 static QualType 8269 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8270 ExprResult &LHS, ExprResult &RHS, 8271 SourceLocation QuestionLoc) { 8272 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8273 if (Cond.isInvalid()) 8274 return QualType(); 8275 QualType CondTy = Cond.get()->getType(); 8276 8277 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8278 return QualType(); 8279 8280 // If either operand is a vector then find the vector type of the 8281 // result as specified in OpenCL v1.1 s6.3.i. 8282 if (LHS.get()->getType()->isVectorType() || 8283 RHS.get()->getType()->isVectorType()) { 8284 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8285 /*isCompAssign*/false, 8286 /*AllowBothBool*/true, 8287 /*AllowBoolConversions*/false); 8288 if (VecResTy.isNull()) return QualType(); 8289 // The result type must match the condition type as specified in 8290 // OpenCL v1.1 s6.11.6. 8291 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8292 return QualType(); 8293 return VecResTy; 8294 } 8295 8296 // Both operands are scalar. 8297 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8298 } 8299 8300 /// Return true if the Expr is block type 8301 static bool checkBlockType(Sema &S, const Expr *E) { 8302 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8303 QualType Ty = CE->getCallee()->getType(); 8304 if (Ty->isBlockPointerType()) { 8305 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8306 return true; 8307 } 8308 } 8309 return false; 8310 } 8311 8312 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8313 /// In that case, LHS = cond. 8314 /// C99 6.5.15 8315 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8316 ExprResult &RHS, ExprValueKind &VK, 8317 ExprObjectKind &OK, 8318 SourceLocation QuestionLoc) { 8319 8320 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8321 if (!LHSResult.isUsable()) return QualType(); 8322 LHS = LHSResult; 8323 8324 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8325 if (!RHSResult.isUsable()) return QualType(); 8326 RHS = RHSResult; 8327 8328 // C++ is sufficiently different to merit its own checker. 8329 if (getLangOpts().CPlusPlus) 8330 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8331 8332 VK = VK_PRValue; 8333 OK = OK_Ordinary; 8334 8335 if (Context.isDependenceAllowed() && 8336 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8337 RHS.get()->isTypeDependent())) { 8338 assert(!getLangOpts().CPlusPlus); 8339 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8340 RHS.get()->containsErrors()) && 8341 "should only occur in error-recovery path."); 8342 return Context.DependentTy; 8343 } 8344 8345 // The OpenCL operator with a vector condition is sufficiently 8346 // different to merit its own checker. 8347 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8348 Cond.get()->getType()->isExtVectorType()) 8349 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8350 8351 // First, check the condition. 8352 Cond = UsualUnaryConversions(Cond.get()); 8353 if (Cond.isInvalid()) 8354 return QualType(); 8355 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8356 return QualType(); 8357 8358 // Now check the two expressions. 8359 if (LHS.get()->getType()->isVectorType() || 8360 RHS.get()->getType()->isVectorType()) 8361 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8362 /*AllowBothBool*/true, 8363 /*AllowBoolConversions*/false); 8364 8365 QualType ResTy = 8366 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8367 if (LHS.isInvalid() || RHS.isInvalid()) 8368 return QualType(); 8369 8370 QualType LHSTy = LHS.get()->getType(); 8371 QualType RHSTy = RHS.get()->getType(); 8372 8373 // Diagnose attempts to convert between __ibm128, __float128 and long double 8374 // where such conversions currently can't be handled. 8375 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8376 Diag(QuestionLoc, 8377 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8378 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8379 return QualType(); 8380 } 8381 8382 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8383 // selection operator (?:). 8384 if (getLangOpts().OpenCL && 8385 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8386 return QualType(); 8387 } 8388 8389 // If both operands have arithmetic type, do the usual arithmetic conversions 8390 // to find a common type: C99 6.5.15p3,5. 8391 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8392 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8393 // different sizes, or between ExtInts and other types. 8394 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8395 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8396 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8397 << RHS.get()->getSourceRange(); 8398 return QualType(); 8399 } 8400 8401 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8402 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8403 8404 return ResTy; 8405 } 8406 8407 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8408 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8409 return LHSTy; 8410 } 8411 8412 // If both operands are the same structure or union type, the result is that 8413 // type. 8414 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8415 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8416 if (LHSRT->getDecl() == RHSRT->getDecl()) 8417 // "If both the operands have structure or union type, the result has 8418 // that type." This implies that CV qualifiers are dropped. 8419 return LHSTy.getUnqualifiedType(); 8420 // FIXME: Type of conditional expression must be complete in C mode. 8421 } 8422 8423 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8424 // The following || allows only one side to be void (a GCC-ism). 8425 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8426 return checkConditionalVoidType(*this, LHS, RHS); 8427 } 8428 8429 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8430 // the type of the other operand." 8431 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8432 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8433 8434 // All objective-c pointer type analysis is done here. 8435 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8436 QuestionLoc); 8437 if (LHS.isInvalid() || RHS.isInvalid()) 8438 return QualType(); 8439 if (!compositeType.isNull()) 8440 return compositeType; 8441 8442 8443 // Handle block pointer types. 8444 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8445 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8446 QuestionLoc); 8447 8448 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8449 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8450 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8451 QuestionLoc); 8452 8453 // GCC compatibility: soften pointer/integer mismatch. Note that 8454 // null pointers have been filtered out by this point. 8455 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8456 /*IsIntFirstExpr=*/true)) 8457 return RHSTy; 8458 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8459 /*IsIntFirstExpr=*/false)) 8460 return LHSTy; 8461 8462 // Allow ?: operations in which both operands have the same 8463 // built-in sizeless type. 8464 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8465 return LHSTy; 8466 8467 // Emit a better diagnostic if one of the expressions is a null pointer 8468 // constant and the other is not a pointer type. In this case, the user most 8469 // likely forgot to take the address of the other expression. 8470 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8471 return QualType(); 8472 8473 // Otherwise, the operands are not compatible. 8474 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8475 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8476 << RHS.get()->getSourceRange(); 8477 return QualType(); 8478 } 8479 8480 /// FindCompositeObjCPointerType - Helper method to find composite type of 8481 /// two objective-c pointer types of the two input expressions. 8482 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8483 SourceLocation QuestionLoc) { 8484 QualType LHSTy = LHS.get()->getType(); 8485 QualType RHSTy = RHS.get()->getType(); 8486 8487 // Handle things like Class and struct objc_class*. Here we case the result 8488 // to the pseudo-builtin, because that will be implicitly cast back to the 8489 // redefinition type if an attempt is made to access its fields. 8490 if (LHSTy->isObjCClassType() && 8491 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8492 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8493 return LHSTy; 8494 } 8495 if (RHSTy->isObjCClassType() && 8496 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8497 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8498 return RHSTy; 8499 } 8500 // And the same for struct objc_object* / id 8501 if (LHSTy->isObjCIdType() && 8502 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8503 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8504 return LHSTy; 8505 } 8506 if (RHSTy->isObjCIdType() && 8507 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8508 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8509 return RHSTy; 8510 } 8511 // And the same for struct objc_selector* / SEL 8512 if (Context.isObjCSelType(LHSTy) && 8513 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8514 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8515 return LHSTy; 8516 } 8517 if (Context.isObjCSelType(RHSTy) && 8518 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8519 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8520 return RHSTy; 8521 } 8522 // Check constraints for Objective-C object pointers types. 8523 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8524 8525 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8526 // Two identical object pointer types are always compatible. 8527 return LHSTy; 8528 } 8529 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8530 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8531 QualType compositeType = LHSTy; 8532 8533 // If both operands are interfaces and either operand can be 8534 // assigned to the other, use that type as the composite 8535 // type. This allows 8536 // xxx ? (A*) a : (B*) b 8537 // where B is a subclass of A. 8538 // 8539 // Additionally, as for assignment, if either type is 'id' 8540 // allow silent coercion. Finally, if the types are 8541 // incompatible then make sure to use 'id' as the composite 8542 // type so the result is acceptable for sending messages to. 8543 8544 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8545 // It could return the composite type. 8546 if (!(compositeType = 8547 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8548 // Nothing more to do. 8549 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8550 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8551 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8552 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8553 } else if ((LHSOPT->isObjCQualifiedIdType() || 8554 RHSOPT->isObjCQualifiedIdType()) && 8555 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8556 true)) { 8557 // Need to handle "id<xx>" explicitly. 8558 // GCC allows qualified id and any Objective-C type to devolve to 8559 // id. Currently localizing to here until clear this should be 8560 // part of ObjCQualifiedIdTypesAreCompatible. 8561 compositeType = Context.getObjCIdType(); 8562 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8563 compositeType = Context.getObjCIdType(); 8564 } else { 8565 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8566 << LHSTy << RHSTy 8567 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8568 QualType incompatTy = Context.getObjCIdType(); 8569 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8570 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8571 return incompatTy; 8572 } 8573 // The object pointer types are compatible. 8574 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8575 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8576 return compositeType; 8577 } 8578 // Check Objective-C object pointer types and 'void *' 8579 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8580 if (getLangOpts().ObjCAutoRefCount) { 8581 // ARC forbids the implicit conversion of object pointers to 'void *', 8582 // so these types are not compatible. 8583 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8584 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8585 LHS = RHS = true; 8586 return QualType(); 8587 } 8588 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8589 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8590 QualType destPointee 8591 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8592 QualType destType = Context.getPointerType(destPointee); 8593 // Add qualifiers if necessary. 8594 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8595 // Promote to void*. 8596 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8597 return destType; 8598 } 8599 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8600 if (getLangOpts().ObjCAutoRefCount) { 8601 // ARC forbids the implicit conversion of object pointers to 'void *', 8602 // so these types are not compatible. 8603 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8604 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8605 LHS = RHS = true; 8606 return QualType(); 8607 } 8608 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8609 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8610 QualType destPointee 8611 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8612 QualType destType = Context.getPointerType(destPointee); 8613 // Add qualifiers if necessary. 8614 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8615 // Promote to void*. 8616 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8617 return destType; 8618 } 8619 return QualType(); 8620 } 8621 8622 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8623 /// ParenRange in parentheses. 8624 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8625 const PartialDiagnostic &Note, 8626 SourceRange ParenRange) { 8627 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8628 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8629 EndLoc.isValid()) { 8630 Self.Diag(Loc, Note) 8631 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8632 << FixItHint::CreateInsertion(EndLoc, ")"); 8633 } else { 8634 // We can't display the parentheses, so just show the bare note. 8635 Self.Diag(Loc, Note) << ParenRange; 8636 } 8637 } 8638 8639 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8640 return BinaryOperator::isAdditiveOp(Opc) || 8641 BinaryOperator::isMultiplicativeOp(Opc) || 8642 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8643 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8644 // not any of the logical operators. Bitwise-xor is commonly used as a 8645 // logical-xor because there is no logical-xor operator. The logical 8646 // operators, including uses of xor, have a high false positive rate for 8647 // precedence warnings. 8648 } 8649 8650 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8651 /// expression, either using a built-in or overloaded operator, 8652 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8653 /// expression. 8654 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8655 Expr **RHSExprs) { 8656 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8657 E = E->IgnoreImpCasts(); 8658 E = E->IgnoreConversionOperatorSingleStep(); 8659 E = E->IgnoreImpCasts(); 8660 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8661 E = MTE->getSubExpr(); 8662 E = E->IgnoreImpCasts(); 8663 } 8664 8665 // Built-in binary operator. 8666 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8667 if (IsArithmeticOp(OP->getOpcode())) { 8668 *Opcode = OP->getOpcode(); 8669 *RHSExprs = OP->getRHS(); 8670 return true; 8671 } 8672 } 8673 8674 // Overloaded operator. 8675 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8676 if (Call->getNumArgs() != 2) 8677 return false; 8678 8679 // Make sure this is really a binary operator that is safe to pass into 8680 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8681 OverloadedOperatorKind OO = Call->getOperator(); 8682 if (OO < OO_Plus || OO > OO_Arrow || 8683 OO == OO_PlusPlus || OO == OO_MinusMinus) 8684 return false; 8685 8686 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8687 if (IsArithmeticOp(OpKind)) { 8688 *Opcode = OpKind; 8689 *RHSExprs = Call->getArg(1); 8690 return true; 8691 } 8692 } 8693 8694 return false; 8695 } 8696 8697 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8698 /// or is a logical expression such as (x==y) which has int type, but is 8699 /// commonly interpreted as boolean. 8700 static bool ExprLooksBoolean(Expr *E) { 8701 E = E->IgnoreParenImpCasts(); 8702 8703 if (E->getType()->isBooleanType()) 8704 return true; 8705 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8706 return OP->isComparisonOp() || OP->isLogicalOp(); 8707 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8708 return OP->getOpcode() == UO_LNot; 8709 if (E->getType()->isPointerType()) 8710 return true; 8711 // FIXME: What about overloaded operator calls returning "unspecified boolean 8712 // type"s (commonly pointer-to-members)? 8713 8714 return false; 8715 } 8716 8717 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8718 /// and binary operator are mixed in a way that suggests the programmer assumed 8719 /// the conditional operator has higher precedence, for example: 8720 /// "int x = a + someBinaryCondition ? 1 : 2". 8721 static void DiagnoseConditionalPrecedence(Sema &Self, 8722 SourceLocation OpLoc, 8723 Expr *Condition, 8724 Expr *LHSExpr, 8725 Expr *RHSExpr) { 8726 BinaryOperatorKind CondOpcode; 8727 Expr *CondRHS; 8728 8729 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8730 return; 8731 if (!ExprLooksBoolean(CondRHS)) 8732 return; 8733 8734 // The condition is an arithmetic binary expression, with a right- 8735 // hand side that looks boolean, so warn. 8736 8737 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8738 ? diag::warn_precedence_bitwise_conditional 8739 : diag::warn_precedence_conditional; 8740 8741 Self.Diag(OpLoc, DiagID) 8742 << Condition->getSourceRange() 8743 << BinaryOperator::getOpcodeStr(CondOpcode); 8744 8745 SuggestParentheses( 8746 Self, OpLoc, 8747 Self.PDiag(diag::note_precedence_silence) 8748 << BinaryOperator::getOpcodeStr(CondOpcode), 8749 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8750 8751 SuggestParentheses(Self, OpLoc, 8752 Self.PDiag(diag::note_precedence_conditional_first), 8753 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8754 } 8755 8756 /// Compute the nullability of a conditional expression. 8757 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8758 QualType LHSTy, QualType RHSTy, 8759 ASTContext &Ctx) { 8760 if (!ResTy->isAnyPointerType()) 8761 return ResTy; 8762 8763 auto GetNullability = [&Ctx](QualType Ty) { 8764 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8765 if (Kind) { 8766 // For our purposes, treat _Nullable_result as _Nullable. 8767 if (*Kind == NullabilityKind::NullableResult) 8768 return NullabilityKind::Nullable; 8769 return *Kind; 8770 } 8771 return NullabilityKind::Unspecified; 8772 }; 8773 8774 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8775 NullabilityKind MergedKind; 8776 8777 // Compute nullability of a binary conditional expression. 8778 if (IsBin) { 8779 if (LHSKind == NullabilityKind::NonNull) 8780 MergedKind = NullabilityKind::NonNull; 8781 else 8782 MergedKind = RHSKind; 8783 // Compute nullability of a normal conditional expression. 8784 } else { 8785 if (LHSKind == NullabilityKind::Nullable || 8786 RHSKind == NullabilityKind::Nullable) 8787 MergedKind = NullabilityKind::Nullable; 8788 else if (LHSKind == NullabilityKind::NonNull) 8789 MergedKind = RHSKind; 8790 else if (RHSKind == NullabilityKind::NonNull) 8791 MergedKind = LHSKind; 8792 else 8793 MergedKind = NullabilityKind::Unspecified; 8794 } 8795 8796 // Return if ResTy already has the correct nullability. 8797 if (GetNullability(ResTy) == MergedKind) 8798 return ResTy; 8799 8800 // Strip all nullability from ResTy. 8801 while (ResTy->getNullability(Ctx)) 8802 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8803 8804 // Create a new AttributedType with the new nullability kind. 8805 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8806 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8807 } 8808 8809 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8810 /// in the case of a the GNU conditional expr extension. 8811 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8812 SourceLocation ColonLoc, 8813 Expr *CondExpr, Expr *LHSExpr, 8814 Expr *RHSExpr) { 8815 if (!Context.isDependenceAllowed()) { 8816 // C cannot handle TypoExpr nodes in the condition because it 8817 // doesn't handle dependent types properly, so make sure any TypoExprs have 8818 // been dealt with before checking the operands. 8819 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8820 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8821 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8822 8823 if (!CondResult.isUsable()) 8824 return ExprError(); 8825 8826 if (LHSExpr) { 8827 if (!LHSResult.isUsable()) 8828 return ExprError(); 8829 } 8830 8831 if (!RHSResult.isUsable()) 8832 return ExprError(); 8833 8834 CondExpr = CondResult.get(); 8835 LHSExpr = LHSResult.get(); 8836 RHSExpr = RHSResult.get(); 8837 } 8838 8839 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8840 // was the condition. 8841 OpaqueValueExpr *opaqueValue = nullptr; 8842 Expr *commonExpr = nullptr; 8843 if (!LHSExpr) { 8844 commonExpr = CondExpr; 8845 // Lower out placeholder types first. This is important so that we don't 8846 // try to capture a placeholder. This happens in few cases in C++; such 8847 // as Objective-C++'s dictionary subscripting syntax. 8848 if (commonExpr->hasPlaceholderType()) { 8849 ExprResult result = CheckPlaceholderExpr(commonExpr); 8850 if (!result.isUsable()) return ExprError(); 8851 commonExpr = result.get(); 8852 } 8853 // We usually want to apply unary conversions *before* saving, except 8854 // in the special case of a C++ l-value conditional. 8855 if (!(getLangOpts().CPlusPlus 8856 && !commonExpr->isTypeDependent() 8857 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8858 && commonExpr->isGLValue() 8859 && commonExpr->isOrdinaryOrBitFieldObject() 8860 && RHSExpr->isOrdinaryOrBitFieldObject() 8861 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8862 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8863 if (commonRes.isInvalid()) 8864 return ExprError(); 8865 commonExpr = commonRes.get(); 8866 } 8867 8868 // If the common expression is a class or array prvalue, materialize it 8869 // so that we can safely refer to it multiple times. 8870 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8871 commonExpr->getType()->isArrayType())) { 8872 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8873 if (MatExpr.isInvalid()) 8874 return ExprError(); 8875 commonExpr = MatExpr.get(); 8876 } 8877 8878 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8879 commonExpr->getType(), 8880 commonExpr->getValueKind(), 8881 commonExpr->getObjectKind(), 8882 commonExpr); 8883 LHSExpr = CondExpr = opaqueValue; 8884 } 8885 8886 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8887 ExprValueKind VK = VK_PRValue; 8888 ExprObjectKind OK = OK_Ordinary; 8889 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8890 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8891 VK, OK, QuestionLoc); 8892 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8893 RHS.isInvalid()) 8894 return ExprError(); 8895 8896 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8897 RHS.get()); 8898 8899 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8900 8901 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8902 Context); 8903 8904 if (!commonExpr) 8905 return new (Context) 8906 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8907 RHS.get(), result, VK, OK); 8908 8909 return new (Context) BinaryConditionalOperator( 8910 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8911 ColonLoc, result, VK, OK); 8912 } 8913 8914 // Check if we have a conversion between incompatible cmse function pointer 8915 // types, that is, a conversion between a function pointer with the 8916 // cmse_nonsecure_call attribute and one without. 8917 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8918 QualType ToType) { 8919 if (const auto *ToFn = 8920 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8921 if (const auto *FromFn = 8922 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8923 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8924 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8925 8926 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8927 } 8928 } 8929 return false; 8930 } 8931 8932 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8933 // being closely modeled after the C99 spec:-). The odd characteristic of this 8934 // routine is it effectively iqnores the qualifiers on the top level pointee. 8935 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8936 // FIXME: add a couple examples in this comment. 8937 static Sema::AssignConvertType 8938 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8939 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8940 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8941 8942 // get the "pointed to" type (ignoring qualifiers at the top level) 8943 const Type *lhptee, *rhptee; 8944 Qualifiers lhq, rhq; 8945 std::tie(lhptee, lhq) = 8946 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8947 std::tie(rhptee, rhq) = 8948 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8949 8950 Sema::AssignConvertType ConvTy = Sema::Compatible; 8951 8952 // C99 6.5.16.1p1: This following citation is common to constraints 8953 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8954 // qualifiers of the type *pointed to* by the right; 8955 8956 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8957 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8958 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8959 // Ignore lifetime for further calculation. 8960 lhq.removeObjCLifetime(); 8961 rhq.removeObjCLifetime(); 8962 } 8963 8964 if (!lhq.compatiblyIncludes(rhq)) { 8965 // Treat address-space mismatches as fatal. 8966 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8967 return Sema::IncompatiblePointerDiscardsQualifiers; 8968 8969 // It's okay to add or remove GC or lifetime qualifiers when converting to 8970 // and from void*. 8971 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8972 .compatiblyIncludes( 8973 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8974 && (lhptee->isVoidType() || rhptee->isVoidType())) 8975 ; // keep old 8976 8977 // Treat lifetime mismatches as fatal. 8978 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8979 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8980 8981 // For GCC/MS compatibility, other qualifier mismatches are treated 8982 // as still compatible in C. 8983 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8984 } 8985 8986 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8987 // incomplete type and the other is a pointer to a qualified or unqualified 8988 // version of void... 8989 if (lhptee->isVoidType()) { 8990 if (rhptee->isIncompleteOrObjectType()) 8991 return ConvTy; 8992 8993 // As an extension, we allow cast to/from void* to function pointer. 8994 assert(rhptee->isFunctionType()); 8995 return Sema::FunctionVoidPointer; 8996 } 8997 8998 if (rhptee->isVoidType()) { 8999 if (lhptee->isIncompleteOrObjectType()) 9000 return ConvTy; 9001 9002 // As an extension, we allow cast to/from void* to function pointer. 9003 assert(lhptee->isFunctionType()); 9004 return Sema::FunctionVoidPointer; 9005 } 9006 9007 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9008 // unqualified versions of compatible types, ... 9009 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9010 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9011 // Check if the pointee types are compatible ignoring the sign. 9012 // We explicitly check for char so that we catch "char" vs 9013 // "unsigned char" on systems where "char" is unsigned. 9014 if (lhptee->isCharType()) 9015 ltrans = S.Context.UnsignedCharTy; 9016 else if (lhptee->hasSignedIntegerRepresentation()) 9017 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9018 9019 if (rhptee->isCharType()) 9020 rtrans = S.Context.UnsignedCharTy; 9021 else if (rhptee->hasSignedIntegerRepresentation()) 9022 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9023 9024 if (ltrans == rtrans) { 9025 // Types are compatible ignoring the sign. Qualifier incompatibility 9026 // takes priority over sign incompatibility because the sign 9027 // warning can be disabled. 9028 if (ConvTy != Sema::Compatible) 9029 return ConvTy; 9030 9031 return Sema::IncompatiblePointerSign; 9032 } 9033 9034 // If we are a multi-level pointer, it's possible that our issue is simply 9035 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9036 // the eventual target type is the same and the pointers have the same 9037 // level of indirection, this must be the issue. 9038 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9039 do { 9040 std::tie(lhptee, lhq) = 9041 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9042 std::tie(rhptee, rhq) = 9043 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9044 9045 // Inconsistent address spaces at this point is invalid, even if the 9046 // address spaces would be compatible. 9047 // FIXME: This doesn't catch address space mismatches for pointers of 9048 // different nesting levels, like: 9049 // __local int *** a; 9050 // int ** b = a; 9051 // It's not clear how to actually determine when such pointers are 9052 // invalidly incompatible. 9053 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9054 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9055 9056 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9057 9058 if (lhptee == rhptee) 9059 return Sema::IncompatibleNestedPointerQualifiers; 9060 } 9061 9062 // General pointer incompatibility takes priority over qualifiers. 9063 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9064 return Sema::IncompatibleFunctionPointer; 9065 return Sema::IncompatiblePointer; 9066 } 9067 if (!S.getLangOpts().CPlusPlus && 9068 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9069 return Sema::IncompatibleFunctionPointer; 9070 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9071 return Sema::IncompatibleFunctionPointer; 9072 return ConvTy; 9073 } 9074 9075 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9076 /// block pointer types are compatible or whether a block and normal pointer 9077 /// are compatible. It is more restrict than comparing two function pointer 9078 // types. 9079 static Sema::AssignConvertType 9080 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9081 QualType RHSType) { 9082 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9083 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9084 9085 QualType lhptee, rhptee; 9086 9087 // get the "pointed to" type (ignoring qualifiers at the top level) 9088 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9089 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9090 9091 // In C++, the types have to match exactly. 9092 if (S.getLangOpts().CPlusPlus) 9093 return Sema::IncompatibleBlockPointer; 9094 9095 Sema::AssignConvertType ConvTy = Sema::Compatible; 9096 9097 // For blocks we enforce that qualifiers are identical. 9098 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9099 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9100 if (S.getLangOpts().OpenCL) { 9101 LQuals.removeAddressSpace(); 9102 RQuals.removeAddressSpace(); 9103 } 9104 if (LQuals != RQuals) 9105 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9106 9107 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9108 // assignment. 9109 // The current behavior is similar to C++ lambdas. A block might be 9110 // assigned to a variable iff its return type and parameters are compatible 9111 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9112 // an assignment. Presumably it should behave in way that a function pointer 9113 // assignment does in C, so for each parameter and return type: 9114 // * CVR and address space of LHS should be a superset of CVR and address 9115 // space of RHS. 9116 // * unqualified types should be compatible. 9117 if (S.getLangOpts().OpenCL) { 9118 if (!S.Context.typesAreBlockPointerCompatible( 9119 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9120 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9121 return Sema::IncompatibleBlockPointer; 9122 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9123 return Sema::IncompatibleBlockPointer; 9124 9125 return ConvTy; 9126 } 9127 9128 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9129 /// for assignment compatibility. 9130 static Sema::AssignConvertType 9131 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9132 QualType RHSType) { 9133 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9134 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9135 9136 if (LHSType->isObjCBuiltinType()) { 9137 // Class is not compatible with ObjC object pointers. 9138 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9139 !RHSType->isObjCQualifiedClassType()) 9140 return Sema::IncompatiblePointer; 9141 return Sema::Compatible; 9142 } 9143 if (RHSType->isObjCBuiltinType()) { 9144 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9145 !LHSType->isObjCQualifiedClassType()) 9146 return Sema::IncompatiblePointer; 9147 return Sema::Compatible; 9148 } 9149 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9150 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9151 9152 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9153 // make an exception for id<P> 9154 !LHSType->isObjCQualifiedIdType()) 9155 return Sema::CompatiblePointerDiscardsQualifiers; 9156 9157 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9158 return Sema::Compatible; 9159 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9160 return Sema::IncompatibleObjCQualifiedId; 9161 return Sema::IncompatiblePointer; 9162 } 9163 9164 Sema::AssignConvertType 9165 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9166 QualType LHSType, QualType RHSType) { 9167 // Fake up an opaque expression. We don't actually care about what 9168 // cast operations are required, so if CheckAssignmentConstraints 9169 // adds casts to this they'll be wasted, but fortunately that doesn't 9170 // usually happen on valid code. 9171 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9172 ExprResult RHSPtr = &RHSExpr; 9173 CastKind K; 9174 9175 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9176 } 9177 9178 /// This helper function returns true if QT is a vector type that has element 9179 /// type ElementType. 9180 static bool isVector(QualType QT, QualType ElementType) { 9181 if (const VectorType *VT = QT->getAs<VectorType>()) 9182 return VT->getElementType().getCanonicalType() == ElementType; 9183 return false; 9184 } 9185 9186 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9187 /// has code to accommodate several GCC extensions when type checking 9188 /// pointers. Here are some objectionable examples that GCC considers warnings: 9189 /// 9190 /// int a, *pint; 9191 /// short *pshort; 9192 /// struct foo *pfoo; 9193 /// 9194 /// pint = pshort; // warning: assignment from incompatible pointer type 9195 /// a = pint; // warning: assignment makes integer from pointer without a cast 9196 /// pint = a; // warning: assignment makes pointer from integer without a cast 9197 /// pint = pfoo; // warning: assignment from incompatible pointer type 9198 /// 9199 /// As a result, the code for dealing with pointers is more complex than the 9200 /// C99 spec dictates. 9201 /// 9202 /// Sets 'Kind' for any result kind except Incompatible. 9203 Sema::AssignConvertType 9204 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9205 CastKind &Kind, bool ConvertRHS) { 9206 QualType RHSType = RHS.get()->getType(); 9207 QualType OrigLHSType = LHSType; 9208 9209 // Get canonical types. We're not formatting these types, just comparing 9210 // them. 9211 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9212 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9213 9214 // Common case: no conversion required. 9215 if (LHSType == RHSType) { 9216 Kind = CK_NoOp; 9217 return Compatible; 9218 } 9219 9220 // If we have an atomic type, try a non-atomic assignment, then just add an 9221 // atomic qualification step. 9222 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9223 Sema::AssignConvertType result = 9224 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9225 if (result != Compatible) 9226 return result; 9227 if (Kind != CK_NoOp && ConvertRHS) 9228 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9229 Kind = CK_NonAtomicToAtomic; 9230 return Compatible; 9231 } 9232 9233 // If the left-hand side is a reference type, then we are in a 9234 // (rare!) case where we've allowed the use of references in C, 9235 // e.g., as a parameter type in a built-in function. In this case, 9236 // just make sure that the type referenced is compatible with the 9237 // right-hand side type. The caller is responsible for adjusting 9238 // LHSType so that the resulting expression does not have reference 9239 // type. 9240 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9241 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9242 Kind = CK_LValueBitCast; 9243 return Compatible; 9244 } 9245 return Incompatible; 9246 } 9247 9248 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9249 // to the same ExtVector type. 9250 if (LHSType->isExtVectorType()) { 9251 if (RHSType->isExtVectorType()) 9252 return Incompatible; 9253 if (RHSType->isArithmeticType()) { 9254 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9255 if (ConvertRHS) 9256 RHS = prepareVectorSplat(LHSType, RHS.get()); 9257 Kind = CK_VectorSplat; 9258 return Compatible; 9259 } 9260 } 9261 9262 // Conversions to or from vector type. 9263 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9264 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9265 // Allow assignments of an AltiVec vector type to an equivalent GCC 9266 // vector type and vice versa 9267 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9268 Kind = CK_BitCast; 9269 return Compatible; 9270 } 9271 9272 // If we are allowing lax vector conversions, and LHS and RHS are both 9273 // vectors, the total size only needs to be the same. This is a bitcast; 9274 // no bits are changed but the result type is different. 9275 if (isLaxVectorConversion(RHSType, LHSType)) { 9276 Kind = CK_BitCast; 9277 return IncompatibleVectors; 9278 } 9279 } 9280 9281 // When the RHS comes from another lax conversion (e.g. binops between 9282 // scalars and vectors) the result is canonicalized as a vector. When the 9283 // LHS is also a vector, the lax is allowed by the condition above. Handle 9284 // the case where LHS is a scalar. 9285 if (LHSType->isScalarType()) { 9286 const VectorType *VecType = RHSType->getAs<VectorType>(); 9287 if (VecType && VecType->getNumElements() == 1 && 9288 isLaxVectorConversion(RHSType, LHSType)) { 9289 ExprResult *VecExpr = &RHS; 9290 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9291 Kind = CK_BitCast; 9292 return Compatible; 9293 } 9294 } 9295 9296 // Allow assignments between fixed-length and sizeless SVE vectors. 9297 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9298 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9299 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9300 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9301 Kind = CK_BitCast; 9302 return Compatible; 9303 } 9304 9305 return Incompatible; 9306 } 9307 9308 // Diagnose attempts to convert between __ibm128, __float128 and long double 9309 // where such conversions currently can't be handled. 9310 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9311 return Incompatible; 9312 9313 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9314 // discards the imaginary part. 9315 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9316 !LHSType->getAs<ComplexType>()) 9317 return Incompatible; 9318 9319 // Arithmetic conversions. 9320 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9321 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9322 if (ConvertRHS) 9323 Kind = PrepareScalarCast(RHS, LHSType); 9324 return Compatible; 9325 } 9326 9327 // Conversions to normal pointers. 9328 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9329 // U* -> T* 9330 if (isa<PointerType>(RHSType)) { 9331 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9332 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9333 if (AddrSpaceL != AddrSpaceR) 9334 Kind = CK_AddressSpaceConversion; 9335 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9336 Kind = CK_NoOp; 9337 else 9338 Kind = CK_BitCast; 9339 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9340 } 9341 9342 // int -> T* 9343 if (RHSType->isIntegerType()) { 9344 Kind = CK_IntegralToPointer; // FIXME: null? 9345 return IntToPointer; 9346 } 9347 9348 // C pointers are not compatible with ObjC object pointers, 9349 // with two exceptions: 9350 if (isa<ObjCObjectPointerType>(RHSType)) { 9351 // - conversions to void* 9352 if (LHSPointer->getPointeeType()->isVoidType()) { 9353 Kind = CK_BitCast; 9354 return Compatible; 9355 } 9356 9357 // - conversions from 'Class' to the redefinition type 9358 if (RHSType->isObjCClassType() && 9359 Context.hasSameType(LHSType, 9360 Context.getObjCClassRedefinitionType())) { 9361 Kind = CK_BitCast; 9362 return Compatible; 9363 } 9364 9365 Kind = CK_BitCast; 9366 return IncompatiblePointer; 9367 } 9368 9369 // U^ -> void* 9370 if (RHSType->getAs<BlockPointerType>()) { 9371 if (LHSPointer->getPointeeType()->isVoidType()) { 9372 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9373 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9374 ->getPointeeType() 9375 .getAddressSpace(); 9376 Kind = 9377 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9378 return Compatible; 9379 } 9380 } 9381 9382 return Incompatible; 9383 } 9384 9385 // Conversions to block pointers. 9386 if (isa<BlockPointerType>(LHSType)) { 9387 // U^ -> T^ 9388 if (RHSType->isBlockPointerType()) { 9389 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9390 ->getPointeeType() 9391 .getAddressSpace(); 9392 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9393 ->getPointeeType() 9394 .getAddressSpace(); 9395 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9396 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9397 } 9398 9399 // int or null -> T^ 9400 if (RHSType->isIntegerType()) { 9401 Kind = CK_IntegralToPointer; // FIXME: null 9402 return IntToBlockPointer; 9403 } 9404 9405 // id -> T^ 9406 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9407 Kind = CK_AnyPointerToBlockPointerCast; 9408 return Compatible; 9409 } 9410 9411 // void* -> T^ 9412 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9413 if (RHSPT->getPointeeType()->isVoidType()) { 9414 Kind = CK_AnyPointerToBlockPointerCast; 9415 return Compatible; 9416 } 9417 9418 return Incompatible; 9419 } 9420 9421 // Conversions to Objective-C pointers. 9422 if (isa<ObjCObjectPointerType>(LHSType)) { 9423 // A* -> B* 9424 if (RHSType->isObjCObjectPointerType()) { 9425 Kind = CK_BitCast; 9426 Sema::AssignConvertType result = 9427 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9428 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9429 result == Compatible && 9430 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9431 result = IncompatibleObjCWeakRef; 9432 return result; 9433 } 9434 9435 // int or null -> A* 9436 if (RHSType->isIntegerType()) { 9437 Kind = CK_IntegralToPointer; // FIXME: null 9438 return IntToPointer; 9439 } 9440 9441 // In general, C pointers are not compatible with ObjC object pointers, 9442 // with two exceptions: 9443 if (isa<PointerType>(RHSType)) { 9444 Kind = CK_CPointerToObjCPointerCast; 9445 9446 // - conversions from 'void*' 9447 if (RHSType->isVoidPointerType()) { 9448 return Compatible; 9449 } 9450 9451 // - conversions to 'Class' from its redefinition type 9452 if (LHSType->isObjCClassType() && 9453 Context.hasSameType(RHSType, 9454 Context.getObjCClassRedefinitionType())) { 9455 return Compatible; 9456 } 9457 9458 return IncompatiblePointer; 9459 } 9460 9461 // Only under strict condition T^ is compatible with an Objective-C pointer. 9462 if (RHSType->isBlockPointerType() && 9463 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9464 if (ConvertRHS) 9465 maybeExtendBlockObject(RHS); 9466 Kind = CK_BlockPointerToObjCPointerCast; 9467 return Compatible; 9468 } 9469 9470 return Incompatible; 9471 } 9472 9473 // Conversions from pointers that are not covered by the above. 9474 if (isa<PointerType>(RHSType)) { 9475 // T* -> _Bool 9476 if (LHSType == Context.BoolTy) { 9477 Kind = CK_PointerToBoolean; 9478 return Compatible; 9479 } 9480 9481 // T* -> int 9482 if (LHSType->isIntegerType()) { 9483 Kind = CK_PointerToIntegral; 9484 return PointerToInt; 9485 } 9486 9487 return Incompatible; 9488 } 9489 9490 // Conversions from Objective-C pointers that are not covered by the above. 9491 if (isa<ObjCObjectPointerType>(RHSType)) { 9492 // T* -> _Bool 9493 if (LHSType == Context.BoolTy) { 9494 Kind = CK_PointerToBoolean; 9495 return Compatible; 9496 } 9497 9498 // T* -> int 9499 if (LHSType->isIntegerType()) { 9500 Kind = CK_PointerToIntegral; 9501 return PointerToInt; 9502 } 9503 9504 return Incompatible; 9505 } 9506 9507 // struct A -> struct B 9508 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9509 if (Context.typesAreCompatible(LHSType, RHSType)) { 9510 Kind = CK_NoOp; 9511 return Compatible; 9512 } 9513 } 9514 9515 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9516 Kind = CK_IntToOCLSampler; 9517 return Compatible; 9518 } 9519 9520 return Incompatible; 9521 } 9522 9523 /// Constructs a transparent union from an expression that is 9524 /// used to initialize the transparent union. 9525 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9526 ExprResult &EResult, QualType UnionType, 9527 FieldDecl *Field) { 9528 // Build an initializer list that designates the appropriate member 9529 // of the transparent union. 9530 Expr *E = EResult.get(); 9531 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9532 E, SourceLocation()); 9533 Initializer->setType(UnionType); 9534 Initializer->setInitializedFieldInUnion(Field); 9535 9536 // Build a compound literal constructing a value of the transparent 9537 // union type from this initializer list. 9538 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9539 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9540 VK_PRValue, Initializer, false); 9541 } 9542 9543 Sema::AssignConvertType 9544 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9545 ExprResult &RHS) { 9546 QualType RHSType = RHS.get()->getType(); 9547 9548 // If the ArgType is a Union type, we want to handle a potential 9549 // transparent_union GCC extension. 9550 const RecordType *UT = ArgType->getAsUnionType(); 9551 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9552 return Incompatible; 9553 9554 // The field to initialize within the transparent union. 9555 RecordDecl *UD = UT->getDecl(); 9556 FieldDecl *InitField = nullptr; 9557 // It's compatible if the expression matches any of the fields. 9558 for (auto *it : UD->fields()) { 9559 if (it->getType()->isPointerType()) { 9560 // If the transparent union contains a pointer type, we allow: 9561 // 1) void pointer 9562 // 2) null pointer constant 9563 if (RHSType->isPointerType()) 9564 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9565 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9566 InitField = it; 9567 break; 9568 } 9569 9570 if (RHS.get()->isNullPointerConstant(Context, 9571 Expr::NPC_ValueDependentIsNull)) { 9572 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9573 CK_NullToPointer); 9574 InitField = it; 9575 break; 9576 } 9577 } 9578 9579 CastKind Kind; 9580 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9581 == Compatible) { 9582 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9583 InitField = it; 9584 break; 9585 } 9586 } 9587 9588 if (!InitField) 9589 return Incompatible; 9590 9591 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9592 return Compatible; 9593 } 9594 9595 Sema::AssignConvertType 9596 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9597 bool Diagnose, 9598 bool DiagnoseCFAudited, 9599 bool ConvertRHS) { 9600 // We need to be able to tell the caller whether we diagnosed a problem, if 9601 // they ask us to issue diagnostics. 9602 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9603 9604 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9605 // we can't avoid *all* modifications at the moment, so we need some somewhere 9606 // to put the updated value. 9607 ExprResult LocalRHS = CallerRHS; 9608 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9609 9610 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9611 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9612 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9613 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9614 Diag(RHS.get()->getExprLoc(), 9615 diag::warn_noderef_to_dereferenceable_pointer) 9616 << RHS.get()->getSourceRange(); 9617 } 9618 } 9619 } 9620 9621 if (getLangOpts().CPlusPlus) { 9622 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9623 // C++ 5.17p3: If the left operand is not of class type, the 9624 // expression is implicitly converted (C++ 4) to the 9625 // cv-unqualified type of the left operand. 9626 QualType RHSType = RHS.get()->getType(); 9627 if (Diagnose) { 9628 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9629 AA_Assigning); 9630 } else { 9631 ImplicitConversionSequence ICS = 9632 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9633 /*SuppressUserConversions=*/false, 9634 AllowedExplicit::None, 9635 /*InOverloadResolution=*/false, 9636 /*CStyle=*/false, 9637 /*AllowObjCWritebackConversion=*/false); 9638 if (ICS.isFailure()) 9639 return Incompatible; 9640 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9641 ICS, AA_Assigning); 9642 } 9643 if (RHS.isInvalid()) 9644 return Incompatible; 9645 Sema::AssignConvertType result = Compatible; 9646 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9647 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9648 result = IncompatibleObjCWeakRef; 9649 return result; 9650 } 9651 9652 // FIXME: Currently, we fall through and treat C++ classes like C 9653 // structures. 9654 // FIXME: We also fall through for atomics; not sure what should 9655 // happen there, though. 9656 } else if (RHS.get()->getType() == Context.OverloadTy) { 9657 // As a set of extensions to C, we support overloading on functions. These 9658 // functions need to be resolved here. 9659 DeclAccessPair DAP; 9660 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9661 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9662 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9663 else 9664 return Incompatible; 9665 } 9666 9667 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9668 // a null pointer constant. 9669 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9670 LHSType->isBlockPointerType()) && 9671 RHS.get()->isNullPointerConstant(Context, 9672 Expr::NPC_ValueDependentIsNull)) { 9673 if (Diagnose || ConvertRHS) { 9674 CastKind Kind; 9675 CXXCastPath Path; 9676 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9677 /*IgnoreBaseAccess=*/false, Diagnose); 9678 if (ConvertRHS) 9679 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9680 } 9681 return Compatible; 9682 } 9683 9684 // OpenCL queue_t type assignment. 9685 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9686 Context, Expr::NPC_ValueDependentIsNull)) { 9687 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9688 return Compatible; 9689 } 9690 9691 // This check seems unnatural, however it is necessary to ensure the proper 9692 // conversion of functions/arrays. If the conversion were done for all 9693 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9694 // expressions that suppress this implicit conversion (&, sizeof). 9695 // 9696 // Suppress this for references: C++ 8.5.3p5. 9697 if (!LHSType->isReferenceType()) { 9698 // FIXME: We potentially allocate here even if ConvertRHS is false. 9699 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9700 if (RHS.isInvalid()) 9701 return Incompatible; 9702 } 9703 CastKind Kind; 9704 Sema::AssignConvertType result = 9705 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9706 9707 // C99 6.5.16.1p2: The value of the right operand is converted to the 9708 // type of the assignment expression. 9709 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9710 // so that we can use references in built-in functions even in C. 9711 // The getNonReferenceType() call makes sure that the resulting expression 9712 // does not have reference type. 9713 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9714 QualType Ty = LHSType.getNonLValueExprType(Context); 9715 Expr *E = RHS.get(); 9716 9717 // Check for various Objective-C errors. If we are not reporting 9718 // diagnostics and just checking for errors, e.g., during overload 9719 // resolution, return Incompatible to indicate the failure. 9720 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9721 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9722 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9723 if (!Diagnose) 9724 return Incompatible; 9725 } 9726 if (getLangOpts().ObjC && 9727 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9728 E->getType(), E, Diagnose) || 9729 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9730 if (!Diagnose) 9731 return Incompatible; 9732 // Replace the expression with a corrected version and continue so we 9733 // can find further errors. 9734 RHS = E; 9735 return Compatible; 9736 } 9737 9738 if (ConvertRHS) 9739 RHS = ImpCastExprToType(E, Ty, Kind); 9740 } 9741 9742 return result; 9743 } 9744 9745 namespace { 9746 /// The original operand to an operator, prior to the application of the usual 9747 /// arithmetic conversions and converting the arguments of a builtin operator 9748 /// candidate. 9749 struct OriginalOperand { 9750 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9751 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9752 Op = MTE->getSubExpr(); 9753 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9754 Op = BTE->getSubExpr(); 9755 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9756 Orig = ICE->getSubExprAsWritten(); 9757 Conversion = ICE->getConversionFunction(); 9758 } 9759 } 9760 9761 QualType getType() const { return Orig->getType(); } 9762 9763 Expr *Orig; 9764 NamedDecl *Conversion; 9765 }; 9766 } 9767 9768 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9769 ExprResult &RHS) { 9770 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9771 9772 Diag(Loc, diag::err_typecheck_invalid_operands) 9773 << OrigLHS.getType() << OrigRHS.getType() 9774 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9775 9776 // If a user-defined conversion was applied to either of the operands prior 9777 // to applying the built-in operator rules, tell the user about it. 9778 if (OrigLHS.Conversion) { 9779 Diag(OrigLHS.Conversion->getLocation(), 9780 diag::note_typecheck_invalid_operands_converted) 9781 << 0 << LHS.get()->getType(); 9782 } 9783 if (OrigRHS.Conversion) { 9784 Diag(OrigRHS.Conversion->getLocation(), 9785 diag::note_typecheck_invalid_operands_converted) 9786 << 1 << RHS.get()->getType(); 9787 } 9788 9789 return QualType(); 9790 } 9791 9792 // Diagnose cases where a scalar was implicitly converted to a vector and 9793 // diagnose the underlying types. Otherwise, diagnose the error 9794 // as invalid vector logical operands for non-C++ cases. 9795 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9796 ExprResult &RHS) { 9797 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9798 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9799 9800 bool LHSNatVec = LHSType->isVectorType(); 9801 bool RHSNatVec = RHSType->isVectorType(); 9802 9803 if (!(LHSNatVec && RHSNatVec)) { 9804 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9805 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9806 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9807 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9808 << Vector->getSourceRange(); 9809 return QualType(); 9810 } 9811 9812 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9813 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9814 << RHS.get()->getSourceRange(); 9815 9816 return QualType(); 9817 } 9818 9819 /// Try to convert a value of non-vector type to a vector type by converting 9820 /// the type to the element type of the vector and then performing a splat. 9821 /// If the language is OpenCL, we only use conversions that promote scalar 9822 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9823 /// for float->int. 9824 /// 9825 /// OpenCL V2.0 6.2.6.p2: 9826 /// An error shall occur if any scalar operand type has greater rank 9827 /// than the type of the vector element. 9828 /// 9829 /// \param scalar - if non-null, actually perform the conversions 9830 /// \return true if the operation fails (but without diagnosing the failure) 9831 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9832 QualType scalarTy, 9833 QualType vectorEltTy, 9834 QualType vectorTy, 9835 unsigned &DiagID) { 9836 // The conversion to apply to the scalar before splatting it, 9837 // if necessary. 9838 CastKind scalarCast = CK_NoOp; 9839 9840 if (vectorEltTy->isIntegralType(S.Context)) { 9841 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9842 (scalarTy->isIntegerType() && 9843 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9844 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9845 return true; 9846 } 9847 if (!scalarTy->isIntegralType(S.Context)) 9848 return true; 9849 scalarCast = CK_IntegralCast; 9850 } else if (vectorEltTy->isRealFloatingType()) { 9851 if (scalarTy->isRealFloatingType()) { 9852 if (S.getLangOpts().OpenCL && 9853 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9854 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9855 return true; 9856 } 9857 scalarCast = CK_FloatingCast; 9858 } 9859 else if (scalarTy->isIntegralType(S.Context)) 9860 scalarCast = CK_IntegralToFloating; 9861 else 9862 return true; 9863 } else { 9864 return true; 9865 } 9866 9867 // Adjust scalar if desired. 9868 if (scalar) { 9869 if (scalarCast != CK_NoOp) 9870 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9871 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9872 } 9873 return false; 9874 } 9875 9876 /// Convert vector E to a vector with the same number of elements but different 9877 /// element type. 9878 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9879 const auto *VecTy = E->getType()->getAs<VectorType>(); 9880 assert(VecTy && "Expression E must be a vector"); 9881 QualType NewVecTy = S.Context.getVectorType(ElementType, 9882 VecTy->getNumElements(), 9883 VecTy->getVectorKind()); 9884 9885 // Look through the implicit cast. Return the subexpression if its type is 9886 // NewVecTy. 9887 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9888 if (ICE->getSubExpr()->getType() == NewVecTy) 9889 return ICE->getSubExpr(); 9890 9891 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9892 return S.ImpCastExprToType(E, NewVecTy, Cast); 9893 } 9894 9895 /// Test if a (constant) integer Int can be casted to another integer type 9896 /// IntTy without losing precision. 9897 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9898 QualType OtherIntTy) { 9899 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9900 9901 // Reject cases where the value of the Int is unknown as that would 9902 // possibly cause truncation, but accept cases where the scalar can be 9903 // demoted without loss of precision. 9904 Expr::EvalResult EVResult; 9905 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9906 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9907 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9908 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9909 9910 if (CstInt) { 9911 // If the scalar is constant and is of a higher order and has more active 9912 // bits that the vector element type, reject it. 9913 llvm::APSInt Result = EVResult.Val.getInt(); 9914 unsigned NumBits = IntSigned 9915 ? (Result.isNegative() ? Result.getMinSignedBits() 9916 : Result.getActiveBits()) 9917 : Result.getActiveBits(); 9918 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9919 return true; 9920 9921 // If the signedness of the scalar type and the vector element type 9922 // differs and the number of bits is greater than that of the vector 9923 // element reject it. 9924 return (IntSigned != OtherIntSigned && 9925 NumBits > S.Context.getIntWidth(OtherIntTy)); 9926 } 9927 9928 // Reject cases where the value of the scalar is not constant and it's 9929 // order is greater than that of the vector element type. 9930 return (Order < 0); 9931 } 9932 9933 /// Test if a (constant) integer Int can be casted to floating point type 9934 /// FloatTy without losing precision. 9935 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9936 QualType FloatTy) { 9937 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9938 9939 // Determine if the integer constant can be expressed as a floating point 9940 // number of the appropriate type. 9941 Expr::EvalResult EVResult; 9942 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9943 9944 uint64_t Bits = 0; 9945 if (CstInt) { 9946 // Reject constants that would be truncated if they were converted to 9947 // the floating point type. Test by simple to/from conversion. 9948 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9949 // could be avoided if there was a convertFromAPInt method 9950 // which could signal back if implicit truncation occurred. 9951 llvm::APSInt Result = EVResult.Val.getInt(); 9952 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9953 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9954 llvm::APFloat::rmTowardZero); 9955 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9956 !IntTy->hasSignedIntegerRepresentation()); 9957 bool Ignored = false; 9958 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9959 &Ignored); 9960 if (Result != ConvertBack) 9961 return true; 9962 } else { 9963 // Reject types that cannot be fully encoded into the mantissa of 9964 // the float. 9965 Bits = S.Context.getTypeSize(IntTy); 9966 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9967 S.Context.getFloatTypeSemantics(FloatTy)); 9968 if (Bits > FloatPrec) 9969 return true; 9970 } 9971 9972 return false; 9973 } 9974 9975 /// Attempt to convert and splat Scalar into a vector whose types matches 9976 /// Vector following GCC conversion rules. The rule is that implicit 9977 /// conversion can occur when Scalar can be casted to match Vector's element 9978 /// type without causing truncation of Scalar. 9979 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9980 ExprResult *Vector) { 9981 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9982 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9983 const VectorType *VT = VectorTy->getAs<VectorType>(); 9984 9985 assert(!isa<ExtVectorType>(VT) && 9986 "ExtVectorTypes should not be handled here!"); 9987 9988 QualType VectorEltTy = VT->getElementType(); 9989 9990 // Reject cases where the vector element type or the scalar element type are 9991 // not integral or floating point types. 9992 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9993 return true; 9994 9995 // The conversion to apply to the scalar before splatting it, 9996 // if necessary. 9997 CastKind ScalarCast = CK_NoOp; 9998 9999 // Accept cases where the vector elements are integers and the scalar is 10000 // an integer. 10001 // FIXME: Notionally if the scalar was a floating point value with a precise 10002 // integral representation, we could cast it to an appropriate integer 10003 // type and then perform the rest of the checks here. GCC will perform 10004 // this conversion in some cases as determined by the input language. 10005 // We should accept it on a language independent basis. 10006 if (VectorEltTy->isIntegralType(S.Context) && 10007 ScalarTy->isIntegralType(S.Context) && 10008 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10009 10010 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10011 return true; 10012 10013 ScalarCast = CK_IntegralCast; 10014 } else if (VectorEltTy->isIntegralType(S.Context) && 10015 ScalarTy->isRealFloatingType()) { 10016 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10017 ScalarCast = CK_FloatingToIntegral; 10018 else 10019 return true; 10020 } else if (VectorEltTy->isRealFloatingType()) { 10021 if (ScalarTy->isRealFloatingType()) { 10022 10023 // Reject cases where the scalar type is not a constant and has a higher 10024 // Order than the vector element type. 10025 llvm::APFloat Result(0.0); 10026 10027 // Determine whether this is a constant scalar. In the event that the 10028 // value is dependent (and thus cannot be evaluated by the constant 10029 // evaluator), skip the evaluation. This will then diagnose once the 10030 // expression is instantiated. 10031 bool CstScalar = Scalar->get()->isValueDependent() || 10032 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10033 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10034 if (!CstScalar && Order < 0) 10035 return true; 10036 10037 // If the scalar cannot be safely casted to the vector element type, 10038 // reject it. 10039 if (CstScalar) { 10040 bool Truncated = false; 10041 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10042 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10043 if (Truncated) 10044 return true; 10045 } 10046 10047 ScalarCast = CK_FloatingCast; 10048 } else if (ScalarTy->isIntegralType(S.Context)) { 10049 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10050 return true; 10051 10052 ScalarCast = CK_IntegralToFloating; 10053 } else 10054 return true; 10055 } else if (ScalarTy->isEnumeralType()) 10056 return true; 10057 10058 // Adjust scalar if desired. 10059 if (Scalar) { 10060 if (ScalarCast != CK_NoOp) 10061 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10062 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10063 } 10064 return false; 10065 } 10066 10067 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10068 SourceLocation Loc, bool IsCompAssign, 10069 bool AllowBothBool, 10070 bool AllowBoolConversions) { 10071 if (!IsCompAssign) { 10072 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10073 if (LHS.isInvalid()) 10074 return QualType(); 10075 } 10076 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10077 if (RHS.isInvalid()) 10078 return QualType(); 10079 10080 // For conversion purposes, we ignore any qualifiers. 10081 // For example, "const float" and "float" are equivalent. 10082 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10083 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10084 10085 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10086 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10087 assert(LHSVecType || RHSVecType); 10088 10089 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10090 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10091 return InvalidOperands(Loc, LHS, RHS); 10092 10093 // AltiVec-style "vector bool op vector bool" combinations are allowed 10094 // for some operators but not others. 10095 if (!AllowBothBool && 10096 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10097 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10098 return InvalidOperands(Loc, LHS, RHS); 10099 10100 // If the vector types are identical, return. 10101 if (Context.hasSameType(LHSType, RHSType)) 10102 return LHSType; 10103 10104 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10105 if (LHSVecType && RHSVecType && 10106 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10107 if (isa<ExtVectorType>(LHSVecType)) { 10108 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10109 return LHSType; 10110 } 10111 10112 if (!IsCompAssign) 10113 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10114 return RHSType; 10115 } 10116 10117 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10118 // can be mixed, with the result being the non-bool type. The non-bool 10119 // operand must have integer element type. 10120 if (AllowBoolConversions && LHSVecType && RHSVecType && 10121 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10122 (Context.getTypeSize(LHSVecType->getElementType()) == 10123 Context.getTypeSize(RHSVecType->getElementType()))) { 10124 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10125 LHSVecType->getElementType()->isIntegerType() && 10126 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10127 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10128 return LHSType; 10129 } 10130 if (!IsCompAssign && 10131 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10132 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10133 RHSVecType->getElementType()->isIntegerType()) { 10134 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10135 return RHSType; 10136 } 10137 } 10138 10139 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10140 // since the ambiguity can affect the ABI. 10141 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10142 const VectorType *VecType = SecondType->getAs<VectorType>(); 10143 return FirstType->isSizelessBuiltinType() && VecType && 10144 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10145 VecType->getVectorKind() == 10146 VectorType::SveFixedLengthPredicateVector); 10147 }; 10148 10149 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10150 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10151 return QualType(); 10152 } 10153 10154 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10155 // since the ambiguity can affect the ABI. 10156 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10157 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10158 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10159 10160 if (FirstVecType && SecondVecType) 10161 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10162 (SecondVecType->getVectorKind() == 10163 VectorType::SveFixedLengthDataVector || 10164 SecondVecType->getVectorKind() == 10165 VectorType::SveFixedLengthPredicateVector); 10166 10167 return FirstType->isSizelessBuiltinType() && SecondVecType && 10168 SecondVecType->getVectorKind() == VectorType::GenericVector; 10169 }; 10170 10171 if (IsSveGnuConversion(LHSType, RHSType) || 10172 IsSveGnuConversion(RHSType, LHSType)) { 10173 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10174 return QualType(); 10175 } 10176 10177 // If there's a vector type and a scalar, try to convert the scalar to 10178 // the vector element type and splat. 10179 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10180 if (!RHSVecType) { 10181 if (isa<ExtVectorType>(LHSVecType)) { 10182 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10183 LHSVecType->getElementType(), LHSType, 10184 DiagID)) 10185 return LHSType; 10186 } else { 10187 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10188 return LHSType; 10189 } 10190 } 10191 if (!LHSVecType) { 10192 if (isa<ExtVectorType>(RHSVecType)) { 10193 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10194 LHSType, RHSVecType->getElementType(), 10195 RHSType, DiagID)) 10196 return RHSType; 10197 } else { 10198 if (LHS.get()->isLValue() || 10199 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10200 return RHSType; 10201 } 10202 } 10203 10204 // FIXME: The code below also handles conversion between vectors and 10205 // non-scalars, we should break this down into fine grained specific checks 10206 // and emit proper diagnostics. 10207 QualType VecType = LHSVecType ? LHSType : RHSType; 10208 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10209 QualType OtherType = LHSVecType ? RHSType : LHSType; 10210 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10211 if (isLaxVectorConversion(OtherType, VecType)) { 10212 // If we're allowing lax vector conversions, only the total (data) size 10213 // needs to be the same. For non compound assignment, if one of the types is 10214 // scalar, the result is always the vector type. 10215 if (!IsCompAssign) { 10216 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10217 return VecType; 10218 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10219 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10220 // type. Note that this is already done by non-compound assignments in 10221 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10222 // <1 x T> -> T. The result is also a vector type. 10223 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10224 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10225 ExprResult *RHSExpr = &RHS; 10226 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10227 return VecType; 10228 } 10229 } 10230 10231 // Okay, the expression is invalid. 10232 10233 // If there's a non-vector, non-real operand, diagnose that. 10234 if ((!RHSVecType && !RHSType->isRealType()) || 10235 (!LHSVecType && !LHSType->isRealType())) { 10236 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10237 << LHSType << RHSType 10238 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10239 return QualType(); 10240 } 10241 10242 // OpenCL V1.1 6.2.6.p1: 10243 // If the operands are of more than one vector type, then an error shall 10244 // occur. Implicit conversions between vector types are not permitted, per 10245 // section 6.2.1. 10246 if (getLangOpts().OpenCL && 10247 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10248 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10249 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10250 << RHSType; 10251 return QualType(); 10252 } 10253 10254 10255 // If there is a vector type that is not a ExtVector and a scalar, we reach 10256 // this point if scalar could not be converted to the vector's element type 10257 // without truncation. 10258 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10259 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10260 QualType Scalar = LHSVecType ? RHSType : LHSType; 10261 QualType Vector = LHSVecType ? LHSType : RHSType; 10262 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10263 Diag(Loc, 10264 diag::err_typecheck_vector_not_convertable_implict_truncation) 10265 << ScalarOrVector << Scalar << Vector; 10266 10267 return QualType(); 10268 } 10269 10270 // Otherwise, use the generic diagnostic. 10271 Diag(Loc, DiagID) 10272 << LHSType << RHSType 10273 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10274 return QualType(); 10275 } 10276 10277 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10278 // expression. These are mainly cases where the null pointer is used as an 10279 // integer instead of a pointer. 10280 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10281 SourceLocation Loc, bool IsCompare) { 10282 // The canonical way to check for a GNU null is with isNullPointerConstant, 10283 // but we use a bit of a hack here for speed; this is a relatively 10284 // hot path, and isNullPointerConstant is slow. 10285 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10286 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10287 10288 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10289 10290 // Avoid analyzing cases where the result will either be invalid (and 10291 // diagnosed as such) or entirely valid and not something to warn about. 10292 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10293 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10294 return; 10295 10296 // Comparison operations would not make sense with a null pointer no matter 10297 // what the other expression is. 10298 if (!IsCompare) { 10299 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10300 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10301 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10302 return; 10303 } 10304 10305 // The rest of the operations only make sense with a null pointer 10306 // if the other expression is a pointer. 10307 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10308 NonNullType->canDecayToPointerType()) 10309 return; 10310 10311 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10312 << LHSNull /* LHS is NULL */ << NonNullType 10313 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10314 } 10315 10316 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10317 SourceLocation Loc) { 10318 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10319 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10320 if (!LUE || !RUE) 10321 return; 10322 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10323 RUE->getKind() != UETT_SizeOf) 10324 return; 10325 10326 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10327 QualType LHSTy = LHSArg->getType(); 10328 QualType RHSTy; 10329 10330 if (RUE->isArgumentType()) 10331 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10332 else 10333 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10334 10335 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10336 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10337 return; 10338 10339 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10340 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10341 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10342 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10343 << LHSArgDecl; 10344 } 10345 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10346 QualType ArrayElemTy = ArrayTy->getElementType(); 10347 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10348 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10349 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10350 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10351 return; 10352 S.Diag(Loc, diag::warn_division_sizeof_array) 10353 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10354 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10355 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10356 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10357 << LHSArgDecl; 10358 } 10359 10360 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10361 } 10362 } 10363 10364 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10365 ExprResult &RHS, 10366 SourceLocation Loc, bool IsDiv) { 10367 // Check for division/remainder by zero. 10368 Expr::EvalResult RHSValue; 10369 if (!RHS.get()->isValueDependent() && 10370 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10371 RHSValue.Val.getInt() == 0) 10372 S.DiagRuntimeBehavior(Loc, RHS.get(), 10373 S.PDiag(diag::warn_remainder_division_by_zero) 10374 << IsDiv << RHS.get()->getSourceRange()); 10375 } 10376 10377 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10378 SourceLocation Loc, 10379 bool IsCompAssign, bool IsDiv) { 10380 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10381 10382 QualType LHSTy = LHS.get()->getType(); 10383 QualType RHSTy = RHS.get()->getType(); 10384 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10385 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10386 /*AllowBothBool*/getLangOpts().AltiVec, 10387 /*AllowBoolConversions*/false); 10388 if (!IsDiv && 10389 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10390 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10391 // For division, only matrix-by-scalar is supported. Other combinations with 10392 // matrix types are invalid. 10393 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10394 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10395 10396 QualType compType = UsualArithmeticConversions( 10397 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10398 if (LHS.isInvalid() || RHS.isInvalid()) 10399 return QualType(); 10400 10401 10402 if (compType.isNull() || !compType->isArithmeticType()) 10403 return InvalidOperands(Loc, LHS, RHS); 10404 if (IsDiv) { 10405 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10406 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10407 } 10408 return compType; 10409 } 10410 10411 QualType Sema::CheckRemainderOperands( 10412 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10413 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10414 10415 if (LHS.get()->getType()->isVectorType() || 10416 RHS.get()->getType()->isVectorType()) { 10417 if (LHS.get()->getType()->hasIntegerRepresentation() && 10418 RHS.get()->getType()->hasIntegerRepresentation()) 10419 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10420 /*AllowBothBool*/getLangOpts().AltiVec, 10421 /*AllowBoolConversions*/false); 10422 return InvalidOperands(Loc, LHS, RHS); 10423 } 10424 10425 QualType compType = UsualArithmeticConversions( 10426 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10427 if (LHS.isInvalid() || RHS.isInvalid()) 10428 return QualType(); 10429 10430 if (compType.isNull() || !compType->isIntegerType()) 10431 return InvalidOperands(Loc, LHS, RHS); 10432 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10433 return compType; 10434 } 10435 10436 /// Diagnose invalid arithmetic on two void pointers. 10437 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10438 Expr *LHSExpr, Expr *RHSExpr) { 10439 S.Diag(Loc, S.getLangOpts().CPlusPlus 10440 ? diag::err_typecheck_pointer_arith_void_type 10441 : diag::ext_gnu_void_ptr) 10442 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10443 << RHSExpr->getSourceRange(); 10444 } 10445 10446 /// Diagnose invalid arithmetic on a void pointer. 10447 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10448 Expr *Pointer) { 10449 S.Diag(Loc, S.getLangOpts().CPlusPlus 10450 ? diag::err_typecheck_pointer_arith_void_type 10451 : diag::ext_gnu_void_ptr) 10452 << 0 /* one pointer */ << Pointer->getSourceRange(); 10453 } 10454 10455 /// Diagnose invalid arithmetic on a null pointer. 10456 /// 10457 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10458 /// idiom, which we recognize as a GNU extension. 10459 /// 10460 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10461 Expr *Pointer, bool IsGNUIdiom) { 10462 if (IsGNUIdiom) 10463 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10464 << Pointer->getSourceRange(); 10465 else 10466 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10467 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10468 } 10469 10470 /// Diagnose invalid subraction on a null pointer. 10471 /// 10472 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10473 Expr *Pointer, bool BothNull) { 10474 // Null - null is valid in C++ [expr.add]p7 10475 if (BothNull && S.getLangOpts().CPlusPlus) 10476 return; 10477 10478 // Is this s a macro from a system header? 10479 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10480 return; 10481 10482 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10483 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10484 } 10485 10486 /// Diagnose invalid arithmetic on two function pointers. 10487 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10488 Expr *LHS, Expr *RHS) { 10489 assert(LHS->getType()->isAnyPointerType()); 10490 assert(RHS->getType()->isAnyPointerType()); 10491 S.Diag(Loc, S.getLangOpts().CPlusPlus 10492 ? diag::err_typecheck_pointer_arith_function_type 10493 : diag::ext_gnu_ptr_func_arith) 10494 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10495 // We only show the second type if it differs from the first. 10496 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10497 RHS->getType()) 10498 << RHS->getType()->getPointeeType() 10499 << LHS->getSourceRange() << RHS->getSourceRange(); 10500 } 10501 10502 /// Diagnose invalid arithmetic on a function pointer. 10503 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10504 Expr *Pointer) { 10505 assert(Pointer->getType()->isAnyPointerType()); 10506 S.Diag(Loc, S.getLangOpts().CPlusPlus 10507 ? diag::err_typecheck_pointer_arith_function_type 10508 : diag::ext_gnu_ptr_func_arith) 10509 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10510 << 0 /* one pointer, so only one type */ 10511 << Pointer->getSourceRange(); 10512 } 10513 10514 /// Emit error if Operand is incomplete pointer type 10515 /// 10516 /// \returns True if pointer has incomplete type 10517 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10518 Expr *Operand) { 10519 QualType ResType = Operand->getType(); 10520 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10521 ResType = ResAtomicType->getValueType(); 10522 10523 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10524 QualType PointeeTy = ResType->getPointeeType(); 10525 return S.RequireCompleteSizedType( 10526 Loc, PointeeTy, 10527 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10528 Operand->getSourceRange()); 10529 } 10530 10531 /// Check the validity of an arithmetic pointer operand. 10532 /// 10533 /// If the operand has pointer type, this code will check for pointer types 10534 /// which are invalid in arithmetic operations. These will be diagnosed 10535 /// appropriately, including whether or not the use is supported as an 10536 /// extension. 10537 /// 10538 /// \returns True when the operand is valid to use (even if as an extension). 10539 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10540 Expr *Operand) { 10541 QualType ResType = Operand->getType(); 10542 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10543 ResType = ResAtomicType->getValueType(); 10544 10545 if (!ResType->isAnyPointerType()) return true; 10546 10547 QualType PointeeTy = ResType->getPointeeType(); 10548 if (PointeeTy->isVoidType()) { 10549 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10550 return !S.getLangOpts().CPlusPlus; 10551 } 10552 if (PointeeTy->isFunctionType()) { 10553 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10554 return !S.getLangOpts().CPlusPlus; 10555 } 10556 10557 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10558 10559 return true; 10560 } 10561 10562 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10563 /// operands. 10564 /// 10565 /// This routine will diagnose any invalid arithmetic on pointer operands much 10566 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10567 /// for emitting a single diagnostic even for operations where both LHS and RHS 10568 /// are (potentially problematic) pointers. 10569 /// 10570 /// \returns True when the operand is valid to use (even if as an extension). 10571 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10572 Expr *LHSExpr, Expr *RHSExpr) { 10573 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10574 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10575 if (!isLHSPointer && !isRHSPointer) return true; 10576 10577 QualType LHSPointeeTy, RHSPointeeTy; 10578 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10579 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10580 10581 // if both are pointers check if operation is valid wrt address spaces 10582 if (isLHSPointer && isRHSPointer) { 10583 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10584 S.Diag(Loc, 10585 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10586 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10587 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10588 return false; 10589 } 10590 } 10591 10592 // Check for arithmetic on pointers to incomplete types. 10593 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10594 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10595 if (isLHSVoidPtr || isRHSVoidPtr) { 10596 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10597 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10598 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10599 10600 return !S.getLangOpts().CPlusPlus; 10601 } 10602 10603 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10604 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10605 if (isLHSFuncPtr || isRHSFuncPtr) { 10606 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10607 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10608 RHSExpr); 10609 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10610 10611 return !S.getLangOpts().CPlusPlus; 10612 } 10613 10614 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10615 return false; 10616 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10617 return false; 10618 10619 return true; 10620 } 10621 10622 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10623 /// literal. 10624 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10625 Expr *LHSExpr, Expr *RHSExpr) { 10626 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10627 Expr* IndexExpr = RHSExpr; 10628 if (!StrExpr) { 10629 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10630 IndexExpr = LHSExpr; 10631 } 10632 10633 bool IsStringPlusInt = StrExpr && 10634 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10635 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10636 return; 10637 10638 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10639 Self.Diag(OpLoc, diag::warn_string_plus_int) 10640 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10641 10642 // Only print a fixit for "str" + int, not for int + "str". 10643 if (IndexExpr == RHSExpr) { 10644 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10645 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10646 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10647 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10648 << FixItHint::CreateInsertion(EndLoc, "]"); 10649 } else 10650 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10651 } 10652 10653 /// Emit a warning when adding a char literal to a string. 10654 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10655 Expr *LHSExpr, Expr *RHSExpr) { 10656 const Expr *StringRefExpr = LHSExpr; 10657 const CharacterLiteral *CharExpr = 10658 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10659 10660 if (!CharExpr) { 10661 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10662 StringRefExpr = RHSExpr; 10663 } 10664 10665 if (!CharExpr || !StringRefExpr) 10666 return; 10667 10668 const QualType StringType = StringRefExpr->getType(); 10669 10670 // Return if not a PointerType. 10671 if (!StringType->isAnyPointerType()) 10672 return; 10673 10674 // Return if not a CharacterType. 10675 if (!StringType->getPointeeType()->isAnyCharacterType()) 10676 return; 10677 10678 ASTContext &Ctx = Self.getASTContext(); 10679 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10680 10681 const QualType CharType = CharExpr->getType(); 10682 if (!CharType->isAnyCharacterType() && 10683 CharType->isIntegerType() && 10684 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10685 Self.Diag(OpLoc, diag::warn_string_plus_char) 10686 << DiagRange << Ctx.CharTy; 10687 } else { 10688 Self.Diag(OpLoc, diag::warn_string_plus_char) 10689 << DiagRange << CharExpr->getType(); 10690 } 10691 10692 // Only print a fixit for str + char, not for char + str. 10693 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10694 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10695 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10696 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10697 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10698 << FixItHint::CreateInsertion(EndLoc, "]"); 10699 } else { 10700 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10701 } 10702 } 10703 10704 /// Emit error when two pointers are incompatible. 10705 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10706 Expr *LHSExpr, Expr *RHSExpr) { 10707 assert(LHSExpr->getType()->isAnyPointerType()); 10708 assert(RHSExpr->getType()->isAnyPointerType()); 10709 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10710 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10711 << RHSExpr->getSourceRange(); 10712 } 10713 10714 // C99 6.5.6 10715 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10716 SourceLocation Loc, BinaryOperatorKind Opc, 10717 QualType* CompLHSTy) { 10718 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10719 10720 if (LHS.get()->getType()->isVectorType() || 10721 RHS.get()->getType()->isVectorType()) { 10722 QualType compType = CheckVectorOperands( 10723 LHS, RHS, Loc, CompLHSTy, 10724 /*AllowBothBool*/getLangOpts().AltiVec, 10725 /*AllowBoolConversions*/getLangOpts().ZVector); 10726 if (CompLHSTy) *CompLHSTy = compType; 10727 return compType; 10728 } 10729 10730 if (LHS.get()->getType()->isConstantMatrixType() || 10731 RHS.get()->getType()->isConstantMatrixType()) { 10732 QualType compType = 10733 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10734 if (CompLHSTy) 10735 *CompLHSTy = compType; 10736 return compType; 10737 } 10738 10739 QualType compType = UsualArithmeticConversions( 10740 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10741 if (LHS.isInvalid() || RHS.isInvalid()) 10742 return QualType(); 10743 10744 // Diagnose "string literal" '+' int and string '+' "char literal". 10745 if (Opc == BO_Add) { 10746 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10747 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10748 } 10749 10750 // handle the common case first (both operands are arithmetic). 10751 if (!compType.isNull() && compType->isArithmeticType()) { 10752 if (CompLHSTy) *CompLHSTy = compType; 10753 return compType; 10754 } 10755 10756 // Type-checking. Ultimately the pointer's going to be in PExp; 10757 // note that we bias towards the LHS being the pointer. 10758 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10759 10760 bool isObjCPointer; 10761 if (PExp->getType()->isPointerType()) { 10762 isObjCPointer = false; 10763 } else if (PExp->getType()->isObjCObjectPointerType()) { 10764 isObjCPointer = true; 10765 } else { 10766 std::swap(PExp, IExp); 10767 if (PExp->getType()->isPointerType()) { 10768 isObjCPointer = false; 10769 } else if (PExp->getType()->isObjCObjectPointerType()) { 10770 isObjCPointer = true; 10771 } else { 10772 return InvalidOperands(Loc, LHS, RHS); 10773 } 10774 } 10775 assert(PExp->getType()->isAnyPointerType()); 10776 10777 if (!IExp->getType()->isIntegerType()) 10778 return InvalidOperands(Loc, LHS, RHS); 10779 10780 // Adding to a null pointer results in undefined behavior. 10781 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10782 Context, Expr::NPC_ValueDependentIsNotNull)) { 10783 // In C++ adding zero to a null pointer is defined. 10784 Expr::EvalResult KnownVal; 10785 if (!getLangOpts().CPlusPlus || 10786 (!IExp->isValueDependent() && 10787 (!IExp->EvaluateAsInt(KnownVal, Context) || 10788 KnownVal.Val.getInt() != 0))) { 10789 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10790 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10791 Context, BO_Add, PExp, IExp); 10792 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10793 } 10794 } 10795 10796 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10797 return QualType(); 10798 10799 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10800 return QualType(); 10801 10802 // Check array bounds for pointer arithemtic 10803 CheckArrayAccess(PExp, IExp); 10804 10805 if (CompLHSTy) { 10806 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10807 if (LHSTy.isNull()) { 10808 LHSTy = LHS.get()->getType(); 10809 if (LHSTy->isPromotableIntegerType()) 10810 LHSTy = Context.getPromotedIntegerType(LHSTy); 10811 } 10812 *CompLHSTy = LHSTy; 10813 } 10814 10815 return PExp->getType(); 10816 } 10817 10818 // C99 6.5.6 10819 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10820 SourceLocation Loc, 10821 QualType* CompLHSTy) { 10822 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10823 10824 if (LHS.get()->getType()->isVectorType() || 10825 RHS.get()->getType()->isVectorType()) { 10826 QualType compType = CheckVectorOperands( 10827 LHS, RHS, Loc, CompLHSTy, 10828 /*AllowBothBool*/getLangOpts().AltiVec, 10829 /*AllowBoolConversions*/getLangOpts().ZVector); 10830 if (CompLHSTy) *CompLHSTy = compType; 10831 return compType; 10832 } 10833 10834 if (LHS.get()->getType()->isConstantMatrixType() || 10835 RHS.get()->getType()->isConstantMatrixType()) { 10836 QualType compType = 10837 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10838 if (CompLHSTy) 10839 *CompLHSTy = compType; 10840 return compType; 10841 } 10842 10843 QualType compType = UsualArithmeticConversions( 10844 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10845 if (LHS.isInvalid() || RHS.isInvalid()) 10846 return QualType(); 10847 10848 // Enforce type constraints: C99 6.5.6p3. 10849 10850 // Handle the common case first (both operands are arithmetic). 10851 if (!compType.isNull() && compType->isArithmeticType()) { 10852 if (CompLHSTy) *CompLHSTy = compType; 10853 return compType; 10854 } 10855 10856 // Either ptr - int or ptr - ptr. 10857 if (LHS.get()->getType()->isAnyPointerType()) { 10858 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10859 10860 // Diagnose bad cases where we step over interface counts. 10861 if (LHS.get()->getType()->isObjCObjectPointerType() && 10862 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10863 return QualType(); 10864 10865 // The result type of a pointer-int computation is the pointer type. 10866 if (RHS.get()->getType()->isIntegerType()) { 10867 // Subtracting from a null pointer should produce a warning. 10868 // The last argument to the diagnose call says this doesn't match the 10869 // GNU int-to-pointer idiom. 10870 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10871 Expr::NPC_ValueDependentIsNotNull)) { 10872 // In C++ adding zero to a null pointer is defined. 10873 Expr::EvalResult KnownVal; 10874 if (!getLangOpts().CPlusPlus || 10875 (!RHS.get()->isValueDependent() && 10876 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10877 KnownVal.Val.getInt() != 0))) { 10878 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10879 } 10880 } 10881 10882 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10883 return QualType(); 10884 10885 // Check array bounds for pointer arithemtic 10886 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10887 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10888 10889 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10890 return LHS.get()->getType(); 10891 } 10892 10893 // Handle pointer-pointer subtractions. 10894 if (const PointerType *RHSPTy 10895 = RHS.get()->getType()->getAs<PointerType>()) { 10896 QualType rpointee = RHSPTy->getPointeeType(); 10897 10898 if (getLangOpts().CPlusPlus) { 10899 // Pointee types must be the same: C++ [expr.add] 10900 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10901 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10902 } 10903 } else { 10904 // Pointee types must be compatible C99 6.5.6p3 10905 if (!Context.typesAreCompatible( 10906 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10907 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10908 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10909 return QualType(); 10910 } 10911 } 10912 10913 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10914 LHS.get(), RHS.get())) 10915 return QualType(); 10916 10917 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10918 Context, Expr::NPC_ValueDependentIsNotNull); 10919 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10920 Context, Expr::NPC_ValueDependentIsNotNull); 10921 10922 // Subtracting nullptr or from nullptr is suspect 10923 if (LHSIsNullPtr) 10924 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10925 if (RHSIsNullPtr) 10926 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10927 10928 // The pointee type may have zero size. As an extension, a structure or 10929 // union may have zero size or an array may have zero length. In this 10930 // case subtraction does not make sense. 10931 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10932 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10933 if (ElementSize.isZero()) { 10934 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10935 << rpointee.getUnqualifiedType() 10936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10937 } 10938 } 10939 10940 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10941 return Context.getPointerDiffType(); 10942 } 10943 } 10944 10945 return InvalidOperands(Loc, LHS, RHS); 10946 } 10947 10948 static bool isScopedEnumerationType(QualType T) { 10949 if (const EnumType *ET = T->getAs<EnumType>()) 10950 return ET->getDecl()->isScoped(); 10951 return false; 10952 } 10953 10954 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10955 SourceLocation Loc, BinaryOperatorKind Opc, 10956 QualType LHSType) { 10957 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10958 // so skip remaining warnings as we don't want to modify values within Sema. 10959 if (S.getLangOpts().OpenCL) 10960 return; 10961 10962 // Check right/shifter operand 10963 Expr::EvalResult RHSResult; 10964 if (RHS.get()->isValueDependent() || 10965 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10966 return; 10967 llvm::APSInt Right = RHSResult.Val.getInt(); 10968 10969 if (Right.isNegative()) { 10970 S.DiagRuntimeBehavior(Loc, RHS.get(), 10971 S.PDiag(diag::warn_shift_negative) 10972 << RHS.get()->getSourceRange()); 10973 return; 10974 } 10975 10976 QualType LHSExprType = LHS.get()->getType(); 10977 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10978 if (LHSExprType->isExtIntType()) 10979 LeftSize = S.Context.getIntWidth(LHSExprType); 10980 else if (LHSExprType->isFixedPointType()) { 10981 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10982 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10983 } 10984 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10985 if (Right.uge(LeftBits)) { 10986 S.DiagRuntimeBehavior(Loc, RHS.get(), 10987 S.PDiag(diag::warn_shift_gt_typewidth) 10988 << RHS.get()->getSourceRange()); 10989 return; 10990 } 10991 10992 // FIXME: We probably need to handle fixed point types specially here. 10993 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10994 return; 10995 10996 // When left shifting an ICE which is signed, we can check for overflow which 10997 // according to C++ standards prior to C++2a has undefined behavior 10998 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10999 // more than the maximum value representable in the result type, so never 11000 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11001 // expression is still probably a bug.) 11002 Expr::EvalResult LHSResult; 11003 if (LHS.get()->isValueDependent() || 11004 LHSType->hasUnsignedIntegerRepresentation() || 11005 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11006 return; 11007 llvm::APSInt Left = LHSResult.Val.getInt(); 11008 11009 // If LHS does not have a signed type and non-negative value 11010 // then, the behavior is undefined before C++2a. Warn about it. 11011 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11012 !S.getLangOpts().CPlusPlus20) { 11013 S.DiagRuntimeBehavior(Loc, LHS.get(), 11014 S.PDiag(diag::warn_shift_lhs_negative) 11015 << LHS.get()->getSourceRange()); 11016 return; 11017 } 11018 11019 llvm::APInt ResultBits = 11020 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11021 if (LeftBits.uge(ResultBits)) 11022 return; 11023 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11024 Result = Result.shl(Right); 11025 11026 // Print the bit representation of the signed integer as an unsigned 11027 // hexadecimal number. 11028 SmallString<40> HexResult; 11029 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11030 11031 // If we are only missing a sign bit, this is less likely to result in actual 11032 // bugs -- if the result is cast back to an unsigned type, it will have the 11033 // expected value. Thus we place this behind a different warning that can be 11034 // turned off separately if needed. 11035 if (LeftBits == ResultBits - 1) { 11036 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11037 << HexResult << LHSType 11038 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11039 return; 11040 } 11041 11042 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11043 << HexResult.str() << Result.getMinSignedBits() << LHSType 11044 << Left.getBitWidth() << LHS.get()->getSourceRange() 11045 << RHS.get()->getSourceRange(); 11046 } 11047 11048 /// Return the resulting type when a vector is shifted 11049 /// by a scalar or vector shift amount. 11050 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11051 SourceLocation Loc, bool IsCompAssign) { 11052 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11053 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11054 !LHS.get()->getType()->isVectorType()) { 11055 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11056 << RHS.get()->getType() << LHS.get()->getType() 11057 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11058 return QualType(); 11059 } 11060 11061 if (!IsCompAssign) { 11062 LHS = S.UsualUnaryConversions(LHS.get()); 11063 if (LHS.isInvalid()) return QualType(); 11064 } 11065 11066 RHS = S.UsualUnaryConversions(RHS.get()); 11067 if (RHS.isInvalid()) return QualType(); 11068 11069 QualType LHSType = LHS.get()->getType(); 11070 // Note that LHS might be a scalar because the routine calls not only in 11071 // OpenCL case. 11072 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11073 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11074 11075 // Note that RHS might not be a vector. 11076 QualType RHSType = RHS.get()->getType(); 11077 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11078 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11079 11080 // The operands need to be integers. 11081 if (!LHSEleType->isIntegerType()) { 11082 S.Diag(Loc, diag::err_typecheck_expect_int) 11083 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11084 return QualType(); 11085 } 11086 11087 if (!RHSEleType->isIntegerType()) { 11088 S.Diag(Loc, diag::err_typecheck_expect_int) 11089 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11090 return QualType(); 11091 } 11092 11093 if (!LHSVecTy) { 11094 assert(RHSVecTy); 11095 if (IsCompAssign) 11096 return RHSType; 11097 if (LHSEleType != RHSEleType) { 11098 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11099 LHSEleType = RHSEleType; 11100 } 11101 QualType VecTy = 11102 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11103 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11104 LHSType = VecTy; 11105 } else if (RHSVecTy) { 11106 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11107 // are applied component-wise. So if RHS is a vector, then ensure 11108 // that the number of elements is the same as LHS... 11109 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11110 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11111 << LHS.get()->getType() << RHS.get()->getType() 11112 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11113 return QualType(); 11114 } 11115 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11116 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11117 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11118 if (LHSBT != RHSBT && 11119 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11120 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11121 << LHS.get()->getType() << RHS.get()->getType() 11122 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11123 } 11124 } 11125 } else { 11126 // ...else expand RHS to match the number of elements in LHS. 11127 QualType VecTy = 11128 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11129 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11130 } 11131 11132 return LHSType; 11133 } 11134 11135 // C99 6.5.7 11136 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11137 SourceLocation Loc, BinaryOperatorKind Opc, 11138 bool IsCompAssign) { 11139 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11140 11141 // Vector shifts promote their scalar inputs to vector type. 11142 if (LHS.get()->getType()->isVectorType() || 11143 RHS.get()->getType()->isVectorType()) { 11144 if (LangOpts.ZVector) { 11145 // The shift operators for the z vector extensions work basically 11146 // like general shifts, except that neither the LHS nor the RHS is 11147 // allowed to be a "vector bool". 11148 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11149 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11150 return InvalidOperands(Loc, LHS, RHS); 11151 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11152 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11153 return InvalidOperands(Loc, LHS, RHS); 11154 } 11155 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11156 } 11157 11158 // Shifts don't perform usual arithmetic conversions, they just do integer 11159 // promotions on each operand. C99 6.5.7p3 11160 11161 // For the LHS, do usual unary conversions, but then reset them away 11162 // if this is a compound assignment. 11163 ExprResult OldLHS = LHS; 11164 LHS = UsualUnaryConversions(LHS.get()); 11165 if (LHS.isInvalid()) 11166 return QualType(); 11167 QualType LHSType = LHS.get()->getType(); 11168 if (IsCompAssign) LHS = OldLHS; 11169 11170 // The RHS is simpler. 11171 RHS = UsualUnaryConversions(RHS.get()); 11172 if (RHS.isInvalid()) 11173 return QualType(); 11174 QualType RHSType = RHS.get()->getType(); 11175 11176 // C99 6.5.7p2: Each of the operands shall have integer type. 11177 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11178 if ((!LHSType->isFixedPointOrIntegerType() && 11179 !LHSType->hasIntegerRepresentation()) || 11180 !RHSType->hasIntegerRepresentation()) 11181 return InvalidOperands(Loc, LHS, RHS); 11182 11183 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11184 // hasIntegerRepresentation() above instead of this. 11185 if (isScopedEnumerationType(LHSType) || 11186 isScopedEnumerationType(RHSType)) { 11187 return InvalidOperands(Loc, LHS, RHS); 11188 } 11189 // Sanity-check shift operands 11190 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11191 11192 // "The type of the result is that of the promoted left operand." 11193 return LHSType; 11194 } 11195 11196 /// Diagnose bad pointer comparisons. 11197 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11198 ExprResult &LHS, ExprResult &RHS, 11199 bool IsError) { 11200 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11201 : diag::ext_typecheck_comparison_of_distinct_pointers) 11202 << LHS.get()->getType() << RHS.get()->getType() 11203 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11204 } 11205 11206 /// Returns false if the pointers are converted to a composite type, 11207 /// true otherwise. 11208 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11209 ExprResult &LHS, ExprResult &RHS) { 11210 // C++ [expr.rel]p2: 11211 // [...] Pointer conversions (4.10) and qualification 11212 // conversions (4.4) are performed on pointer operands (or on 11213 // a pointer operand and a null pointer constant) to bring 11214 // them to their composite pointer type. [...] 11215 // 11216 // C++ [expr.eq]p1 uses the same notion for (in)equality 11217 // comparisons of pointers. 11218 11219 QualType LHSType = LHS.get()->getType(); 11220 QualType RHSType = RHS.get()->getType(); 11221 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11222 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11223 11224 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11225 if (T.isNull()) { 11226 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11227 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11228 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11229 else 11230 S.InvalidOperands(Loc, LHS, RHS); 11231 return true; 11232 } 11233 11234 return false; 11235 } 11236 11237 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11238 ExprResult &LHS, 11239 ExprResult &RHS, 11240 bool IsError) { 11241 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11242 : diag::ext_typecheck_comparison_of_fptr_to_void) 11243 << LHS.get()->getType() << RHS.get()->getType() 11244 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11245 } 11246 11247 static bool isObjCObjectLiteral(ExprResult &E) { 11248 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11249 case Stmt::ObjCArrayLiteralClass: 11250 case Stmt::ObjCDictionaryLiteralClass: 11251 case Stmt::ObjCStringLiteralClass: 11252 case Stmt::ObjCBoxedExprClass: 11253 return true; 11254 default: 11255 // Note that ObjCBoolLiteral is NOT an object literal! 11256 return false; 11257 } 11258 } 11259 11260 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11261 const ObjCObjectPointerType *Type = 11262 LHS->getType()->getAs<ObjCObjectPointerType>(); 11263 11264 // If this is not actually an Objective-C object, bail out. 11265 if (!Type) 11266 return false; 11267 11268 // Get the LHS object's interface type. 11269 QualType InterfaceType = Type->getPointeeType(); 11270 11271 // If the RHS isn't an Objective-C object, bail out. 11272 if (!RHS->getType()->isObjCObjectPointerType()) 11273 return false; 11274 11275 // Try to find the -isEqual: method. 11276 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11277 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11278 InterfaceType, 11279 /*IsInstance=*/true); 11280 if (!Method) { 11281 if (Type->isObjCIdType()) { 11282 // For 'id', just check the global pool. 11283 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11284 /*receiverId=*/true); 11285 } else { 11286 // Check protocols. 11287 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11288 /*IsInstance=*/true); 11289 } 11290 } 11291 11292 if (!Method) 11293 return false; 11294 11295 QualType T = Method->parameters()[0]->getType(); 11296 if (!T->isObjCObjectPointerType()) 11297 return false; 11298 11299 QualType R = Method->getReturnType(); 11300 if (!R->isScalarType()) 11301 return false; 11302 11303 return true; 11304 } 11305 11306 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11307 FromE = FromE->IgnoreParenImpCasts(); 11308 switch (FromE->getStmtClass()) { 11309 default: 11310 break; 11311 case Stmt::ObjCStringLiteralClass: 11312 // "string literal" 11313 return LK_String; 11314 case Stmt::ObjCArrayLiteralClass: 11315 // "array literal" 11316 return LK_Array; 11317 case Stmt::ObjCDictionaryLiteralClass: 11318 // "dictionary literal" 11319 return LK_Dictionary; 11320 case Stmt::BlockExprClass: 11321 return LK_Block; 11322 case Stmt::ObjCBoxedExprClass: { 11323 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11324 switch (Inner->getStmtClass()) { 11325 case Stmt::IntegerLiteralClass: 11326 case Stmt::FloatingLiteralClass: 11327 case Stmt::CharacterLiteralClass: 11328 case Stmt::ObjCBoolLiteralExprClass: 11329 case Stmt::CXXBoolLiteralExprClass: 11330 // "numeric literal" 11331 return LK_Numeric; 11332 case Stmt::ImplicitCastExprClass: { 11333 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11334 // Boolean literals can be represented by implicit casts. 11335 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11336 return LK_Numeric; 11337 break; 11338 } 11339 default: 11340 break; 11341 } 11342 return LK_Boxed; 11343 } 11344 } 11345 return LK_None; 11346 } 11347 11348 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11349 ExprResult &LHS, ExprResult &RHS, 11350 BinaryOperator::Opcode Opc){ 11351 Expr *Literal; 11352 Expr *Other; 11353 if (isObjCObjectLiteral(LHS)) { 11354 Literal = LHS.get(); 11355 Other = RHS.get(); 11356 } else { 11357 Literal = RHS.get(); 11358 Other = LHS.get(); 11359 } 11360 11361 // Don't warn on comparisons against nil. 11362 Other = Other->IgnoreParenCasts(); 11363 if (Other->isNullPointerConstant(S.getASTContext(), 11364 Expr::NPC_ValueDependentIsNotNull)) 11365 return; 11366 11367 // This should be kept in sync with warn_objc_literal_comparison. 11368 // LK_String should always be after the other literals, since it has its own 11369 // warning flag. 11370 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11371 assert(LiteralKind != Sema::LK_Block); 11372 if (LiteralKind == Sema::LK_None) { 11373 llvm_unreachable("Unknown Objective-C object literal kind"); 11374 } 11375 11376 if (LiteralKind == Sema::LK_String) 11377 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11378 << Literal->getSourceRange(); 11379 else 11380 S.Diag(Loc, diag::warn_objc_literal_comparison) 11381 << LiteralKind << Literal->getSourceRange(); 11382 11383 if (BinaryOperator::isEqualityOp(Opc) && 11384 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11385 SourceLocation Start = LHS.get()->getBeginLoc(); 11386 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11387 CharSourceRange OpRange = 11388 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11389 11390 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11391 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11392 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11393 << FixItHint::CreateInsertion(End, "]"); 11394 } 11395 } 11396 11397 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11398 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11399 ExprResult &RHS, SourceLocation Loc, 11400 BinaryOperatorKind Opc) { 11401 // Check that left hand side is !something. 11402 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11403 if (!UO || UO->getOpcode() != UO_LNot) return; 11404 11405 // Only check if the right hand side is non-bool arithmetic type. 11406 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11407 11408 // Make sure that the something in !something is not bool. 11409 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11410 if (SubExpr->isKnownToHaveBooleanValue()) return; 11411 11412 // Emit warning. 11413 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11414 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11415 << Loc << IsBitwiseOp; 11416 11417 // First note suggest !(x < y) 11418 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11419 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11420 FirstClose = S.getLocForEndOfToken(FirstClose); 11421 if (FirstClose.isInvalid()) 11422 FirstOpen = SourceLocation(); 11423 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11424 << IsBitwiseOp 11425 << FixItHint::CreateInsertion(FirstOpen, "(") 11426 << FixItHint::CreateInsertion(FirstClose, ")"); 11427 11428 // Second note suggests (!x) < y 11429 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11430 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11431 SecondClose = S.getLocForEndOfToken(SecondClose); 11432 if (SecondClose.isInvalid()) 11433 SecondOpen = SourceLocation(); 11434 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11435 << FixItHint::CreateInsertion(SecondOpen, "(") 11436 << FixItHint::CreateInsertion(SecondClose, ")"); 11437 } 11438 11439 // Returns true if E refers to a non-weak array. 11440 static bool checkForArray(const Expr *E) { 11441 const ValueDecl *D = nullptr; 11442 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11443 D = DR->getDecl(); 11444 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11445 if (Mem->isImplicitAccess()) 11446 D = Mem->getMemberDecl(); 11447 } 11448 if (!D) 11449 return false; 11450 return D->getType()->isArrayType() && !D->isWeak(); 11451 } 11452 11453 /// Diagnose some forms of syntactically-obvious tautological comparison. 11454 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11455 Expr *LHS, Expr *RHS, 11456 BinaryOperatorKind Opc) { 11457 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11458 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11459 11460 QualType LHSType = LHS->getType(); 11461 QualType RHSType = RHS->getType(); 11462 if (LHSType->hasFloatingRepresentation() || 11463 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11464 S.inTemplateInstantiation()) 11465 return; 11466 11467 // Comparisons between two array types are ill-formed for operator<=>, so 11468 // we shouldn't emit any additional warnings about it. 11469 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11470 return; 11471 11472 // For non-floating point types, check for self-comparisons of the form 11473 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11474 // often indicate logic errors in the program. 11475 // 11476 // NOTE: Don't warn about comparison expressions resulting from macro 11477 // expansion. Also don't warn about comparisons which are only self 11478 // comparisons within a template instantiation. The warnings should catch 11479 // obvious cases in the definition of the template anyways. The idea is to 11480 // warn when the typed comparison operator will always evaluate to the same 11481 // result. 11482 11483 // Used for indexing into %select in warn_comparison_always 11484 enum { 11485 AlwaysConstant, 11486 AlwaysTrue, 11487 AlwaysFalse, 11488 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11489 }; 11490 11491 // C++2a [depr.array.comp]: 11492 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11493 // operands of array type are deprecated. 11494 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11495 RHSStripped->getType()->isArrayType()) { 11496 S.Diag(Loc, diag::warn_depr_array_comparison) 11497 << LHS->getSourceRange() << RHS->getSourceRange() 11498 << LHSStripped->getType() << RHSStripped->getType(); 11499 // Carry on to produce the tautological comparison warning, if this 11500 // expression is potentially-evaluated, we can resolve the array to a 11501 // non-weak declaration, and so on. 11502 } 11503 11504 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11505 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11506 unsigned Result; 11507 switch (Opc) { 11508 case BO_EQ: 11509 case BO_LE: 11510 case BO_GE: 11511 Result = AlwaysTrue; 11512 break; 11513 case BO_NE: 11514 case BO_LT: 11515 case BO_GT: 11516 Result = AlwaysFalse; 11517 break; 11518 case BO_Cmp: 11519 Result = AlwaysEqual; 11520 break; 11521 default: 11522 Result = AlwaysConstant; 11523 break; 11524 } 11525 S.DiagRuntimeBehavior(Loc, nullptr, 11526 S.PDiag(diag::warn_comparison_always) 11527 << 0 /*self-comparison*/ 11528 << Result); 11529 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11530 // What is it always going to evaluate to? 11531 unsigned Result; 11532 switch (Opc) { 11533 case BO_EQ: // e.g. array1 == array2 11534 Result = AlwaysFalse; 11535 break; 11536 case BO_NE: // e.g. array1 != array2 11537 Result = AlwaysTrue; 11538 break; 11539 default: // e.g. array1 <= array2 11540 // The best we can say is 'a constant' 11541 Result = AlwaysConstant; 11542 break; 11543 } 11544 S.DiagRuntimeBehavior(Loc, nullptr, 11545 S.PDiag(diag::warn_comparison_always) 11546 << 1 /*array comparison*/ 11547 << Result); 11548 } 11549 } 11550 11551 if (isa<CastExpr>(LHSStripped)) 11552 LHSStripped = LHSStripped->IgnoreParenCasts(); 11553 if (isa<CastExpr>(RHSStripped)) 11554 RHSStripped = RHSStripped->IgnoreParenCasts(); 11555 11556 // Warn about comparisons against a string constant (unless the other 11557 // operand is null); the user probably wants string comparison function. 11558 Expr *LiteralString = nullptr; 11559 Expr *LiteralStringStripped = nullptr; 11560 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11561 !RHSStripped->isNullPointerConstant(S.Context, 11562 Expr::NPC_ValueDependentIsNull)) { 11563 LiteralString = LHS; 11564 LiteralStringStripped = LHSStripped; 11565 } else if ((isa<StringLiteral>(RHSStripped) || 11566 isa<ObjCEncodeExpr>(RHSStripped)) && 11567 !LHSStripped->isNullPointerConstant(S.Context, 11568 Expr::NPC_ValueDependentIsNull)) { 11569 LiteralString = RHS; 11570 LiteralStringStripped = RHSStripped; 11571 } 11572 11573 if (LiteralString) { 11574 S.DiagRuntimeBehavior(Loc, nullptr, 11575 S.PDiag(diag::warn_stringcompare) 11576 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11577 << LiteralString->getSourceRange()); 11578 } 11579 } 11580 11581 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11582 switch (CK) { 11583 default: { 11584 #ifndef NDEBUG 11585 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11586 << "\n"; 11587 #endif 11588 llvm_unreachable("unhandled cast kind"); 11589 } 11590 case CK_UserDefinedConversion: 11591 return ICK_Identity; 11592 case CK_LValueToRValue: 11593 return ICK_Lvalue_To_Rvalue; 11594 case CK_ArrayToPointerDecay: 11595 return ICK_Array_To_Pointer; 11596 case CK_FunctionToPointerDecay: 11597 return ICK_Function_To_Pointer; 11598 case CK_IntegralCast: 11599 return ICK_Integral_Conversion; 11600 case CK_FloatingCast: 11601 return ICK_Floating_Conversion; 11602 case CK_IntegralToFloating: 11603 case CK_FloatingToIntegral: 11604 return ICK_Floating_Integral; 11605 case CK_IntegralComplexCast: 11606 case CK_FloatingComplexCast: 11607 case CK_FloatingComplexToIntegralComplex: 11608 case CK_IntegralComplexToFloatingComplex: 11609 return ICK_Complex_Conversion; 11610 case CK_FloatingComplexToReal: 11611 case CK_FloatingRealToComplex: 11612 case CK_IntegralComplexToReal: 11613 case CK_IntegralRealToComplex: 11614 return ICK_Complex_Real; 11615 } 11616 } 11617 11618 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11619 QualType FromType, 11620 SourceLocation Loc) { 11621 // Check for a narrowing implicit conversion. 11622 StandardConversionSequence SCS; 11623 SCS.setAsIdentityConversion(); 11624 SCS.setToType(0, FromType); 11625 SCS.setToType(1, ToType); 11626 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11627 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11628 11629 APValue PreNarrowingValue; 11630 QualType PreNarrowingType; 11631 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11632 PreNarrowingType, 11633 /*IgnoreFloatToIntegralConversion*/ true)) { 11634 case NK_Dependent_Narrowing: 11635 // Implicit conversion to a narrower type, but the expression is 11636 // value-dependent so we can't tell whether it's actually narrowing. 11637 case NK_Not_Narrowing: 11638 return false; 11639 11640 case NK_Constant_Narrowing: 11641 // Implicit conversion to a narrower type, and the value is not a constant 11642 // expression. 11643 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11644 << /*Constant*/ 1 11645 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11646 return true; 11647 11648 case NK_Variable_Narrowing: 11649 // Implicit conversion to a narrower type, and the value is not a constant 11650 // expression. 11651 case NK_Type_Narrowing: 11652 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11653 << /*Constant*/ 0 << FromType << ToType; 11654 // TODO: It's not a constant expression, but what if the user intended it 11655 // to be? Can we produce notes to help them figure out why it isn't? 11656 return true; 11657 } 11658 llvm_unreachable("unhandled case in switch"); 11659 } 11660 11661 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11662 ExprResult &LHS, 11663 ExprResult &RHS, 11664 SourceLocation Loc) { 11665 QualType LHSType = LHS.get()->getType(); 11666 QualType RHSType = RHS.get()->getType(); 11667 // Dig out the original argument type and expression before implicit casts 11668 // were applied. These are the types/expressions we need to check the 11669 // [expr.spaceship] requirements against. 11670 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11671 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11672 QualType LHSStrippedType = LHSStripped.get()->getType(); 11673 QualType RHSStrippedType = RHSStripped.get()->getType(); 11674 11675 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11676 // other is not, the program is ill-formed. 11677 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11678 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11679 return QualType(); 11680 } 11681 11682 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11683 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11684 RHSStrippedType->isEnumeralType(); 11685 if (NumEnumArgs == 1) { 11686 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11687 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11688 if (OtherTy->hasFloatingRepresentation()) { 11689 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11690 return QualType(); 11691 } 11692 } 11693 if (NumEnumArgs == 2) { 11694 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11695 // type E, the operator yields the result of converting the operands 11696 // to the underlying type of E and applying <=> to the converted operands. 11697 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11698 S.InvalidOperands(Loc, LHS, RHS); 11699 return QualType(); 11700 } 11701 QualType IntType = 11702 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11703 assert(IntType->isArithmeticType()); 11704 11705 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11706 // promote the boolean type, and all other promotable integer types, to 11707 // avoid this. 11708 if (IntType->isPromotableIntegerType()) 11709 IntType = S.Context.getPromotedIntegerType(IntType); 11710 11711 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11712 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11713 LHSType = RHSType = IntType; 11714 } 11715 11716 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11717 // usual arithmetic conversions are applied to the operands. 11718 QualType Type = 11719 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11720 if (LHS.isInvalid() || RHS.isInvalid()) 11721 return QualType(); 11722 if (Type.isNull()) 11723 return S.InvalidOperands(Loc, LHS, RHS); 11724 11725 Optional<ComparisonCategoryType> CCT = 11726 getComparisonCategoryForBuiltinCmp(Type); 11727 if (!CCT) 11728 return S.InvalidOperands(Loc, LHS, RHS); 11729 11730 bool HasNarrowing = checkThreeWayNarrowingConversion( 11731 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11732 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11733 RHS.get()->getBeginLoc()); 11734 if (HasNarrowing) 11735 return QualType(); 11736 11737 assert(!Type.isNull() && "composite type for <=> has not been set"); 11738 11739 return S.CheckComparisonCategoryType( 11740 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11741 } 11742 11743 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11744 ExprResult &RHS, 11745 SourceLocation Loc, 11746 BinaryOperatorKind Opc) { 11747 if (Opc == BO_Cmp) 11748 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11749 11750 // C99 6.5.8p3 / C99 6.5.9p4 11751 QualType Type = 11752 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11753 if (LHS.isInvalid() || RHS.isInvalid()) 11754 return QualType(); 11755 if (Type.isNull()) 11756 return S.InvalidOperands(Loc, LHS, RHS); 11757 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11758 11759 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11760 return S.InvalidOperands(Loc, LHS, RHS); 11761 11762 // Check for comparisons of floating point operands using != and ==. 11763 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11764 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11765 11766 // The result of comparisons is 'bool' in C++, 'int' in C. 11767 return S.Context.getLogicalOperationType(); 11768 } 11769 11770 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11771 if (!NullE.get()->getType()->isAnyPointerType()) 11772 return; 11773 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11774 if (!E.get()->getType()->isAnyPointerType() && 11775 E.get()->isNullPointerConstant(Context, 11776 Expr::NPC_ValueDependentIsNotNull) == 11777 Expr::NPCK_ZeroExpression) { 11778 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11779 if (CL->getValue() == 0) 11780 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11781 << NullValue 11782 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11783 NullValue ? "NULL" : "(void *)0"); 11784 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11785 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11786 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11787 if (T == Context.CharTy) 11788 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11789 << NullValue 11790 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11791 NullValue ? "NULL" : "(void *)0"); 11792 } 11793 } 11794 } 11795 11796 // C99 6.5.8, C++ [expr.rel] 11797 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11798 SourceLocation Loc, 11799 BinaryOperatorKind Opc) { 11800 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11801 bool IsThreeWay = Opc == BO_Cmp; 11802 bool IsOrdered = IsRelational || IsThreeWay; 11803 auto IsAnyPointerType = [](ExprResult E) { 11804 QualType Ty = E.get()->getType(); 11805 return Ty->isPointerType() || Ty->isMemberPointerType(); 11806 }; 11807 11808 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11809 // type, array-to-pointer, ..., conversions are performed on both operands to 11810 // bring them to their composite type. 11811 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11812 // any type-related checks. 11813 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11814 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11815 if (LHS.isInvalid()) 11816 return QualType(); 11817 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11818 if (RHS.isInvalid()) 11819 return QualType(); 11820 } else { 11821 LHS = DefaultLvalueConversion(LHS.get()); 11822 if (LHS.isInvalid()) 11823 return QualType(); 11824 RHS = DefaultLvalueConversion(RHS.get()); 11825 if (RHS.isInvalid()) 11826 return QualType(); 11827 } 11828 11829 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11830 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11831 CheckPtrComparisonWithNullChar(LHS, RHS); 11832 CheckPtrComparisonWithNullChar(RHS, LHS); 11833 } 11834 11835 // Handle vector comparisons separately. 11836 if (LHS.get()->getType()->isVectorType() || 11837 RHS.get()->getType()->isVectorType()) 11838 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11839 11840 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11841 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11842 11843 QualType LHSType = LHS.get()->getType(); 11844 QualType RHSType = RHS.get()->getType(); 11845 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11846 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11847 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11848 11849 const Expr::NullPointerConstantKind LHSNullKind = 11850 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11851 const Expr::NullPointerConstantKind RHSNullKind = 11852 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11853 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11854 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11855 11856 auto computeResultTy = [&]() { 11857 if (Opc != BO_Cmp) 11858 return Context.getLogicalOperationType(); 11859 assert(getLangOpts().CPlusPlus); 11860 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11861 11862 QualType CompositeTy = LHS.get()->getType(); 11863 assert(!CompositeTy->isReferenceType()); 11864 11865 Optional<ComparisonCategoryType> CCT = 11866 getComparisonCategoryForBuiltinCmp(CompositeTy); 11867 if (!CCT) 11868 return InvalidOperands(Loc, LHS, RHS); 11869 11870 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11871 // P0946R0: Comparisons between a null pointer constant and an object 11872 // pointer result in std::strong_equality, which is ill-formed under 11873 // P1959R0. 11874 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11875 << (LHSIsNull ? LHS.get()->getSourceRange() 11876 : RHS.get()->getSourceRange()); 11877 return QualType(); 11878 } 11879 11880 return CheckComparisonCategoryType( 11881 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11882 }; 11883 11884 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11885 bool IsEquality = Opc == BO_EQ; 11886 if (RHSIsNull) 11887 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11888 RHS.get()->getSourceRange()); 11889 else 11890 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11891 LHS.get()->getSourceRange()); 11892 } 11893 11894 if (IsOrdered && LHSType->isFunctionPointerType() && 11895 RHSType->isFunctionPointerType()) { 11896 // Valid unless a relational comparison of function pointers 11897 bool IsError = Opc == BO_Cmp; 11898 auto DiagID = 11899 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11900 : getLangOpts().CPlusPlus 11901 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11902 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11903 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11904 << RHS.get()->getSourceRange(); 11905 if (IsError) 11906 return QualType(); 11907 } 11908 11909 if ((LHSType->isIntegerType() && !LHSIsNull) || 11910 (RHSType->isIntegerType() && !RHSIsNull)) { 11911 // Skip normal pointer conversion checks in this case; we have better 11912 // diagnostics for this below. 11913 } else if (getLangOpts().CPlusPlus) { 11914 // Equality comparison of a function pointer to a void pointer is invalid, 11915 // but we allow it as an extension. 11916 // FIXME: If we really want to allow this, should it be part of composite 11917 // pointer type computation so it works in conditionals too? 11918 if (!IsOrdered && 11919 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11920 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11921 // This is a gcc extension compatibility comparison. 11922 // In a SFINAE context, we treat this as a hard error to maintain 11923 // conformance with the C++ standard. 11924 diagnoseFunctionPointerToVoidComparison( 11925 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11926 11927 if (isSFINAEContext()) 11928 return QualType(); 11929 11930 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11931 return computeResultTy(); 11932 } 11933 11934 // C++ [expr.eq]p2: 11935 // If at least one operand is a pointer [...] bring them to their 11936 // composite pointer type. 11937 // C++ [expr.spaceship]p6 11938 // If at least one of the operands is of pointer type, [...] bring them 11939 // to their composite pointer type. 11940 // C++ [expr.rel]p2: 11941 // If both operands are pointers, [...] bring them to their composite 11942 // pointer type. 11943 // For <=>, the only valid non-pointer types are arrays and functions, and 11944 // we already decayed those, so this is really the same as the relational 11945 // comparison rule. 11946 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11947 (IsOrdered ? 2 : 1) && 11948 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11949 RHSType->isObjCObjectPointerType()))) { 11950 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11951 return QualType(); 11952 return computeResultTy(); 11953 } 11954 } else if (LHSType->isPointerType() && 11955 RHSType->isPointerType()) { // C99 6.5.8p2 11956 // All of the following pointer-related warnings are GCC extensions, except 11957 // when handling null pointer constants. 11958 QualType LCanPointeeTy = 11959 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11960 QualType RCanPointeeTy = 11961 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11962 11963 // C99 6.5.9p2 and C99 6.5.8p2 11964 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11965 RCanPointeeTy.getUnqualifiedType())) { 11966 if (IsRelational) { 11967 // Pointers both need to point to complete or incomplete types 11968 if ((LCanPointeeTy->isIncompleteType() != 11969 RCanPointeeTy->isIncompleteType()) && 11970 !getLangOpts().C11) { 11971 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11972 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11973 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11974 << RCanPointeeTy->isIncompleteType(); 11975 } 11976 } 11977 } else if (!IsRelational && 11978 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11979 // Valid unless comparison between non-null pointer and function pointer 11980 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11981 && !LHSIsNull && !RHSIsNull) 11982 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11983 /*isError*/false); 11984 } else { 11985 // Invalid 11986 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11987 } 11988 if (LCanPointeeTy != RCanPointeeTy) { 11989 // Treat NULL constant as a special case in OpenCL. 11990 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11991 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11992 Diag(Loc, 11993 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11994 << LHSType << RHSType << 0 /* comparison */ 11995 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11996 } 11997 } 11998 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11999 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12000 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12001 : CK_BitCast; 12002 if (LHSIsNull && !RHSIsNull) 12003 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12004 else 12005 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12006 } 12007 return computeResultTy(); 12008 } 12009 12010 if (getLangOpts().CPlusPlus) { 12011 // C++ [expr.eq]p4: 12012 // Two operands of type std::nullptr_t or one operand of type 12013 // std::nullptr_t and the other a null pointer constant compare equal. 12014 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12015 if (LHSType->isNullPtrType()) { 12016 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12017 return computeResultTy(); 12018 } 12019 if (RHSType->isNullPtrType()) { 12020 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12021 return computeResultTy(); 12022 } 12023 } 12024 12025 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12026 // These aren't covered by the composite pointer type rules. 12027 if (!IsOrdered && RHSType->isNullPtrType() && 12028 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12029 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12030 return computeResultTy(); 12031 } 12032 if (!IsOrdered && LHSType->isNullPtrType() && 12033 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12034 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12035 return computeResultTy(); 12036 } 12037 12038 if (IsRelational && 12039 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12040 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12041 // HACK: Relational comparison of nullptr_t against a pointer type is 12042 // invalid per DR583, but we allow it within std::less<> and friends, 12043 // since otherwise common uses of it break. 12044 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12045 // friends to have std::nullptr_t overload candidates. 12046 DeclContext *DC = CurContext; 12047 if (isa<FunctionDecl>(DC)) 12048 DC = DC->getParent(); 12049 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12050 if (CTSD->isInStdNamespace() && 12051 llvm::StringSwitch<bool>(CTSD->getName()) 12052 .Cases("less", "less_equal", "greater", "greater_equal", true) 12053 .Default(false)) { 12054 if (RHSType->isNullPtrType()) 12055 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12056 else 12057 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12058 return computeResultTy(); 12059 } 12060 } 12061 } 12062 12063 // C++ [expr.eq]p2: 12064 // If at least one operand is a pointer to member, [...] bring them to 12065 // their composite pointer type. 12066 if (!IsOrdered && 12067 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12068 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12069 return QualType(); 12070 else 12071 return computeResultTy(); 12072 } 12073 } 12074 12075 // Handle block pointer types. 12076 if (!IsOrdered && LHSType->isBlockPointerType() && 12077 RHSType->isBlockPointerType()) { 12078 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12079 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12080 12081 if (!LHSIsNull && !RHSIsNull && 12082 !Context.typesAreCompatible(lpointee, rpointee)) { 12083 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12084 << LHSType << RHSType << LHS.get()->getSourceRange() 12085 << RHS.get()->getSourceRange(); 12086 } 12087 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12088 return computeResultTy(); 12089 } 12090 12091 // Allow block pointers to be compared with null pointer constants. 12092 if (!IsOrdered 12093 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12094 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12095 if (!LHSIsNull && !RHSIsNull) { 12096 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12097 ->getPointeeType()->isVoidType()) 12098 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12099 ->getPointeeType()->isVoidType()))) 12100 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12101 << LHSType << RHSType << LHS.get()->getSourceRange() 12102 << RHS.get()->getSourceRange(); 12103 } 12104 if (LHSIsNull && !RHSIsNull) 12105 LHS = ImpCastExprToType(LHS.get(), RHSType, 12106 RHSType->isPointerType() ? CK_BitCast 12107 : CK_AnyPointerToBlockPointerCast); 12108 else 12109 RHS = ImpCastExprToType(RHS.get(), LHSType, 12110 LHSType->isPointerType() ? CK_BitCast 12111 : CK_AnyPointerToBlockPointerCast); 12112 return computeResultTy(); 12113 } 12114 12115 if (LHSType->isObjCObjectPointerType() || 12116 RHSType->isObjCObjectPointerType()) { 12117 const PointerType *LPT = LHSType->getAs<PointerType>(); 12118 const PointerType *RPT = RHSType->getAs<PointerType>(); 12119 if (LPT || RPT) { 12120 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12121 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12122 12123 if (!LPtrToVoid && !RPtrToVoid && 12124 !Context.typesAreCompatible(LHSType, RHSType)) { 12125 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12126 /*isError*/false); 12127 } 12128 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12129 // the RHS, but we have test coverage for this behavior. 12130 // FIXME: Consider using convertPointersToCompositeType in C++. 12131 if (LHSIsNull && !RHSIsNull) { 12132 Expr *E = LHS.get(); 12133 if (getLangOpts().ObjCAutoRefCount) 12134 CheckObjCConversion(SourceRange(), RHSType, E, 12135 CCK_ImplicitConversion); 12136 LHS = ImpCastExprToType(E, RHSType, 12137 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12138 } 12139 else { 12140 Expr *E = RHS.get(); 12141 if (getLangOpts().ObjCAutoRefCount) 12142 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12143 /*Diagnose=*/true, 12144 /*DiagnoseCFAudited=*/false, Opc); 12145 RHS = ImpCastExprToType(E, LHSType, 12146 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12147 } 12148 return computeResultTy(); 12149 } 12150 if (LHSType->isObjCObjectPointerType() && 12151 RHSType->isObjCObjectPointerType()) { 12152 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12153 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12154 /*isError*/false); 12155 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12156 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12157 12158 if (LHSIsNull && !RHSIsNull) 12159 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12160 else 12161 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12162 return computeResultTy(); 12163 } 12164 12165 if (!IsOrdered && LHSType->isBlockPointerType() && 12166 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12167 LHS = ImpCastExprToType(LHS.get(), RHSType, 12168 CK_BlockPointerToObjCPointerCast); 12169 return computeResultTy(); 12170 } else if (!IsOrdered && 12171 LHSType->isBlockCompatibleObjCPointerType(Context) && 12172 RHSType->isBlockPointerType()) { 12173 RHS = ImpCastExprToType(RHS.get(), LHSType, 12174 CK_BlockPointerToObjCPointerCast); 12175 return computeResultTy(); 12176 } 12177 } 12178 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12179 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12180 unsigned DiagID = 0; 12181 bool isError = false; 12182 if (LangOpts.DebuggerSupport) { 12183 // Under a debugger, allow the comparison of pointers to integers, 12184 // since users tend to want to compare addresses. 12185 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12186 (RHSIsNull && RHSType->isIntegerType())) { 12187 if (IsOrdered) { 12188 isError = getLangOpts().CPlusPlus; 12189 DiagID = 12190 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12191 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12192 } 12193 } else if (getLangOpts().CPlusPlus) { 12194 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12195 isError = true; 12196 } else if (IsOrdered) 12197 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12198 else 12199 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12200 12201 if (DiagID) { 12202 Diag(Loc, DiagID) 12203 << LHSType << RHSType << LHS.get()->getSourceRange() 12204 << RHS.get()->getSourceRange(); 12205 if (isError) 12206 return QualType(); 12207 } 12208 12209 if (LHSType->isIntegerType()) 12210 LHS = ImpCastExprToType(LHS.get(), RHSType, 12211 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12212 else 12213 RHS = ImpCastExprToType(RHS.get(), LHSType, 12214 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12215 return computeResultTy(); 12216 } 12217 12218 // Handle block pointers. 12219 if (!IsOrdered && RHSIsNull 12220 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12221 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12222 return computeResultTy(); 12223 } 12224 if (!IsOrdered && LHSIsNull 12225 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12226 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12227 return computeResultTy(); 12228 } 12229 12230 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12231 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12232 return computeResultTy(); 12233 } 12234 12235 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12236 return computeResultTy(); 12237 } 12238 12239 if (LHSIsNull && RHSType->isQueueT()) { 12240 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12241 return computeResultTy(); 12242 } 12243 12244 if (LHSType->isQueueT() && RHSIsNull) { 12245 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12246 return computeResultTy(); 12247 } 12248 } 12249 12250 return InvalidOperands(Loc, LHS, RHS); 12251 } 12252 12253 // Return a signed ext_vector_type that is of identical size and number of 12254 // elements. For floating point vectors, return an integer type of identical 12255 // size and number of elements. In the non ext_vector_type case, search from 12256 // the largest type to the smallest type to avoid cases where long long == long, 12257 // where long gets picked over long long. 12258 QualType Sema::GetSignedVectorType(QualType V) { 12259 const VectorType *VTy = V->castAs<VectorType>(); 12260 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12261 12262 if (isa<ExtVectorType>(VTy)) { 12263 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12264 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12265 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12266 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12267 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12268 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12269 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12270 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12271 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12272 "Unhandled vector element size in vector compare"); 12273 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12274 } 12275 12276 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12277 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12278 VectorType::GenericVector); 12279 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12280 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12281 VectorType::GenericVector); 12282 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12283 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12284 VectorType::GenericVector); 12285 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12286 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12287 VectorType::GenericVector); 12288 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12289 "Unhandled vector element size in vector compare"); 12290 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12291 VectorType::GenericVector); 12292 } 12293 12294 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12295 /// operates on extended vector types. Instead of producing an IntTy result, 12296 /// like a scalar comparison, a vector comparison produces a vector of integer 12297 /// types. 12298 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12299 SourceLocation Loc, 12300 BinaryOperatorKind Opc) { 12301 if (Opc == BO_Cmp) { 12302 Diag(Loc, diag::err_three_way_vector_comparison); 12303 return QualType(); 12304 } 12305 12306 // Check to make sure we're operating on vectors of the same type and width, 12307 // Allowing one side to be a scalar of element type. 12308 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12309 /*AllowBothBool*/true, 12310 /*AllowBoolConversions*/getLangOpts().ZVector); 12311 if (vType.isNull()) 12312 return vType; 12313 12314 QualType LHSType = LHS.get()->getType(); 12315 12316 // Determine the return type of a vector compare. By default clang will return 12317 // a scalar for all vector compares except vector bool and vector pixel. 12318 // With the gcc compiler we will always return a vector type and with the xl 12319 // compiler we will always return a scalar type. This switch allows choosing 12320 // which behavior is prefered. 12321 if (getLangOpts().AltiVec) { 12322 switch (getLangOpts().getAltivecSrcCompat()) { 12323 case LangOptions::AltivecSrcCompatKind::Mixed: 12324 // If AltiVec, the comparison results in a numeric type, i.e. 12325 // bool for C++, int for C 12326 if (vType->castAs<VectorType>()->getVectorKind() == 12327 VectorType::AltiVecVector) 12328 return Context.getLogicalOperationType(); 12329 else 12330 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12331 break; 12332 case LangOptions::AltivecSrcCompatKind::GCC: 12333 // For GCC we always return the vector type. 12334 break; 12335 case LangOptions::AltivecSrcCompatKind::XL: 12336 return Context.getLogicalOperationType(); 12337 break; 12338 } 12339 } 12340 12341 // For non-floating point types, check for self-comparisons of the form 12342 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12343 // often indicate logic errors in the program. 12344 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12345 12346 // Check for comparisons of floating point operands using != and ==. 12347 if (BinaryOperator::isEqualityOp(Opc) && 12348 LHSType->hasFloatingRepresentation()) { 12349 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12350 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12351 } 12352 12353 // Return a signed type for the vector. 12354 return GetSignedVectorType(vType); 12355 } 12356 12357 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12358 const ExprResult &XorRHS, 12359 const SourceLocation Loc) { 12360 // Do not diagnose macros. 12361 if (Loc.isMacroID()) 12362 return; 12363 12364 // Do not diagnose if both LHS and RHS are macros. 12365 if (XorLHS.get()->getExprLoc().isMacroID() && 12366 XorRHS.get()->getExprLoc().isMacroID()) 12367 return; 12368 12369 bool Negative = false; 12370 bool ExplicitPlus = false; 12371 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12372 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12373 12374 if (!LHSInt) 12375 return; 12376 if (!RHSInt) { 12377 // Check negative literals. 12378 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12379 UnaryOperatorKind Opc = UO->getOpcode(); 12380 if (Opc != UO_Minus && Opc != UO_Plus) 12381 return; 12382 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12383 if (!RHSInt) 12384 return; 12385 Negative = (Opc == UO_Minus); 12386 ExplicitPlus = !Negative; 12387 } else { 12388 return; 12389 } 12390 } 12391 12392 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12393 llvm::APInt RightSideValue = RHSInt->getValue(); 12394 if (LeftSideValue != 2 && LeftSideValue != 10) 12395 return; 12396 12397 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12398 return; 12399 12400 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12401 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12402 llvm::StringRef ExprStr = 12403 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12404 12405 CharSourceRange XorRange = 12406 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12407 llvm::StringRef XorStr = 12408 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12409 // Do not diagnose if xor keyword/macro is used. 12410 if (XorStr == "xor") 12411 return; 12412 12413 std::string LHSStr = std::string(Lexer::getSourceText( 12414 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12415 S.getSourceManager(), S.getLangOpts())); 12416 std::string RHSStr = std::string(Lexer::getSourceText( 12417 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12418 S.getSourceManager(), S.getLangOpts())); 12419 12420 if (Negative) { 12421 RightSideValue = -RightSideValue; 12422 RHSStr = "-" + RHSStr; 12423 } else if (ExplicitPlus) { 12424 RHSStr = "+" + RHSStr; 12425 } 12426 12427 StringRef LHSStrRef = LHSStr; 12428 StringRef RHSStrRef = RHSStr; 12429 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12430 // literals. 12431 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12432 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12433 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12434 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12435 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12436 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12437 LHSStrRef.find('\'') != StringRef::npos || 12438 RHSStrRef.find('\'') != StringRef::npos) 12439 return; 12440 12441 bool SuggestXor = 12442 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12443 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12444 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12445 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12446 std::string SuggestedExpr = "1 << " + RHSStr; 12447 bool Overflow = false; 12448 llvm::APInt One = (LeftSideValue - 1); 12449 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12450 if (Overflow) { 12451 if (RightSideIntValue < 64) 12452 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12453 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12454 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12455 else if (RightSideIntValue == 64) 12456 S.Diag(Loc, diag::warn_xor_used_as_pow) 12457 << ExprStr << toString(XorValue, 10, true); 12458 else 12459 return; 12460 } else { 12461 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12462 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12463 << toString(PowValue, 10, true) 12464 << FixItHint::CreateReplacement( 12465 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12466 } 12467 12468 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12469 << ("0x2 ^ " + RHSStr) << SuggestXor; 12470 } else if (LeftSideValue == 10) { 12471 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12472 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12473 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12474 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12475 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12476 << ("0xA ^ " + RHSStr) << SuggestXor; 12477 } 12478 } 12479 12480 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12481 SourceLocation Loc) { 12482 // Ensure that either both operands are of the same vector type, or 12483 // one operand is of a vector type and the other is of its element type. 12484 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12485 /*AllowBothBool*/true, 12486 /*AllowBoolConversions*/false); 12487 if (vType.isNull()) 12488 return InvalidOperands(Loc, LHS, RHS); 12489 if (getLangOpts().OpenCL && 12490 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12491 vType->hasFloatingRepresentation()) 12492 return InvalidOperands(Loc, LHS, RHS); 12493 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12494 // usage of the logical operators && and || with vectors in C. This 12495 // check could be notionally dropped. 12496 if (!getLangOpts().CPlusPlus && 12497 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12498 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12499 12500 return GetSignedVectorType(LHS.get()->getType()); 12501 } 12502 12503 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12504 SourceLocation Loc, 12505 bool IsCompAssign) { 12506 if (!IsCompAssign) { 12507 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12508 if (LHS.isInvalid()) 12509 return QualType(); 12510 } 12511 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12512 if (RHS.isInvalid()) 12513 return QualType(); 12514 12515 // For conversion purposes, we ignore any qualifiers. 12516 // For example, "const float" and "float" are equivalent. 12517 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12518 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12519 12520 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12521 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12522 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12523 12524 if (Context.hasSameType(LHSType, RHSType)) 12525 return LHSType; 12526 12527 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12528 // case we have to return InvalidOperands. 12529 ExprResult OriginalLHS = LHS; 12530 ExprResult OriginalRHS = RHS; 12531 if (LHSMatType && !RHSMatType) { 12532 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12533 if (!RHS.isInvalid()) 12534 return LHSType; 12535 12536 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12537 } 12538 12539 if (!LHSMatType && RHSMatType) { 12540 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12541 if (!LHS.isInvalid()) 12542 return RHSType; 12543 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12544 } 12545 12546 return InvalidOperands(Loc, LHS, RHS); 12547 } 12548 12549 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12550 SourceLocation Loc, 12551 bool IsCompAssign) { 12552 if (!IsCompAssign) { 12553 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12554 if (LHS.isInvalid()) 12555 return QualType(); 12556 } 12557 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12558 if (RHS.isInvalid()) 12559 return QualType(); 12560 12561 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12562 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12563 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12564 12565 if (LHSMatType && RHSMatType) { 12566 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12567 return InvalidOperands(Loc, LHS, RHS); 12568 12569 if (!Context.hasSameType(LHSMatType->getElementType(), 12570 RHSMatType->getElementType())) 12571 return InvalidOperands(Loc, LHS, RHS); 12572 12573 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12574 LHSMatType->getNumRows(), 12575 RHSMatType->getNumColumns()); 12576 } 12577 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12578 } 12579 12580 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12581 SourceLocation Loc, 12582 BinaryOperatorKind Opc) { 12583 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12584 12585 bool IsCompAssign = 12586 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12587 12588 if (LHS.get()->getType()->isVectorType() || 12589 RHS.get()->getType()->isVectorType()) { 12590 if (LHS.get()->getType()->hasIntegerRepresentation() && 12591 RHS.get()->getType()->hasIntegerRepresentation()) 12592 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12593 /*AllowBothBool*/true, 12594 /*AllowBoolConversions*/getLangOpts().ZVector); 12595 return InvalidOperands(Loc, LHS, RHS); 12596 } 12597 12598 if (Opc == BO_And) 12599 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12600 12601 if (LHS.get()->getType()->hasFloatingRepresentation() || 12602 RHS.get()->getType()->hasFloatingRepresentation()) 12603 return InvalidOperands(Loc, LHS, RHS); 12604 12605 ExprResult LHSResult = LHS, RHSResult = RHS; 12606 QualType compType = UsualArithmeticConversions( 12607 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12608 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12609 return QualType(); 12610 LHS = LHSResult.get(); 12611 RHS = RHSResult.get(); 12612 12613 if (Opc == BO_Xor) 12614 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12615 12616 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12617 return compType; 12618 return InvalidOperands(Loc, LHS, RHS); 12619 } 12620 12621 // C99 6.5.[13,14] 12622 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12623 SourceLocation Loc, 12624 BinaryOperatorKind Opc) { 12625 // Check vector operands differently. 12626 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12627 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12628 12629 bool EnumConstantInBoolContext = false; 12630 for (const ExprResult &HS : {LHS, RHS}) { 12631 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12632 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12633 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12634 EnumConstantInBoolContext = true; 12635 } 12636 } 12637 12638 if (EnumConstantInBoolContext) 12639 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12640 12641 // Diagnose cases where the user write a logical and/or but probably meant a 12642 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12643 // is a constant. 12644 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12645 !LHS.get()->getType()->isBooleanType() && 12646 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12647 // Don't warn in macros or template instantiations. 12648 !Loc.isMacroID() && !inTemplateInstantiation()) { 12649 // If the RHS can be constant folded, and if it constant folds to something 12650 // that isn't 0 or 1 (which indicate a potential logical operation that 12651 // happened to fold to true/false) then warn. 12652 // Parens on the RHS are ignored. 12653 Expr::EvalResult EVResult; 12654 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12655 llvm::APSInt Result = EVResult.Val.getInt(); 12656 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12657 !RHS.get()->getExprLoc().isMacroID()) || 12658 (Result != 0 && Result != 1)) { 12659 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12660 << RHS.get()->getSourceRange() 12661 << (Opc == BO_LAnd ? "&&" : "||"); 12662 // Suggest replacing the logical operator with the bitwise version 12663 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12664 << (Opc == BO_LAnd ? "&" : "|") 12665 << FixItHint::CreateReplacement(SourceRange( 12666 Loc, getLocForEndOfToken(Loc)), 12667 Opc == BO_LAnd ? "&" : "|"); 12668 if (Opc == BO_LAnd) 12669 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12670 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12671 << FixItHint::CreateRemoval( 12672 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12673 RHS.get()->getEndLoc())); 12674 } 12675 } 12676 } 12677 12678 if (!Context.getLangOpts().CPlusPlus) { 12679 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12680 // not operate on the built-in scalar and vector float types. 12681 if (Context.getLangOpts().OpenCL && 12682 Context.getLangOpts().OpenCLVersion < 120) { 12683 if (LHS.get()->getType()->isFloatingType() || 12684 RHS.get()->getType()->isFloatingType()) 12685 return InvalidOperands(Loc, LHS, RHS); 12686 } 12687 12688 LHS = UsualUnaryConversions(LHS.get()); 12689 if (LHS.isInvalid()) 12690 return QualType(); 12691 12692 RHS = UsualUnaryConversions(RHS.get()); 12693 if (RHS.isInvalid()) 12694 return QualType(); 12695 12696 if (!LHS.get()->getType()->isScalarType() || 12697 !RHS.get()->getType()->isScalarType()) 12698 return InvalidOperands(Loc, LHS, RHS); 12699 12700 return Context.IntTy; 12701 } 12702 12703 // The following is safe because we only use this method for 12704 // non-overloadable operands. 12705 12706 // C++ [expr.log.and]p1 12707 // C++ [expr.log.or]p1 12708 // The operands are both contextually converted to type bool. 12709 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12710 if (LHSRes.isInvalid()) 12711 return InvalidOperands(Loc, LHS, RHS); 12712 LHS = LHSRes; 12713 12714 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12715 if (RHSRes.isInvalid()) 12716 return InvalidOperands(Loc, LHS, RHS); 12717 RHS = RHSRes; 12718 12719 // C++ [expr.log.and]p2 12720 // C++ [expr.log.or]p2 12721 // The result is a bool. 12722 return Context.BoolTy; 12723 } 12724 12725 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12726 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12727 if (!ME) return false; 12728 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12729 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12730 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12731 if (!Base) return false; 12732 return Base->getMethodDecl() != nullptr; 12733 } 12734 12735 /// Is the given expression (which must be 'const') a reference to a 12736 /// variable which was originally non-const, but which has become 12737 /// 'const' due to being captured within a block? 12738 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12739 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12740 assert(E->isLValue() && E->getType().isConstQualified()); 12741 E = E->IgnoreParens(); 12742 12743 // Must be a reference to a declaration from an enclosing scope. 12744 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12745 if (!DRE) return NCCK_None; 12746 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12747 12748 // The declaration must be a variable which is not declared 'const'. 12749 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12750 if (!var) return NCCK_None; 12751 if (var->getType().isConstQualified()) return NCCK_None; 12752 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12753 12754 // Decide whether the first capture was for a block or a lambda. 12755 DeclContext *DC = S.CurContext, *Prev = nullptr; 12756 // Decide whether the first capture was for a block or a lambda. 12757 while (DC) { 12758 // For init-capture, it is possible that the variable belongs to the 12759 // template pattern of the current context. 12760 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12761 if (var->isInitCapture() && 12762 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12763 break; 12764 if (DC == var->getDeclContext()) 12765 break; 12766 Prev = DC; 12767 DC = DC->getParent(); 12768 } 12769 // Unless we have an init-capture, we've gone one step too far. 12770 if (!var->isInitCapture()) 12771 DC = Prev; 12772 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12773 } 12774 12775 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12776 Ty = Ty.getNonReferenceType(); 12777 if (IsDereference && Ty->isPointerType()) 12778 Ty = Ty->getPointeeType(); 12779 return !Ty.isConstQualified(); 12780 } 12781 12782 // Update err_typecheck_assign_const and note_typecheck_assign_const 12783 // when this enum is changed. 12784 enum { 12785 ConstFunction, 12786 ConstVariable, 12787 ConstMember, 12788 ConstMethod, 12789 NestedConstMember, 12790 ConstUnknown, // Keep as last element 12791 }; 12792 12793 /// Emit the "read-only variable not assignable" error and print notes to give 12794 /// more information about why the variable is not assignable, such as pointing 12795 /// to the declaration of a const variable, showing that a method is const, or 12796 /// that the function is returning a const reference. 12797 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12798 SourceLocation Loc) { 12799 SourceRange ExprRange = E->getSourceRange(); 12800 12801 // Only emit one error on the first const found. All other consts will emit 12802 // a note to the error. 12803 bool DiagnosticEmitted = false; 12804 12805 // Track if the current expression is the result of a dereference, and if the 12806 // next checked expression is the result of a dereference. 12807 bool IsDereference = false; 12808 bool NextIsDereference = false; 12809 12810 // Loop to process MemberExpr chains. 12811 while (true) { 12812 IsDereference = NextIsDereference; 12813 12814 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12815 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12816 NextIsDereference = ME->isArrow(); 12817 const ValueDecl *VD = ME->getMemberDecl(); 12818 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12819 // Mutable fields can be modified even if the class is const. 12820 if (Field->isMutable()) { 12821 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12822 break; 12823 } 12824 12825 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12826 if (!DiagnosticEmitted) { 12827 S.Diag(Loc, diag::err_typecheck_assign_const) 12828 << ExprRange << ConstMember << false /*static*/ << Field 12829 << Field->getType(); 12830 DiagnosticEmitted = true; 12831 } 12832 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12833 << ConstMember << false /*static*/ << Field << Field->getType() 12834 << Field->getSourceRange(); 12835 } 12836 E = ME->getBase(); 12837 continue; 12838 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12839 if (VDecl->getType().isConstQualified()) { 12840 if (!DiagnosticEmitted) { 12841 S.Diag(Loc, diag::err_typecheck_assign_const) 12842 << ExprRange << ConstMember << true /*static*/ << VDecl 12843 << VDecl->getType(); 12844 DiagnosticEmitted = true; 12845 } 12846 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12847 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12848 << VDecl->getSourceRange(); 12849 } 12850 // Static fields do not inherit constness from parents. 12851 break; 12852 } 12853 break; // End MemberExpr 12854 } else if (const ArraySubscriptExpr *ASE = 12855 dyn_cast<ArraySubscriptExpr>(E)) { 12856 E = ASE->getBase()->IgnoreParenImpCasts(); 12857 continue; 12858 } else if (const ExtVectorElementExpr *EVE = 12859 dyn_cast<ExtVectorElementExpr>(E)) { 12860 E = EVE->getBase()->IgnoreParenImpCasts(); 12861 continue; 12862 } 12863 break; 12864 } 12865 12866 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12867 // Function calls 12868 const FunctionDecl *FD = CE->getDirectCallee(); 12869 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12870 if (!DiagnosticEmitted) { 12871 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12872 << ConstFunction << FD; 12873 DiagnosticEmitted = true; 12874 } 12875 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12876 diag::note_typecheck_assign_const) 12877 << ConstFunction << FD << FD->getReturnType() 12878 << FD->getReturnTypeSourceRange(); 12879 } 12880 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12881 // Point to variable declaration. 12882 if (const ValueDecl *VD = DRE->getDecl()) { 12883 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12884 if (!DiagnosticEmitted) { 12885 S.Diag(Loc, diag::err_typecheck_assign_const) 12886 << ExprRange << ConstVariable << VD << VD->getType(); 12887 DiagnosticEmitted = true; 12888 } 12889 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12890 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12891 } 12892 } 12893 } else if (isa<CXXThisExpr>(E)) { 12894 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12895 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12896 if (MD->isConst()) { 12897 if (!DiagnosticEmitted) { 12898 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12899 << ConstMethod << MD; 12900 DiagnosticEmitted = true; 12901 } 12902 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12903 << ConstMethod << MD << MD->getSourceRange(); 12904 } 12905 } 12906 } 12907 } 12908 12909 if (DiagnosticEmitted) 12910 return; 12911 12912 // Can't determine a more specific message, so display the generic error. 12913 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12914 } 12915 12916 enum OriginalExprKind { 12917 OEK_Variable, 12918 OEK_Member, 12919 OEK_LValue 12920 }; 12921 12922 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12923 const RecordType *Ty, 12924 SourceLocation Loc, SourceRange Range, 12925 OriginalExprKind OEK, 12926 bool &DiagnosticEmitted) { 12927 std::vector<const RecordType *> RecordTypeList; 12928 RecordTypeList.push_back(Ty); 12929 unsigned NextToCheckIndex = 0; 12930 // We walk the record hierarchy breadth-first to ensure that we print 12931 // diagnostics in field nesting order. 12932 while (RecordTypeList.size() > NextToCheckIndex) { 12933 bool IsNested = NextToCheckIndex > 0; 12934 for (const FieldDecl *Field : 12935 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12936 // First, check every field for constness. 12937 QualType FieldTy = Field->getType(); 12938 if (FieldTy.isConstQualified()) { 12939 if (!DiagnosticEmitted) { 12940 S.Diag(Loc, diag::err_typecheck_assign_const) 12941 << Range << NestedConstMember << OEK << VD 12942 << IsNested << Field; 12943 DiagnosticEmitted = true; 12944 } 12945 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12946 << NestedConstMember << IsNested << Field 12947 << FieldTy << Field->getSourceRange(); 12948 } 12949 12950 // Then we append it to the list to check next in order. 12951 FieldTy = FieldTy.getCanonicalType(); 12952 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12953 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 12954 RecordTypeList.push_back(FieldRecTy); 12955 } 12956 } 12957 ++NextToCheckIndex; 12958 } 12959 } 12960 12961 /// Emit an error for the case where a record we are trying to assign to has a 12962 /// const-qualified field somewhere in its hierarchy. 12963 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12964 SourceLocation Loc) { 12965 QualType Ty = E->getType(); 12966 assert(Ty->isRecordType() && "lvalue was not record?"); 12967 SourceRange Range = E->getSourceRange(); 12968 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12969 bool DiagEmitted = false; 12970 12971 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12972 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12973 Range, OEK_Member, DiagEmitted); 12974 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12975 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12976 Range, OEK_Variable, DiagEmitted); 12977 else 12978 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12979 Range, OEK_LValue, DiagEmitted); 12980 if (!DiagEmitted) 12981 DiagnoseConstAssignment(S, E, Loc); 12982 } 12983 12984 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12985 /// emit an error and return true. If so, return false. 12986 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12987 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12988 12989 S.CheckShadowingDeclModification(E, Loc); 12990 12991 SourceLocation OrigLoc = Loc; 12992 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12993 &Loc); 12994 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12995 IsLV = Expr::MLV_InvalidMessageExpression; 12996 if (IsLV == Expr::MLV_Valid) 12997 return false; 12998 12999 unsigned DiagID = 0; 13000 bool NeedType = false; 13001 switch (IsLV) { // C99 6.5.16p2 13002 case Expr::MLV_ConstQualified: 13003 // Use a specialized diagnostic when we're assigning to an object 13004 // from an enclosing function or block. 13005 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13006 if (NCCK == NCCK_Block) 13007 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13008 else 13009 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13010 break; 13011 } 13012 13013 // In ARC, use some specialized diagnostics for occasions where we 13014 // infer 'const'. These are always pseudo-strong variables. 13015 if (S.getLangOpts().ObjCAutoRefCount) { 13016 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13017 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13018 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13019 13020 // Use the normal diagnostic if it's pseudo-__strong but the 13021 // user actually wrote 'const'. 13022 if (var->isARCPseudoStrong() && 13023 (!var->getTypeSourceInfo() || 13024 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13025 // There are three pseudo-strong cases: 13026 // - self 13027 ObjCMethodDecl *method = S.getCurMethodDecl(); 13028 if (method && var == method->getSelfDecl()) { 13029 DiagID = method->isClassMethod() 13030 ? diag::err_typecheck_arc_assign_self_class_method 13031 : diag::err_typecheck_arc_assign_self; 13032 13033 // - Objective-C externally_retained attribute. 13034 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13035 isa<ParmVarDecl>(var)) { 13036 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13037 13038 // - fast enumeration variables 13039 } else { 13040 DiagID = diag::err_typecheck_arr_assign_enumeration; 13041 } 13042 13043 SourceRange Assign; 13044 if (Loc != OrigLoc) 13045 Assign = SourceRange(OrigLoc, OrigLoc); 13046 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13047 // We need to preserve the AST regardless, so migration tool 13048 // can do its job. 13049 return false; 13050 } 13051 } 13052 } 13053 13054 // If none of the special cases above are triggered, then this is a 13055 // simple const assignment. 13056 if (DiagID == 0) { 13057 DiagnoseConstAssignment(S, E, Loc); 13058 return true; 13059 } 13060 13061 break; 13062 case Expr::MLV_ConstAddrSpace: 13063 DiagnoseConstAssignment(S, E, Loc); 13064 return true; 13065 case Expr::MLV_ConstQualifiedField: 13066 DiagnoseRecursiveConstFields(S, E, Loc); 13067 return true; 13068 case Expr::MLV_ArrayType: 13069 case Expr::MLV_ArrayTemporary: 13070 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13071 NeedType = true; 13072 break; 13073 case Expr::MLV_NotObjectType: 13074 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13075 NeedType = true; 13076 break; 13077 case Expr::MLV_LValueCast: 13078 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13079 break; 13080 case Expr::MLV_Valid: 13081 llvm_unreachable("did not take early return for MLV_Valid"); 13082 case Expr::MLV_InvalidExpression: 13083 case Expr::MLV_MemberFunction: 13084 case Expr::MLV_ClassTemporary: 13085 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13086 break; 13087 case Expr::MLV_IncompleteType: 13088 case Expr::MLV_IncompleteVoidType: 13089 return S.RequireCompleteType(Loc, E->getType(), 13090 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13091 case Expr::MLV_DuplicateVectorComponents: 13092 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13093 break; 13094 case Expr::MLV_NoSetterProperty: 13095 llvm_unreachable("readonly properties should be processed differently"); 13096 case Expr::MLV_InvalidMessageExpression: 13097 DiagID = diag::err_readonly_message_assignment; 13098 break; 13099 case Expr::MLV_SubObjCPropertySetting: 13100 DiagID = diag::err_no_subobject_property_setting; 13101 break; 13102 } 13103 13104 SourceRange Assign; 13105 if (Loc != OrigLoc) 13106 Assign = SourceRange(OrigLoc, OrigLoc); 13107 if (NeedType) 13108 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13109 else 13110 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13111 return true; 13112 } 13113 13114 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13115 SourceLocation Loc, 13116 Sema &Sema) { 13117 if (Sema.inTemplateInstantiation()) 13118 return; 13119 if (Sema.isUnevaluatedContext()) 13120 return; 13121 if (Loc.isInvalid() || Loc.isMacroID()) 13122 return; 13123 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13124 return; 13125 13126 // C / C++ fields 13127 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13128 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13129 if (ML && MR) { 13130 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13131 return; 13132 const ValueDecl *LHSDecl = 13133 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13134 const ValueDecl *RHSDecl = 13135 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13136 if (LHSDecl != RHSDecl) 13137 return; 13138 if (LHSDecl->getType().isVolatileQualified()) 13139 return; 13140 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13141 if (RefTy->getPointeeType().isVolatileQualified()) 13142 return; 13143 13144 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13145 } 13146 13147 // Objective-C instance variables 13148 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13149 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13150 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13151 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13152 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13153 if (RL && RR && RL->getDecl() == RR->getDecl()) 13154 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13155 } 13156 } 13157 13158 // C99 6.5.16.1 13159 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13160 SourceLocation Loc, 13161 QualType CompoundType) { 13162 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13163 13164 // Verify that LHS is a modifiable lvalue, and emit error if not. 13165 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13166 return QualType(); 13167 13168 QualType LHSType = LHSExpr->getType(); 13169 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13170 CompoundType; 13171 // OpenCL v1.2 s6.1.1.1 p2: 13172 // The half data type can only be used to declare a pointer to a buffer that 13173 // contains half values 13174 if (getLangOpts().OpenCL && 13175 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13176 LHSType->isHalfType()) { 13177 Diag(Loc, diag::err_opencl_half_load_store) << 1 13178 << LHSType.getUnqualifiedType(); 13179 return QualType(); 13180 } 13181 13182 AssignConvertType ConvTy; 13183 if (CompoundType.isNull()) { 13184 Expr *RHSCheck = RHS.get(); 13185 13186 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13187 13188 QualType LHSTy(LHSType); 13189 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13190 if (RHS.isInvalid()) 13191 return QualType(); 13192 // Special case of NSObject attributes on c-style pointer types. 13193 if (ConvTy == IncompatiblePointer && 13194 ((Context.isObjCNSObjectType(LHSType) && 13195 RHSType->isObjCObjectPointerType()) || 13196 (Context.isObjCNSObjectType(RHSType) && 13197 LHSType->isObjCObjectPointerType()))) 13198 ConvTy = Compatible; 13199 13200 if (ConvTy == Compatible && 13201 LHSType->isObjCObjectType()) 13202 Diag(Loc, diag::err_objc_object_assignment) 13203 << LHSType; 13204 13205 // If the RHS is a unary plus or minus, check to see if they = and + are 13206 // right next to each other. If so, the user may have typo'd "x =+ 4" 13207 // instead of "x += 4". 13208 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13209 RHSCheck = ICE->getSubExpr(); 13210 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13211 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13212 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13213 // Only if the two operators are exactly adjacent. 13214 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13215 // And there is a space or other character before the subexpr of the 13216 // unary +/-. We don't want to warn on "x=-1". 13217 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13218 UO->getSubExpr()->getBeginLoc().isFileID()) { 13219 Diag(Loc, diag::warn_not_compound_assign) 13220 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13221 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13222 } 13223 } 13224 13225 if (ConvTy == Compatible) { 13226 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13227 // Warn about retain cycles where a block captures the LHS, but 13228 // not if the LHS is a simple variable into which the block is 13229 // being stored...unless that variable can be captured by reference! 13230 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13231 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13232 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13233 checkRetainCycles(LHSExpr, RHS.get()); 13234 } 13235 13236 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13237 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13238 // It is safe to assign a weak reference into a strong variable. 13239 // Although this code can still have problems: 13240 // id x = self.weakProp; 13241 // id y = self.weakProp; 13242 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13243 // paths through the function. This should be revisited if 13244 // -Wrepeated-use-of-weak is made flow-sensitive. 13245 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13246 // variable, which will be valid for the current autorelease scope. 13247 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13248 RHS.get()->getBeginLoc())) 13249 getCurFunction()->markSafeWeakUse(RHS.get()); 13250 13251 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13252 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13253 } 13254 } 13255 } else { 13256 // Compound assignment "x += y" 13257 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13258 } 13259 13260 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13261 RHS.get(), AA_Assigning)) 13262 return QualType(); 13263 13264 CheckForNullPointerDereference(*this, LHSExpr); 13265 13266 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13267 if (CompoundType.isNull()) { 13268 // C++2a [expr.ass]p5: 13269 // A simple-assignment whose left operand is of a volatile-qualified 13270 // type is deprecated unless the assignment is either a discarded-value 13271 // expression or an unevaluated operand 13272 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13273 } else { 13274 // C++2a [expr.ass]p6: 13275 // [Compound-assignment] expressions are deprecated if E1 has 13276 // volatile-qualified type 13277 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13278 } 13279 } 13280 13281 // C99 6.5.16p3: The type of an assignment expression is the type of the 13282 // left operand unless the left operand has qualified type, in which case 13283 // it is the unqualified version of the type of the left operand. 13284 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13285 // is converted to the type of the assignment expression (above). 13286 // C++ 5.17p1: the type of the assignment expression is that of its left 13287 // operand. 13288 return (getLangOpts().CPlusPlus 13289 ? LHSType : LHSType.getUnqualifiedType()); 13290 } 13291 13292 // Only ignore explicit casts to void. 13293 static bool IgnoreCommaOperand(const Expr *E) { 13294 E = E->IgnoreParens(); 13295 13296 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13297 if (CE->getCastKind() == CK_ToVoid) { 13298 return true; 13299 } 13300 13301 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13302 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13303 CE->getSubExpr()->getType()->isDependentType()) { 13304 return true; 13305 } 13306 } 13307 13308 return false; 13309 } 13310 13311 // Look for instances where it is likely the comma operator is confused with 13312 // another operator. There is an explicit list of acceptable expressions for 13313 // the left hand side of the comma operator, otherwise emit a warning. 13314 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13315 // No warnings in macros 13316 if (Loc.isMacroID()) 13317 return; 13318 13319 // Don't warn in template instantiations. 13320 if (inTemplateInstantiation()) 13321 return; 13322 13323 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13324 // instead, skip more than needed, then call back into here with the 13325 // CommaVisitor in SemaStmt.cpp. 13326 // The listed locations are the initialization and increment portions 13327 // of a for loop. The additional checks are on the condition of 13328 // if statements, do/while loops, and for loops. 13329 // Differences in scope flags for C89 mode requires the extra logic. 13330 const unsigned ForIncrementFlags = 13331 getLangOpts().C99 || getLangOpts().CPlusPlus 13332 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13333 : Scope::ContinueScope | Scope::BreakScope; 13334 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13335 const unsigned ScopeFlags = getCurScope()->getFlags(); 13336 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13337 (ScopeFlags & ForInitFlags) == ForInitFlags) 13338 return; 13339 13340 // If there are multiple comma operators used together, get the RHS of the 13341 // of the comma operator as the LHS. 13342 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13343 if (BO->getOpcode() != BO_Comma) 13344 break; 13345 LHS = BO->getRHS(); 13346 } 13347 13348 // Only allow some expressions on LHS to not warn. 13349 if (IgnoreCommaOperand(LHS)) 13350 return; 13351 13352 Diag(Loc, diag::warn_comma_operator); 13353 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13354 << LHS->getSourceRange() 13355 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13356 LangOpts.CPlusPlus ? "static_cast<void>(" 13357 : "(void)(") 13358 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13359 ")"); 13360 } 13361 13362 // C99 6.5.17 13363 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13364 SourceLocation Loc) { 13365 LHS = S.CheckPlaceholderExpr(LHS.get()); 13366 RHS = S.CheckPlaceholderExpr(RHS.get()); 13367 if (LHS.isInvalid() || RHS.isInvalid()) 13368 return QualType(); 13369 13370 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13371 // operands, but not unary promotions. 13372 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13373 13374 // So we treat the LHS as a ignored value, and in C++ we allow the 13375 // containing site to determine what should be done with the RHS. 13376 LHS = S.IgnoredValueConversions(LHS.get()); 13377 if (LHS.isInvalid()) 13378 return QualType(); 13379 13380 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13381 13382 if (!S.getLangOpts().CPlusPlus) { 13383 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13384 if (RHS.isInvalid()) 13385 return QualType(); 13386 if (!RHS.get()->getType()->isVoidType()) 13387 S.RequireCompleteType(Loc, RHS.get()->getType(), 13388 diag::err_incomplete_type); 13389 } 13390 13391 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13392 S.DiagnoseCommaOperator(LHS.get(), Loc); 13393 13394 return RHS.get()->getType(); 13395 } 13396 13397 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13398 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13399 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13400 ExprValueKind &VK, 13401 ExprObjectKind &OK, 13402 SourceLocation OpLoc, 13403 bool IsInc, bool IsPrefix) { 13404 if (Op->isTypeDependent()) 13405 return S.Context.DependentTy; 13406 13407 QualType ResType = Op->getType(); 13408 // Atomic types can be used for increment / decrement where the non-atomic 13409 // versions can, so ignore the _Atomic() specifier for the purpose of 13410 // checking. 13411 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13412 ResType = ResAtomicType->getValueType(); 13413 13414 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13415 13416 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13417 // Decrement of bool is not allowed. 13418 if (!IsInc) { 13419 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13420 return QualType(); 13421 } 13422 // Increment of bool sets it to true, but is deprecated. 13423 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13424 : diag::warn_increment_bool) 13425 << Op->getSourceRange(); 13426 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13427 // Error on enum increments and decrements in C++ mode 13428 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13429 return QualType(); 13430 } else if (ResType->isRealType()) { 13431 // OK! 13432 } else if (ResType->isPointerType()) { 13433 // C99 6.5.2.4p2, 6.5.6p2 13434 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13435 return QualType(); 13436 } else if (ResType->isObjCObjectPointerType()) { 13437 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13438 // Otherwise, we just need a complete type. 13439 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13440 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13441 return QualType(); 13442 } else if (ResType->isAnyComplexType()) { 13443 // C99 does not support ++/-- on complex types, we allow as an extension. 13444 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13445 << ResType << Op->getSourceRange(); 13446 } else if (ResType->isPlaceholderType()) { 13447 ExprResult PR = S.CheckPlaceholderExpr(Op); 13448 if (PR.isInvalid()) return QualType(); 13449 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13450 IsInc, IsPrefix); 13451 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13452 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13453 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13454 (ResType->castAs<VectorType>()->getVectorKind() != 13455 VectorType::AltiVecBool)) { 13456 // The z vector extensions allow ++ and -- for non-bool vectors. 13457 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13458 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13459 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13460 } else { 13461 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13462 << ResType << int(IsInc) << Op->getSourceRange(); 13463 return QualType(); 13464 } 13465 // At this point, we know we have a real, complex or pointer type. 13466 // Now make sure the operand is a modifiable lvalue. 13467 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13468 return QualType(); 13469 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13470 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13471 // An operand with volatile-qualified type is deprecated 13472 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13473 << IsInc << ResType; 13474 } 13475 // In C++, a prefix increment is the same type as the operand. Otherwise 13476 // (in C or with postfix), the increment is the unqualified type of the 13477 // operand. 13478 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13479 VK = VK_LValue; 13480 OK = Op->getObjectKind(); 13481 return ResType; 13482 } else { 13483 VK = VK_PRValue; 13484 return ResType.getUnqualifiedType(); 13485 } 13486 } 13487 13488 13489 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13490 /// This routine allows us to typecheck complex/recursive expressions 13491 /// where the declaration is needed for type checking. We only need to 13492 /// handle cases when the expression references a function designator 13493 /// or is an lvalue. Here are some examples: 13494 /// - &(x) => x 13495 /// - &*****f => f for f a function designator. 13496 /// - &s.xx => s 13497 /// - &s.zz[1].yy -> s, if zz is an array 13498 /// - *(x + 1) -> x, if x is an array 13499 /// - &"123"[2] -> 0 13500 /// - & __real__ x -> x 13501 /// 13502 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13503 /// members. 13504 static ValueDecl *getPrimaryDecl(Expr *E) { 13505 switch (E->getStmtClass()) { 13506 case Stmt::DeclRefExprClass: 13507 return cast<DeclRefExpr>(E)->getDecl(); 13508 case Stmt::MemberExprClass: 13509 // If this is an arrow operator, the address is an offset from 13510 // the base's value, so the object the base refers to is 13511 // irrelevant. 13512 if (cast<MemberExpr>(E)->isArrow()) 13513 return nullptr; 13514 // Otherwise, the expression refers to a part of the base 13515 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13516 case Stmt::ArraySubscriptExprClass: { 13517 // FIXME: This code shouldn't be necessary! We should catch the implicit 13518 // promotion of register arrays earlier. 13519 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13520 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13521 if (ICE->getSubExpr()->getType()->isArrayType()) 13522 return getPrimaryDecl(ICE->getSubExpr()); 13523 } 13524 return nullptr; 13525 } 13526 case Stmt::UnaryOperatorClass: { 13527 UnaryOperator *UO = cast<UnaryOperator>(E); 13528 13529 switch(UO->getOpcode()) { 13530 case UO_Real: 13531 case UO_Imag: 13532 case UO_Extension: 13533 return getPrimaryDecl(UO->getSubExpr()); 13534 default: 13535 return nullptr; 13536 } 13537 } 13538 case Stmt::ParenExprClass: 13539 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13540 case Stmt::ImplicitCastExprClass: 13541 // If the result of an implicit cast is an l-value, we care about 13542 // the sub-expression; otherwise, the result here doesn't matter. 13543 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13544 case Stmt::CXXUuidofExprClass: 13545 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13546 default: 13547 return nullptr; 13548 } 13549 } 13550 13551 namespace { 13552 enum { 13553 AO_Bit_Field = 0, 13554 AO_Vector_Element = 1, 13555 AO_Property_Expansion = 2, 13556 AO_Register_Variable = 3, 13557 AO_Matrix_Element = 4, 13558 AO_No_Error = 5 13559 }; 13560 } 13561 /// Diagnose invalid operand for address of operations. 13562 /// 13563 /// \param Type The type of operand which cannot have its address taken. 13564 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13565 Expr *E, unsigned Type) { 13566 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13567 } 13568 13569 /// CheckAddressOfOperand - The operand of & must be either a function 13570 /// designator or an lvalue designating an object. If it is an lvalue, the 13571 /// object cannot be declared with storage class register or be a bit field. 13572 /// Note: The usual conversions are *not* applied to the operand of the & 13573 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13574 /// In C++, the operand might be an overloaded function name, in which case 13575 /// we allow the '&' but retain the overloaded-function type. 13576 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13577 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13578 if (PTy->getKind() == BuiltinType::Overload) { 13579 Expr *E = OrigOp.get()->IgnoreParens(); 13580 if (!isa<OverloadExpr>(E)) { 13581 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13582 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13583 << OrigOp.get()->getSourceRange(); 13584 return QualType(); 13585 } 13586 13587 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13588 if (isa<UnresolvedMemberExpr>(Ovl)) 13589 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13590 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13591 << OrigOp.get()->getSourceRange(); 13592 return QualType(); 13593 } 13594 13595 return Context.OverloadTy; 13596 } 13597 13598 if (PTy->getKind() == BuiltinType::UnknownAny) 13599 return Context.UnknownAnyTy; 13600 13601 if (PTy->getKind() == BuiltinType::BoundMember) { 13602 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13603 << OrigOp.get()->getSourceRange(); 13604 return QualType(); 13605 } 13606 13607 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13608 if (OrigOp.isInvalid()) return QualType(); 13609 } 13610 13611 if (OrigOp.get()->isTypeDependent()) 13612 return Context.DependentTy; 13613 13614 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13615 13616 // Make sure to ignore parentheses in subsequent checks 13617 Expr *op = OrigOp.get()->IgnoreParens(); 13618 13619 // In OpenCL captures for blocks called as lambda functions 13620 // are located in the private address space. Blocks used in 13621 // enqueue_kernel can be located in a different address space 13622 // depending on a vendor implementation. Thus preventing 13623 // taking an address of the capture to avoid invalid AS casts. 13624 if (LangOpts.OpenCL) { 13625 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13626 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13627 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13628 return QualType(); 13629 } 13630 } 13631 13632 if (getLangOpts().C99) { 13633 // Implement C99-only parts of addressof rules. 13634 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13635 if (uOp->getOpcode() == UO_Deref) 13636 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13637 // (assuming the deref expression is valid). 13638 return uOp->getSubExpr()->getType(); 13639 } 13640 // Technically, there should be a check for array subscript 13641 // expressions here, but the result of one is always an lvalue anyway. 13642 } 13643 ValueDecl *dcl = getPrimaryDecl(op); 13644 13645 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13646 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13647 op->getBeginLoc())) 13648 return QualType(); 13649 13650 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13651 unsigned AddressOfError = AO_No_Error; 13652 13653 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13654 bool sfinae = (bool)isSFINAEContext(); 13655 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13656 : diag::ext_typecheck_addrof_temporary) 13657 << op->getType() << op->getSourceRange(); 13658 if (sfinae) 13659 return QualType(); 13660 // Materialize the temporary as an lvalue so that we can take its address. 13661 OrigOp = op = 13662 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13663 } else if (isa<ObjCSelectorExpr>(op)) { 13664 return Context.getPointerType(op->getType()); 13665 } else if (lval == Expr::LV_MemberFunction) { 13666 // If it's an instance method, make a member pointer. 13667 // The expression must have exactly the form &A::foo. 13668 13669 // If the underlying expression isn't a decl ref, give up. 13670 if (!isa<DeclRefExpr>(op)) { 13671 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13672 << OrigOp.get()->getSourceRange(); 13673 return QualType(); 13674 } 13675 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13676 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13677 13678 // The id-expression was parenthesized. 13679 if (OrigOp.get() != DRE) { 13680 Diag(OpLoc, diag::err_parens_pointer_member_function) 13681 << OrigOp.get()->getSourceRange(); 13682 13683 // The method was named without a qualifier. 13684 } else if (!DRE->getQualifier()) { 13685 if (MD->getParent()->getName().empty()) 13686 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13687 << op->getSourceRange(); 13688 else { 13689 SmallString<32> Str; 13690 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13691 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13692 << op->getSourceRange() 13693 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13694 } 13695 } 13696 13697 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13698 if (isa<CXXDestructorDecl>(MD)) 13699 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13700 13701 QualType MPTy = Context.getMemberPointerType( 13702 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13703 // Under the MS ABI, lock down the inheritance model now. 13704 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13705 (void)isCompleteType(OpLoc, MPTy); 13706 return MPTy; 13707 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13708 // C99 6.5.3.2p1 13709 // The operand must be either an l-value or a function designator 13710 if (!op->getType()->isFunctionType()) { 13711 // Use a special diagnostic for loads from property references. 13712 if (isa<PseudoObjectExpr>(op)) { 13713 AddressOfError = AO_Property_Expansion; 13714 } else { 13715 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13716 << op->getType() << op->getSourceRange(); 13717 return QualType(); 13718 } 13719 } 13720 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13721 // The operand cannot be a bit-field 13722 AddressOfError = AO_Bit_Field; 13723 } else if (op->getObjectKind() == OK_VectorComponent) { 13724 // The operand cannot be an element of a vector 13725 AddressOfError = AO_Vector_Element; 13726 } else if (op->getObjectKind() == OK_MatrixComponent) { 13727 // The operand cannot be an element of a matrix. 13728 AddressOfError = AO_Matrix_Element; 13729 } else if (dcl) { // C99 6.5.3.2p1 13730 // We have an lvalue with a decl. Make sure the decl is not declared 13731 // with the register storage-class specifier. 13732 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13733 // in C++ it is not error to take address of a register 13734 // variable (c++03 7.1.1P3) 13735 if (vd->getStorageClass() == SC_Register && 13736 !getLangOpts().CPlusPlus) { 13737 AddressOfError = AO_Register_Variable; 13738 } 13739 } else if (isa<MSPropertyDecl>(dcl)) { 13740 AddressOfError = AO_Property_Expansion; 13741 } else if (isa<FunctionTemplateDecl>(dcl)) { 13742 return Context.OverloadTy; 13743 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13744 // Okay: we can take the address of a field. 13745 // Could be a pointer to member, though, if there is an explicit 13746 // scope qualifier for the class. 13747 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13748 DeclContext *Ctx = dcl->getDeclContext(); 13749 if (Ctx && Ctx->isRecord()) { 13750 if (dcl->getType()->isReferenceType()) { 13751 Diag(OpLoc, 13752 diag::err_cannot_form_pointer_to_member_of_reference_type) 13753 << dcl->getDeclName() << dcl->getType(); 13754 return QualType(); 13755 } 13756 13757 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13758 Ctx = Ctx->getParent(); 13759 13760 QualType MPTy = Context.getMemberPointerType( 13761 op->getType(), 13762 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13763 // Under the MS ABI, lock down the inheritance model now. 13764 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13765 (void)isCompleteType(OpLoc, MPTy); 13766 return MPTy; 13767 } 13768 } 13769 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13770 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13771 llvm_unreachable("Unknown/unexpected decl type"); 13772 } 13773 13774 if (AddressOfError != AO_No_Error) { 13775 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13776 return QualType(); 13777 } 13778 13779 if (lval == Expr::LV_IncompleteVoidType) { 13780 // Taking the address of a void variable is technically illegal, but we 13781 // allow it in cases which are otherwise valid. 13782 // Example: "extern void x; void* y = &x;". 13783 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13784 } 13785 13786 // If the operand has type "type", the result has type "pointer to type". 13787 if (op->getType()->isObjCObjectType()) 13788 return Context.getObjCObjectPointerType(op->getType()); 13789 13790 CheckAddressOfPackedMember(op); 13791 13792 return Context.getPointerType(op->getType()); 13793 } 13794 13795 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13796 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13797 if (!DRE) 13798 return; 13799 const Decl *D = DRE->getDecl(); 13800 if (!D) 13801 return; 13802 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13803 if (!Param) 13804 return; 13805 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13806 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13807 return; 13808 if (FunctionScopeInfo *FD = S.getCurFunction()) 13809 if (!FD->ModifiedNonNullParams.count(Param)) 13810 FD->ModifiedNonNullParams.insert(Param); 13811 } 13812 13813 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13814 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13815 SourceLocation OpLoc) { 13816 if (Op->isTypeDependent()) 13817 return S.Context.DependentTy; 13818 13819 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13820 if (ConvResult.isInvalid()) 13821 return QualType(); 13822 Op = ConvResult.get(); 13823 QualType OpTy = Op->getType(); 13824 QualType Result; 13825 13826 if (isa<CXXReinterpretCastExpr>(Op)) { 13827 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13828 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13829 Op->getSourceRange()); 13830 } 13831 13832 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13833 { 13834 Result = PT->getPointeeType(); 13835 } 13836 else if (const ObjCObjectPointerType *OPT = 13837 OpTy->getAs<ObjCObjectPointerType>()) 13838 Result = OPT->getPointeeType(); 13839 else { 13840 ExprResult PR = S.CheckPlaceholderExpr(Op); 13841 if (PR.isInvalid()) return QualType(); 13842 if (PR.get() != Op) 13843 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13844 } 13845 13846 if (Result.isNull()) { 13847 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13848 << OpTy << Op->getSourceRange(); 13849 return QualType(); 13850 } 13851 13852 // Note that per both C89 and C99, indirection is always legal, even if Result 13853 // is an incomplete type or void. It would be possible to warn about 13854 // dereferencing a void pointer, but it's completely well-defined, and such a 13855 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13856 // for pointers to 'void' but is fine for any other pointer type: 13857 // 13858 // C++ [expr.unary.op]p1: 13859 // [...] the expression to which [the unary * operator] is applied shall 13860 // be a pointer to an object type, or a pointer to a function type 13861 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13862 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13863 << OpTy << Op->getSourceRange(); 13864 13865 // Dereferences are usually l-values... 13866 VK = VK_LValue; 13867 13868 // ...except that certain expressions are never l-values in C. 13869 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13870 VK = VK_PRValue; 13871 13872 return Result; 13873 } 13874 13875 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13876 BinaryOperatorKind Opc; 13877 switch (Kind) { 13878 default: llvm_unreachable("Unknown binop!"); 13879 case tok::periodstar: Opc = BO_PtrMemD; break; 13880 case tok::arrowstar: Opc = BO_PtrMemI; break; 13881 case tok::star: Opc = BO_Mul; break; 13882 case tok::slash: Opc = BO_Div; break; 13883 case tok::percent: Opc = BO_Rem; break; 13884 case tok::plus: Opc = BO_Add; break; 13885 case tok::minus: Opc = BO_Sub; break; 13886 case tok::lessless: Opc = BO_Shl; break; 13887 case tok::greatergreater: Opc = BO_Shr; break; 13888 case tok::lessequal: Opc = BO_LE; break; 13889 case tok::less: Opc = BO_LT; break; 13890 case tok::greaterequal: Opc = BO_GE; break; 13891 case tok::greater: Opc = BO_GT; break; 13892 case tok::exclaimequal: Opc = BO_NE; break; 13893 case tok::equalequal: Opc = BO_EQ; break; 13894 case tok::spaceship: Opc = BO_Cmp; break; 13895 case tok::amp: Opc = BO_And; break; 13896 case tok::caret: Opc = BO_Xor; break; 13897 case tok::pipe: Opc = BO_Or; break; 13898 case tok::ampamp: Opc = BO_LAnd; break; 13899 case tok::pipepipe: Opc = BO_LOr; break; 13900 case tok::equal: Opc = BO_Assign; break; 13901 case tok::starequal: Opc = BO_MulAssign; break; 13902 case tok::slashequal: Opc = BO_DivAssign; break; 13903 case tok::percentequal: Opc = BO_RemAssign; break; 13904 case tok::plusequal: Opc = BO_AddAssign; break; 13905 case tok::minusequal: Opc = BO_SubAssign; break; 13906 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13907 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13908 case tok::ampequal: Opc = BO_AndAssign; break; 13909 case tok::caretequal: Opc = BO_XorAssign; break; 13910 case tok::pipeequal: Opc = BO_OrAssign; break; 13911 case tok::comma: Opc = BO_Comma; break; 13912 } 13913 return Opc; 13914 } 13915 13916 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13917 tok::TokenKind Kind) { 13918 UnaryOperatorKind Opc; 13919 switch (Kind) { 13920 default: llvm_unreachable("Unknown unary op!"); 13921 case tok::plusplus: Opc = UO_PreInc; break; 13922 case tok::minusminus: Opc = UO_PreDec; break; 13923 case tok::amp: Opc = UO_AddrOf; break; 13924 case tok::star: Opc = UO_Deref; break; 13925 case tok::plus: Opc = UO_Plus; break; 13926 case tok::minus: Opc = UO_Minus; break; 13927 case tok::tilde: Opc = UO_Not; break; 13928 case tok::exclaim: Opc = UO_LNot; break; 13929 case tok::kw___real: Opc = UO_Real; break; 13930 case tok::kw___imag: Opc = UO_Imag; break; 13931 case tok::kw___extension__: Opc = UO_Extension; break; 13932 } 13933 return Opc; 13934 } 13935 13936 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13937 /// This warning suppressed in the event of macro expansions. 13938 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13939 SourceLocation OpLoc, bool IsBuiltin) { 13940 if (S.inTemplateInstantiation()) 13941 return; 13942 if (S.isUnevaluatedContext()) 13943 return; 13944 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13945 return; 13946 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13947 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13948 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13949 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13950 if (!LHSDeclRef || !RHSDeclRef || 13951 LHSDeclRef->getLocation().isMacroID() || 13952 RHSDeclRef->getLocation().isMacroID()) 13953 return; 13954 const ValueDecl *LHSDecl = 13955 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13956 const ValueDecl *RHSDecl = 13957 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13958 if (LHSDecl != RHSDecl) 13959 return; 13960 if (LHSDecl->getType().isVolatileQualified()) 13961 return; 13962 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13963 if (RefTy->getPointeeType().isVolatileQualified()) 13964 return; 13965 13966 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13967 : diag::warn_self_assignment_overloaded) 13968 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13969 << RHSExpr->getSourceRange(); 13970 } 13971 13972 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13973 /// is usually indicative of introspection within the Objective-C pointer. 13974 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13975 SourceLocation OpLoc) { 13976 if (!S.getLangOpts().ObjC) 13977 return; 13978 13979 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13980 const Expr *LHS = L.get(); 13981 const Expr *RHS = R.get(); 13982 13983 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13984 ObjCPointerExpr = LHS; 13985 OtherExpr = RHS; 13986 } 13987 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13988 ObjCPointerExpr = RHS; 13989 OtherExpr = LHS; 13990 } 13991 13992 // This warning is deliberately made very specific to reduce false 13993 // positives with logic that uses '&' for hashing. This logic mainly 13994 // looks for code trying to introspect into tagged pointers, which 13995 // code should generally never do. 13996 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13997 unsigned Diag = diag::warn_objc_pointer_masking; 13998 // Determine if we are introspecting the result of performSelectorXXX. 13999 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 14000 // Special case messages to -performSelector and friends, which 14001 // can return non-pointer values boxed in a pointer value. 14002 // Some clients may wish to silence warnings in this subcase. 14003 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14004 Selector S = ME->getSelector(); 14005 StringRef SelArg0 = S.getNameForSlot(0); 14006 if (SelArg0.startswith("performSelector")) 14007 Diag = diag::warn_objc_pointer_masking_performSelector; 14008 } 14009 14010 S.Diag(OpLoc, Diag) 14011 << ObjCPointerExpr->getSourceRange(); 14012 } 14013 } 14014 14015 static NamedDecl *getDeclFromExpr(Expr *E) { 14016 if (!E) 14017 return nullptr; 14018 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14019 return DRE->getDecl(); 14020 if (auto *ME = dyn_cast<MemberExpr>(E)) 14021 return ME->getMemberDecl(); 14022 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14023 return IRE->getDecl(); 14024 return nullptr; 14025 } 14026 14027 // This helper function promotes a binary operator's operands (which are of a 14028 // half vector type) to a vector of floats and then truncates the result to 14029 // a vector of either half or short. 14030 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14031 BinaryOperatorKind Opc, QualType ResultTy, 14032 ExprValueKind VK, ExprObjectKind OK, 14033 bool IsCompAssign, SourceLocation OpLoc, 14034 FPOptionsOverride FPFeatures) { 14035 auto &Context = S.getASTContext(); 14036 assert((isVector(ResultTy, Context.HalfTy) || 14037 isVector(ResultTy, Context.ShortTy)) && 14038 "Result must be a vector of half or short"); 14039 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14040 isVector(RHS.get()->getType(), Context.HalfTy) && 14041 "both operands expected to be a half vector"); 14042 14043 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14044 QualType BinOpResTy = RHS.get()->getType(); 14045 14046 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14047 // change BinOpResTy to a vector of ints. 14048 if (isVector(ResultTy, Context.ShortTy)) 14049 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14050 14051 if (IsCompAssign) 14052 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14053 ResultTy, VK, OK, OpLoc, FPFeatures, 14054 BinOpResTy, BinOpResTy); 14055 14056 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14057 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14058 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14059 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14060 } 14061 14062 static std::pair<ExprResult, ExprResult> 14063 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14064 Expr *RHSExpr) { 14065 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14066 if (!S.Context.isDependenceAllowed()) { 14067 // C cannot handle TypoExpr nodes on either side of a binop because it 14068 // doesn't handle dependent types properly, so make sure any TypoExprs have 14069 // been dealt with before checking the operands. 14070 LHS = S.CorrectDelayedTyposInExpr(LHS); 14071 RHS = S.CorrectDelayedTyposInExpr( 14072 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14073 [Opc, LHS](Expr *E) { 14074 if (Opc != BO_Assign) 14075 return ExprResult(E); 14076 // Avoid correcting the RHS to the same Expr as the LHS. 14077 Decl *D = getDeclFromExpr(E); 14078 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14079 }); 14080 } 14081 return std::make_pair(LHS, RHS); 14082 } 14083 14084 /// Returns true if conversion between vectors of halfs and vectors of floats 14085 /// is needed. 14086 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14087 Expr *E0, Expr *E1 = nullptr) { 14088 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14089 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14090 return false; 14091 14092 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14093 QualType Ty = E->IgnoreImplicit()->getType(); 14094 14095 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14096 // to vectors of floats. Although the element type of the vectors is __fp16, 14097 // the vectors shouldn't be treated as storage-only types. See the 14098 // discussion here: https://reviews.llvm.org/rG825235c140e7 14099 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14100 if (VT->getVectorKind() == VectorType::NeonVector) 14101 return false; 14102 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14103 } 14104 return false; 14105 }; 14106 14107 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14108 } 14109 14110 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14111 /// operator @p Opc at location @c TokLoc. This routine only supports 14112 /// built-in operations; ActOnBinOp handles overloaded operators. 14113 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14114 BinaryOperatorKind Opc, 14115 Expr *LHSExpr, Expr *RHSExpr) { 14116 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14117 // The syntax only allows initializer lists on the RHS of assignment, 14118 // so we don't need to worry about accepting invalid code for 14119 // non-assignment operators. 14120 // C++11 5.17p9: 14121 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14122 // of x = {} is x = T(). 14123 InitializationKind Kind = InitializationKind::CreateDirectList( 14124 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14125 InitializedEntity Entity = 14126 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14127 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14128 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14129 if (Init.isInvalid()) 14130 return Init; 14131 RHSExpr = Init.get(); 14132 } 14133 14134 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14135 QualType ResultTy; // Result type of the binary operator. 14136 // The following two variables are used for compound assignment operators 14137 QualType CompLHSTy; // Type of LHS after promotions for computation 14138 QualType CompResultTy; // Type of computation result 14139 ExprValueKind VK = VK_PRValue; 14140 ExprObjectKind OK = OK_Ordinary; 14141 bool ConvertHalfVec = false; 14142 14143 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14144 if (!LHS.isUsable() || !RHS.isUsable()) 14145 return ExprError(); 14146 14147 if (getLangOpts().OpenCL) { 14148 QualType LHSTy = LHSExpr->getType(); 14149 QualType RHSTy = RHSExpr->getType(); 14150 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14151 // the ATOMIC_VAR_INIT macro. 14152 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14153 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14154 if (BO_Assign == Opc) 14155 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14156 else 14157 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14158 return ExprError(); 14159 } 14160 14161 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14162 // only with a builtin functions and therefore should be disallowed here. 14163 if (LHSTy->isImageType() || RHSTy->isImageType() || 14164 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14165 LHSTy->isPipeType() || RHSTy->isPipeType() || 14166 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14167 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14168 return ExprError(); 14169 } 14170 } 14171 14172 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14173 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14174 14175 switch (Opc) { 14176 case BO_Assign: 14177 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14178 if (getLangOpts().CPlusPlus && 14179 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14180 VK = LHS.get()->getValueKind(); 14181 OK = LHS.get()->getObjectKind(); 14182 } 14183 if (!ResultTy.isNull()) { 14184 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14185 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14186 14187 // Avoid copying a block to the heap if the block is assigned to a local 14188 // auto variable that is declared in the same scope as the block. This 14189 // optimization is unsafe if the local variable is declared in an outer 14190 // scope. For example: 14191 // 14192 // BlockTy b; 14193 // { 14194 // b = ^{...}; 14195 // } 14196 // // It is unsafe to invoke the block here if it wasn't copied to the 14197 // // heap. 14198 // b(); 14199 14200 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14201 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14202 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14203 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14204 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14205 14206 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14207 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14208 NTCUC_Assignment, NTCUK_Copy); 14209 } 14210 RecordModifiableNonNullParam(*this, LHS.get()); 14211 break; 14212 case BO_PtrMemD: 14213 case BO_PtrMemI: 14214 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14215 Opc == BO_PtrMemI); 14216 break; 14217 case BO_Mul: 14218 case BO_Div: 14219 ConvertHalfVec = true; 14220 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14221 Opc == BO_Div); 14222 break; 14223 case BO_Rem: 14224 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14225 break; 14226 case BO_Add: 14227 ConvertHalfVec = true; 14228 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14229 break; 14230 case BO_Sub: 14231 ConvertHalfVec = true; 14232 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14233 break; 14234 case BO_Shl: 14235 case BO_Shr: 14236 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14237 break; 14238 case BO_LE: 14239 case BO_LT: 14240 case BO_GE: 14241 case BO_GT: 14242 ConvertHalfVec = true; 14243 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14244 break; 14245 case BO_EQ: 14246 case BO_NE: 14247 ConvertHalfVec = true; 14248 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14249 break; 14250 case BO_Cmp: 14251 ConvertHalfVec = true; 14252 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14253 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14254 break; 14255 case BO_And: 14256 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14257 LLVM_FALLTHROUGH; 14258 case BO_Xor: 14259 case BO_Or: 14260 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14261 break; 14262 case BO_LAnd: 14263 case BO_LOr: 14264 ConvertHalfVec = true; 14265 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14266 break; 14267 case BO_MulAssign: 14268 case BO_DivAssign: 14269 ConvertHalfVec = true; 14270 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14271 Opc == BO_DivAssign); 14272 CompLHSTy = CompResultTy; 14273 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14274 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14275 break; 14276 case BO_RemAssign: 14277 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14278 CompLHSTy = CompResultTy; 14279 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14280 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14281 break; 14282 case BO_AddAssign: 14283 ConvertHalfVec = true; 14284 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14285 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14286 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14287 break; 14288 case BO_SubAssign: 14289 ConvertHalfVec = true; 14290 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14291 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14292 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14293 break; 14294 case BO_ShlAssign: 14295 case BO_ShrAssign: 14296 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14297 CompLHSTy = CompResultTy; 14298 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14299 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14300 break; 14301 case BO_AndAssign: 14302 case BO_OrAssign: // fallthrough 14303 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14304 LLVM_FALLTHROUGH; 14305 case BO_XorAssign: 14306 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14307 CompLHSTy = CompResultTy; 14308 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14309 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14310 break; 14311 case BO_Comma: 14312 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14313 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14314 VK = RHS.get()->getValueKind(); 14315 OK = RHS.get()->getObjectKind(); 14316 } 14317 break; 14318 } 14319 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14320 return ExprError(); 14321 14322 // Some of the binary operations require promoting operands of half vector to 14323 // float vectors and truncating the result back to half vector. For now, we do 14324 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14325 // arm64). 14326 assert( 14327 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14328 isVector(LHS.get()->getType(), Context.HalfTy)) && 14329 "both sides are half vectors or neither sides are"); 14330 ConvertHalfVec = 14331 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14332 14333 // Check for array bounds violations for both sides of the BinaryOperator 14334 CheckArrayAccess(LHS.get()); 14335 CheckArrayAccess(RHS.get()); 14336 14337 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14338 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14339 &Context.Idents.get("object_setClass"), 14340 SourceLocation(), LookupOrdinaryName); 14341 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14342 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14343 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14344 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14345 "object_setClass(") 14346 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14347 ",") 14348 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14349 } 14350 else 14351 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14352 } 14353 else if (const ObjCIvarRefExpr *OIRE = 14354 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14355 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14356 14357 // Opc is not a compound assignment if CompResultTy is null. 14358 if (CompResultTy.isNull()) { 14359 if (ConvertHalfVec) 14360 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14361 OpLoc, CurFPFeatureOverrides()); 14362 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14363 VK, OK, OpLoc, CurFPFeatureOverrides()); 14364 } 14365 14366 // Handle compound assignments. 14367 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14368 OK_ObjCProperty) { 14369 VK = VK_LValue; 14370 OK = LHS.get()->getObjectKind(); 14371 } 14372 14373 // The LHS is not converted to the result type for fixed-point compound 14374 // assignment as the common type is computed on demand. Reset the CompLHSTy 14375 // to the LHS type we would have gotten after unary conversions. 14376 if (CompResultTy->isFixedPointType()) 14377 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14378 14379 if (ConvertHalfVec) 14380 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14381 OpLoc, CurFPFeatureOverrides()); 14382 14383 return CompoundAssignOperator::Create( 14384 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14385 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14386 } 14387 14388 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14389 /// operators are mixed in a way that suggests that the programmer forgot that 14390 /// comparison operators have higher precedence. The most typical example of 14391 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14392 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14393 SourceLocation OpLoc, Expr *LHSExpr, 14394 Expr *RHSExpr) { 14395 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14396 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14397 14398 // Check that one of the sides is a comparison operator and the other isn't. 14399 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14400 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14401 if (isLeftComp == isRightComp) 14402 return; 14403 14404 // Bitwise operations are sometimes used as eager logical ops. 14405 // Don't diagnose this. 14406 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14407 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14408 if (isLeftBitwise || isRightBitwise) 14409 return; 14410 14411 SourceRange DiagRange = isLeftComp 14412 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14413 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14414 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14415 SourceRange ParensRange = 14416 isLeftComp 14417 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14418 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14419 14420 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14421 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14422 SuggestParentheses(Self, OpLoc, 14423 Self.PDiag(diag::note_precedence_silence) << OpStr, 14424 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14425 SuggestParentheses(Self, OpLoc, 14426 Self.PDiag(diag::note_precedence_bitwise_first) 14427 << BinaryOperator::getOpcodeStr(Opc), 14428 ParensRange); 14429 } 14430 14431 /// It accepts a '&&' expr that is inside a '||' one. 14432 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14433 /// in parentheses. 14434 static void 14435 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14436 BinaryOperator *Bop) { 14437 assert(Bop->getOpcode() == BO_LAnd); 14438 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14439 << Bop->getSourceRange() << OpLoc; 14440 SuggestParentheses(Self, Bop->getOperatorLoc(), 14441 Self.PDiag(diag::note_precedence_silence) 14442 << Bop->getOpcodeStr(), 14443 Bop->getSourceRange()); 14444 } 14445 14446 /// Returns true if the given expression can be evaluated as a constant 14447 /// 'true'. 14448 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14449 bool Res; 14450 return !E->isValueDependent() && 14451 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14452 } 14453 14454 /// Returns true if the given expression can be evaluated as a constant 14455 /// 'false'. 14456 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14457 bool Res; 14458 return !E->isValueDependent() && 14459 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14460 } 14461 14462 /// Look for '&&' in the left hand of a '||' expr. 14463 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14464 Expr *LHSExpr, Expr *RHSExpr) { 14465 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14466 if (Bop->getOpcode() == BO_LAnd) { 14467 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14468 if (EvaluatesAsFalse(S, RHSExpr)) 14469 return; 14470 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14471 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14472 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14473 } else if (Bop->getOpcode() == BO_LOr) { 14474 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14475 // If it's "a || b && 1 || c" we didn't warn earlier for 14476 // "a || b && 1", but warn now. 14477 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14478 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14479 } 14480 } 14481 } 14482 } 14483 14484 /// Look for '&&' in the right hand of a '||' expr. 14485 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14486 Expr *LHSExpr, Expr *RHSExpr) { 14487 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14488 if (Bop->getOpcode() == BO_LAnd) { 14489 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14490 if (EvaluatesAsFalse(S, LHSExpr)) 14491 return; 14492 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14493 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14494 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14495 } 14496 } 14497 } 14498 14499 /// Look for bitwise op in the left or right hand of a bitwise op with 14500 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14501 /// the '&' expression in parentheses. 14502 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14503 SourceLocation OpLoc, Expr *SubExpr) { 14504 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14505 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14506 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14507 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14508 << Bop->getSourceRange() << OpLoc; 14509 SuggestParentheses(S, Bop->getOperatorLoc(), 14510 S.PDiag(diag::note_precedence_silence) 14511 << Bop->getOpcodeStr(), 14512 Bop->getSourceRange()); 14513 } 14514 } 14515 } 14516 14517 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14518 Expr *SubExpr, StringRef Shift) { 14519 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14520 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14521 StringRef Op = Bop->getOpcodeStr(); 14522 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14523 << Bop->getSourceRange() << OpLoc << Shift << Op; 14524 SuggestParentheses(S, Bop->getOperatorLoc(), 14525 S.PDiag(diag::note_precedence_silence) << Op, 14526 Bop->getSourceRange()); 14527 } 14528 } 14529 } 14530 14531 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14532 Expr *LHSExpr, Expr *RHSExpr) { 14533 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14534 if (!OCE) 14535 return; 14536 14537 FunctionDecl *FD = OCE->getDirectCallee(); 14538 if (!FD || !FD->isOverloadedOperator()) 14539 return; 14540 14541 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14542 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14543 return; 14544 14545 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14546 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14547 << (Kind == OO_LessLess); 14548 SuggestParentheses(S, OCE->getOperatorLoc(), 14549 S.PDiag(diag::note_precedence_silence) 14550 << (Kind == OO_LessLess ? "<<" : ">>"), 14551 OCE->getSourceRange()); 14552 SuggestParentheses( 14553 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14554 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14555 } 14556 14557 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14558 /// precedence. 14559 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14560 SourceLocation OpLoc, Expr *LHSExpr, 14561 Expr *RHSExpr){ 14562 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14563 if (BinaryOperator::isBitwiseOp(Opc)) 14564 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14565 14566 // Diagnose "arg1 & arg2 | arg3" 14567 if ((Opc == BO_Or || Opc == BO_Xor) && 14568 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14569 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14570 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14571 } 14572 14573 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14574 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14575 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14576 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14577 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14578 } 14579 14580 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14581 || Opc == BO_Shr) { 14582 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14583 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14584 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14585 } 14586 14587 // Warn on overloaded shift operators and comparisons, such as: 14588 // cout << 5 == 4; 14589 if (BinaryOperator::isComparisonOp(Opc)) 14590 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14591 } 14592 14593 // Binary Operators. 'Tok' is the token for the operator. 14594 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14595 tok::TokenKind Kind, 14596 Expr *LHSExpr, Expr *RHSExpr) { 14597 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14598 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14599 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14600 14601 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14602 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14603 14604 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14605 } 14606 14607 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14608 UnresolvedSetImpl &Functions) { 14609 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14610 if (OverOp != OO_None && OverOp != OO_Equal) 14611 LookupOverloadedOperatorName(OverOp, S, Functions); 14612 14613 // In C++20 onwards, we may have a second operator to look up. 14614 if (getLangOpts().CPlusPlus20) { 14615 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14616 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14617 } 14618 } 14619 14620 /// Build an overloaded binary operator expression in the given scope. 14621 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14622 BinaryOperatorKind Opc, 14623 Expr *LHS, Expr *RHS) { 14624 switch (Opc) { 14625 case BO_Assign: 14626 case BO_DivAssign: 14627 case BO_RemAssign: 14628 case BO_SubAssign: 14629 case BO_AndAssign: 14630 case BO_OrAssign: 14631 case BO_XorAssign: 14632 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14633 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14634 break; 14635 default: 14636 break; 14637 } 14638 14639 // Find all of the overloaded operators visible from this point. 14640 UnresolvedSet<16> Functions; 14641 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14642 14643 // Build the (potentially-overloaded, potentially-dependent) 14644 // binary operation. 14645 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14646 } 14647 14648 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14649 BinaryOperatorKind Opc, 14650 Expr *LHSExpr, Expr *RHSExpr) { 14651 ExprResult LHS, RHS; 14652 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14653 if (!LHS.isUsable() || !RHS.isUsable()) 14654 return ExprError(); 14655 LHSExpr = LHS.get(); 14656 RHSExpr = RHS.get(); 14657 14658 // We want to end up calling one of checkPseudoObjectAssignment 14659 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14660 // both expressions are overloadable or either is type-dependent), 14661 // or CreateBuiltinBinOp (in any other case). We also want to get 14662 // any placeholder types out of the way. 14663 14664 // Handle pseudo-objects in the LHS. 14665 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14666 // Assignments with a pseudo-object l-value need special analysis. 14667 if (pty->getKind() == BuiltinType::PseudoObject && 14668 BinaryOperator::isAssignmentOp(Opc)) 14669 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14670 14671 // Don't resolve overloads if the other type is overloadable. 14672 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14673 // We can't actually test that if we still have a placeholder, 14674 // though. Fortunately, none of the exceptions we see in that 14675 // code below are valid when the LHS is an overload set. Note 14676 // that an overload set can be dependently-typed, but it never 14677 // instantiates to having an overloadable type. 14678 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14679 if (resolvedRHS.isInvalid()) return ExprError(); 14680 RHSExpr = resolvedRHS.get(); 14681 14682 if (RHSExpr->isTypeDependent() || 14683 RHSExpr->getType()->isOverloadableType()) 14684 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14685 } 14686 14687 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14688 // template, diagnose the missing 'template' keyword instead of diagnosing 14689 // an invalid use of a bound member function. 14690 // 14691 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14692 // to C++1z [over.over]/1.4, but we already checked for that case above. 14693 if (Opc == BO_LT && inTemplateInstantiation() && 14694 (pty->getKind() == BuiltinType::BoundMember || 14695 pty->getKind() == BuiltinType::Overload)) { 14696 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14697 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14698 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14699 return isa<FunctionTemplateDecl>(ND); 14700 })) { 14701 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14702 : OE->getNameLoc(), 14703 diag::err_template_kw_missing) 14704 << OE->getName().getAsString() << ""; 14705 return ExprError(); 14706 } 14707 } 14708 14709 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14710 if (LHS.isInvalid()) return ExprError(); 14711 LHSExpr = LHS.get(); 14712 } 14713 14714 // Handle pseudo-objects in the RHS. 14715 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14716 // An overload in the RHS can potentially be resolved by the type 14717 // being assigned to. 14718 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14719 if (getLangOpts().CPlusPlus && 14720 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14721 LHSExpr->getType()->isOverloadableType())) 14722 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14723 14724 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14725 } 14726 14727 // Don't resolve overloads if the other type is overloadable. 14728 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14729 LHSExpr->getType()->isOverloadableType()) 14730 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14731 14732 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14733 if (!resolvedRHS.isUsable()) return ExprError(); 14734 RHSExpr = resolvedRHS.get(); 14735 } 14736 14737 if (getLangOpts().CPlusPlus) { 14738 // If either expression is type-dependent, always build an 14739 // overloaded op. 14740 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14741 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14742 14743 // Otherwise, build an overloaded op if either expression has an 14744 // overloadable type. 14745 if (LHSExpr->getType()->isOverloadableType() || 14746 RHSExpr->getType()->isOverloadableType()) 14747 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14748 } 14749 14750 if (getLangOpts().RecoveryAST && 14751 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14752 assert(!getLangOpts().CPlusPlus); 14753 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14754 "Should only occur in error-recovery path."); 14755 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14756 // C [6.15.16] p3: 14757 // An assignment expression has the value of the left operand after the 14758 // assignment, but is not an lvalue. 14759 return CompoundAssignOperator::Create( 14760 Context, LHSExpr, RHSExpr, Opc, 14761 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14762 OpLoc, CurFPFeatureOverrides()); 14763 QualType ResultType; 14764 switch (Opc) { 14765 case BO_Assign: 14766 ResultType = LHSExpr->getType().getUnqualifiedType(); 14767 break; 14768 case BO_LT: 14769 case BO_GT: 14770 case BO_LE: 14771 case BO_GE: 14772 case BO_EQ: 14773 case BO_NE: 14774 case BO_LAnd: 14775 case BO_LOr: 14776 // These operators have a fixed result type regardless of operands. 14777 ResultType = Context.IntTy; 14778 break; 14779 case BO_Comma: 14780 ResultType = RHSExpr->getType(); 14781 break; 14782 default: 14783 ResultType = Context.DependentTy; 14784 break; 14785 } 14786 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14787 VK_PRValue, OK_Ordinary, OpLoc, 14788 CurFPFeatureOverrides()); 14789 } 14790 14791 // Build a built-in binary operation. 14792 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14793 } 14794 14795 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14796 if (T.isNull() || T->isDependentType()) 14797 return false; 14798 14799 if (!T->isPromotableIntegerType()) 14800 return true; 14801 14802 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14803 } 14804 14805 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14806 UnaryOperatorKind Opc, 14807 Expr *InputExpr) { 14808 ExprResult Input = InputExpr; 14809 ExprValueKind VK = VK_PRValue; 14810 ExprObjectKind OK = OK_Ordinary; 14811 QualType resultType; 14812 bool CanOverflow = false; 14813 14814 bool ConvertHalfVec = false; 14815 if (getLangOpts().OpenCL) { 14816 QualType Ty = InputExpr->getType(); 14817 // The only legal unary operation for atomics is '&'. 14818 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14819 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14820 // only with a builtin functions and therefore should be disallowed here. 14821 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14822 || Ty->isBlockPointerType())) { 14823 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14824 << InputExpr->getType() 14825 << Input.get()->getSourceRange()); 14826 } 14827 } 14828 14829 switch (Opc) { 14830 case UO_PreInc: 14831 case UO_PreDec: 14832 case UO_PostInc: 14833 case UO_PostDec: 14834 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14835 OpLoc, 14836 Opc == UO_PreInc || 14837 Opc == UO_PostInc, 14838 Opc == UO_PreInc || 14839 Opc == UO_PreDec); 14840 CanOverflow = isOverflowingIntegerType(Context, resultType); 14841 break; 14842 case UO_AddrOf: 14843 resultType = CheckAddressOfOperand(Input, OpLoc); 14844 CheckAddressOfNoDeref(InputExpr); 14845 RecordModifiableNonNullParam(*this, InputExpr); 14846 break; 14847 case UO_Deref: { 14848 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14849 if (Input.isInvalid()) return ExprError(); 14850 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14851 break; 14852 } 14853 case UO_Plus: 14854 case UO_Minus: 14855 CanOverflow = Opc == UO_Minus && 14856 isOverflowingIntegerType(Context, Input.get()->getType()); 14857 Input = UsualUnaryConversions(Input.get()); 14858 if (Input.isInvalid()) return ExprError(); 14859 // Unary plus and minus require promoting an operand of half vector to a 14860 // float vector and truncating the result back to a half vector. For now, we 14861 // do this only when HalfArgsAndReturns is set (that is, when the target is 14862 // arm or arm64). 14863 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14864 14865 // If the operand is a half vector, promote it to a float vector. 14866 if (ConvertHalfVec) 14867 Input = convertVector(Input.get(), Context.FloatTy, *this); 14868 resultType = Input.get()->getType(); 14869 if (resultType->isDependentType()) 14870 break; 14871 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14872 break; 14873 else if (resultType->isVectorType() && 14874 // The z vector extensions don't allow + or - with bool vectors. 14875 (!Context.getLangOpts().ZVector || 14876 resultType->castAs<VectorType>()->getVectorKind() != 14877 VectorType::AltiVecBool)) 14878 break; 14879 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14880 Opc == UO_Plus && 14881 resultType->isPointerType()) 14882 break; 14883 14884 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14885 << resultType << Input.get()->getSourceRange()); 14886 14887 case UO_Not: // bitwise complement 14888 Input = UsualUnaryConversions(Input.get()); 14889 if (Input.isInvalid()) 14890 return ExprError(); 14891 resultType = Input.get()->getType(); 14892 if (resultType->isDependentType()) 14893 break; 14894 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14895 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14896 // C99 does not support '~' for complex conjugation. 14897 Diag(OpLoc, diag::ext_integer_complement_complex) 14898 << resultType << Input.get()->getSourceRange(); 14899 else if (resultType->hasIntegerRepresentation()) 14900 break; 14901 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14902 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14903 // on vector float types. 14904 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14905 if (!T->isIntegerType()) 14906 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14907 << resultType << Input.get()->getSourceRange()); 14908 } else { 14909 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14910 << resultType << Input.get()->getSourceRange()); 14911 } 14912 break; 14913 14914 case UO_LNot: // logical negation 14915 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14916 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14917 if (Input.isInvalid()) return ExprError(); 14918 resultType = Input.get()->getType(); 14919 14920 // Though we still have to promote half FP to float... 14921 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14922 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14923 resultType = Context.FloatTy; 14924 } 14925 14926 if (resultType->isDependentType()) 14927 break; 14928 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14929 // C99 6.5.3.3p1: ok, fallthrough; 14930 if (Context.getLangOpts().CPlusPlus) { 14931 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14932 // operand contextually converted to bool. 14933 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14934 ScalarTypeToBooleanCastKind(resultType)); 14935 } else if (Context.getLangOpts().OpenCL && 14936 Context.getLangOpts().OpenCLVersion < 120) { 14937 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14938 // operate on scalar float types. 14939 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14940 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14941 << resultType << Input.get()->getSourceRange()); 14942 } 14943 } else if (resultType->isExtVectorType()) { 14944 if (Context.getLangOpts().OpenCL && 14945 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 14946 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14947 // operate on vector float types. 14948 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14949 if (!T->isIntegerType()) 14950 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14951 << resultType << Input.get()->getSourceRange()); 14952 } 14953 // Vector logical not returns the signed variant of the operand type. 14954 resultType = GetSignedVectorType(resultType); 14955 break; 14956 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14957 const VectorType *VTy = resultType->castAs<VectorType>(); 14958 if (VTy->getVectorKind() != VectorType::GenericVector) 14959 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14960 << resultType << Input.get()->getSourceRange()); 14961 14962 // Vector logical not returns the signed variant of the operand type. 14963 resultType = GetSignedVectorType(resultType); 14964 break; 14965 } else { 14966 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14967 << resultType << Input.get()->getSourceRange()); 14968 } 14969 14970 // LNot always has type int. C99 6.5.3.3p5. 14971 // In C++, it's bool. C++ 5.3.1p8 14972 resultType = Context.getLogicalOperationType(); 14973 break; 14974 case UO_Real: 14975 case UO_Imag: 14976 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14977 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14978 // complex l-values to ordinary l-values and all other values to r-values. 14979 if (Input.isInvalid()) return ExprError(); 14980 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14981 if (Input.get()->isGLValue() && 14982 Input.get()->getObjectKind() == OK_Ordinary) 14983 VK = Input.get()->getValueKind(); 14984 } else if (!getLangOpts().CPlusPlus) { 14985 // In C, a volatile scalar is read by __imag. In C++, it is not. 14986 Input = DefaultLvalueConversion(Input.get()); 14987 } 14988 break; 14989 case UO_Extension: 14990 resultType = Input.get()->getType(); 14991 VK = Input.get()->getValueKind(); 14992 OK = Input.get()->getObjectKind(); 14993 break; 14994 case UO_Coawait: 14995 // It's unnecessary to represent the pass-through operator co_await in the 14996 // AST; just return the input expression instead. 14997 assert(!Input.get()->getType()->isDependentType() && 14998 "the co_await expression must be non-dependant before " 14999 "building operator co_await"); 15000 return Input; 15001 } 15002 if (resultType.isNull() || Input.isInvalid()) 15003 return ExprError(); 15004 15005 // Check for array bounds violations in the operand of the UnaryOperator, 15006 // except for the '*' and '&' operators that have to be handled specially 15007 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15008 // that are explicitly defined as valid by the standard). 15009 if (Opc != UO_AddrOf && Opc != UO_Deref) 15010 CheckArrayAccess(Input.get()); 15011 15012 auto *UO = 15013 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15014 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15015 15016 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15017 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15018 !isUnevaluatedContext()) 15019 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15020 15021 // Convert the result back to a half vector. 15022 if (ConvertHalfVec) 15023 return convertVector(UO, Context.HalfTy, *this); 15024 return UO; 15025 } 15026 15027 /// Determine whether the given expression is a qualified member 15028 /// access expression, of a form that could be turned into a pointer to member 15029 /// with the address-of operator. 15030 bool Sema::isQualifiedMemberAccess(Expr *E) { 15031 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15032 if (!DRE->getQualifier()) 15033 return false; 15034 15035 ValueDecl *VD = DRE->getDecl(); 15036 if (!VD->isCXXClassMember()) 15037 return false; 15038 15039 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15040 return true; 15041 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15042 return Method->isInstance(); 15043 15044 return false; 15045 } 15046 15047 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15048 if (!ULE->getQualifier()) 15049 return false; 15050 15051 for (NamedDecl *D : ULE->decls()) { 15052 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15053 if (Method->isInstance()) 15054 return true; 15055 } else { 15056 // Overload set does not contain methods. 15057 break; 15058 } 15059 } 15060 15061 return false; 15062 } 15063 15064 return false; 15065 } 15066 15067 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15068 UnaryOperatorKind Opc, Expr *Input) { 15069 // First things first: handle placeholders so that the 15070 // overloaded-operator check considers the right type. 15071 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15072 // Increment and decrement of pseudo-object references. 15073 if (pty->getKind() == BuiltinType::PseudoObject && 15074 UnaryOperator::isIncrementDecrementOp(Opc)) 15075 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15076 15077 // extension is always a builtin operator. 15078 if (Opc == UO_Extension) 15079 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15080 15081 // & gets special logic for several kinds of placeholder. 15082 // The builtin code knows what to do. 15083 if (Opc == UO_AddrOf && 15084 (pty->getKind() == BuiltinType::Overload || 15085 pty->getKind() == BuiltinType::UnknownAny || 15086 pty->getKind() == BuiltinType::BoundMember)) 15087 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15088 15089 // Anything else needs to be handled now. 15090 ExprResult Result = CheckPlaceholderExpr(Input); 15091 if (Result.isInvalid()) return ExprError(); 15092 Input = Result.get(); 15093 } 15094 15095 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15096 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15097 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15098 // Find all of the overloaded operators visible from this point. 15099 UnresolvedSet<16> Functions; 15100 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15101 if (S && OverOp != OO_None) 15102 LookupOverloadedOperatorName(OverOp, S, Functions); 15103 15104 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15105 } 15106 15107 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15108 } 15109 15110 // Unary Operators. 'Tok' is the token for the operator. 15111 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15112 tok::TokenKind Op, Expr *Input) { 15113 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15114 } 15115 15116 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15117 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15118 LabelDecl *TheDecl) { 15119 TheDecl->markUsed(Context); 15120 // Create the AST node. The address of a label always has type 'void*'. 15121 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15122 Context.getPointerType(Context.VoidTy)); 15123 } 15124 15125 void Sema::ActOnStartStmtExpr() { 15126 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15127 } 15128 15129 void Sema::ActOnStmtExprError() { 15130 // Note that function is also called by TreeTransform when leaving a 15131 // StmtExpr scope without rebuilding anything. 15132 15133 DiscardCleanupsInEvaluationContext(); 15134 PopExpressionEvaluationContext(); 15135 } 15136 15137 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15138 SourceLocation RPLoc) { 15139 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15140 } 15141 15142 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15143 SourceLocation RPLoc, unsigned TemplateDepth) { 15144 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15145 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15146 15147 if (hasAnyUnrecoverableErrorsInThisFunction()) 15148 DiscardCleanupsInEvaluationContext(); 15149 assert(!Cleanup.exprNeedsCleanups() && 15150 "cleanups within StmtExpr not correctly bound!"); 15151 PopExpressionEvaluationContext(); 15152 15153 // FIXME: there are a variety of strange constraints to enforce here, for 15154 // example, it is not possible to goto into a stmt expression apparently. 15155 // More semantic analysis is needed. 15156 15157 // If there are sub-stmts in the compound stmt, take the type of the last one 15158 // as the type of the stmtexpr. 15159 QualType Ty = Context.VoidTy; 15160 bool StmtExprMayBindToTemp = false; 15161 if (!Compound->body_empty()) { 15162 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15163 if (const auto *LastStmt = 15164 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15165 if (const Expr *Value = LastStmt->getExprStmt()) { 15166 StmtExprMayBindToTemp = true; 15167 Ty = Value->getType(); 15168 } 15169 } 15170 } 15171 15172 // FIXME: Check that expression type is complete/non-abstract; statement 15173 // expressions are not lvalues. 15174 Expr *ResStmtExpr = 15175 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15176 if (StmtExprMayBindToTemp) 15177 return MaybeBindToTemporary(ResStmtExpr); 15178 return ResStmtExpr; 15179 } 15180 15181 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15182 if (ER.isInvalid()) 15183 return ExprError(); 15184 15185 // Do function/array conversion on the last expression, but not 15186 // lvalue-to-rvalue. However, initialize an unqualified type. 15187 ER = DefaultFunctionArrayConversion(ER.get()); 15188 if (ER.isInvalid()) 15189 return ExprError(); 15190 Expr *E = ER.get(); 15191 15192 if (E->isTypeDependent()) 15193 return E; 15194 15195 // In ARC, if the final expression ends in a consume, splice 15196 // the consume out and bind it later. In the alternate case 15197 // (when dealing with a retainable type), the result 15198 // initialization will create a produce. In both cases the 15199 // result will be +1, and we'll need to balance that out with 15200 // a bind. 15201 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15202 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15203 return Cast->getSubExpr(); 15204 15205 // FIXME: Provide a better location for the initialization. 15206 return PerformCopyInitialization( 15207 InitializedEntity::InitializeStmtExprResult( 15208 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15209 SourceLocation(), E); 15210 } 15211 15212 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15213 TypeSourceInfo *TInfo, 15214 ArrayRef<OffsetOfComponent> Components, 15215 SourceLocation RParenLoc) { 15216 QualType ArgTy = TInfo->getType(); 15217 bool Dependent = ArgTy->isDependentType(); 15218 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15219 15220 // We must have at least one component that refers to the type, and the first 15221 // one is known to be a field designator. Verify that the ArgTy represents 15222 // a struct/union/class. 15223 if (!Dependent && !ArgTy->isRecordType()) 15224 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15225 << ArgTy << TypeRange); 15226 15227 // Type must be complete per C99 7.17p3 because a declaring a variable 15228 // with an incomplete type would be ill-formed. 15229 if (!Dependent 15230 && RequireCompleteType(BuiltinLoc, ArgTy, 15231 diag::err_offsetof_incomplete_type, TypeRange)) 15232 return ExprError(); 15233 15234 bool DidWarnAboutNonPOD = false; 15235 QualType CurrentType = ArgTy; 15236 SmallVector<OffsetOfNode, 4> Comps; 15237 SmallVector<Expr*, 4> Exprs; 15238 for (const OffsetOfComponent &OC : Components) { 15239 if (OC.isBrackets) { 15240 // Offset of an array sub-field. TODO: Should we allow vector elements? 15241 if (!CurrentType->isDependentType()) { 15242 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15243 if(!AT) 15244 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15245 << CurrentType); 15246 CurrentType = AT->getElementType(); 15247 } else 15248 CurrentType = Context.DependentTy; 15249 15250 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15251 if (IdxRval.isInvalid()) 15252 return ExprError(); 15253 Expr *Idx = IdxRval.get(); 15254 15255 // The expression must be an integral expression. 15256 // FIXME: An integral constant expression? 15257 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15258 !Idx->getType()->isIntegerType()) 15259 return ExprError( 15260 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15261 << Idx->getSourceRange()); 15262 15263 // Record this array index. 15264 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15265 Exprs.push_back(Idx); 15266 continue; 15267 } 15268 15269 // Offset of a field. 15270 if (CurrentType->isDependentType()) { 15271 // We have the offset of a field, but we can't look into the dependent 15272 // type. Just record the identifier of the field. 15273 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15274 CurrentType = Context.DependentTy; 15275 continue; 15276 } 15277 15278 // We need to have a complete type to look into. 15279 if (RequireCompleteType(OC.LocStart, CurrentType, 15280 diag::err_offsetof_incomplete_type)) 15281 return ExprError(); 15282 15283 // Look for the designated field. 15284 const RecordType *RC = CurrentType->getAs<RecordType>(); 15285 if (!RC) 15286 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15287 << CurrentType); 15288 RecordDecl *RD = RC->getDecl(); 15289 15290 // C++ [lib.support.types]p5: 15291 // The macro offsetof accepts a restricted set of type arguments in this 15292 // International Standard. type shall be a POD structure or a POD union 15293 // (clause 9). 15294 // C++11 [support.types]p4: 15295 // If type is not a standard-layout class (Clause 9), the results are 15296 // undefined. 15297 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15298 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15299 unsigned DiagID = 15300 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15301 : diag::ext_offsetof_non_pod_type; 15302 15303 if (!IsSafe && !DidWarnAboutNonPOD && 15304 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15305 PDiag(DiagID) 15306 << SourceRange(Components[0].LocStart, OC.LocEnd) 15307 << CurrentType)) 15308 DidWarnAboutNonPOD = true; 15309 } 15310 15311 // Look for the field. 15312 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15313 LookupQualifiedName(R, RD); 15314 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15315 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15316 if (!MemberDecl) { 15317 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15318 MemberDecl = IndirectMemberDecl->getAnonField(); 15319 } 15320 15321 if (!MemberDecl) 15322 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15323 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15324 OC.LocEnd)); 15325 15326 // C99 7.17p3: 15327 // (If the specified member is a bit-field, the behavior is undefined.) 15328 // 15329 // We diagnose this as an error. 15330 if (MemberDecl->isBitField()) { 15331 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15332 << MemberDecl->getDeclName() 15333 << SourceRange(BuiltinLoc, RParenLoc); 15334 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15335 return ExprError(); 15336 } 15337 15338 RecordDecl *Parent = MemberDecl->getParent(); 15339 if (IndirectMemberDecl) 15340 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15341 15342 // If the member was found in a base class, introduce OffsetOfNodes for 15343 // the base class indirections. 15344 CXXBasePaths Paths; 15345 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15346 Paths)) { 15347 if (Paths.getDetectedVirtual()) { 15348 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15349 << MemberDecl->getDeclName() 15350 << SourceRange(BuiltinLoc, RParenLoc); 15351 return ExprError(); 15352 } 15353 15354 CXXBasePath &Path = Paths.front(); 15355 for (const CXXBasePathElement &B : Path) 15356 Comps.push_back(OffsetOfNode(B.Base)); 15357 } 15358 15359 if (IndirectMemberDecl) { 15360 for (auto *FI : IndirectMemberDecl->chain()) { 15361 assert(isa<FieldDecl>(FI)); 15362 Comps.push_back(OffsetOfNode(OC.LocStart, 15363 cast<FieldDecl>(FI), OC.LocEnd)); 15364 } 15365 } else 15366 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15367 15368 CurrentType = MemberDecl->getType().getNonReferenceType(); 15369 } 15370 15371 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15372 Comps, Exprs, RParenLoc); 15373 } 15374 15375 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15376 SourceLocation BuiltinLoc, 15377 SourceLocation TypeLoc, 15378 ParsedType ParsedArgTy, 15379 ArrayRef<OffsetOfComponent> Components, 15380 SourceLocation RParenLoc) { 15381 15382 TypeSourceInfo *ArgTInfo; 15383 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15384 if (ArgTy.isNull()) 15385 return ExprError(); 15386 15387 if (!ArgTInfo) 15388 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15389 15390 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15391 } 15392 15393 15394 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15395 Expr *CondExpr, 15396 Expr *LHSExpr, Expr *RHSExpr, 15397 SourceLocation RPLoc) { 15398 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15399 15400 ExprValueKind VK = VK_PRValue; 15401 ExprObjectKind OK = OK_Ordinary; 15402 QualType resType; 15403 bool CondIsTrue = false; 15404 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15405 resType = Context.DependentTy; 15406 } else { 15407 // The conditional expression is required to be a constant expression. 15408 llvm::APSInt condEval(32); 15409 ExprResult CondICE = VerifyIntegerConstantExpression( 15410 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15411 if (CondICE.isInvalid()) 15412 return ExprError(); 15413 CondExpr = CondICE.get(); 15414 CondIsTrue = condEval.getZExtValue(); 15415 15416 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15417 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15418 15419 resType = ActiveExpr->getType(); 15420 VK = ActiveExpr->getValueKind(); 15421 OK = ActiveExpr->getObjectKind(); 15422 } 15423 15424 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15425 resType, VK, OK, RPLoc, CondIsTrue); 15426 } 15427 15428 //===----------------------------------------------------------------------===// 15429 // Clang Extensions. 15430 //===----------------------------------------------------------------------===// 15431 15432 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15433 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15434 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15435 15436 if (LangOpts.CPlusPlus) { 15437 MangleNumberingContext *MCtx; 15438 Decl *ManglingContextDecl; 15439 std::tie(MCtx, ManglingContextDecl) = 15440 getCurrentMangleNumberContext(Block->getDeclContext()); 15441 if (MCtx) { 15442 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15443 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15444 } 15445 } 15446 15447 PushBlockScope(CurScope, Block); 15448 CurContext->addDecl(Block); 15449 if (CurScope) 15450 PushDeclContext(CurScope, Block); 15451 else 15452 CurContext = Block; 15453 15454 getCurBlock()->HasImplicitReturnType = true; 15455 15456 // Enter a new evaluation context to insulate the block from any 15457 // cleanups from the enclosing full-expression. 15458 PushExpressionEvaluationContext( 15459 ExpressionEvaluationContext::PotentiallyEvaluated); 15460 } 15461 15462 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15463 Scope *CurScope) { 15464 assert(ParamInfo.getIdentifier() == nullptr && 15465 "block-id should have no identifier!"); 15466 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15467 BlockScopeInfo *CurBlock = getCurBlock(); 15468 15469 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15470 QualType T = Sig->getType(); 15471 15472 // FIXME: We should allow unexpanded parameter packs here, but that would, 15473 // in turn, make the block expression contain unexpanded parameter packs. 15474 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15475 // Drop the parameters. 15476 FunctionProtoType::ExtProtoInfo EPI; 15477 EPI.HasTrailingReturn = false; 15478 EPI.TypeQuals.addConst(); 15479 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15480 Sig = Context.getTrivialTypeSourceInfo(T); 15481 } 15482 15483 // GetTypeForDeclarator always produces a function type for a block 15484 // literal signature. Furthermore, it is always a FunctionProtoType 15485 // unless the function was written with a typedef. 15486 assert(T->isFunctionType() && 15487 "GetTypeForDeclarator made a non-function block signature"); 15488 15489 // Look for an explicit signature in that function type. 15490 FunctionProtoTypeLoc ExplicitSignature; 15491 15492 if ((ExplicitSignature = Sig->getTypeLoc() 15493 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15494 15495 // Check whether that explicit signature was synthesized by 15496 // GetTypeForDeclarator. If so, don't save that as part of the 15497 // written signature. 15498 if (ExplicitSignature.getLocalRangeBegin() == 15499 ExplicitSignature.getLocalRangeEnd()) { 15500 // This would be much cheaper if we stored TypeLocs instead of 15501 // TypeSourceInfos. 15502 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15503 unsigned Size = Result.getFullDataSize(); 15504 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15505 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15506 15507 ExplicitSignature = FunctionProtoTypeLoc(); 15508 } 15509 } 15510 15511 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15512 CurBlock->FunctionType = T; 15513 15514 const auto *Fn = T->castAs<FunctionType>(); 15515 QualType RetTy = Fn->getReturnType(); 15516 bool isVariadic = 15517 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15518 15519 CurBlock->TheDecl->setIsVariadic(isVariadic); 15520 15521 // Context.DependentTy is used as a placeholder for a missing block 15522 // return type. TODO: what should we do with declarators like: 15523 // ^ * { ... } 15524 // If the answer is "apply template argument deduction".... 15525 if (RetTy != Context.DependentTy) { 15526 CurBlock->ReturnType = RetTy; 15527 CurBlock->TheDecl->setBlockMissingReturnType(false); 15528 CurBlock->HasImplicitReturnType = false; 15529 } 15530 15531 // Push block parameters from the declarator if we had them. 15532 SmallVector<ParmVarDecl*, 8> Params; 15533 if (ExplicitSignature) { 15534 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15535 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15536 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15537 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15538 // Diagnose this as an extension in C17 and earlier. 15539 if (!getLangOpts().C2x) 15540 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15541 } 15542 Params.push_back(Param); 15543 } 15544 15545 // Fake up parameter variables if we have a typedef, like 15546 // ^ fntype { ... } 15547 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15548 for (const auto &I : Fn->param_types()) { 15549 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15550 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15551 Params.push_back(Param); 15552 } 15553 } 15554 15555 // Set the parameters on the block decl. 15556 if (!Params.empty()) { 15557 CurBlock->TheDecl->setParams(Params); 15558 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15559 /*CheckParameterNames=*/false); 15560 } 15561 15562 // Finally we can process decl attributes. 15563 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15564 15565 // Put the parameter variables in scope. 15566 for (auto AI : CurBlock->TheDecl->parameters()) { 15567 AI->setOwningFunction(CurBlock->TheDecl); 15568 15569 // If this has an identifier, add it to the scope stack. 15570 if (AI->getIdentifier()) { 15571 CheckShadow(CurBlock->TheScope, AI); 15572 15573 PushOnScopeChains(AI, CurBlock->TheScope); 15574 } 15575 } 15576 } 15577 15578 /// ActOnBlockError - If there is an error parsing a block, this callback 15579 /// is invoked to pop the information about the block from the action impl. 15580 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15581 // Leave the expression-evaluation context. 15582 DiscardCleanupsInEvaluationContext(); 15583 PopExpressionEvaluationContext(); 15584 15585 // Pop off CurBlock, handle nested blocks. 15586 PopDeclContext(); 15587 PopFunctionScopeInfo(); 15588 } 15589 15590 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15591 /// literal was successfully completed. ^(int x){...} 15592 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15593 Stmt *Body, Scope *CurScope) { 15594 // If blocks are disabled, emit an error. 15595 if (!LangOpts.Blocks) 15596 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15597 15598 // Leave the expression-evaluation context. 15599 if (hasAnyUnrecoverableErrorsInThisFunction()) 15600 DiscardCleanupsInEvaluationContext(); 15601 assert(!Cleanup.exprNeedsCleanups() && 15602 "cleanups within block not correctly bound!"); 15603 PopExpressionEvaluationContext(); 15604 15605 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15606 BlockDecl *BD = BSI->TheDecl; 15607 15608 if (BSI->HasImplicitReturnType) 15609 deduceClosureReturnType(*BSI); 15610 15611 QualType RetTy = Context.VoidTy; 15612 if (!BSI->ReturnType.isNull()) 15613 RetTy = BSI->ReturnType; 15614 15615 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15616 QualType BlockTy; 15617 15618 // If the user wrote a function type in some form, try to use that. 15619 if (!BSI->FunctionType.isNull()) { 15620 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15621 15622 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15623 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15624 15625 // Turn protoless block types into nullary block types. 15626 if (isa<FunctionNoProtoType>(FTy)) { 15627 FunctionProtoType::ExtProtoInfo EPI; 15628 EPI.ExtInfo = Ext; 15629 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15630 15631 // Otherwise, if we don't need to change anything about the function type, 15632 // preserve its sugar structure. 15633 } else if (FTy->getReturnType() == RetTy && 15634 (!NoReturn || FTy->getNoReturnAttr())) { 15635 BlockTy = BSI->FunctionType; 15636 15637 // Otherwise, make the minimal modifications to the function type. 15638 } else { 15639 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15640 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15641 EPI.TypeQuals = Qualifiers(); 15642 EPI.ExtInfo = Ext; 15643 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15644 } 15645 15646 // If we don't have a function type, just build one from nothing. 15647 } else { 15648 FunctionProtoType::ExtProtoInfo EPI; 15649 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15650 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15651 } 15652 15653 DiagnoseUnusedParameters(BD->parameters()); 15654 BlockTy = Context.getBlockPointerType(BlockTy); 15655 15656 // If needed, diagnose invalid gotos and switches in the block. 15657 if (getCurFunction()->NeedsScopeChecking() && 15658 !PP.isCodeCompletionEnabled()) 15659 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15660 15661 BD->setBody(cast<CompoundStmt>(Body)); 15662 15663 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15664 DiagnoseUnguardedAvailabilityViolations(BD); 15665 15666 // Try to apply the named return value optimization. We have to check again 15667 // if we can do this, though, because blocks keep return statements around 15668 // to deduce an implicit return type. 15669 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15670 !BD->isDependentContext()) 15671 computeNRVO(Body, BSI); 15672 15673 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15674 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15675 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15676 NTCUK_Destruct|NTCUK_Copy); 15677 15678 PopDeclContext(); 15679 15680 // Set the captured variables on the block. 15681 SmallVector<BlockDecl::Capture, 4> Captures; 15682 for (Capture &Cap : BSI->Captures) { 15683 if (Cap.isInvalid() || Cap.isThisCapture()) 15684 continue; 15685 15686 VarDecl *Var = Cap.getVariable(); 15687 Expr *CopyExpr = nullptr; 15688 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15689 if (const RecordType *Record = 15690 Cap.getCaptureType()->getAs<RecordType>()) { 15691 // The capture logic needs the destructor, so make sure we mark it. 15692 // Usually this is unnecessary because most local variables have 15693 // their destructors marked at declaration time, but parameters are 15694 // an exception because it's technically only the call site that 15695 // actually requires the destructor. 15696 if (isa<ParmVarDecl>(Var)) 15697 FinalizeVarWithDestructor(Var, Record); 15698 15699 // Enter a separate potentially-evaluated context while building block 15700 // initializers to isolate their cleanups from those of the block 15701 // itself. 15702 // FIXME: Is this appropriate even when the block itself occurs in an 15703 // unevaluated operand? 15704 EnterExpressionEvaluationContext EvalContext( 15705 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15706 15707 SourceLocation Loc = Cap.getLocation(); 15708 15709 ExprResult Result = BuildDeclarationNameExpr( 15710 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15711 15712 // According to the blocks spec, the capture of a variable from 15713 // the stack requires a const copy constructor. This is not true 15714 // of the copy/move done to move a __block variable to the heap. 15715 if (!Result.isInvalid() && 15716 !Result.get()->getType().isConstQualified()) { 15717 Result = ImpCastExprToType(Result.get(), 15718 Result.get()->getType().withConst(), 15719 CK_NoOp, VK_LValue); 15720 } 15721 15722 if (!Result.isInvalid()) { 15723 Result = PerformCopyInitialization( 15724 InitializedEntity::InitializeBlock(Var->getLocation(), 15725 Cap.getCaptureType()), 15726 Loc, Result.get()); 15727 } 15728 15729 // Build a full-expression copy expression if initialization 15730 // succeeded and used a non-trivial constructor. Recover from 15731 // errors by pretending that the copy isn't necessary. 15732 if (!Result.isInvalid() && 15733 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15734 ->isTrivial()) { 15735 Result = MaybeCreateExprWithCleanups(Result); 15736 CopyExpr = Result.get(); 15737 } 15738 } 15739 } 15740 15741 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15742 CopyExpr); 15743 Captures.push_back(NewCap); 15744 } 15745 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15746 15747 // Pop the block scope now but keep it alive to the end of this function. 15748 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15749 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15750 15751 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15752 15753 // If the block isn't obviously global, i.e. it captures anything at 15754 // all, then we need to do a few things in the surrounding context: 15755 if (Result->getBlockDecl()->hasCaptures()) { 15756 // First, this expression has a new cleanup object. 15757 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15758 Cleanup.setExprNeedsCleanups(true); 15759 15760 // It also gets a branch-protected scope if any of the captured 15761 // variables needs destruction. 15762 for (const auto &CI : Result->getBlockDecl()->captures()) { 15763 const VarDecl *var = CI.getVariable(); 15764 if (var->getType().isDestructedType() != QualType::DK_none) { 15765 setFunctionHasBranchProtectedScope(); 15766 break; 15767 } 15768 } 15769 } 15770 15771 if (getCurFunction()) 15772 getCurFunction()->addBlock(BD); 15773 15774 return Result; 15775 } 15776 15777 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15778 SourceLocation RPLoc) { 15779 TypeSourceInfo *TInfo; 15780 GetTypeFromParser(Ty, &TInfo); 15781 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15782 } 15783 15784 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15785 Expr *E, TypeSourceInfo *TInfo, 15786 SourceLocation RPLoc) { 15787 Expr *OrigExpr = E; 15788 bool IsMS = false; 15789 15790 // CUDA device code does not support varargs. 15791 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15792 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15793 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15794 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15795 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15796 } 15797 } 15798 15799 // NVPTX does not support va_arg expression. 15800 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15801 Context.getTargetInfo().getTriple().isNVPTX()) 15802 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15803 15804 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15805 // as Microsoft ABI on an actual Microsoft platform, where 15806 // __builtin_ms_va_list and __builtin_va_list are the same.) 15807 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15808 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15809 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15810 if (Context.hasSameType(MSVaListType, E->getType())) { 15811 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15812 return ExprError(); 15813 IsMS = true; 15814 } 15815 } 15816 15817 // Get the va_list type 15818 QualType VaListType = Context.getBuiltinVaListType(); 15819 if (!IsMS) { 15820 if (VaListType->isArrayType()) { 15821 // Deal with implicit array decay; for example, on x86-64, 15822 // va_list is an array, but it's supposed to decay to 15823 // a pointer for va_arg. 15824 VaListType = Context.getArrayDecayedType(VaListType); 15825 // Make sure the input expression also decays appropriately. 15826 ExprResult Result = UsualUnaryConversions(E); 15827 if (Result.isInvalid()) 15828 return ExprError(); 15829 E = Result.get(); 15830 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15831 // If va_list is a record type and we are compiling in C++ mode, 15832 // check the argument using reference binding. 15833 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15834 Context, Context.getLValueReferenceType(VaListType), false); 15835 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15836 if (Init.isInvalid()) 15837 return ExprError(); 15838 E = Init.getAs<Expr>(); 15839 } else { 15840 // Otherwise, the va_list argument must be an l-value because 15841 // it is modified by va_arg. 15842 if (!E->isTypeDependent() && 15843 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15844 return ExprError(); 15845 } 15846 } 15847 15848 if (!IsMS && !E->isTypeDependent() && 15849 !Context.hasSameType(VaListType, E->getType())) 15850 return ExprError( 15851 Diag(E->getBeginLoc(), 15852 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15853 << OrigExpr->getType() << E->getSourceRange()); 15854 15855 if (!TInfo->getType()->isDependentType()) { 15856 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15857 diag::err_second_parameter_to_va_arg_incomplete, 15858 TInfo->getTypeLoc())) 15859 return ExprError(); 15860 15861 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15862 TInfo->getType(), 15863 diag::err_second_parameter_to_va_arg_abstract, 15864 TInfo->getTypeLoc())) 15865 return ExprError(); 15866 15867 if (!TInfo->getType().isPODType(Context)) { 15868 Diag(TInfo->getTypeLoc().getBeginLoc(), 15869 TInfo->getType()->isObjCLifetimeType() 15870 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15871 : diag::warn_second_parameter_to_va_arg_not_pod) 15872 << TInfo->getType() 15873 << TInfo->getTypeLoc().getSourceRange(); 15874 } 15875 15876 // Check for va_arg where arguments of the given type will be promoted 15877 // (i.e. this va_arg is guaranteed to have undefined behavior). 15878 QualType PromoteType; 15879 if (TInfo->getType()->isPromotableIntegerType()) { 15880 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15881 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15882 // and C2x 7.16.1.1p2 says, in part: 15883 // If type is not compatible with the type of the actual next argument 15884 // (as promoted according to the default argument promotions), the 15885 // behavior is undefined, except for the following cases: 15886 // - both types are pointers to qualified or unqualified versions of 15887 // compatible types; 15888 // - one type is a signed integer type, the other type is the 15889 // corresponding unsigned integer type, and the value is 15890 // representable in both types; 15891 // - one type is pointer to qualified or unqualified void and the 15892 // other is a pointer to a qualified or unqualified character type. 15893 // Given that type compatibility is the primary requirement (ignoring 15894 // qualifications), you would think we could call typesAreCompatible() 15895 // directly to test this. However, in C++, that checks for *same type*, 15896 // which causes false positives when passing an enumeration type to 15897 // va_arg. Instead, get the underlying type of the enumeration and pass 15898 // that. 15899 QualType UnderlyingType = TInfo->getType(); 15900 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15901 UnderlyingType = ET->getDecl()->getIntegerType(); 15902 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15903 /*CompareUnqualified*/ true)) 15904 PromoteType = QualType(); 15905 15906 // If the types are still not compatible, we need to test whether the 15907 // promoted type and the underlying type are the same except for 15908 // signedness. Ask the AST for the correctly corresponding type and see 15909 // if that's compatible. 15910 if (!PromoteType.isNull() && 15911 PromoteType->isUnsignedIntegerType() != 15912 UnderlyingType->isUnsignedIntegerType()) { 15913 UnderlyingType = 15914 UnderlyingType->isUnsignedIntegerType() 15915 ? Context.getCorrespondingSignedType(UnderlyingType) 15916 : Context.getCorrespondingUnsignedType(UnderlyingType); 15917 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15918 /*CompareUnqualified*/ true)) 15919 PromoteType = QualType(); 15920 } 15921 } 15922 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15923 PromoteType = Context.DoubleTy; 15924 if (!PromoteType.isNull()) 15925 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15926 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15927 << TInfo->getType() 15928 << PromoteType 15929 << TInfo->getTypeLoc().getSourceRange()); 15930 } 15931 15932 QualType T = TInfo->getType().getNonLValueExprType(Context); 15933 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15934 } 15935 15936 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15937 // The type of __null will be int or long, depending on the size of 15938 // pointers on the target. 15939 QualType Ty; 15940 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15941 if (pw == Context.getTargetInfo().getIntWidth()) 15942 Ty = Context.IntTy; 15943 else if (pw == Context.getTargetInfo().getLongWidth()) 15944 Ty = Context.LongTy; 15945 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15946 Ty = Context.LongLongTy; 15947 else { 15948 llvm_unreachable("I don't know size of pointer!"); 15949 } 15950 15951 return new (Context) GNUNullExpr(Ty, TokenLoc); 15952 } 15953 15954 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15955 SourceLocation BuiltinLoc, 15956 SourceLocation RPLoc) { 15957 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15958 } 15959 15960 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15961 SourceLocation BuiltinLoc, 15962 SourceLocation RPLoc, 15963 DeclContext *ParentContext) { 15964 return new (Context) 15965 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15966 } 15967 15968 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15969 bool Diagnose) { 15970 if (!getLangOpts().ObjC) 15971 return false; 15972 15973 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15974 if (!PT) 15975 return false; 15976 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15977 15978 // Ignore any parens, implicit casts (should only be 15979 // array-to-pointer decays), and not-so-opaque values. The last is 15980 // important for making this trigger for property assignments. 15981 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15982 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15983 if (OV->getSourceExpr()) 15984 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15985 15986 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15987 if (!PT->isObjCIdType() && 15988 !(ID && ID->getIdentifier()->isStr("NSString"))) 15989 return false; 15990 if (!SL->isAscii()) 15991 return false; 15992 15993 if (Diagnose) { 15994 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15995 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15996 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15997 } 15998 return true; 15999 } 16000 16001 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16002 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16003 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16004 !SrcExpr->isNullPointerConstant( 16005 getASTContext(), Expr::NPC_NeverValueDependent)) { 16006 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16007 return false; 16008 if (Diagnose) { 16009 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16010 << /*number*/1 16011 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16012 Expr *NumLit = 16013 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16014 if (NumLit) 16015 Exp = NumLit; 16016 } 16017 return true; 16018 } 16019 16020 return false; 16021 } 16022 16023 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16024 const Expr *SrcExpr) { 16025 if (!DstType->isFunctionPointerType() || 16026 !SrcExpr->getType()->isFunctionType()) 16027 return false; 16028 16029 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16030 if (!DRE) 16031 return false; 16032 16033 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16034 if (!FD) 16035 return false; 16036 16037 return !S.checkAddressOfFunctionIsAvailable(FD, 16038 /*Complain=*/true, 16039 SrcExpr->getBeginLoc()); 16040 } 16041 16042 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16043 SourceLocation Loc, 16044 QualType DstType, QualType SrcType, 16045 Expr *SrcExpr, AssignmentAction Action, 16046 bool *Complained) { 16047 if (Complained) 16048 *Complained = false; 16049 16050 // Decode the result (notice that AST's are still created for extensions). 16051 bool CheckInferredResultType = false; 16052 bool isInvalid = false; 16053 unsigned DiagKind = 0; 16054 ConversionFixItGenerator ConvHints; 16055 bool MayHaveConvFixit = false; 16056 bool MayHaveFunctionDiff = false; 16057 const ObjCInterfaceDecl *IFace = nullptr; 16058 const ObjCProtocolDecl *PDecl = nullptr; 16059 16060 switch (ConvTy) { 16061 case Compatible: 16062 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16063 return false; 16064 16065 case PointerToInt: 16066 if (getLangOpts().CPlusPlus) { 16067 DiagKind = diag::err_typecheck_convert_pointer_int; 16068 isInvalid = true; 16069 } else { 16070 DiagKind = diag::ext_typecheck_convert_pointer_int; 16071 } 16072 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16073 MayHaveConvFixit = true; 16074 break; 16075 case IntToPointer: 16076 if (getLangOpts().CPlusPlus) { 16077 DiagKind = diag::err_typecheck_convert_int_pointer; 16078 isInvalid = true; 16079 } else { 16080 DiagKind = diag::ext_typecheck_convert_int_pointer; 16081 } 16082 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16083 MayHaveConvFixit = true; 16084 break; 16085 case IncompatibleFunctionPointer: 16086 if (getLangOpts().CPlusPlus) { 16087 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16088 isInvalid = true; 16089 } else { 16090 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16091 } 16092 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16093 MayHaveConvFixit = true; 16094 break; 16095 case IncompatiblePointer: 16096 if (Action == AA_Passing_CFAudited) { 16097 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16098 } else if (getLangOpts().CPlusPlus) { 16099 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16100 isInvalid = true; 16101 } else { 16102 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16103 } 16104 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16105 SrcType->isObjCObjectPointerType(); 16106 if (!CheckInferredResultType) { 16107 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16108 } else if (CheckInferredResultType) { 16109 SrcType = SrcType.getUnqualifiedType(); 16110 DstType = DstType.getUnqualifiedType(); 16111 } 16112 MayHaveConvFixit = true; 16113 break; 16114 case IncompatiblePointerSign: 16115 if (getLangOpts().CPlusPlus) { 16116 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16117 isInvalid = true; 16118 } else { 16119 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16120 } 16121 break; 16122 case FunctionVoidPointer: 16123 if (getLangOpts().CPlusPlus) { 16124 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16125 isInvalid = true; 16126 } else { 16127 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16128 } 16129 break; 16130 case IncompatiblePointerDiscardsQualifiers: { 16131 // Perform array-to-pointer decay if necessary. 16132 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16133 16134 isInvalid = true; 16135 16136 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16137 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16138 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16139 DiagKind = diag::err_typecheck_incompatible_address_space; 16140 break; 16141 16142 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16143 DiagKind = diag::err_typecheck_incompatible_ownership; 16144 break; 16145 } 16146 16147 llvm_unreachable("unknown error case for discarding qualifiers!"); 16148 // fallthrough 16149 } 16150 case CompatiblePointerDiscardsQualifiers: 16151 // If the qualifiers lost were because we were applying the 16152 // (deprecated) C++ conversion from a string literal to a char* 16153 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16154 // Ideally, this check would be performed in 16155 // checkPointerTypesForAssignment. However, that would require a 16156 // bit of refactoring (so that the second argument is an 16157 // expression, rather than a type), which should be done as part 16158 // of a larger effort to fix checkPointerTypesForAssignment for 16159 // C++ semantics. 16160 if (getLangOpts().CPlusPlus && 16161 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16162 return false; 16163 if (getLangOpts().CPlusPlus) { 16164 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16165 isInvalid = true; 16166 } else { 16167 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16168 } 16169 16170 break; 16171 case IncompatibleNestedPointerQualifiers: 16172 if (getLangOpts().CPlusPlus) { 16173 isInvalid = true; 16174 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16175 } else { 16176 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16177 } 16178 break; 16179 case IncompatibleNestedPointerAddressSpaceMismatch: 16180 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16181 isInvalid = true; 16182 break; 16183 case IntToBlockPointer: 16184 DiagKind = diag::err_int_to_block_pointer; 16185 isInvalid = true; 16186 break; 16187 case IncompatibleBlockPointer: 16188 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16189 isInvalid = true; 16190 break; 16191 case IncompatibleObjCQualifiedId: { 16192 if (SrcType->isObjCQualifiedIdType()) { 16193 const ObjCObjectPointerType *srcOPT = 16194 SrcType->castAs<ObjCObjectPointerType>(); 16195 for (auto *srcProto : srcOPT->quals()) { 16196 PDecl = srcProto; 16197 break; 16198 } 16199 if (const ObjCInterfaceType *IFaceT = 16200 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16201 IFace = IFaceT->getDecl(); 16202 } 16203 else if (DstType->isObjCQualifiedIdType()) { 16204 const ObjCObjectPointerType *dstOPT = 16205 DstType->castAs<ObjCObjectPointerType>(); 16206 for (auto *dstProto : dstOPT->quals()) { 16207 PDecl = dstProto; 16208 break; 16209 } 16210 if (const ObjCInterfaceType *IFaceT = 16211 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16212 IFace = IFaceT->getDecl(); 16213 } 16214 if (getLangOpts().CPlusPlus) { 16215 DiagKind = diag::err_incompatible_qualified_id; 16216 isInvalid = true; 16217 } else { 16218 DiagKind = diag::warn_incompatible_qualified_id; 16219 } 16220 break; 16221 } 16222 case IncompatibleVectors: 16223 if (getLangOpts().CPlusPlus) { 16224 DiagKind = diag::err_incompatible_vectors; 16225 isInvalid = true; 16226 } else { 16227 DiagKind = diag::warn_incompatible_vectors; 16228 } 16229 break; 16230 case IncompatibleObjCWeakRef: 16231 DiagKind = diag::err_arc_weak_unavailable_assign; 16232 isInvalid = true; 16233 break; 16234 case Incompatible: 16235 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16236 if (Complained) 16237 *Complained = true; 16238 return true; 16239 } 16240 16241 DiagKind = diag::err_typecheck_convert_incompatible; 16242 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16243 MayHaveConvFixit = true; 16244 isInvalid = true; 16245 MayHaveFunctionDiff = true; 16246 break; 16247 } 16248 16249 QualType FirstType, SecondType; 16250 switch (Action) { 16251 case AA_Assigning: 16252 case AA_Initializing: 16253 // The destination type comes first. 16254 FirstType = DstType; 16255 SecondType = SrcType; 16256 break; 16257 16258 case AA_Returning: 16259 case AA_Passing: 16260 case AA_Passing_CFAudited: 16261 case AA_Converting: 16262 case AA_Sending: 16263 case AA_Casting: 16264 // The source type comes first. 16265 FirstType = SrcType; 16266 SecondType = DstType; 16267 break; 16268 } 16269 16270 PartialDiagnostic FDiag = PDiag(DiagKind); 16271 if (Action == AA_Passing_CFAudited) 16272 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16273 else 16274 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16275 16276 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16277 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16278 auto isPlainChar = [](const clang::Type *Type) { 16279 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16280 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16281 }; 16282 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16283 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16284 } 16285 16286 // If we can fix the conversion, suggest the FixIts. 16287 if (!ConvHints.isNull()) { 16288 for (FixItHint &H : ConvHints.Hints) 16289 FDiag << H; 16290 } 16291 16292 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16293 16294 if (MayHaveFunctionDiff) 16295 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16296 16297 Diag(Loc, FDiag); 16298 if ((DiagKind == diag::warn_incompatible_qualified_id || 16299 DiagKind == diag::err_incompatible_qualified_id) && 16300 PDecl && IFace && !IFace->hasDefinition()) 16301 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16302 << IFace << PDecl; 16303 16304 if (SecondType == Context.OverloadTy) 16305 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16306 FirstType, /*TakingAddress=*/true); 16307 16308 if (CheckInferredResultType) 16309 EmitRelatedResultTypeNote(SrcExpr); 16310 16311 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16312 EmitRelatedResultTypeNoteForReturn(DstType); 16313 16314 if (Complained) 16315 *Complained = true; 16316 return isInvalid; 16317 } 16318 16319 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16320 llvm::APSInt *Result, 16321 AllowFoldKind CanFold) { 16322 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16323 public: 16324 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16325 QualType T) override { 16326 return S.Diag(Loc, diag::err_ice_not_integral) 16327 << T << S.LangOpts.CPlusPlus; 16328 } 16329 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16330 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16331 } 16332 } Diagnoser; 16333 16334 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16335 } 16336 16337 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16338 llvm::APSInt *Result, 16339 unsigned DiagID, 16340 AllowFoldKind CanFold) { 16341 class IDDiagnoser : public VerifyICEDiagnoser { 16342 unsigned DiagID; 16343 16344 public: 16345 IDDiagnoser(unsigned DiagID) 16346 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16347 16348 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16349 return S.Diag(Loc, DiagID); 16350 } 16351 } Diagnoser(DiagID); 16352 16353 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16354 } 16355 16356 Sema::SemaDiagnosticBuilder 16357 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16358 QualType T) { 16359 return diagnoseNotICE(S, Loc); 16360 } 16361 16362 Sema::SemaDiagnosticBuilder 16363 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16364 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16365 } 16366 16367 ExprResult 16368 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16369 VerifyICEDiagnoser &Diagnoser, 16370 AllowFoldKind CanFold) { 16371 SourceLocation DiagLoc = E->getBeginLoc(); 16372 16373 if (getLangOpts().CPlusPlus11) { 16374 // C++11 [expr.const]p5: 16375 // If an expression of literal class type is used in a context where an 16376 // integral constant expression is required, then that class type shall 16377 // have a single non-explicit conversion function to an integral or 16378 // unscoped enumeration type 16379 ExprResult Converted; 16380 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16381 VerifyICEDiagnoser &BaseDiagnoser; 16382 public: 16383 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16384 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16385 BaseDiagnoser.Suppress, true), 16386 BaseDiagnoser(BaseDiagnoser) {} 16387 16388 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16389 QualType T) override { 16390 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16391 } 16392 16393 SemaDiagnosticBuilder diagnoseIncomplete( 16394 Sema &S, SourceLocation Loc, QualType T) override { 16395 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16396 } 16397 16398 SemaDiagnosticBuilder diagnoseExplicitConv( 16399 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16400 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16401 } 16402 16403 SemaDiagnosticBuilder noteExplicitConv( 16404 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16405 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16406 << ConvTy->isEnumeralType() << ConvTy; 16407 } 16408 16409 SemaDiagnosticBuilder diagnoseAmbiguous( 16410 Sema &S, SourceLocation Loc, QualType T) override { 16411 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16412 } 16413 16414 SemaDiagnosticBuilder noteAmbiguous( 16415 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16416 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16417 << ConvTy->isEnumeralType() << ConvTy; 16418 } 16419 16420 SemaDiagnosticBuilder diagnoseConversion( 16421 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16422 llvm_unreachable("conversion functions are permitted"); 16423 } 16424 } ConvertDiagnoser(Diagnoser); 16425 16426 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16427 ConvertDiagnoser); 16428 if (Converted.isInvalid()) 16429 return Converted; 16430 E = Converted.get(); 16431 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16432 return ExprError(); 16433 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16434 // An ICE must be of integral or unscoped enumeration type. 16435 if (!Diagnoser.Suppress) 16436 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16437 << E->getSourceRange(); 16438 return ExprError(); 16439 } 16440 16441 ExprResult RValueExpr = DefaultLvalueConversion(E); 16442 if (RValueExpr.isInvalid()) 16443 return ExprError(); 16444 16445 E = RValueExpr.get(); 16446 16447 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16448 // in the non-ICE case. 16449 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16450 if (Result) 16451 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16452 if (!isa<ConstantExpr>(E)) 16453 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16454 : ConstantExpr::Create(Context, E); 16455 return E; 16456 } 16457 16458 Expr::EvalResult EvalResult; 16459 SmallVector<PartialDiagnosticAt, 8> Notes; 16460 EvalResult.Diag = &Notes; 16461 16462 // Try to evaluate the expression, and produce diagnostics explaining why it's 16463 // not a constant expression as a side-effect. 16464 bool Folded = 16465 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16466 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16467 16468 if (!isa<ConstantExpr>(E)) 16469 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16470 16471 // In C++11, we can rely on diagnostics being produced for any expression 16472 // which is not a constant expression. If no diagnostics were produced, then 16473 // this is a constant expression. 16474 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16475 if (Result) 16476 *Result = EvalResult.Val.getInt(); 16477 return E; 16478 } 16479 16480 // If our only note is the usual "invalid subexpression" note, just point 16481 // the caret at its location rather than producing an essentially 16482 // redundant note. 16483 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16484 diag::note_invalid_subexpr_in_const_expr) { 16485 DiagLoc = Notes[0].first; 16486 Notes.clear(); 16487 } 16488 16489 if (!Folded || !CanFold) { 16490 if (!Diagnoser.Suppress) { 16491 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16492 for (const PartialDiagnosticAt &Note : Notes) 16493 Diag(Note.first, Note.second); 16494 } 16495 16496 return ExprError(); 16497 } 16498 16499 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16500 for (const PartialDiagnosticAt &Note : Notes) 16501 Diag(Note.first, Note.second); 16502 16503 if (Result) 16504 *Result = EvalResult.Val.getInt(); 16505 return E; 16506 } 16507 16508 namespace { 16509 // Handle the case where we conclude a expression which we speculatively 16510 // considered to be unevaluated is actually evaluated. 16511 class TransformToPE : public TreeTransform<TransformToPE> { 16512 typedef TreeTransform<TransformToPE> BaseTransform; 16513 16514 public: 16515 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16516 16517 // Make sure we redo semantic analysis 16518 bool AlwaysRebuild() { return true; } 16519 bool ReplacingOriginal() { return true; } 16520 16521 // We need to special-case DeclRefExprs referring to FieldDecls which 16522 // are not part of a member pointer formation; normal TreeTransforming 16523 // doesn't catch this case because of the way we represent them in the AST. 16524 // FIXME: This is a bit ugly; is it really the best way to handle this 16525 // case? 16526 // 16527 // Error on DeclRefExprs referring to FieldDecls. 16528 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16529 if (isa<FieldDecl>(E->getDecl()) && 16530 !SemaRef.isUnevaluatedContext()) 16531 return SemaRef.Diag(E->getLocation(), 16532 diag::err_invalid_non_static_member_use) 16533 << E->getDecl() << E->getSourceRange(); 16534 16535 return BaseTransform::TransformDeclRefExpr(E); 16536 } 16537 16538 // Exception: filter out member pointer formation 16539 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16540 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16541 return E; 16542 16543 return BaseTransform::TransformUnaryOperator(E); 16544 } 16545 16546 // The body of a lambda-expression is in a separate expression evaluation 16547 // context so never needs to be transformed. 16548 // FIXME: Ideally we wouldn't transform the closure type either, and would 16549 // just recreate the capture expressions and lambda expression. 16550 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16551 return SkipLambdaBody(E, Body); 16552 } 16553 }; 16554 } 16555 16556 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16557 assert(isUnevaluatedContext() && 16558 "Should only transform unevaluated expressions"); 16559 ExprEvalContexts.back().Context = 16560 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16561 if (isUnevaluatedContext()) 16562 return E; 16563 return TransformToPE(*this).TransformExpr(E); 16564 } 16565 16566 void 16567 Sema::PushExpressionEvaluationContext( 16568 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16569 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16570 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16571 LambdaContextDecl, ExprContext); 16572 Cleanup.reset(); 16573 if (!MaybeODRUseExprs.empty()) 16574 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16575 } 16576 16577 void 16578 Sema::PushExpressionEvaluationContext( 16579 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16580 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16581 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16582 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16583 } 16584 16585 namespace { 16586 16587 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16588 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16589 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16590 if (E->getOpcode() == UO_Deref) 16591 return CheckPossibleDeref(S, E->getSubExpr()); 16592 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16593 return CheckPossibleDeref(S, E->getBase()); 16594 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16595 return CheckPossibleDeref(S, E->getBase()); 16596 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16597 QualType Inner; 16598 QualType Ty = E->getType(); 16599 if (const auto *Ptr = Ty->getAs<PointerType>()) 16600 Inner = Ptr->getPointeeType(); 16601 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16602 Inner = Arr->getElementType(); 16603 else 16604 return nullptr; 16605 16606 if (Inner->hasAttr(attr::NoDeref)) 16607 return E; 16608 } 16609 return nullptr; 16610 } 16611 16612 } // namespace 16613 16614 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16615 for (const Expr *E : Rec.PossibleDerefs) { 16616 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16617 if (DeclRef) { 16618 const ValueDecl *Decl = DeclRef->getDecl(); 16619 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16620 << Decl->getName() << E->getSourceRange(); 16621 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16622 } else { 16623 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16624 << E->getSourceRange(); 16625 } 16626 } 16627 Rec.PossibleDerefs.clear(); 16628 } 16629 16630 /// Check whether E, which is either a discarded-value expression or an 16631 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16632 /// and if so, remove it from the list of volatile-qualified assignments that 16633 /// we are going to warn are deprecated. 16634 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16635 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16636 return; 16637 16638 // Note: ignoring parens here is not justified by the standard rules, but 16639 // ignoring parentheses seems like a more reasonable approach, and this only 16640 // drives a deprecation warning so doesn't affect conformance. 16641 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16642 if (BO->getOpcode() == BO_Assign) { 16643 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16644 llvm::erase_value(LHSs, BO->getLHS()); 16645 } 16646 } 16647 } 16648 16649 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16650 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16651 !Decl->isConsteval() || isConstantEvaluated() || 16652 RebuildingImmediateInvocation || isImmediateFunctionContext()) 16653 return E; 16654 16655 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16656 /// It's OK if this fails; we'll also remove this in 16657 /// HandleImmediateInvocations, but catching it here allows us to avoid 16658 /// walking the AST looking for it in simple cases. 16659 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16660 if (auto *DeclRef = 16661 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16662 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16663 16664 E = MaybeCreateExprWithCleanups(E); 16665 16666 ConstantExpr *Res = ConstantExpr::Create( 16667 getASTContext(), E.get(), 16668 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16669 getASTContext()), 16670 /*IsImmediateInvocation*/ true); 16671 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16672 return Res; 16673 } 16674 16675 static void EvaluateAndDiagnoseImmediateInvocation( 16676 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16677 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16678 Expr::EvalResult Eval; 16679 Eval.Diag = &Notes; 16680 ConstantExpr *CE = Candidate.getPointer(); 16681 bool Result = CE->EvaluateAsConstantExpr( 16682 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16683 if (!Result || !Notes.empty()) { 16684 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16685 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16686 InnerExpr = FunctionalCast->getSubExpr(); 16687 FunctionDecl *FD = nullptr; 16688 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16689 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16690 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16691 FD = Call->getConstructor(); 16692 else 16693 llvm_unreachable("unhandled decl kind"); 16694 assert(FD->isConsteval()); 16695 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16696 for (auto &Note : Notes) 16697 SemaRef.Diag(Note.first, Note.second); 16698 return; 16699 } 16700 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16701 } 16702 16703 static void RemoveNestedImmediateInvocation( 16704 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16705 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16706 struct ComplexRemove : TreeTransform<ComplexRemove> { 16707 using Base = TreeTransform<ComplexRemove>; 16708 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16709 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16710 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16711 CurrentII; 16712 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16713 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16714 SmallVector<Sema::ImmediateInvocationCandidate, 16715 4>::reverse_iterator Current) 16716 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16717 void RemoveImmediateInvocation(ConstantExpr* E) { 16718 auto It = std::find_if(CurrentII, IISet.rend(), 16719 [E](Sema::ImmediateInvocationCandidate Elem) { 16720 return Elem.getPointer() == E; 16721 }); 16722 assert(It != IISet.rend() && 16723 "ConstantExpr marked IsImmediateInvocation should " 16724 "be present"); 16725 It->setInt(1); // Mark as deleted 16726 } 16727 ExprResult TransformConstantExpr(ConstantExpr *E) { 16728 if (!E->isImmediateInvocation()) 16729 return Base::TransformConstantExpr(E); 16730 RemoveImmediateInvocation(E); 16731 return Base::TransformExpr(E->getSubExpr()); 16732 } 16733 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16734 /// we need to remove its DeclRefExpr from the DRSet. 16735 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16736 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16737 return Base::TransformCXXOperatorCallExpr(E); 16738 } 16739 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16740 /// here. 16741 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16742 if (!Init) 16743 return Init; 16744 /// ConstantExpr are the first layer of implicit node to be removed so if 16745 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16746 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16747 if (CE->isImmediateInvocation()) 16748 RemoveImmediateInvocation(CE); 16749 return Base::TransformInitializer(Init, NotCopyInit); 16750 } 16751 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16752 DRSet.erase(E); 16753 return E; 16754 } 16755 bool AlwaysRebuild() { return false; } 16756 bool ReplacingOriginal() { return true; } 16757 bool AllowSkippingCXXConstructExpr() { 16758 bool Res = AllowSkippingFirstCXXConstructExpr; 16759 AllowSkippingFirstCXXConstructExpr = true; 16760 return Res; 16761 } 16762 bool AllowSkippingFirstCXXConstructExpr = true; 16763 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16764 Rec.ImmediateInvocationCandidates, It); 16765 16766 /// CXXConstructExpr with a single argument are getting skipped by 16767 /// TreeTransform in some situtation because they could be implicit. This 16768 /// can only occur for the top-level CXXConstructExpr because it is used 16769 /// nowhere in the expression being transformed therefore will not be rebuilt. 16770 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16771 /// skipping the first CXXConstructExpr. 16772 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16773 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16774 16775 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16776 assert(Res.isUsable()); 16777 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16778 It->getPointer()->setSubExpr(Res.get()); 16779 } 16780 16781 static void 16782 HandleImmediateInvocations(Sema &SemaRef, 16783 Sema::ExpressionEvaluationContextRecord &Rec) { 16784 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16785 Rec.ReferenceToConsteval.size() == 0) || 16786 SemaRef.RebuildingImmediateInvocation) 16787 return; 16788 16789 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16790 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16791 /// need to remove ReferenceToConsteval in the immediate invocation. 16792 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16793 16794 /// Prevent sema calls during the tree transform from adding pointers that 16795 /// are already in the sets. 16796 llvm::SaveAndRestore<bool> DisableIITracking( 16797 SemaRef.RebuildingImmediateInvocation, true); 16798 16799 /// Prevent diagnostic during tree transfrom as they are duplicates 16800 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16801 16802 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16803 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16804 if (!It->getInt()) 16805 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16806 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16807 Rec.ReferenceToConsteval.size()) { 16808 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16809 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16810 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16811 bool VisitDeclRefExpr(DeclRefExpr *E) { 16812 DRSet.erase(E); 16813 return DRSet.size(); 16814 } 16815 } Visitor(Rec.ReferenceToConsteval); 16816 Visitor.TraverseStmt( 16817 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16818 } 16819 for (auto CE : Rec.ImmediateInvocationCandidates) 16820 if (!CE.getInt()) 16821 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16822 for (auto DR : Rec.ReferenceToConsteval) { 16823 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16824 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16825 << FD; 16826 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16827 } 16828 } 16829 16830 void Sema::PopExpressionEvaluationContext() { 16831 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16832 unsigned NumTypos = Rec.NumTypos; 16833 16834 if (!Rec.Lambdas.empty()) { 16835 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16836 if (!getLangOpts().CPlusPlus20 && 16837 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16838 Rec.isUnevaluated() || 16839 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16840 unsigned D; 16841 if (Rec.isUnevaluated()) { 16842 // C++11 [expr.prim.lambda]p2: 16843 // A lambda-expression shall not appear in an unevaluated operand 16844 // (Clause 5). 16845 D = diag::err_lambda_unevaluated_operand; 16846 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16847 // C++1y [expr.const]p2: 16848 // A conditional-expression e is a core constant expression unless the 16849 // evaluation of e, following the rules of the abstract machine, would 16850 // evaluate [...] a lambda-expression. 16851 D = diag::err_lambda_in_constant_expression; 16852 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16853 // C++17 [expr.prim.lamda]p2: 16854 // A lambda-expression shall not appear [...] in a template-argument. 16855 D = diag::err_lambda_in_invalid_context; 16856 } else 16857 llvm_unreachable("Couldn't infer lambda error message."); 16858 16859 for (const auto *L : Rec.Lambdas) 16860 Diag(L->getBeginLoc(), D); 16861 } 16862 } 16863 16864 WarnOnPendingNoDerefs(Rec); 16865 HandleImmediateInvocations(*this, Rec); 16866 16867 // Warn on any volatile-qualified simple-assignments that are not discarded- 16868 // value expressions nor unevaluated operands (those cases get removed from 16869 // this list by CheckUnusedVolatileAssignment). 16870 for (auto *BO : Rec.VolatileAssignmentLHSs) 16871 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16872 << BO->getType(); 16873 16874 // When are coming out of an unevaluated context, clear out any 16875 // temporaries that we may have created as part of the evaluation of 16876 // the expression in that context: they aren't relevant because they 16877 // will never be constructed. 16878 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16879 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16880 ExprCleanupObjects.end()); 16881 Cleanup = Rec.ParentCleanup; 16882 CleanupVarDeclMarking(); 16883 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16884 // Otherwise, merge the contexts together. 16885 } else { 16886 Cleanup.mergeFrom(Rec.ParentCleanup); 16887 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16888 Rec.SavedMaybeODRUseExprs.end()); 16889 } 16890 16891 // Pop the current expression evaluation context off the stack. 16892 ExprEvalContexts.pop_back(); 16893 16894 // The global expression evaluation context record is never popped. 16895 ExprEvalContexts.back().NumTypos += NumTypos; 16896 } 16897 16898 void Sema::DiscardCleanupsInEvaluationContext() { 16899 ExprCleanupObjects.erase( 16900 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16901 ExprCleanupObjects.end()); 16902 Cleanup.reset(); 16903 MaybeODRUseExprs.clear(); 16904 } 16905 16906 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16907 ExprResult Result = CheckPlaceholderExpr(E); 16908 if (Result.isInvalid()) 16909 return ExprError(); 16910 E = Result.get(); 16911 if (!E->getType()->isVariablyModifiedType()) 16912 return E; 16913 return TransformToPotentiallyEvaluated(E); 16914 } 16915 16916 /// Are we in a context that is potentially constant evaluated per C++20 16917 /// [expr.const]p12? 16918 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16919 /// C++2a [expr.const]p12: 16920 // An expression or conversion is potentially constant evaluated if it is 16921 switch (SemaRef.ExprEvalContexts.back().Context) { 16922 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16923 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 16924 16925 // -- a manifestly constant-evaluated expression, 16926 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16927 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16928 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16929 // -- a potentially-evaluated expression, 16930 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16931 // -- an immediate subexpression of a braced-init-list, 16932 16933 // -- [FIXME] an expression of the form & cast-expression that occurs 16934 // within a templated entity 16935 // -- a subexpression of one of the above that is not a subexpression of 16936 // a nested unevaluated operand. 16937 return true; 16938 16939 case Sema::ExpressionEvaluationContext::Unevaluated: 16940 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16941 // Expressions in this context are never evaluated. 16942 return false; 16943 } 16944 llvm_unreachable("Invalid context"); 16945 } 16946 16947 /// Return true if this function has a calling convention that requires mangling 16948 /// in the size of the parameter pack. 16949 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16950 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16951 // we don't need parameter type sizes. 16952 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16953 if (!TT.isOSWindows() || !TT.isX86()) 16954 return false; 16955 16956 // If this is C++ and this isn't an extern "C" function, parameters do not 16957 // need to be complete. In this case, C++ mangling will apply, which doesn't 16958 // use the size of the parameters. 16959 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16960 return false; 16961 16962 // Stdcall, fastcall, and vectorcall need this special treatment. 16963 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16964 switch (CC) { 16965 case CC_X86StdCall: 16966 case CC_X86FastCall: 16967 case CC_X86VectorCall: 16968 return true; 16969 default: 16970 break; 16971 } 16972 return false; 16973 } 16974 16975 /// Require that all of the parameter types of function be complete. Normally, 16976 /// parameter types are only required to be complete when a function is called 16977 /// or defined, but to mangle functions with certain calling conventions, the 16978 /// mangler needs to know the size of the parameter list. In this situation, 16979 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16980 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16981 /// result in a linker error. Clang doesn't implement this behavior, and instead 16982 /// attempts to error at compile time. 16983 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16984 SourceLocation Loc) { 16985 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16986 FunctionDecl *FD; 16987 ParmVarDecl *Param; 16988 16989 public: 16990 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16991 : FD(FD), Param(Param) {} 16992 16993 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16994 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16995 StringRef CCName; 16996 switch (CC) { 16997 case CC_X86StdCall: 16998 CCName = "stdcall"; 16999 break; 17000 case CC_X86FastCall: 17001 CCName = "fastcall"; 17002 break; 17003 case CC_X86VectorCall: 17004 CCName = "vectorcall"; 17005 break; 17006 default: 17007 llvm_unreachable("CC does not need mangling"); 17008 } 17009 17010 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17011 << Param->getDeclName() << FD->getDeclName() << CCName; 17012 } 17013 }; 17014 17015 for (ParmVarDecl *Param : FD->parameters()) { 17016 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17017 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17018 } 17019 } 17020 17021 namespace { 17022 enum class OdrUseContext { 17023 /// Declarations in this context are not odr-used. 17024 None, 17025 /// Declarations in this context are formally odr-used, but this is a 17026 /// dependent context. 17027 Dependent, 17028 /// Declarations in this context are odr-used but not actually used (yet). 17029 FormallyOdrUsed, 17030 /// Declarations in this context are used. 17031 Used 17032 }; 17033 } 17034 17035 /// Are we within a context in which references to resolved functions or to 17036 /// variables result in odr-use? 17037 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17038 OdrUseContext Result; 17039 17040 switch (SemaRef.ExprEvalContexts.back().Context) { 17041 case Sema::ExpressionEvaluationContext::Unevaluated: 17042 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17043 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17044 return OdrUseContext::None; 17045 17046 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17047 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17048 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17049 Result = OdrUseContext::Used; 17050 break; 17051 17052 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17053 Result = OdrUseContext::FormallyOdrUsed; 17054 break; 17055 17056 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17057 // A default argument formally results in odr-use, but doesn't actually 17058 // result in a use in any real sense until it itself is used. 17059 Result = OdrUseContext::FormallyOdrUsed; 17060 break; 17061 } 17062 17063 if (SemaRef.CurContext->isDependentContext()) 17064 return OdrUseContext::Dependent; 17065 17066 return Result; 17067 } 17068 17069 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17070 if (!Func->isConstexpr()) 17071 return false; 17072 17073 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17074 return true; 17075 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17076 return CCD && CCD->getInheritedConstructor(); 17077 } 17078 17079 /// Mark a function referenced, and check whether it is odr-used 17080 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17081 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17082 bool MightBeOdrUse) { 17083 assert(Func && "No function?"); 17084 17085 Func->setReferenced(); 17086 17087 // Recursive functions aren't really used until they're used from some other 17088 // context. 17089 bool IsRecursiveCall = CurContext == Func; 17090 17091 // C++11 [basic.def.odr]p3: 17092 // A function whose name appears as a potentially-evaluated expression is 17093 // odr-used if it is the unique lookup result or the selected member of a 17094 // set of overloaded functions [...]. 17095 // 17096 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17097 // can just check that here. 17098 OdrUseContext OdrUse = 17099 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17100 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17101 OdrUse = OdrUseContext::FormallyOdrUsed; 17102 17103 // Trivial default constructors and destructors are never actually used. 17104 // FIXME: What about other special members? 17105 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17106 OdrUse == OdrUseContext::Used) { 17107 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17108 if (Constructor->isDefaultConstructor()) 17109 OdrUse = OdrUseContext::FormallyOdrUsed; 17110 if (isa<CXXDestructorDecl>(Func)) 17111 OdrUse = OdrUseContext::FormallyOdrUsed; 17112 } 17113 17114 // C++20 [expr.const]p12: 17115 // A function [...] is needed for constant evaluation if it is [...] a 17116 // constexpr function that is named by an expression that is potentially 17117 // constant evaluated 17118 bool NeededForConstantEvaluation = 17119 isPotentiallyConstantEvaluatedContext(*this) && 17120 isImplicitlyDefinableConstexprFunction(Func); 17121 17122 // Determine whether we require a function definition to exist, per 17123 // C++11 [temp.inst]p3: 17124 // Unless a function template specialization has been explicitly 17125 // instantiated or explicitly specialized, the function template 17126 // specialization is implicitly instantiated when the specialization is 17127 // referenced in a context that requires a function definition to exist. 17128 // C++20 [temp.inst]p7: 17129 // The existence of a definition of a [...] function is considered to 17130 // affect the semantics of the program if the [...] function is needed for 17131 // constant evaluation by an expression 17132 // C++20 [basic.def.odr]p10: 17133 // Every program shall contain exactly one definition of every non-inline 17134 // function or variable that is odr-used in that program outside of a 17135 // discarded statement 17136 // C++20 [special]p1: 17137 // The implementation will implicitly define [defaulted special members] 17138 // if they are odr-used or needed for constant evaluation. 17139 // 17140 // Note that we skip the implicit instantiation of templates that are only 17141 // used in unused default arguments or by recursive calls to themselves. 17142 // This is formally non-conforming, but seems reasonable in practice. 17143 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17144 NeededForConstantEvaluation); 17145 17146 // C++14 [temp.expl.spec]p6: 17147 // If a template [...] is explicitly specialized then that specialization 17148 // shall be declared before the first use of that specialization that would 17149 // cause an implicit instantiation to take place, in every translation unit 17150 // in which such a use occurs 17151 if (NeedDefinition && 17152 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17153 Func->getMemberSpecializationInfo())) 17154 checkSpecializationVisibility(Loc, Func); 17155 17156 if (getLangOpts().CUDA) 17157 CheckCUDACall(Loc, Func); 17158 17159 if (getLangOpts().SYCLIsDevice) 17160 checkSYCLDeviceFunction(Loc, Func); 17161 17162 // If we need a definition, try to create one. 17163 if (NeedDefinition && !Func->getBody()) { 17164 runWithSufficientStackSpace(Loc, [&] { 17165 if (CXXConstructorDecl *Constructor = 17166 dyn_cast<CXXConstructorDecl>(Func)) { 17167 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17168 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17169 if (Constructor->isDefaultConstructor()) { 17170 if (Constructor->isTrivial() && 17171 !Constructor->hasAttr<DLLExportAttr>()) 17172 return; 17173 DefineImplicitDefaultConstructor(Loc, Constructor); 17174 } else if (Constructor->isCopyConstructor()) { 17175 DefineImplicitCopyConstructor(Loc, Constructor); 17176 } else if (Constructor->isMoveConstructor()) { 17177 DefineImplicitMoveConstructor(Loc, Constructor); 17178 } 17179 } else if (Constructor->getInheritedConstructor()) { 17180 DefineInheritingConstructor(Loc, Constructor); 17181 } 17182 } else if (CXXDestructorDecl *Destructor = 17183 dyn_cast<CXXDestructorDecl>(Func)) { 17184 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17185 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17186 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17187 return; 17188 DefineImplicitDestructor(Loc, Destructor); 17189 } 17190 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17191 MarkVTableUsed(Loc, Destructor->getParent()); 17192 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17193 if (MethodDecl->isOverloadedOperator() && 17194 MethodDecl->getOverloadedOperator() == OO_Equal) { 17195 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17196 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17197 if (MethodDecl->isCopyAssignmentOperator()) 17198 DefineImplicitCopyAssignment(Loc, MethodDecl); 17199 else if (MethodDecl->isMoveAssignmentOperator()) 17200 DefineImplicitMoveAssignment(Loc, MethodDecl); 17201 } 17202 } else if (isa<CXXConversionDecl>(MethodDecl) && 17203 MethodDecl->getParent()->isLambda()) { 17204 CXXConversionDecl *Conversion = 17205 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17206 if (Conversion->isLambdaToBlockPointerConversion()) 17207 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17208 else 17209 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17210 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17211 MarkVTableUsed(Loc, MethodDecl->getParent()); 17212 } 17213 17214 if (Func->isDefaulted() && !Func->isDeleted()) { 17215 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17216 if (DCK != DefaultedComparisonKind::None) 17217 DefineDefaultedComparison(Loc, Func, DCK); 17218 } 17219 17220 // Implicit instantiation of function templates and member functions of 17221 // class templates. 17222 if (Func->isImplicitlyInstantiable()) { 17223 TemplateSpecializationKind TSK = 17224 Func->getTemplateSpecializationKindForInstantiation(); 17225 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17226 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17227 if (FirstInstantiation) { 17228 PointOfInstantiation = Loc; 17229 if (auto *MSI = Func->getMemberSpecializationInfo()) 17230 MSI->setPointOfInstantiation(Loc); 17231 // FIXME: Notify listener. 17232 else 17233 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17234 } else if (TSK != TSK_ImplicitInstantiation) { 17235 // Use the point of use as the point of instantiation, instead of the 17236 // point of explicit instantiation (which we track as the actual point 17237 // of instantiation). This gives better backtraces in diagnostics. 17238 PointOfInstantiation = Loc; 17239 } 17240 17241 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17242 Func->isConstexpr()) { 17243 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17244 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17245 CodeSynthesisContexts.size()) 17246 PendingLocalImplicitInstantiations.push_back( 17247 std::make_pair(Func, PointOfInstantiation)); 17248 else if (Func->isConstexpr()) 17249 // Do not defer instantiations of constexpr functions, to avoid the 17250 // expression evaluator needing to call back into Sema if it sees a 17251 // call to such a function. 17252 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17253 else { 17254 Func->setInstantiationIsPending(true); 17255 PendingInstantiations.push_back( 17256 std::make_pair(Func, PointOfInstantiation)); 17257 // Notify the consumer that a function was implicitly instantiated. 17258 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17259 } 17260 } 17261 } else { 17262 // Walk redefinitions, as some of them may be instantiable. 17263 for (auto i : Func->redecls()) { 17264 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17265 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17266 } 17267 } 17268 }); 17269 } 17270 17271 // C++14 [except.spec]p17: 17272 // An exception-specification is considered to be needed when: 17273 // - the function is odr-used or, if it appears in an unevaluated operand, 17274 // would be odr-used if the expression were potentially-evaluated; 17275 // 17276 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17277 // function is a pure virtual function we're calling, and in that case the 17278 // function was selected by overload resolution and we need to resolve its 17279 // exception specification for a different reason. 17280 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17281 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17282 ResolveExceptionSpec(Loc, FPT); 17283 17284 // If this is the first "real" use, act on that. 17285 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17286 // Keep track of used but undefined functions. 17287 if (!Func->isDefined()) { 17288 if (mightHaveNonExternalLinkage(Func)) 17289 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17290 else if (Func->getMostRecentDecl()->isInlined() && 17291 !LangOpts.GNUInline && 17292 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17293 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17294 else if (isExternalWithNoLinkageType(Func)) 17295 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17296 } 17297 17298 // Some x86 Windows calling conventions mangle the size of the parameter 17299 // pack into the name. Computing the size of the parameters requires the 17300 // parameter types to be complete. Check that now. 17301 if (funcHasParameterSizeMangling(*this, Func)) 17302 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17303 17304 // In the MS C++ ABI, the compiler emits destructor variants where they are 17305 // used. If the destructor is used here but defined elsewhere, mark the 17306 // virtual base destructors referenced. If those virtual base destructors 17307 // are inline, this will ensure they are defined when emitting the complete 17308 // destructor variant. This checking may be redundant if the destructor is 17309 // provided later in this TU. 17310 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17311 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17312 CXXRecordDecl *Parent = Dtor->getParent(); 17313 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17314 CheckCompleteDestructorVariant(Loc, Dtor); 17315 } 17316 } 17317 17318 Func->markUsed(Context); 17319 } 17320 } 17321 17322 /// Directly mark a variable odr-used. Given a choice, prefer to use 17323 /// MarkVariableReferenced since it does additional checks and then 17324 /// calls MarkVarDeclODRUsed. 17325 /// If the variable must be captured: 17326 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17327 /// - else capture it in the DeclContext that maps to the 17328 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17329 static void 17330 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17331 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17332 // Keep track of used but undefined variables. 17333 // FIXME: We shouldn't suppress this warning for static data members. 17334 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17335 (!Var->isExternallyVisible() || Var->isInline() || 17336 SemaRef.isExternalWithNoLinkageType(Var)) && 17337 !(Var->isStaticDataMember() && Var->hasInit())) { 17338 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17339 if (old.isInvalid()) 17340 old = Loc; 17341 } 17342 QualType CaptureType, DeclRefType; 17343 if (SemaRef.LangOpts.OpenMP) 17344 SemaRef.tryCaptureOpenMPLambdas(Var); 17345 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17346 /*EllipsisLoc*/ SourceLocation(), 17347 /*BuildAndDiagnose*/ true, 17348 CaptureType, DeclRefType, 17349 FunctionScopeIndexToStopAt); 17350 17351 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17352 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17353 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17354 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17355 if (VarTarget == Sema::CVT_Host && 17356 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17357 UserTarget == Sema::CFT_Global)) { 17358 // Diagnose ODR-use of host global variables in device functions. 17359 // Reference of device global variables in host functions is allowed 17360 // through shadow variables therefore it is not diagnosed. 17361 if (SemaRef.LangOpts.CUDAIsDevice) { 17362 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17363 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17364 SemaRef.targetDiag(Var->getLocation(), 17365 Var->getType().isConstQualified() 17366 ? diag::note_cuda_const_var_unpromoted 17367 : diag::note_cuda_host_var); 17368 } 17369 } else if (VarTarget == Sema::CVT_Device && 17370 (UserTarget == Sema::CFT_Host || 17371 UserTarget == Sema::CFT_HostDevice) && 17372 !Var->hasExternalStorage()) { 17373 // Record a CUDA/HIP device side variable if it is ODR-used 17374 // by host code. This is done conservatively, when the variable is 17375 // referenced in any of the following contexts: 17376 // - a non-function context 17377 // - a host function 17378 // - a host device function 17379 // This makes the ODR-use of the device side variable by host code to 17380 // be visible in the device compilation for the compiler to be able to 17381 // emit template variables instantiated by host code only and to 17382 // externalize the static device side variable ODR-used by host code. 17383 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17384 } 17385 } 17386 17387 Var->markUsed(SemaRef.Context); 17388 } 17389 17390 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17391 SourceLocation Loc, 17392 unsigned CapturingScopeIndex) { 17393 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17394 } 17395 17396 static void 17397 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17398 ValueDecl *var, DeclContext *DC) { 17399 DeclContext *VarDC = var->getDeclContext(); 17400 17401 // If the parameter still belongs to the translation unit, then 17402 // we're actually just using one parameter in the declaration of 17403 // the next. 17404 if (isa<ParmVarDecl>(var) && 17405 isa<TranslationUnitDecl>(VarDC)) 17406 return; 17407 17408 // For C code, don't diagnose about capture if we're not actually in code 17409 // right now; it's impossible to write a non-constant expression outside of 17410 // function context, so we'll get other (more useful) diagnostics later. 17411 // 17412 // For C++, things get a bit more nasty... it would be nice to suppress this 17413 // diagnostic for certain cases like using a local variable in an array bound 17414 // for a member of a local class, but the correct predicate is not obvious. 17415 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17416 return; 17417 17418 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17419 unsigned ContextKind = 3; // unknown 17420 if (isa<CXXMethodDecl>(VarDC) && 17421 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17422 ContextKind = 2; 17423 } else if (isa<FunctionDecl>(VarDC)) { 17424 ContextKind = 0; 17425 } else if (isa<BlockDecl>(VarDC)) { 17426 ContextKind = 1; 17427 } 17428 17429 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17430 << var << ValueKind << ContextKind << VarDC; 17431 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17432 << var; 17433 17434 // FIXME: Add additional diagnostic info about class etc. which prevents 17435 // capture. 17436 } 17437 17438 17439 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17440 bool &SubCapturesAreNested, 17441 QualType &CaptureType, 17442 QualType &DeclRefType) { 17443 // Check whether we've already captured it. 17444 if (CSI->CaptureMap.count(Var)) { 17445 // If we found a capture, any subcaptures are nested. 17446 SubCapturesAreNested = true; 17447 17448 // Retrieve the capture type for this variable. 17449 CaptureType = CSI->getCapture(Var).getCaptureType(); 17450 17451 // Compute the type of an expression that refers to this variable. 17452 DeclRefType = CaptureType.getNonReferenceType(); 17453 17454 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17455 // are mutable in the sense that user can change their value - they are 17456 // private instances of the captured declarations. 17457 const Capture &Cap = CSI->getCapture(Var); 17458 if (Cap.isCopyCapture() && 17459 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17460 !(isa<CapturedRegionScopeInfo>(CSI) && 17461 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17462 DeclRefType.addConst(); 17463 return true; 17464 } 17465 return false; 17466 } 17467 17468 // Only block literals, captured statements, and lambda expressions can 17469 // capture; other scopes don't work. 17470 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17471 SourceLocation Loc, 17472 const bool Diagnose, Sema &S) { 17473 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17474 return getLambdaAwareParentOfDeclContext(DC); 17475 else if (Var->hasLocalStorage()) { 17476 if (Diagnose) 17477 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17478 } 17479 return nullptr; 17480 } 17481 17482 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17483 // certain types of variables (unnamed, variably modified types etc.) 17484 // so check for eligibility. 17485 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17486 SourceLocation Loc, 17487 const bool Diagnose, Sema &S) { 17488 17489 bool IsBlock = isa<BlockScopeInfo>(CSI); 17490 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17491 17492 // Lambdas are not allowed to capture unnamed variables 17493 // (e.g. anonymous unions). 17494 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17495 // assuming that's the intent. 17496 if (IsLambda && !Var->getDeclName()) { 17497 if (Diagnose) { 17498 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17499 S.Diag(Var->getLocation(), diag::note_declared_at); 17500 } 17501 return false; 17502 } 17503 17504 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17505 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17506 if (Diagnose) { 17507 S.Diag(Loc, diag::err_ref_vm_type); 17508 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17509 } 17510 return false; 17511 } 17512 // Prohibit structs with flexible array members too. 17513 // We cannot capture what is in the tail end of the struct. 17514 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17515 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17516 if (Diagnose) { 17517 if (IsBlock) 17518 S.Diag(Loc, diag::err_ref_flexarray_type); 17519 else 17520 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17521 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17522 } 17523 return false; 17524 } 17525 } 17526 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17527 // Lambdas and captured statements are not allowed to capture __block 17528 // variables; they don't support the expected semantics. 17529 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17530 if (Diagnose) { 17531 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17532 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17533 } 17534 return false; 17535 } 17536 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17537 if (S.getLangOpts().OpenCL && IsBlock && 17538 Var->getType()->isBlockPointerType()) { 17539 if (Diagnose) 17540 S.Diag(Loc, diag::err_opencl_block_ref_block); 17541 return false; 17542 } 17543 17544 return true; 17545 } 17546 17547 // Returns true if the capture by block was successful. 17548 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17549 SourceLocation Loc, 17550 const bool BuildAndDiagnose, 17551 QualType &CaptureType, 17552 QualType &DeclRefType, 17553 const bool Nested, 17554 Sema &S, bool Invalid) { 17555 bool ByRef = false; 17556 17557 // Blocks are not allowed to capture arrays, excepting OpenCL. 17558 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17559 // (decayed to pointers). 17560 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17561 if (BuildAndDiagnose) { 17562 S.Diag(Loc, diag::err_ref_array_type); 17563 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17564 Invalid = true; 17565 } else { 17566 return false; 17567 } 17568 } 17569 17570 // Forbid the block-capture of autoreleasing variables. 17571 if (!Invalid && 17572 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17573 if (BuildAndDiagnose) { 17574 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17575 << /*block*/ 0; 17576 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17577 Invalid = true; 17578 } else { 17579 return false; 17580 } 17581 } 17582 17583 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17584 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17585 QualType PointeeTy = PT->getPointeeType(); 17586 17587 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17588 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17589 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17590 if (BuildAndDiagnose) { 17591 SourceLocation VarLoc = Var->getLocation(); 17592 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17593 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17594 } 17595 } 17596 } 17597 17598 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17599 if (HasBlocksAttr || CaptureType->isReferenceType() || 17600 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17601 // Block capture by reference does not change the capture or 17602 // declaration reference types. 17603 ByRef = true; 17604 } else { 17605 // Block capture by copy introduces 'const'. 17606 CaptureType = CaptureType.getNonReferenceType().withConst(); 17607 DeclRefType = CaptureType; 17608 } 17609 17610 // Actually capture the variable. 17611 if (BuildAndDiagnose) 17612 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17613 CaptureType, Invalid); 17614 17615 return !Invalid; 17616 } 17617 17618 17619 /// Capture the given variable in the captured region. 17620 static bool captureInCapturedRegion( 17621 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17622 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17623 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17624 bool IsTopScope, Sema &S, bool Invalid) { 17625 // By default, capture variables by reference. 17626 bool ByRef = true; 17627 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17628 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17629 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17630 // Using an LValue reference type is consistent with Lambdas (see below). 17631 if (S.isOpenMPCapturedDecl(Var)) { 17632 bool HasConst = DeclRefType.isConstQualified(); 17633 DeclRefType = DeclRefType.getUnqualifiedType(); 17634 // Don't lose diagnostics about assignments to const. 17635 if (HasConst) 17636 DeclRefType.addConst(); 17637 } 17638 // Do not capture firstprivates in tasks. 17639 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17640 OMPC_unknown) 17641 return true; 17642 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17643 RSI->OpenMPCaptureLevel); 17644 } 17645 17646 if (ByRef) 17647 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17648 else 17649 CaptureType = DeclRefType; 17650 17651 // Actually capture the variable. 17652 if (BuildAndDiagnose) 17653 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17654 Loc, SourceLocation(), CaptureType, Invalid); 17655 17656 return !Invalid; 17657 } 17658 17659 /// Capture the given variable in the lambda. 17660 static bool captureInLambda(LambdaScopeInfo *LSI, 17661 VarDecl *Var, 17662 SourceLocation Loc, 17663 const bool BuildAndDiagnose, 17664 QualType &CaptureType, 17665 QualType &DeclRefType, 17666 const bool RefersToCapturedVariable, 17667 const Sema::TryCaptureKind Kind, 17668 SourceLocation EllipsisLoc, 17669 const bool IsTopScope, 17670 Sema &S, bool Invalid) { 17671 // Determine whether we are capturing by reference or by value. 17672 bool ByRef = false; 17673 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17674 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17675 } else { 17676 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17677 } 17678 17679 // Compute the type of the field that will capture this variable. 17680 if (ByRef) { 17681 // C++11 [expr.prim.lambda]p15: 17682 // An entity is captured by reference if it is implicitly or 17683 // explicitly captured but not captured by copy. It is 17684 // unspecified whether additional unnamed non-static data 17685 // members are declared in the closure type for entities 17686 // captured by reference. 17687 // 17688 // FIXME: It is not clear whether we want to build an lvalue reference 17689 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17690 // to do the former, while EDG does the latter. Core issue 1249 will 17691 // clarify, but for now we follow GCC because it's a more permissive and 17692 // easily defensible position. 17693 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17694 } else { 17695 // C++11 [expr.prim.lambda]p14: 17696 // For each entity captured by copy, an unnamed non-static 17697 // data member is declared in the closure type. The 17698 // declaration order of these members is unspecified. The type 17699 // of such a data member is the type of the corresponding 17700 // captured entity if the entity is not a reference to an 17701 // object, or the referenced type otherwise. [Note: If the 17702 // captured entity is a reference to a function, the 17703 // corresponding data member is also a reference to a 17704 // function. - end note ] 17705 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17706 if (!RefType->getPointeeType()->isFunctionType()) 17707 CaptureType = RefType->getPointeeType(); 17708 } 17709 17710 // Forbid the lambda copy-capture of autoreleasing variables. 17711 if (!Invalid && 17712 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17713 if (BuildAndDiagnose) { 17714 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17715 S.Diag(Var->getLocation(), diag::note_previous_decl) 17716 << Var->getDeclName(); 17717 Invalid = true; 17718 } else { 17719 return false; 17720 } 17721 } 17722 17723 // Make sure that by-copy captures are of a complete and non-abstract type. 17724 if (!Invalid && BuildAndDiagnose) { 17725 if (!CaptureType->isDependentType() && 17726 S.RequireCompleteSizedType( 17727 Loc, CaptureType, 17728 diag::err_capture_of_incomplete_or_sizeless_type, 17729 Var->getDeclName())) 17730 Invalid = true; 17731 else if (S.RequireNonAbstractType(Loc, CaptureType, 17732 diag::err_capture_of_abstract_type)) 17733 Invalid = true; 17734 } 17735 } 17736 17737 // Compute the type of a reference to this captured variable. 17738 if (ByRef) 17739 DeclRefType = CaptureType.getNonReferenceType(); 17740 else { 17741 // C++ [expr.prim.lambda]p5: 17742 // The closure type for a lambda-expression has a public inline 17743 // function call operator [...]. This function call operator is 17744 // declared const (9.3.1) if and only if the lambda-expression's 17745 // parameter-declaration-clause is not followed by mutable. 17746 DeclRefType = CaptureType.getNonReferenceType(); 17747 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17748 DeclRefType.addConst(); 17749 } 17750 17751 // Add the capture. 17752 if (BuildAndDiagnose) 17753 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17754 Loc, EllipsisLoc, CaptureType, Invalid); 17755 17756 return !Invalid; 17757 } 17758 17759 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17760 // Offer a Copy fix even if the type is dependent. 17761 if (Var->getType()->isDependentType()) 17762 return true; 17763 QualType T = Var->getType().getNonReferenceType(); 17764 if (T.isTriviallyCopyableType(Context)) 17765 return true; 17766 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17767 17768 if (!(RD = RD->getDefinition())) 17769 return false; 17770 if (RD->hasSimpleCopyConstructor()) 17771 return true; 17772 if (RD->hasUserDeclaredCopyConstructor()) 17773 for (CXXConstructorDecl *Ctor : RD->ctors()) 17774 if (Ctor->isCopyConstructor()) 17775 return !Ctor->isDeleted(); 17776 } 17777 return false; 17778 } 17779 17780 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17781 /// default capture. Fixes may be omitted if they aren't allowed by the 17782 /// standard, for example we can't emit a default copy capture fix-it if we 17783 /// already explicitly copy capture capture another variable. 17784 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17785 VarDecl *Var) { 17786 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17787 // Don't offer Capture by copy of default capture by copy fixes if Var is 17788 // known not to be copy constructible. 17789 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17790 17791 SmallString<32> FixBuffer; 17792 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17793 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17794 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17795 if (ShouldOfferCopyFix) { 17796 // Offer fixes to insert an explicit capture for the variable. 17797 // [] -> [VarName] 17798 // [OtherCapture] -> [OtherCapture, VarName] 17799 FixBuffer.assign({Separator, Var->getName()}); 17800 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17801 << Var << /*value*/ 0 17802 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17803 } 17804 // As above but capture by reference. 17805 FixBuffer.assign({Separator, "&", Var->getName()}); 17806 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17807 << Var << /*reference*/ 1 17808 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17809 } 17810 17811 // Only try to offer default capture if there are no captures excluding this 17812 // and init captures. 17813 // [this]: OK. 17814 // [X = Y]: OK. 17815 // [&A, &B]: Don't offer. 17816 // [A, B]: Don't offer. 17817 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17818 return !C.isThisCapture() && !C.isInitCapture(); 17819 })) 17820 return; 17821 17822 // The default capture specifiers, '=' or '&', must appear first in the 17823 // capture body. 17824 SourceLocation DefaultInsertLoc = 17825 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17826 17827 if (ShouldOfferCopyFix) { 17828 bool CanDefaultCopyCapture = true; 17829 // [=, *this] OK since c++17 17830 // [=, this] OK since c++20 17831 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17832 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17833 ? LSI->getCXXThisCapture().isCopyCapture() 17834 : false; 17835 // We can't use default capture by copy if any captures already specified 17836 // capture by copy. 17837 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17838 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17839 })) { 17840 FixBuffer.assign({"=", Separator}); 17841 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17842 << /*value*/ 0 17843 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17844 } 17845 } 17846 17847 // We can't use default capture by reference if any captures already specified 17848 // capture by reference. 17849 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17850 return !C.isInitCapture() && C.isReferenceCapture() && 17851 !C.isThisCapture(); 17852 })) { 17853 FixBuffer.assign({"&", Separator}); 17854 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17855 << /*reference*/ 1 17856 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17857 } 17858 } 17859 17860 bool Sema::tryCaptureVariable( 17861 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17862 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17863 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17864 // An init-capture is notionally from the context surrounding its 17865 // declaration, but its parent DC is the lambda class. 17866 DeclContext *VarDC = Var->getDeclContext(); 17867 if (Var->isInitCapture()) 17868 VarDC = VarDC->getParent(); 17869 17870 DeclContext *DC = CurContext; 17871 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17872 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17873 // We need to sync up the Declaration Context with the 17874 // FunctionScopeIndexToStopAt 17875 if (FunctionScopeIndexToStopAt) { 17876 unsigned FSIndex = FunctionScopes.size() - 1; 17877 while (FSIndex != MaxFunctionScopesIndex) { 17878 DC = getLambdaAwareParentOfDeclContext(DC); 17879 --FSIndex; 17880 } 17881 } 17882 17883 17884 // If the variable is declared in the current context, there is no need to 17885 // capture it. 17886 if (VarDC == DC) return true; 17887 17888 // Capture global variables if it is required to use private copy of this 17889 // variable. 17890 bool IsGlobal = !Var->hasLocalStorage(); 17891 if (IsGlobal && 17892 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17893 MaxFunctionScopesIndex))) 17894 return true; 17895 Var = Var->getCanonicalDecl(); 17896 17897 // Walk up the stack to determine whether we can capture the variable, 17898 // performing the "simple" checks that don't depend on type. We stop when 17899 // we've either hit the declared scope of the variable or find an existing 17900 // capture of that variable. We start from the innermost capturing-entity 17901 // (the DC) and ensure that all intervening capturing-entities 17902 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17903 // declcontext can either capture the variable or have already captured 17904 // the variable. 17905 CaptureType = Var->getType(); 17906 DeclRefType = CaptureType.getNonReferenceType(); 17907 bool Nested = false; 17908 bool Explicit = (Kind != TryCapture_Implicit); 17909 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17910 do { 17911 // Only block literals, captured statements, and lambda expressions can 17912 // capture; other scopes don't work. 17913 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17914 ExprLoc, 17915 BuildAndDiagnose, 17916 *this); 17917 // We need to check for the parent *first* because, if we *have* 17918 // private-captured a global variable, we need to recursively capture it in 17919 // intermediate blocks, lambdas, etc. 17920 if (!ParentDC) { 17921 if (IsGlobal) { 17922 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17923 break; 17924 } 17925 return true; 17926 } 17927 17928 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17929 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17930 17931 17932 // Check whether we've already captured it. 17933 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17934 DeclRefType)) { 17935 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17936 break; 17937 } 17938 // If we are instantiating a generic lambda call operator body, 17939 // we do not want to capture new variables. What was captured 17940 // during either a lambdas transformation or initial parsing 17941 // should be used. 17942 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17943 if (BuildAndDiagnose) { 17944 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17945 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17946 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17947 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17948 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17949 buildLambdaCaptureFixit(*this, LSI, Var); 17950 } else 17951 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17952 } 17953 return true; 17954 } 17955 17956 // Try to capture variable-length arrays types. 17957 if (Var->getType()->isVariablyModifiedType()) { 17958 // We're going to walk down into the type and look for VLA 17959 // expressions. 17960 QualType QTy = Var->getType(); 17961 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17962 QTy = PVD->getOriginalType(); 17963 captureVariablyModifiedType(Context, QTy, CSI); 17964 } 17965 17966 if (getLangOpts().OpenMP) { 17967 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17968 // OpenMP private variables should not be captured in outer scope, so 17969 // just break here. Similarly, global variables that are captured in a 17970 // target region should not be captured outside the scope of the region. 17971 if (RSI->CapRegionKind == CR_OpenMP) { 17972 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17973 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17974 // If the variable is private (i.e. not captured) and has variably 17975 // modified type, we still need to capture the type for correct 17976 // codegen in all regions, associated with the construct. Currently, 17977 // it is captured in the innermost captured region only. 17978 if (IsOpenMPPrivateDecl != OMPC_unknown && 17979 Var->getType()->isVariablyModifiedType()) { 17980 QualType QTy = Var->getType(); 17981 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17982 QTy = PVD->getOriginalType(); 17983 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17984 I < E; ++I) { 17985 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17986 FunctionScopes[FunctionScopesIndex - I]); 17987 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17988 "Wrong number of captured regions associated with the " 17989 "OpenMP construct."); 17990 captureVariablyModifiedType(Context, QTy, OuterRSI); 17991 } 17992 } 17993 bool IsTargetCap = 17994 IsOpenMPPrivateDecl != OMPC_private && 17995 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17996 RSI->OpenMPCaptureLevel); 17997 // Do not capture global if it is not privatized in outer regions. 17998 bool IsGlobalCap = 17999 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 18000 RSI->OpenMPCaptureLevel); 18001 18002 // When we detect target captures we are looking from inside the 18003 // target region, therefore we need to propagate the capture from the 18004 // enclosing region. Therefore, the capture is not initially nested. 18005 if (IsTargetCap) 18006 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18007 18008 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18009 (IsGlobal && !IsGlobalCap)) { 18010 Nested = !IsTargetCap; 18011 bool HasConst = DeclRefType.isConstQualified(); 18012 DeclRefType = DeclRefType.getUnqualifiedType(); 18013 // Don't lose diagnostics about assignments to const. 18014 if (HasConst) 18015 DeclRefType.addConst(); 18016 CaptureType = Context.getLValueReferenceType(DeclRefType); 18017 break; 18018 } 18019 } 18020 } 18021 } 18022 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18023 // No capture-default, and this is not an explicit capture 18024 // so cannot capture this variable. 18025 if (BuildAndDiagnose) { 18026 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18027 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18028 auto *LSI = cast<LambdaScopeInfo>(CSI); 18029 if (LSI->Lambda) { 18030 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18031 buildLambdaCaptureFixit(*this, LSI, Var); 18032 } 18033 // FIXME: If we error out because an outer lambda can not implicitly 18034 // capture a variable that an inner lambda explicitly captures, we 18035 // should have the inner lambda do the explicit capture - because 18036 // it makes for cleaner diagnostics later. This would purely be done 18037 // so that the diagnostic does not misleadingly claim that a variable 18038 // can not be captured by a lambda implicitly even though it is captured 18039 // explicitly. Suggestion: 18040 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18041 // at the function head 18042 // - cache the StartingDeclContext - this must be a lambda 18043 // - captureInLambda in the innermost lambda the variable. 18044 } 18045 return true; 18046 } 18047 18048 FunctionScopesIndex--; 18049 DC = ParentDC; 18050 Explicit = false; 18051 } while (!VarDC->Equals(DC)); 18052 18053 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18054 // computing the type of the capture at each step, checking type-specific 18055 // requirements, and adding captures if requested. 18056 // If the variable had already been captured previously, we start capturing 18057 // at the lambda nested within that one. 18058 bool Invalid = false; 18059 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18060 ++I) { 18061 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18062 18063 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18064 // certain types of variables (unnamed, variably modified types etc.) 18065 // so check for eligibility. 18066 if (!Invalid) 18067 Invalid = 18068 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18069 18070 // After encountering an error, if we're actually supposed to capture, keep 18071 // capturing in nested contexts to suppress any follow-on diagnostics. 18072 if (Invalid && !BuildAndDiagnose) 18073 return true; 18074 18075 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18076 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18077 DeclRefType, Nested, *this, Invalid); 18078 Nested = true; 18079 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18080 Invalid = !captureInCapturedRegion( 18081 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18082 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18083 Nested = true; 18084 } else { 18085 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18086 Invalid = 18087 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18088 DeclRefType, Nested, Kind, EllipsisLoc, 18089 /*IsTopScope*/ I == N - 1, *this, Invalid); 18090 Nested = true; 18091 } 18092 18093 if (Invalid && !BuildAndDiagnose) 18094 return true; 18095 } 18096 return Invalid; 18097 } 18098 18099 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18100 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18101 QualType CaptureType; 18102 QualType DeclRefType; 18103 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18104 /*BuildAndDiagnose=*/true, CaptureType, 18105 DeclRefType, nullptr); 18106 } 18107 18108 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18109 QualType CaptureType; 18110 QualType DeclRefType; 18111 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18112 /*BuildAndDiagnose=*/false, CaptureType, 18113 DeclRefType, nullptr); 18114 } 18115 18116 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18117 QualType CaptureType; 18118 QualType DeclRefType; 18119 18120 // Determine whether we can capture this variable. 18121 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18122 /*BuildAndDiagnose=*/false, CaptureType, 18123 DeclRefType, nullptr)) 18124 return QualType(); 18125 18126 return DeclRefType; 18127 } 18128 18129 namespace { 18130 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18131 // The produced TemplateArgumentListInfo* points to data stored within this 18132 // object, so should only be used in contexts where the pointer will not be 18133 // used after the CopiedTemplateArgs object is destroyed. 18134 class CopiedTemplateArgs { 18135 bool HasArgs; 18136 TemplateArgumentListInfo TemplateArgStorage; 18137 public: 18138 template<typename RefExpr> 18139 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18140 if (HasArgs) 18141 E->copyTemplateArgumentsInto(TemplateArgStorage); 18142 } 18143 operator TemplateArgumentListInfo*() 18144 #ifdef __has_cpp_attribute 18145 #if __has_cpp_attribute(clang::lifetimebound) 18146 [[clang::lifetimebound]] 18147 #endif 18148 #endif 18149 { 18150 return HasArgs ? &TemplateArgStorage : nullptr; 18151 } 18152 }; 18153 } 18154 18155 /// Walk the set of potential results of an expression and mark them all as 18156 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18157 /// 18158 /// \return A new expression if we found any potential results, ExprEmpty() if 18159 /// not, and ExprError() if we diagnosed an error. 18160 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18161 NonOdrUseReason NOUR) { 18162 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18163 // an object that satisfies the requirements for appearing in a 18164 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18165 // is immediately applied." This function handles the lvalue-to-rvalue 18166 // conversion part. 18167 // 18168 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18169 // transform it into the relevant kind of non-odr-use node and rebuild the 18170 // tree of nodes leading to it. 18171 // 18172 // This is a mini-TreeTransform that only transforms a restricted subset of 18173 // nodes (and only certain operands of them). 18174 18175 // Rebuild a subexpression. 18176 auto Rebuild = [&](Expr *Sub) { 18177 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18178 }; 18179 18180 // Check whether a potential result satisfies the requirements of NOUR. 18181 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18182 // Any entity other than a VarDecl is always odr-used whenever it's named 18183 // in a potentially-evaluated expression. 18184 auto *VD = dyn_cast<VarDecl>(D); 18185 if (!VD) 18186 return true; 18187 18188 // C++2a [basic.def.odr]p4: 18189 // A variable x whose name appears as a potentially-evalauted expression 18190 // e is odr-used by e unless 18191 // -- x is a reference that is usable in constant expressions, or 18192 // -- x is a variable of non-reference type that is usable in constant 18193 // expressions and has no mutable subobjects, and e is an element of 18194 // the set of potential results of an expression of 18195 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18196 // conversion is applied, or 18197 // -- x is a variable of non-reference type, and e is an element of the 18198 // set of potential results of a discarded-value expression to which 18199 // the lvalue-to-rvalue conversion is not applied 18200 // 18201 // We check the first bullet and the "potentially-evaluated" condition in 18202 // BuildDeclRefExpr. We check the type requirements in the second bullet 18203 // in CheckLValueToRValueConversionOperand below. 18204 switch (NOUR) { 18205 case NOUR_None: 18206 case NOUR_Unevaluated: 18207 llvm_unreachable("unexpected non-odr-use-reason"); 18208 18209 case NOUR_Constant: 18210 // Constant references were handled when they were built. 18211 if (VD->getType()->isReferenceType()) 18212 return true; 18213 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18214 if (RD->hasMutableFields()) 18215 return true; 18216 if (!VD->isUsableInConstantExpressions(S.Context)) 18217 return true; 18218 break; 18219 18220 case NOUR_Discarded: 18221 if (VD->getType()->isReferenceType()) 18222 return true; 18223 break; 18224 } 18225 return false; 18226 }; 18227 18228 // Mark that this expression does not constitute an odr-use. 18229 auto MarkNotOdrUsed = [&] { 18230 S.MaybeODRUseExprs.remove(E); 18231 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18232 LSI->markVariableExprAsNonODRUsed(E); 18233 }; 18234 18235 // C++2a [basic.def.odr]p2: 18236 // The set of potential results of an expression e is defined as follows: 18237 switch (E->getStmtClass()) { 18238 // -- If e is an id-expression, ... 18239 case Expr::DeclRefExprClass: { 18240 auto *DRE = cast<DeclRefExpr>(E); 18241 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18242 break; 18243 18244 // Rebuild as a non-odr-use DeclRefExpr. 18245 MarkNotOdrUsed(); 18246 return DeclRefExpr::Create( 18247 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18248 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18249 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18250 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18251 } 18252 18253 case Expr::FunctionParmPackExprClass: { 18254 auto *FPPE = cast<FunctionParmPackExpr>(E); 18255 // If any of the declarations in the pack is odr-used, then the expression 18256 // as a whole constitutes an odr-use. 18257 for (VarDecl *D : *FPPE) 18258 if (IsPotentialResultOdrUsed(D)) 18259 return ExprEmpty(); 18260 18261 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18262 // nothing cares about whether we marked this as an odr-use, but it might 18263 // be useful for non-compiler tools. 18264 MarkNotOdrUsed(); 18265 break; 18266 } 18267 18268 // -- If e is a subscripting operation with an array operand... 18269 case Expr::ArraySubscriptExprClass: { 18270 auto *ASE = cast<ArraySubscriptExpr>(E); 18271 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18272 if (!OldBase->getType()->isArrayType()) 18273 break; 18274 ExprResult Base = Rebuild(OldBase); 18275 if (!Base.isUsable()) 18276 return Base; 18277 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18278 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18279 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18280 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18281 ASE->getRBracketLoc()); 18282 } 18283 18284 case Expr::MemberExprClass: { 18285 auto *ME = cast<MemberExpr>(E); 18286 // -- If e is a class member access expression [...] naming a non-static 18287 // data member... 18288 if (isa<FieldDecl>(ME->getMemberDecl())) { 18289 ExprResult Base = Rebuild(ME->getBase()); 18290 if (!Base.isUsable()) 18291 return Base; 18292 return MemberExpr::Create( 18293 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18294 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18295 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18296 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18297 ME->getObjectKind(), ME->isNonOdrUse()); 18298 } 18299 18300 if (ME->getMemberDecl()->isCXXInstanceMember()) 18301 break; 18302 18303 // -- If e is a class member access expression naming a static data member, 18304 // ... 18305 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18306 break; 18307 18308 // Rebuild as a non-odr-use MemberExpr. 18309 MarkNotOdrUsed(); 18310 return MemberExpr::Create( 18311 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18312 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18313 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18314 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18315 } 18316 18317 case Expr::BinaryOperatorClass: { 18318 auto *BO = cast<BinaryOperator>(E); 18319 Expr *LHS = BO->getLHS(); 18320 Expr *RHS = BO->getRHS(); 18321 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18322 if (BO->getOpcode() == BO_PtrMemD) { 18323 ExprResult Sub = Rebuild(LHS); 18324 if (!Sub.isUsable()) 18325 return Sub; 18326 LHS = Sub.get(); 18327 // -- If e is a comma expression, ... 18328 } else if (BO->getOpcode() == BO_Comma) { 18329 ExprResult Sub = Rebuild(RHS); 18330 if (!Sub.isUsable()) 18331 return Sub; 18332 RHS = Sub.get(); 18333 } else { 18334 break; 18335 } 18336 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18337 LHS, RHS); 18338 } 18339 18340 // -- If e has the form (e1)... 18341 case Expr::ParenExprClass: { 18342 auto *PE = cast<ParenExpr>(E); 18343 ExprResult Sub = Rebuild(PE->getSubExpr()); 18344 if (!Sub.isUsable()) 18345 return Sub; 18346 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18347 } 18348 18349 // -- If e is a glvalue conditional expression, ... 18350 // We don't apply this to a binary conditional operator. FIXME: Should we? 18351 case Expr::ConditionalOperatorClass: { 18352 auto *CO = cast<ConditionalOperator>(E); 18353 ExprResult LHS = Rebuild(CO->getLHS()); 18354 if (LHS.isInvalid()) 18355 return ExprError(); 18356 ExprResult RHS = Rebuild(CO->getRHS()); 18357 if (RHS.isInvalid()) 18358 return ExprError(); 18359 if (!LHS.isUsable() && !RHS.isUsable()) 18360 return ExprEmpty(); 18361 if (!LHS.isUsable()) 18362 LHS = CO->getLHS(); 18363 if (!RHS.isUsable()) 18364 RHS = CO->getRHS(); 18365 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18366 CO->getCond(), LHS.get(), RHS.get()); 18367 } 18368 18369 // [Clang extension] 18370 // -- If e has the form __extension__ e1... 18371 case Expr::UnaryOperatorClass: { 18372 auto *UO = cast<UnaryOperator>(E); 18373 if (UO->getOpcode() != UO_Extension) 18374 break; 18375 ExprResult Sub = Rebuild(UO->getSubExpr()); 18376 if (!Sub.isUsable()) 18377 return Sub; 18378 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18379 Sub.get()); 18380 } 18381 18382 // [Clang extension] 18383 // -- If e has the form _Generic(...), the set of potential results is the 18384 // union of the sets of potential results of the associated expressions. 18385 case Expr::GenericSelectionExprClass: { 18386 auto *GSE = cast<GenericSelectionExpr>(E); 18387 18388 SmallVector<Expr *, 4> AssocExprs; 18389 bool AnyChanged = false; 18390 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18391 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18392 if (AssocExpr.isInvalid()) 18393 return ExprError(); 18394 if (AssocExpr.isUsable()) { 18395 AssocExprs.push_back(AssocExpr.get()); 18396 AnyChanged = true; 18397 } else { 18398 AssocExprs.push_back(OrigAssocExpr); 18399 } 18400 } 18401 18402 return AnyChanged ? S.CreateGenericSelectionExpr( 18403 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18404 GSE->getRParenLoc(), GSE->getControllingExpr(), 18405 GSE->getAssocTypeSourceInfos(), AssocExprs) 18406 : ExprEmpty(); 18407 } 18408 18409 // [Clang extension] 18410 // -- If e has the form __builtin_choose_expr(...), the set of potential 18411 // results is the union of the sets of potential results of the 18412 // second and third subexpressions. 18413 case Expr::ChooseExprClass: { 18414 auto *CE = cast<ChooseExpr>(E); 18415 18416 ExprResult LHS = Rebuild(CE->getLHS()); 18417 if (LHS.isInvalid()) 18418 return ExprError(); 18419 18420 ExprResult RHS = Rebuild(CE->getLHS()); 18421 if (RHS.isInvalid()) 18422 return ExprError(); 18423 18424 if (!LHS.get() && !RHS.get()) 18425 return ExprEmpty(); 18426 if (!LHS.isUsable()) 18427 LHS = CE->getLHS(); 18428 if (!RHS.isUsable()) 18429 RHS = CE->getRHS(); 18430 18431 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18432 RHS.get(), CE->getRParenLoc()); 18433 } 18434 18435 // Step through non-syntactic nodes. 18436 case Expr::ConstantExprClass: { 18437 auto *CE = cast<ConstantExpr>(E); 18438 ExprResult Sub = Rebuild(CE->getSubExpr()); 18439 if (!Sub.isUsable()) 18440 return Sub; 18441 return ConstantExpr::Create(S.Context, Sub.get()); 18442 } 18443 18444 // We could mostly rely on the recursive rebuilding to rebuild implicit 18445 // casts, but not at the top level, so rebuild them here. 18446 case Expr::ImplicitCastExprClass: { 18447 auto *ICE = cast<ImplicitCastExpr>(E); 18448 // Only step through the narrow set of cast kinds we expect to encounter. 18449 // Anything else suggests we've left the region in which potential results 18450 // can be found. 18451 switch (ICE->getCastKind()) { 18452 case CK_NoOp: 18453 case CK_DerivedToBase: 18454 case CK_UncheckedDerivedToBase: { 18455 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18456 if (!Sub.isUsable()) 18457 return Sub; 18458 CXXCastPath Path(ICE->path()); 18459 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18460 ICE->getValueKind(), &Path); 18461 } 18462 18463 default: 18464 break; 18465 } 18466 break; 18467 } 18468 18469 default: 18470 break; 18471 } 18472 18473 // Can't traverse through this node. Nothing to do. 18474 return ExprEmpty(); 18475 } 18476 18477 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18478 // Check whether the operand is or contains an object of non-trivial C union 18479 // type. 18480 if (E->getType().isVolatileQualified() && 18481 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18482 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18483 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18484 Sema::NTCUC_LValueToRValueVolatile, 18485 NTCUK_Destruct|NTCUK_Copy); 18486 18487 // C++2a [basic.def.odr]p4: 18488 // [...] an expression of non-volatile-qualified non-class type to which 18489 // the lvalue-to-rvalue conversion is applied [...] 18490 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18491 return E; 18492 18493 ExprResult Result = 18494 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18495 if (Result.isInvalid()) 18496 return ExprError(); 18497 return Result.get() ? Result : E; 18498 } 18499 18500 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18501 Res = CorrectDelayedTyposInExpr(Res); 18502 18503 if (!Res.isUsable()) 18504 return Res; 18505 18506 // If a constant-expression is a reference to a variable where we delay 18507 // deciding whether it is an odr-use, just assume we will apply the 18508 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18509 // (a non-type template argument), we have special handling anyway. 18510 return CheckLValueToRValueConversionOperand(Res.get()); 18511 } 18512 18513 void Sema::CleanupVarDeclMarking() { 18514 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18515 // call. 18516 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18517 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18518 18519 for (Expr *E : LocalMaybeODRUseExprs) { 18520 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18521 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18522 DRE->getLocation(), *this); 18523 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18524 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18525 *this); 18526 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18527 for (VarDecl *VD : *FP) 18528 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18529 } else { 18530 llvm_unreachable("Unexpected expression"); 18531 } 18532 } 18533 18534 assert(MaybeODRUseExprs.empty() && 18535 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18536 } 18537 18538 static void DoMarkVarDeclReferenced( 18539 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18540 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18541 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18542 isa<FunctionParmPackExpr>(E)) && 18543 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18544 Var->setReferenced(); 18545 18546 if (Var->isInvalidDecl()) 18547 return; 18548 18549 auto *MSI = Var->getMemberSpecializationInfo(); 18550 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18551 : Var->getTemplateSpecializationKind(); 18552 18553 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18554 bool UsableInConstantExpr = 18555 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18556 18557 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18558 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18559 } 18560 18561 // C++20 [expr.const]p12: 18562 // A variable [...] is needed for constant evaluation if it is [...] a 18563 // variable whose name appears as a potentially constant evaluated 18564 // expression that is either a contexpr variable or is of non-volatile 18565 // const-qualified integral type or of reference type 18566 bool NeededForConstantEvaluation = 18567 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18568 18569 bool NeedDefinition = 18570 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18571 18572 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18573 "Can't instantiate a partial template specialization."); 18574 18575 // If this might be a member specialization of a static data member, check 18576 // the specialization is visible. We already did the checks for variable 18577 // template specializations when we created them. 18578 if (NeedDefinition && TSK != TSK_Undeclared && 18579 !isa<VarTemplateSpecializationDecl>(Var)) 18580 SemaRef.checkSpecializationVisibility(Loc, Var); 18581 18582 // Perform implicit instantiation of static data members, static data member 18583 // templates of class templates, and variable template specializations. Delay 18584 // instantiations of variable templates, except for those that could be used 18585 // in a constant expression. 18586 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18587 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18588 // instantiation declaration if a variable is usable in a constant 18589 // expression (among other cases). 18590 bool TryInstantiating = 18591 TSK == TSK_ImplicitInstantiation || 18592 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18593 18594 if (TryInstantiating) { 18595 SourceLocation PointOfInstantiation = 18596 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18597 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18598 if (FirstInstantiation) { 18599 PointOfInstantiation = Loc; 18600 if (MSI) 18601 MSI->setPointOfInstantiation(PointOfInstantiation); 18602 // FIXME: Notify listener. 18603 else 18604 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18605 } 18606 18607 if (UsableInConstantExpr) { 18608 // Do not defer instantiations of variables that could be used in a 18609 // constant expression. 18610 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18611 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18612 }); 18613 18614 // Re-set the member to trigger a recomputation of the dependence bits 18615 // for the expression. 18616 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18617 DRE->setDecl(DRE->getDecl()); 18618 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18619 ME->setMemberDecl(ME->getMemberDecl()); 18620 } else if (FirstInstantiation || 18621 isa<VarTemplateSpecializationDecl>(Var)) { 18622 // FIXME: For a specialization of a variable template, we don't 18623 // distinguish between "declaration and type implicitly instantiated" 18624 // and "implicit instantiation of definition requested", so we have 18625 // no direct way to avoid enqueueing the pending instantiation 18626 // multiple times. 18627 SemaRef.PendingInstantiations 18628 .push_back(std::make_pair(Var, PointOfInstantiation)); 18629 } 18630 } 18631 } 18632 18633 // C++2a [basic.def.odr]p4: 18634 // A variable x whose name appears as a potentially-evaluated expression e 18635 // is odr-used by e unless 18636 // -- x is a reference that is usable in constant expressions 18637 // -- x is a variable of non-reference type that is usable in constant 18638 // expressions and has no mutable subobjects [FIXME], and e is an 18639 // element of the set of potential results of an expression of 18640 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18641 // conversion is applied 18642 // -- x is a variable of non-reference type, and e is an element of the set 18643 // of potential results of a discarded-value expression to which the 18644 // lvalue-to-rvalue conversion is not applied [FIXME] 18645 // 18646 // We check the first part of the second bullet here, and 18647 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18648 // FIXME: To get the third bullet right, we need to delay this even for 18649 // variables that are not usable in constant expressions. 18650 18651 // If we already know this isn't an odr-use, there's nothing more to do. 18652 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18653 if (DRE->isNonOdrUse()) 18654 return; 18655 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18656 if (ME->isNonOdrUse()) 18657 return; 18658 18659 switch (OdrUse) { 18660 case OdrUseContext::None: 18661 assert((!E || isa<FunctionParmPackExpr>(E)) && 18662 "missing non-odr-use marking for unevaluated decl ref"); 18663 break; 18664 18665 case OdrUseContext::FormallyOdrUsed: 18666 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18667 // behavior. 18668 break; 18669 18670 case OdrUseContext::Used: 18671 // If we might later find that this expression isn't actually an odr-use, 18672 // delay the marking. 18673 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18674 SemaRef.MaybeODRUseExprs.insert(E); 18675 else 18676 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18677 break; 18678 18679 case OdrUseContext::Dependent: 18680 // If this is a dependent context, we don't need to mark variables as 18681 // odr-used, but we may still need to track them for lambda capture. 18682 // FIXME: Do we also need to do this inside dependent typeid expressions 18683 // (which are modeled as unevaluated at this point)? 18684 const bool RefersToEnclosingScope = 18685 (SemaRef.CurContext != Var->getDeclContext() && 18686 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18687 if (RefersToEnclosingScope) { 18688 LambdaScopeInfo *const LSI = 18689 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18690 if (LSI && (!LSI->CallOperator || 18691 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18692 // If a variable could potentially be odr-used, defer marking it so 18693 // until we finish analyzing the full expression for any 18694 // lvalue-to-rvalue 18695 // or discarded value conversions that would obviate odr-use. 18696 // Add it to the list of potential captures that will be analyzed 18697 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18698 // unless the variable is a reference that was initialized by a constant 18699 // expression (this will never need to be captured or odr-used). 18700 // 18701 // FIXME: We can simplify this a lot after implementing P0588R1. 18702 assert(E && "Capture variable should be used in an expression."); 18703 if (!Var->getType()->isReferenceType() || 18704 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18705 LSI->addPotentialCapture(E->IgnoreParens()); 18706 } 18707 } 18708 break; 18709 } 18710 } 18711 18712 /// Mark a variable referenced, and check whether it is odr-used 18713 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18714 /// used directly for normal expressions referring to VarDecl. 18715 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18716 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18717 } 18718 18719 static void 18720 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18721 bool MightBeOdrUse, 18722 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18723 if (SemaRef.isInOpenMPDeclareTargetContext()) 18724 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18725 18726 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18727 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18728 return; 18729 } 18730 18731 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18732 18733 // If this is a call to a method via a cast, also mark the method in the 18734 // derived class used in case codegen can devirtualize the call. 18735 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18736 if (!ME) 18737 return; 18738 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18739 if (!MD) 18740 return; 18741 // Only attempt to devirtualize if this is truly a virtual call. 18742 bool IsVirtualCall = MD->isVirtual() && 18743 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18744 if (!IsVirtualCall) 18745 return; 18746 18747 // If it's possible to devirtualize the call, mark the called function 18748 // referenced. 18749 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18750 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18751 if (DM) 18752 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18753 } 18754 18755 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18756 /// 18757 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18758 /// handled with care if the DeclRefExpr is not newly-created. 18759 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18760 // TODO: update this with DR# once a defect report is filed. 18761 // C++11 defect. The address of a pure member should not be an ODR use, even 18762 // if it's a qualified reference. 18763 bool OdrUse = true; 18764 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18765 if (Method->isVirtual() && 18766 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18767 OdrUse = false; 18768 18769 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18770 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18771 FD->isConsteval() && !RebuildingImmediateInvocation) 18772 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18773 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18774 RefsMinusAssignments); 18775 } 18776 18777 /// Perform reference-marking and odr-use handling for a MemberExpr. 18778 void Sema::MarkMemberReferenced(MemberExpr *E) { 18779 // C++11 [basic.def.odr]p2: 18780 // A non-overloaded function whose name appears as a potentially-evaluated 18781 // expression or a member of a set of candidate functions, if selected by 18782 // overload resolution when referred to from a potentially-evaluated 18783 // expression, is odr-used, unless it is a pure virtual function and its 18784 // name is not explicitly qualified. 18785 bool MightBeOdrUse = true; 18786 if (E->performsVirtualDispatch(getLangOpts())) { 18787 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18788 if (Method->isPure()) 18789 MightBeOdrUse = false; 18790 } 18791 SourceLocation Loc = 18792 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18793 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18794 RefsMinusAssignments); 18795 } 18796 18797 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18798 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18799 for (VarDecl *VD : *E) 18800 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18801 RefsMinusAssignments); 18802 } 18803 18804 /// Perform marking for a reference to an arbitrary declaration. It 18805 /// marks the declaration referenced, and performs odr-use checking for 18806 /// functions and variables. This method should not be used when building a 18807 /// normal expression which refers to a variable. 18808 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18809 bool MightBeOdrUse) { 18810 if (MightBeOdrUse) { 18811 if (auto *VD = dyn_cast<VarDecl>(D)) { 18812 MarkVariableReferenced(Loc, VD); 18813 return; 18814 } 18815 } 18816 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18817 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18818 return; 18819 } 18820 D->setReferenced(); 18821 } 18822 18823 namespace { 18824 // Mark all of the declarations used by a type as referenced. 18825 // FIXME: Not fully implemented yet! We need to have a better understanding 18826 // of when we're entering a context we should not recurse into. 18827 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18828 // TreeTransforms rebuilding the type in a new context. Rather than 18829 // duplicating the TreeTransform logic, we should consider reusing it here. 18830 // Currently that causes problems when rebuilding LambdaExprs. 18831 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18832 Sema &S; 18833 SourceLocation Loc; 18834 18835 public: 18836 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18837 18838 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18839 18840 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18841 }; 18842 } 18843 18844 bool MarkReferencedDecls::TraverseTemplateArgument( 18845 const TemplateArgument &Arg) { 18846 { 18847 // A non-type template argument is a constant-evaluated context. 18848 EnterExpressionEvaluationContext Evaluated( 18849 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18850 if (Arg.getKind() == TemplateArgument::Declaration) { 18851 if (Decl *D = Arg.getAsDecl()) 18852 S.MarkAnyDeclReferenced(Loc, D, true); 18853 } else if (Arg.getKind() == TemplateArgument::Expression) { 18854 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18855 } 18856 } 18857 18858 return Inherited::TraverseTemplateArgument(Arg); 18859 } 18860 18861 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18862 MarkReferencedDecls Marker(*this, Loc); 18863 Marker.TraverseType(T); 18864 } 18865 18866 namespace { 18867 /// Helper class that marks all of the declarations referenced by 18868 /// potentially-evaluated subexpressions as "referenced". 18869 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18870 public: 18871 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18872 bool SkipLocalVariables; 18873 18874 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18875 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18876 18877 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18878 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18879 } 18880 18881 void VisitDeclRefExpr(DeclRefExpr *E) { 18882 // If we were asked not to visit local variables, don't. 18883 if (SkipLocalVariables) { 18884 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18885 if (VD->hasLocalStorage()) 18886 return; 18887 } 18888 18889 // FIXME: This can trigger the instantiation of the initializer of a 18890 // variable, which can cause the expression to become value-dependent 18891 // or error-dependent. Do we need to propagate the new dependence bits? 18892 S.MarkDeclRefReferenced(E); 18893 } 18894 18895 void VisitMemberExpr(MemberExpr *E) { 18896 S.MarkMemberReferenced(E); 18897 Visit(E->getBase()); 18898 } 18899 }; 18900 } // namespace 18901 18902 /// Mark any declarations that appear within this expression or any 18903 /// potentially-evaluated subexpressions as "referenced". 18904 /// 18905 /// \param SkipLocalVariables If true, don't mark local variables as 18906 /// 'referenced'. 18907 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18908 bool SkipLocalVariables) { 18909 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18910 } 18911 18912 /// Emit a diagnostic when statements are reachable. 18913 /// FIXME: check for reachability even in expressions for which we don't build a 18914 /// CFG (eg, in the initializer of a global or in a constant expression). 18915 /// For example, 18916 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 18917 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 18918 const PartialDiagnostic &PD) { 18919 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18920 if (!FunctionScopes.empty()) 18921 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 18922 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18923 return true; 18924 } 18925 18926 // The initializer of a constexpr variable or of the first declaration of a 18927 // static data member is not syntactically a constant evaluated constant, 18928 // but nonetheless is always required to be a constant expression, so we 18929 // can skip diagnosing. 18930 // FIXME: Using the mangling context here is a hack. 18931 if (auto *VD = dyn_cast_or_null<VarDecl>( 18932 ExprEvalContexts.back().ManglingContextDecl)) { 18933 if (VD->isConstexpr() || 18934 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18935 return false; 18936 // FIXME: For any other kind of variable, we should build a CFG for its 18937 // initializer and check whether the context in question is reachable. 18938 } 18939 18940 Diag(Loc, PD); 18941 return true; 18942 } 18943 18944 /// Emit a diagnostic that describes an effect on the run-time behavior 18945 /// of the program being compiled. 18946 /// 18947 /// This routine emits the given diagnostic when the code currently being 18948 /// type-checked is "potentially evaluated", meaning that there is a 18949 /// possibility that the code will actually be executable. Code in sizeof() 18950 /// expressions, code used only during overload resolution, etc., are not 18951 /// potentially evaluated. This routine will suppress such diagnostics or, 18952 /// in the absolutely nutty case of potentially potentially evaluated 18953 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18954 /// later. 18955 /// 18956 /// This routine should be used for all diagnostics that describe the run-time 18957 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18958 /// Failure to do so will likely result in spurious diagnostics or failures 18959 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18960 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18961 const PartialDiagnostic &PD) { 18962 switch (ExprEvalContexts.back().Context) { 18963 case ExpressionEvaluationContext::Unevaluated: 18964 case ExpressionEvaluationContext::UnevaluatedList: 18965 case ExpressionEvaluationContext::UnevaluatedAbstract: 18966 case ExpressionEvaluationContext::DiscardedStatement: 18967 // The argument will never be evaluated, so don't complain. 18968 break; 18969 18970 case ExpressionEvaluationContext::ConstantEvaluated: 18971 case ExpressionEvaluationContext::ImmediateFunctionContext: 18972 // Relevant diagnostics should be produced by constant evaluation. 18973 break; 18974 18975 case ExpressionEvaluationContext::PotentiallyEvaluated: 18976 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18977 return DiagIfReachable(Loc, Stmts, PD); 18978 } 18979 18980 return false; 18981 } 18982 18983 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18984 const PartialDiagnostic &PD) { 18985 return DiagRuntimeBehavior( 18986 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18987 } 18988 18989 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18990 CallExpr *CE, FunctionDecl *FD) { 18991 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18992 return false; 18993 18994 // If we're inside a decltype's expression, don't check for a valid return 18995 // type or construct temporaries until we know whether this is the last call. 18996 if (ExprEvalContexts.back().ExprContext == 18997 ExpressionEvaluationContextRecord::EK_Decltype) { 18998 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18999 return false; 19000 } 19001 19002 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19003 FunctionDecl *FD; 19004 CallExpr *CE; 19005 19006 public: 19007 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19008 : FD(FD), CE(CE) { } 19009 19010 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19011 if (!FD) { 19012 S.Diag(Loc, diag::err_call_incomplete_return) 19013 << T << CE->getSourceRange(); 19014 return; 19015 } 19016 19017 S.Diag(Loc, diag::err_call_function_incomplete_return) 19018 << CE->getSourceRange() << FD << T; 19019 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19020 << FD->getDeclName(); 19021 } 19022 } Diagnoser(FD, CE); 19023 19024 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19025 return true; 19026 19027 return false; 19028 } 19029 19030 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19031 // will prevent this condition from triggering, which is what we want. 19032 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19033 SourceLocation Loc; 19034 19035 unsigned diagnostic = diag::warn_condition_is_assignment; 19036 bool IsOrAssign = false; 19037 19038 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19039 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19040 return; 19041 19042 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19043 19044 // Greylist some idioms by putting them into a warning subcategory. 19045 if (ObjCMessageExpr *ME 19046 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19047 Selector Sel = ME->getSelector(); 19048 19049 // self = [<foo> init...] 19050 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19051 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19052 19053 // <foo> = [<bar> nextObject] 19054 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19055 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19056 } 19057 19058 Loc = Op->getOperatorLoc(); 19059 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19060 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19061 return; 19062 19063 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19064 Loc = Op->getOperatorLoc(); 19065 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19066 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19067 else { 19068 // Not an assignment. 19069 return; 19070 } 19071 19072 Diag(Loc, diagnostic) << E->getSourceRange(); 19073 19074 SourceLocation Open = E->getBeginLoc(); 19075 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19076 Diag(Loc, diag::note_condition_assign_silence) 19077 << FixItHint::CreateInsertion(Open, "(") 19078 << FixItHint::CreateInsertion(Close, ")"); 19079 19080 if (IsOrAssign) 19081 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19082 << FixItHint::CreateReplacement(Loc, "!="); 19083 else 19084 Diag(Loc, diag::note_condition_assign_to_comparison) 19085 << FixItHint::CreateReplacement(Loc, "=="); 19086 } 19087 19088 /// Redundant parentheses over an equality comparison can indicate 19089 /// that the user intended an assignment used as condition. 19090 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19091 // Don't warn if the parens came from a macro. 19092 SourceLocation parenLoc = ParenE->getBeginLoc(); 19093 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19094 return; 19095 // Don't warn for dependent expressions. 19096 if (ParenE->isTypeDependent()) 19097 return; 19098 19099 Expr *E = ParenE->IgnoreParens(); 19100 19101 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19102 if (opE->getOpcode() == BO_EQ && 19103 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19104 == Expr::MLV_Valid) { 19105 SourceLocation Loc = opE->getOperatorLoc(); 19106 19107 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19108 SourceRange ParenERange = ParenE->getSourceRange(); 19109 Diag(Loc, diag::note_equality_comparison_silence) 19110 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19111 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19112 Diag(Loc, diag::note_equality_comparison_to_assign) 19113 << FixItHint::CreateReplacement(Loc, "="); 19114 } 19115 } 19116 19117 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19118 bool IsConstexpr) { 19119 DiagnoseAssignmentAsCondition(E); 19120 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19121 DiagnoseEqualityWithExtraParens(parenE); 19122 19123 ExprResult result = CheckPlaceholderExpr(E); 19124 if (result.isInvalid()) return ExprError(); 19125 E = result.get(); 19126 19127 if (!E->isTypeDependent()) { 19128 if (getLangOpts().CPlusPlus) 19129 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19130 19131 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19132 if (ERes.isInvalid()) 19133 return ExprError(); 19134 E = ERes.get(); 19135 19136 QualType T = E->getType(); 19137 if (!T->isScalarType()) { // C99 6.8.4.1p1 19138 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19139 << T << E->getSourceRange(); 19140 return ExprError(); 19141 } 19142 CheckBoolLikeConversion(E, Loc); 19143 } 19144 19145 return E; 19146 } 19147 19148 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19149 Expr *SubExpr, ConditionKind CK) { 19150 // Empty conditions are valid in for-statements. 19151 if (!SubExpr) 19152 return ConditionResult(); 19153 19154 ExprResult Cond; 19155 switch (CK) { 19156 case ConditionKind::Boolean: 19157 Cond = CheckBooleanCondition(Loc, SubExpr); 19158 break; 19159 19160 case ConditionKind::ConstexprIf: 19161 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19162 break; 19163 19164 case ConditionKind::Switch: 19165 Cond = CheckSwitchCondition(Loc, SubExpr); 19166 break; 19167 } 19168 if (Cond.isInvalid()) { 19169 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19170 {SubExpr}); 19171 if (!Cond.get()) 19172 return ConditionError(); 19173 } 19174 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19175 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19176 if (!FullExpr.get()) 19177 return ConditionError(); 19178 19179 return ConditionResult(*this, nullptr, FullExpr, 19180 CK == ConditionKind::ConstexprIf); 19181 } 19182 19183 namespace { 19184 /// A visitor for rebuilding a call to an __unknown_any expression 19185 /// to have an appropriate type. 19186 struct RebuildUnknownAnyFunction 19187 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19188 19189 Sema &S; 19190 19191 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19192 19193 ExprResult VisitStmt(Stmt *S) { 19194 llvm_unreachable("unexpected statement!"); 19195 } 19196 19197 ExprResult VisitExpr(Expr *E) { 19198 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19199 << E->getSourceRange(); 19200 return ExprError(); 19201 } 19202 19203 /// Rebuild an expression which simply semantically wraps another 19204 /// expression which it shares the type and value kind of. 19205 template <class T> ExprResult rebuildSugarExpr(T *E) { 19206 ExprResult SubResult = Visit(E->getSubExpr()); 19207 if (SubResult.isInvalid()) return ExprError(); 19208 19209 Expr *SubExpr = SubResult.get(); 19210 E->setSubExpr(SubExpr); 19211 E->setType(SubExpr->getType()); 19212 E->setValueKind(SubExpr->getValueKind()); 19213 assert(E->getObjectKind() == OK_Ordinary); 19214 return E; 19215 } 19216 19217 ExprResult VisitParenExpr(ParenExpr *E) { 19218 return rebuildSugarExpr(E); 19219 } 19220 19221 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19222 return rebuildSugarExpr(E); 19223 } 19224 19225 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19226 ExprResult SubResult = Visit(E->getSubExpr()); 19227 if (SubResult.isInvalid()) return ExprError(); 19228 19229 Expr *SubExpr = SubResult.get(); 19230 E->setSubExpr(SubExpr); 19231 E->setType(S.Context.getPointerType(SubExpr->getType())); 19232 assert(E->isPRValue()); 19233 assert(E->getObjectKind() == OK_Ordinary); 19234 return E; 19235 } 19236 19237 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19238 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19239 19240 E->setType(VD->getType()); 19241 19242 assert(E->isPRValue()); 19243 if (S.getLangOpts().CPlusPlus && 19244 !(isa<CXXMethodDecl>(VD) && 19245 cast<CXXMethodDecl>(VD)->isInstance())) 19246 E->setValueKind(VK_LValue); 19247 19248 return E; 19249 } 19250 19251 ExprResult VisitMemberExpr(MemberExpr *E) { 19252 return resolveDecl(E, E->getMemberDecl()); 19253 } 19254 19255 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19256 return resolveDecl(E, E->getDecl()); 19257 } 19258 }; 19259 } 19260 19261 /// Given a function expression of unknown-any type, try to rebuild it 19262 /// to have a function type. 19263 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19264 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19265 if (Result.isInvalid()) return ExprError(); 19266 return S.DefaultFunctionArrayConversion(Result.get()); 19267 } 19268 19269 namespace { 19270 /// A visitor for rebuilding an expression of type __unknown_anytype 19271 /// into one which resolves the type directly on the referring 19272 /// expression. Strict preservation of the original source 19273 /// structure is not a goal. 19274 struct RebuildUnknownAnyExpr 19275 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19276 19277 Sema &S; 19278 19279 /// The current destination type. 19280 QualType DestType; 19281 19282 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19283 : S(S), DestType(CastType) {} 19284 19285 ExprResult VisitStmt(Stmt *S) { 19286 llvm_unreachable("unexpected statement!"); 19287 } 19288 19289 ExprResult VisitExpr(Expr *E) { 19290 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19291 << E->getSourceRange(); 19292 return ExprError(); 19293 } 19294 19295 ExprResult VisitCallExpr(CallExpr *E); 19296 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19297 19298 /// Rebuild an expression which simply semantically wraps another 19299 /// expression which it shares the type and value kind of. 19300 template <class T> ExprResult rebuildSugarExpr(T *E) { 19301 ExprResult SubResult = Visit(E->getSubExpr()); 19302 if (SubResult.isInvalid()) return ExprError(); 19303 Expr *SubExpr = SubResult.get(); 19304 E->setSubExpr(SubExpr); 19305 E->setType(SubExpr->getType()); 19306 E->setValueKind(SubExpr->getValueKind()); 19307 assert(E->getObjectKind() == OK_Ordinary); 19308 return E; 19309 } 19310 19311 ExprResult VisitParenExpr(ParenExpr *E) { 19312 return rebuildSugarExpr(E); 19313 } 19314 19315 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19316 return rebuildSugarExpr(E); 19317 } 19318 19319 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19320 const PointerType *Ptr = DestType->getAs<PointerType>(); 19321 if (!Ptr) { 19322 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19323 << E->getSourceRange(); 19324 return ExprError(); 19325 } 19326 19327 if (isa<CallExpr>(E->getSubExpr())) { 19328 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19329 << E->getSourceRange(); 19330 return ExprError(); 19331 } 19332 19333 assert(E->isPRValue()); 19334 assert(E->getObjectKind() == OK_Ordinary); 19335 E->setType(DestType); 19336 19337 // Build the sub-expression as if it were an object of the pointee type. 19338 DestType = Ptr->getPointeeType(); 19339 ExprResult SubResult = Visit(E->getSubExpr()); 19340 if (SubResult.isInvalid()) return ExprError(); 19341 E->setSubExpr(SubResult.get()); 19342 return E; 19343 } 19344 19345 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19346 19347 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19348 19349 ExprResult VisitMemberExpr(MemberExpr *E) { 19350 return resolveDecl(E, E->getMemberDecl()); 19351 } 19352 19353 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19354 return resolveDecl(E, E->getDecl()); 19355 } 19356 }; 19357 } 19358 19359 /// Rebuilds a call expression which yielded __unknown_anytype. 19360 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19361 Expr *CalleeExpr = E->getCallee(); 19362 19363 enum FnKind { 19364 FK_MemberFunction, 19365 FK_FunctionPointer, 19366 FK_BlockPointer 19367 }; 19368 19369 FnKind Kind; 19370 QualType CalleeType = CalleeExpr->getType(); 19371 if (CalleeType == S.Context.BoundMemberTy) { 19372 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19373 Kind = FK_MemberFunction; 19374 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19375 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19376 CalleeType = Ptr->getPointeeType(); 19377 Kind = FK_FunctionPointer; 19378 } else { 19379 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19380 Kind = FK_BlockPointer; 19381 } 19382 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19383 19384 // Verify that this is a legal result type of a function. 19385 if (DestType->isArrayType() || DestType->isFunctionType()) { 19386 unsigned diagID = diag::err_func_returning_array_function; 19387 if (Kind == FK_BlockPointer) 19388 diagID = diag::err_block_returning_array_function; 19389 19390 S.Diag(E->getExprLoc(), diagID) 19391 << DestType->isFunctionType() << DestType; 19392 return ExprError(); 19393 } 19394 19395 // Otherwise, go ahead and set DestType as the call's result. 19396 E->setType(DestType.getNonLValueExprType(S.Context)); 19397 E->setValueKind(Expr::getValueKindForType(DestType)); 19398 assert(E->getObjectKind() == OK_Ordinary); 19399 19400 // Rebuild the function type, replacing the result type with DestType. 19401 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19402 if (Proto) { 19403 // __unknown_anytype(...) is a special case used by the debugger when 19404 // it has no idea what a function's signature is. 19405 // 19406 // We want to build this call essentially under the K&R 19407 // unprototyped rules, but making a FunctionNoProtoType in C++ 19408 // would foul up all sorts of assumptions. However, we cannot 19409 // simply pass all arguments as variadic arguments, nor can we 19410 // portably just call the function under a non-variadic type; see 19411 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19412 // However, it turns out that in practice it is generally safe to 19413 // call a function declared as "A foo(B,C,D);" under the prototype 19414 // "A foo(B,C,D,...);". The only known exception is with the 19415 // Windows ABI, where any variadic function is implicitly cdecl 19416 // regardless of its normal CC. Therefore we change the parameter 19417 // types to match the types of the arguments. 19418 // 19419 // This is a hack, but it is far superior to moving the 19420 // corresponding target-specific code from IR-gen to Sema/AST. 19421 19422 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19423 SmallVector<QualType, 8> ArgTypes; 19424 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19425 ArgTypes.reserve(E->getNumArgs()); 19426 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19427 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19428 } 19429 ParamTypes = ArgTypes; 19430 } 19431 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19432 Proto->getExtProtoInfo()); 19433 } else { 19434 DestType = S.Context.getFunctionNoProtoType(DestType, 19435 FnType->getExtInfo()); 19436 } 19437 19438 // Rebuild the appropriate pointer-to-function type. 19439 switch (Kind) { 19440 case FK_MemberFunction: 19441 // Nothing to do. 19442 break; 19443 19444 case FK_FunctionPointer: 19445 DestType = S.Context.getPointerType(DestType); 19446 break; 19447 19448 case FK_BlockPointer: 19449 DestType = S.Context.getBlockPointerType(DestType); 19450 break; 19451 } 19452 19453 // Finally, we can recurse. 19454 ExprResult CalleeResult = Visit(CalleeExpr); 19455 if (!CalleeResult.isUsable()) return ExprError(); 19456 E->setCallee(CalleeResult.get()); 19457 19458 // Bind a temporary if necessary. 19459 return S.MaybeBindToTemporary(E); 19460 } 19461 19462 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19463 // Verify that this is a legal result type of a call. 19464 if (DestType->isArrayType() || DestType->isFunctionType()) { 19465 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19466 << DestType->isFunctionType() << DestType; 19467 return ExprError(); 19468 } 19469 19470 // Rewrite the method result type if available. 19471 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19472 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19473 Method->setReturnType(DestType); 19474 } 19475 19476 // Change the type of the message. 19477 E->setType(DestType.getNonReferenceType()); 19478 E->setValueKind(Expr::getValueKindForType(DestType)); 19479 19480 return S.MaybeBindToTemporary(E); 19481 } 19482 19483 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19484 // The only case we should ever see here is a function-to-pointer decay. 19485 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19486 assert(E->isPRValue()); 19487 assert(E->getObjectKind() == OK_Ordinary); 19488 19489 E->setType(DestType); 19490 19491 // Rebuild the sub-expression as the pointee (function) type. 19492 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19493 19494 ExprResult Result = Visit(E->getSubExpr()); 19495 if (!Result.isUsable()) return ExprError(); 19496 19497 E->setSubExpr(Result.get()); 19498 return E; 19499 } else if (E->getCastKind() == CK_LValueToRValue) { 19500 assert(E->isPRValue()); 19501 assert(E->getObjectKind() == OK_Ordinary); 19502 19503 assert(isa<BlockPointerType>(E->getType())); 19504 19505 E->setType(DestType); 19506 19507 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19508 DestType = S.Context.getLValueReferenceType(DestType); 19509 19510 ExprResult Result = Visit(E->getSubExpr()); 19511 if (!Result.isUsable()) return ExprError(); 19512 19513 E->setSubExpr(Result.get()); 19514 return E; 19515 } else { 19516 llvm_unreachable("Unhandled cast type!"); 19517 } 19518 } 19519 19520 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19521 ExprValueKind ValueKind = VK_LValue; 19522 QualType Type = DestType; 19523 19524 // We know how to make this work for certain kinds of decls: 19525 19526 // - functions 19527 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19528 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19529 DestType = Ptr->getPointeeType(); 19530 ExprResult Result = resolveDecl(E, VD); 19531 if (Result.isInvalid()) return ExprError(); 19532 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19533 VK_PRValue); 19534 } 19535 19536 if (!Type->isFunctionType()) { 19537 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19538 << VD << E->getSourceRange(); 19539 return ExprError(); 19540 } 19541 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19542 // We must match the FunctionDecl's type to the hack introduced in 19543 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19544 // type. See the lengthy commentary in that routine. 19545 QualType FDT = FD->getType(); 19546 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19547 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19548 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19549 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19550 SourceLocation Loc = FD->getLocation(); 19551 FunctionDecl *NewFD = FunctionDecl::Create( 19552 S.Context, FD->getDeclContext(), Loc, Loc, 19553 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19554 SC_None, S.getCurFPFeatures().isFPConstrained(), 19555 false /*isInlineSpecified*/, FD->hasPrototype(), 19556 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19557 19558 if (FD->getQualifier()) 19559 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19560 19561 SmallVector<ParmVarDecl*, 16> Params; 19562 for (const auto &AI : FT->param_types()) { 19563 ParmVarDecl *Param = 19564 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19565 Param->setScopeInfo(0, Params.size()); 19566 Params.push_back(Param); 19567 } 19568 NewFD->setParams(Params); 19569 DRE->setDecl(NewFD); 19570 VD = DRE->getDecl(); 19571 } 19572 } 19573 19574 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19575 if (MD->isInstance()) { 19576 ValueKind = VK_PRValue; 19577 Type = S.Context.BoundMemberTy; 19578 } 19579 19580 // Function references aren't l-values in C. 19581 if (!S.getLangOpts().CPlusPlus) 19582 ValueKind = VK_PRValue; 19583 19584 // - variables 19585 } else if (isa<VarDecl>(VD)) { 19586 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19587 Type = RefTy->getPointeeType(); 19588 } else if (Type->isFunctionType()) { 19589 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19590 << VD << E->getSourceRange(); 19591 return ExprError(); 19592 } 19593 19594 // - nothing else 19595 } else { 19596 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19597 << VD << E->getSourceRange(); 19598 return ExprError(); 19599 } 19600 19601 // Modifying the declaration like this is friendly to IR-gen but 19602 // also really dangerous. 19603 VD->setType(DestType); 19604 E->setType(Type); 19605 E->setValueKind(ValueKind); 19606 return E; 19607 } 19608 19609 /// Check a cast of an unknown-any type. We intentionally only 19610 /// trigger this for C-style casts. 19611 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19612 Expr *CastExpr, CastKind &CastKind, 19613 ExprValueKind &VK, CXXCastPath &Path) { 19614 // The type we're casting to must be either void or complete. 19615 if (!CastType->isVoidType() && 19616 RequireCompleteType(TypeRange.getBegin(), CastType, 19617 diag::err_typecheck_cast_to_incomplete)) 19618 return ExprError(); 19619 19620 // Rewrite the casted expression from scratch. 19621 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19622 if (!result.isUsable()) return ExprError(); 19623 19624 CastExpr = result.get(); 19625 VK = CastExpr->getValueKind(); 19626 CastKind = CK_NoOp; 19627 19628 return CastExpr; 19629 } 19630 19631 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19632 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19633 } 19634 19635 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19636 Expr *arg, QualType ¶mType) { 19637 // If the syntactic form of the argument is not an explicit cast of 19638 // any sort, just do default argument promotion. 19639 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19640 if (!castArg) { 19641 ExprResult result = DefaultArgumentPromotion(arg); 19642 if (result.isInvalid()) return ExprError(); 19643 paramType = result.get()->getType(); 19644 return result; 19645 } 19646 19647 // Otherwise, use the type that was written in the explicit cast. 19648 assert(!arg->hasPlaceholderType()); 19649 paramType = castArg->getTypeAsWritten(); 19650 19651 // Copy-initialize a parameter of that type. 19652 InitializedEntity entity = 19653 InitializedEntity::InitializeParameter(Context, paramType, 19654 /*consumed*/ false); 19655 return PerformCopyInitialization(entity, callLoc, arg); 19656 } 19657 19658 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19659 Expr *orig = E; 19660 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19661 while (true) { 19662 E = E->IgnoreParenImpCasts(); 19663 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19664 E = call->getCallee(); 19665 diagID = diag::err_uncasted_call_of_unknown_any; 19666 } else { 19667 break; 19668 } 19669 } 19670 19671 SourceLocation loc; 19672 NamedDecl *d; 19673 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19674 loc = ref->getLocation(); 19675 d = ref->getDecl(); 19676 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19677 loc = mem->getMemberLoc(); 19678 d = mem->getMemberDecl(); 19679 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19680 diagID = diag::err_uncasted_call_of_unknown_any; 19681 loc = msg->getSelectorStartLoc(); 19682 d = msg->getMethodDecl(); 19683 if (!d) { 19684 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19685 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19686 << orig->getSourceRange(); 19687 return ExprError(); 19688 } 19689 } else { 19690 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19691 << E->getSourceRange(); 19692 return ExprError(); 19693 } 19694 19695 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19696 19697 // Never recoverable. 19698 return ExprError(); 19699 } 19700 19701 /// Check for operands with placeholder types and complain if found. 19702 /// Returns ExprError() if there was an error and no recovery was possible. 19703 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19704 if (!Context.isDependenceAllowed()) { 19705 // C cannot handle TypoExpr nodes on either side of a binop because it 19706 // doesn't handle dependent types properly, so make sure any TypoExprs have 19707 // been dealt with before checking the operands. 19708 ExprResult Result = CorrectDelayedTyposInExpr(E); 19709 if (!Result.isUsable()) return ExprError(); 19710 E = Result.get(); 19711 } 19712 19713 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19714 if (!placeholderType) return E; 19715 19716 switch (placeholderType->getKind()) { 19717 19718 // Overloaded expressions. 19719 case BuiltinType::Overload: { 19720 // Try to resolve a single function template specialization. 19721 // This is obligatory. 19722 ExprResult Result = E; 19723 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19724 return Result; 19725 19726 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19727 // leaves Result unchanged on failure. 19728 Result = E; 19729 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19730 return Result; 19731 19732 // If that failed, try to recover with a call. 19733 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19734 /*complain*/ true); 19735 return Result; 19736 } 19737 19738 // Bound member functions. 19739 case BuiltinType::BoundMember: { 19740 ExprResult result = E; 19741 const Expr *BME = E->IgnoreParens(); 19742 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19743 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19744 if (isa<CXXPseudoDestructorExpr>(BME)) { 19745 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19746 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19747 if (ME->getMemberNameInfo().getName().getNameKind() == 19748 DeclarationName::CXXDestructorName) 19749 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19750 } 19751 tryToRecoverWithCall(result, PD, 19752 /*complain*/ true); 19753 return result; 19754 } 19755 19756 // ARC unbridged casts. 19757 case BuiltinType::ARCUnbridgedCast: { 19758 Expr *realCast = stripARCUnbridgedCast(E); 19759 diagnoseARCUnbridgedCast(realCast); 19760 return realCast; 19761 } 19762 19763 // Expressions of unknown type. 19764 case BuiltinType::UnknownAny: 19765 return diagnoseUnknownAnyExpr(*this, E); 19766 19767 // Pseudo-objects. 19768 case BuiltinType::PseudoObject: 19769 return checkPseudoObjectRValue(E); 19770 19771 case BuiltinType::BuiltinFn: { 19772 // Accept __noop without parens by implicitly converting it to a call expr. 19773 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19774 if (DRE) { 19775 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19776 if (FD->getBuiltinID() == Builtin::BI__noop) { 19777 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19778 CK_BuiltinFnToFnPtr) 19779 .get(); 19780 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19781 VK_PRValue, SourceLocation(), 19782 FPOptionsOverride()); 19783 } 19784 } 19785 19786 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19787 return ExprError(); 19788 } 19789 19790 case BuiltinType::IncompleteMatrixIdx: 19791 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19792 ->getRowIdx() 19793 ->getBeginLoc(), 19794 diag::err_matrix_incomplete_index); 19795 return ExprError(); 19796 19797 // Expressions of unknown type. 19798 case BuiltinType::OMPArraySection: 19799 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19800 return ExprError(); 19801 19802 // Expressions of unknown type. 19803 case BuiltinType::OMPArrayShaping: 19804 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19805 19806 case BuiltinType::OMPIterator: 19807 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19808 19809 // Everything else should be impossible. 19810 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19811 case BuiltinType::Id: 19812 #include "clang/Basic/OpenCLImageTypes.def" 19813 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19814 case BuiltinType::Id: 19815 #include "clang/Basic/OpenCLExtensionTypes.def" 19816 #define SVE_TYPE(Name, Id, SingletonId) \ 19817 case BuiltinType::Id: 19818 #include "clang/Basic/AArch64SVEACLETypes.def" 19819 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19820 case BuiltinType::Id: 19821 #include "clang/Basic/PPCTypes.def" 19822 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19823 #include "clang/Basic/RISCVVTypes.def" 19824 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19825 #define PLACEHOLDER_TYPE(Id, SingletonId) 19826 #include "clang/AST/BuiltinTypes.def" 19827 break; 19828 } 19829 19830 llvm_unreachable("invalid placeholder type!"); 19831 } 19832 19833 bool Sema::CheckCaseExpression(Expr *E) { 19834 if (E->isTypeDependent()) 19835 return true; 19836 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19837 return E->getType()->isIntegralOrEnumerationType(); 19838 return false; 19839 } 19840 19841 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19842 ExprResult 19843 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19844 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19845 "Unknown Objective-C Boolean value!"); 19846 QualType BoolT = Context.ObjCBuiltinBoolTy; 19847 if (!Context.getBOOLDecl()) { 19848 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19849 Sema::LookupOrdinaryName); 19850 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19851 NamedDecl *ND = Result.getFoundDecl(); 19852 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19853 Context.setBOOLDecl(TD); 19854 } 19855 } 19856 if (Context.getBOOLDecl()) 19857 BoolT = Context.getBOOLType(); 19858 return new (Context) 19859 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19860 } 19861 19862 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19863 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19864 SourceLocation RParen) { 19865 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19866 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19867 return Spec.getPlatform() == Platform; 19868 }); 19869 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19870 // for "maccatalyst" if "maccatalyst" is not specified. 19871 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19872 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19873 return Spec.getPlatform() == "ios"; 19874 }); 19875 } 19876 if (Spec == AvailSpecs.end()) 19877 return None; 19878 return Spec->getVersion(); 19879 }; 19880 19881 VersionTuple Version; 19882 if (auto MaybeVersion = 19883 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19884 Version = *MaybeVersion; 19885 19886 // The use of `@available` in the enclosing context should be analyzed to 19887 // warn when it's used inappropriately (i.e. not if(@available)). 19888 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19889 Context->HasPotentialAvailabilityViolations = true; 19890 19891 return new (Context) 19892 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19893 } 19894 19895 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19896 ArrayRef<Expr *> SubExprs, QualType T) { 19897 if (!Context.getLangOpts().RecoveryAST) 19898 return ExprError(); 19899 19900 if (isSFINAEContext()) 19901 return ExprError(); 19902 19903 if (T.isNull() || T->isUndeducedType() || 19904 !Context.getLangOpts().RecoveryASTType) 19905 // We don't know the concrete type, fallback to dependent type. 19906 T = Context.DependentTy; 19907 19908 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19909 } 19910