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/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/Builtins.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/ADT/STLExtras.h" 50 #include "llvm/ADT/StringExtras.h" 51 #include "llvm/Support/ConvertUTF.h" 52 #include "llvm/Support/SaveAndRestore.h" 53 54 using namespace clang; 55 using namespace sema; 56 using llvm::RoundingMode; 57 58 /// Determine whether the use of this declaration is valid, without 59 /// emitting diagnostics. 60 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 61 // See if this is an auto-typed variable whose initializer we are parsing. 62 if (ParsingInitForAutoVars.count(D)) 63 return false; 64 65 // See if this is a deleted function. 66 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 67 if (FD->isDeleted()) 68 return false; 69 70 // If the function has a deduced return type, and we can't deduce it, 71 // then we can't use it either. 72 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 73 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 74 return false; 75 76 // See if this is an aligned allocation/deallocation function that is 77 // unavailable. 78 if (TreatUnavailableAsInvalid && 79 isUnavailableAlignedAllocationFunction(*FD)) 80 return false; 81 } 82 83 // See if this function is unavailable. 84 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 85 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 86 return false; 87 88 if (isa<UnresolvedUsingIfExistsDecl>(D)) 89 return false; 90 91 return true; 92 } 93 94 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 95 // Warn if this is used but marked unused. 96 if (const auto *A = D->getAttr<UnusedAttr>()) { 97 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 98 // should diagnose them. 99 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 100 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 101 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 102 if (DC && !DC->hasAttr<UnusedAttr>()) 103 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 104 } 105 } 106 } 107 108 /// Emit a note explaining that this function is deleted. 109 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 110 assert(Decl && Decl->isDeleted()); 111 112 if (Decl->isDefaulted()) { 113 // If the method was explicitly defaulted, point at that declaration. 114 if (!Decl->isImplicit()) 115 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 116 117 // Try to diagnose why this special member function was implicitly 118 // deleted. This might fail, if that reason no longer applies. 119 DiagnoseDeletedDefaultedFunction(Decl); 120 return; 121 } 122 123 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 124 if (Ctor && Ctor->isInheritingConstructor()) 125 return NoteDeletedInheritingConstructor(Ctor); 126 127 Diag(Decl->getLocation(), diag::note_availability_specified_here) 128 << Decl << 1; 129 } 130 131 /// Determine whether a FunctionDecl was ever declared with an 132 /// explicit storage class. 133 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 134 for (auto I : D->redecls()) { 135 if (I->getStorageClass() != SC_None) 136 return true; 137 } 138 return false; 139 } 140 141 /// Check whether we're in an extern inline function and referring to a 142 /// variable or function with internal linkage (C11 6.7.4p3). 143 /// 144 /// This is only a warning because we used to silently accept this code, but 145 /// in many cases it will not behave correctly. This is not enabled in C++ mode 146 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 147 /// and so while there may still be user mistakes, most of the time we can't 148 /// prove that there are errors. 149 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 150 const NamedDecl *D, 151 SourceLocation Loc) { 152 // This is disabled under C++; there are too many ways for this to fire in 153 // contexts where the warning is a false positive, or where it is technically 154 // correct but benign. 155 if (S.getLangOpts().CPlusPlus) 156 return; 157 158 // Check if this is an inlined function or method. 159 FunctionDecl *Current = S.getCurFunctionDecl(); 160 if (!Current) 161 return; 162 if (!Current->isInlined()) 163 return; 164 if (!Current->isExternallyVisible()) 165 return; 166 167 // Check if the decl has internal linkage. 168 if (D->getFormalLinkage() != InternalLinkage) 169 return; 170 171 // Downgrade from ExtWarn to Extension if 172 // (1) the supposedly external inline function is in the main file, 173 // and probably won't be included anywhere else. 174 // (2) the thing we're referencing is a pure function. 175 // (3) the thing we're referencing is another inline function. 176 // This last can give us false negatives, but it's better than warning on 177 // wrappers for simple C library functions. 178 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 179 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 180 if (!DowngradeWarning && UsedFn) 181 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 182 183 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 184 : diag::ext_internal_in_extern_inline) 185 << /*IsVar=*/!UsedFn << D; 186 187 S.MaybeSuggestAddingStaticToDecl(Current); 188 189 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 190 << D; 191 } 192 193 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 194 const FunctionDecl *First = Cur->getFirstDecl(); 195 196 // Suggest "static" on the function, if possible. 197 if (!hasAnyExplicitStorageClass(First)) { 198 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 199 Diag(DeclBegin, diag::note_convert_inline_to_static) 200 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 201 } 202 } 203 204 /// Determine whether the use of this declaration is valid, and 205 /// emit any corresponding diagnostics. 206 /// 207 /// This routine diagnoses various problems with referencing 208 /// declarations that can occur when using a declaration. For example, 209 /// it might warn if a deprecated or unavailable declaration is being 210 /// used, or produce an error (and return true) if a C++0x deleted 211 /// function is being used. 212 /// 213 /// \returns true if there was an error (this declaration cannot be 214 /// referenced), false otherwise. 215 /// 216 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 217 const ObjCInterfaceDecl *UnknownObjCClass, 218 bool ObjCPropertyAccess, 219 bool AvoidPartialAvailabilityChecks, 220 ObjCInterfaceDecl *ClassReceiver) { 221 SourceLocation Loc = Locs.front(); 222 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 223 // If there were any diagnostics suppressed by template argument deduction, 224 // emit them now. 225 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 226 if (Pos != SuppressedDiagnostics.end()) { 227 for (const PartialDiagnosticAt &Suppressed : Pos->second) 228 Diag(Suppressed.first, Suppressed.second); 229 230 // Clear out the list of suppressed diagnostics, so that we don't emit 231 // them again for this specialization. However, we don't obsolete this 232 // entry from the table, because we want to avoid ever emitting these 233 // diagnostics again. 234 Pos->second.clear(); 235 } 236 237 // C++ [basic.start.main]p3: 238 // The function 'main' shall not be used within a program. 239 if (cast<FunctionDecl>(D)->isMain()) 240 Diag(Loc, diag::ext_main_used); 241 242 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 243 } 244 245 // See if this is an auto-typed variable whose initializer we are parsing. 246 if (ParsingInitForAutoVars.count(D)) { 247 if (isa<BindingDecl>(D)) { 248 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 249 << D->getDeclName(); 250 } else { 251 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 252 << D->getDeclName() << cast<VarDecl>(D)->getType(); 253 } 254 return true; 255 } 256 257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 258 // See if this is a deleted function. 259 if (FD->isDeleted()) { 260 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 261 if (Ctor && Ctor->isInheritingConstructor()) 262 Diag(Loc, diag::err_deleted_inherited_ctor_use) 263 << Ctor->getParent() 264 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 265 else 266 Diag(Loc, diag::err_deleted_function_use); 267 NoteDeletedFunction(FD); 268 return true; 269 } 270 271 // [expr.prim.id]p4 272 // A program that refers explicitly or implicitly to a function with a 273 // trailing requires-clause whose constraint-expression is not satisfied, 274 // other than to declare it, is ill-formed. [...] 275 // 276 // See if this is a function with constraints that need to be satisfied. 277 // Check this before deducing the return type, as it might instantiate the 278 // definition. 279 if (FD->getTrailingRequiresClause()) { 280 ConstraintSatisfaction Satisfaction; 281 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 282 // A diagnostic will have already been generated (non-constant 283 // constraint expression, for example) 284 return true; 285 if (!Satisfaction.IsSatisfied) { 286 Diag(Loc, 287 diag::err_reference_to_function_with_unsatisfied_constraints) 288 << D; 289 DiagnoseUnsatisfiedConstraint(Satisfaction); 290 return true; 291 } 292 } 293 294 // If the function has a deduced return type, and we can't deduce it, 295 // then we can't use it either. 296 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 297 DeduceReturnType(FD, Loc)) 298 return true; 299 300 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 301 return true; 302 303 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 304 return true; 305 } 306 307 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 308 // Lambdas are only default-constructible or assignable in C++2a onwards. 309 if (MD->getParent()->isLambda() && 310 ((isa<CXXConstructorDecl>(MD) && 311 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 312 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 313 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 314 << !isa<CXXConstructorDecl>(MD); 315 } 316 } 317 318 auto getReferencedObjCProp = [](const NamedDecl *D) -> 319 const ObjCPropertyDecl * { 320 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 321 return MD->findPropertyDecl(); 322 return nullptr; 323 }; 324 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 325 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 326 return true; 327 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 328 return true; 329 } 330 331 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 332 // Only the variables omp_in and omp_out are allowed in the combiner. 333 // Only the variables omp_priv and omp_orig are allowed in the 334 // initializer-clause. 335 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 336 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 337 isa<VarDecl>(D)) { 338 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 339 << getCurFunction()->HasOMPDeclareReductionCombiner; 340 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 341 return true; 342 } 343 344 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 345 // List-items in map clauses on this construct may only refer to the declared 346 // variable var and entities that could be referenced by a procedure defined 347 // at the same location 348 if (LangOpts.OpenMP && isa<VarDecl>(D) && 349 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 350 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 351 << getOpenMPDeclareMapperVarName(); 352 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 353 return true; 354 } 355 356 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 357 Diag(Loc, diag::err_use_of_empty_using_if_exists); 358 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 359 return true; 360 } 361 362 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 363 AvoidPartialAvailabilityChecks, ClassReceiver); 364 365 DiagnoseUnusedOfDecl(*this, D, Loc); 366 367 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 368 369 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 370 if (auto *VD = dyn_cast<ValueDecl>(D)) 371 checkDeviceDecl(VD, Loc); 372 373 if (!Context.getTargetInfo().isTLSSupported()) 374 if (const auto *VD = dyn_cast<VarDecl>(D)) 375 if (VD->getTLSKind() != VarDecl::TLS_None) 376 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 377 } 378 379 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 380 !isUnevaluatedContext()) { 381 // C++ [expr.prim.req.nested] p3 382 // A local parameter shall only appear as an unevaluated operand 383 // (Clause 8) within the constraint-expression. 384 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 385 << D; 386 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 387 return true; 388 } 389 390 return false; 391 } 392 393 /// DiagnoseSentinelCalls - This routine checks whether a call or 394 /// message-send is to a declaration with the sentinel attribute, and 395 /// if so, it checks that the requirements of the sentinel are 396 /// satisfied. 397 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 398 ArrayRef<Expr *> Args) { 399 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 400 if (!attr) 401 return; 402 403 // The number of formal parameters of the declaration. 404 unsigned numFormalParams; 405 406 // The kind of declaration. This is also an index into a %select in 407 // the diagnostic. 408 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 409 410 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 411 numFormalParams = MD->param_size(); 412 calleeType = CT_Method; 413 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 414 numFormalParams = FD->param_size(); 415 calleeType = CT_Function; 416 } else if (isa<VarDecl>(D)) { 417 QualType type = cast<ValueDecl>(D)->getType(); 418 const FunctionType *fn = nullptr; 419 if (const PointerType *ptr = type->getAs<PointerType>()) { 420 fn = ptr->getPointeeType()->getAs<FunctionType>(); 421 if (!fn) return; 422 calleeType = CT_Function; 423 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 424 fn = ptr->getPointeeType()->castAs<FunctionType>(); 425 calleeType = CT_Block; 426 } else { 427 return; 428 } 429 430 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 431 numFormalParams = proto->getNumParams(); 432 } else { 433 numFormalParams = 0; 434 } 435 } else { 436 return; 437 } 438 439 // "nullPos" is the number of formal parameters at the end which 440 // effectively count as part of the variadic arguments. This is 441 // useful if you would prefer to not have *any* formal parameters, 442 // but the language forces you to have at least one. 443 unsigned nullPos = attr->getNullPos(); 444 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 445 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 446 447 // The number of arguments which should follow the sentinel. 448 unsigned numArgsAfterSentinel = attr->getSentinel(); 449 450 // If there aren't enough arguments for all the formal parameters, 451 // the sentinel, and the args after the sentinel, complain. 452 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 453 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 454 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 455 return; 456 } 457 458 // Otherwise, find the sentinel expression. 459 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 460 if (!sentinelExpr) return; 461 if (sentinelExpr->isValueDependent()) return; 462 if (Context.isSentinelNullExpr(sentinelExpr)) return; 463 464 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 465 // or 'NULL' if those are actually defined in the context. Only use 466 // 'nil' for ObjC methods, where it's much more likely that the 467 // variadic arguments form a list of object pointers. 468 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 469 std::string NullValue; 470 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 471 NullValue = "nil"; 472 else if (getLangOpts().CPlusPlus11) 473 NullValue = "nullptr"; 474 else if (PP.isMacroDefined("NULL")) 475 NullValue = "NULL"; 476 else 477 NullValue = "(void*) 0"; 478 479 if (MissingNilLoc.isInvalid()) 480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 481 else 482 Diag(MissingNilLoc, diag::warn_missing_sentinel) 483 << int(calleeType) 484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 486 } 487 488 SourceRange Sema::getExprRange(Expr *E) const { 489 return E ? E->getSourceRange() : SourceRange(); 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Standard Promotions and Conversions 494 //===----------------------------------------------------------------------===// 495 496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 498 // Handle any placeholder expressions which made it here. 499 if (E->getType()->isPlaceholderType()) { 500 ExprResult result = CheckPlaceholderExpr(E); 501 if (result.isInvalid()) return ExprError(); 502 E = result.get(); 503 } 504 505 QualType Ty = E->getType(); 506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 507 508 if (Ty->isFunctionType()) { 509 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 510 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 511 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 512 return ExprError(); 513 514 E = ImpCastExprToType(E, Context.getPointerType(Ty), 515 CK_FunctionToPointerDecay).get(); 516 } else if (Ty->isArrayType()) { 517 // In C90 mode, arrays only promote to pointers if the array expression is 518 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 519 // type 'array of type' is converted to an expression that has type 'pointer 520 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 521 // that has type 'array of type' ...". The relevant change is "an lvalue" 522 // (C90) to "an expression" (C99). 523 // 524 // C++ 4.2p1: 525 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 526 // T" can be converted to an rvalue of type "pointer to T". 527 // 528 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 529 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 530 CK_ArrayToPointerDecay).get(); 531 } 532 return E; 533 } 534 535 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 536 // Check to see if we are dereferencing a null pointer. If so, 537 // and if not volatile-qualified, this is undefined behavior that the 538 // optimizer will delete, so warn about it. People sometimes try to use this 539 // to get a deterministic trap and are surprised by clang's behavior. This 540 // only handles the pattern "*null", which is a very syntactic check. 541 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 542 if (UO && UO->getOpcode() == UO_Deref && 543 UO->getSubExpr()->getType()->isPointerType()) { 544 const LangAS AS = 545 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 546 if ((!isTargetAddressSpace(AS) || 547 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 548 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 549 S.Context, Expr::NPC_ValueDependentIsNotNull) && 550 !UO->getType().isVolatileQualified()) { 551 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 552 S.PDiag(diag::warn_indirection_through_null) 553 << UO->getSubExpr()->getSourceRange()); 554 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 555 S.PDiag(diag::note_indirection_through_null)); 556 } 557 } 558 } 559 560 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 561 SourceLocation AssignLoc, 562 const Expr* RHS) { 563 const ObjCIvarDecl *IV = OIRE->getDecl(); 564 if (!IV) 565 return; 566 567 DeclarationName MemberName = IV->getDeclName(); 568 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 569 if (!Member || !Member->isStr("isa")) 570 return; 571 572 const Expr *Base = OIRE->getBase(); 573 QualType BaseType = Base->getType(); 574 if (OIRE->isArrow()) 575 BaseType = BaseType->getPointeeType(); 576 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 577 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 578 ObjCInterfaceDecl *ClassDeclared = nullptr; 579 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 580 if (!ClassDeclared->getSuperClass() 581 && (*ClassDeclared->ivar_begin()) == IV) { 582 if (RHS) { 583 NamedDecl *ObjectSetClass = 584 S.LookupSingleName(S.TUScope, 585 &S.Context.Idents.get("object_setClass"), 586 SourceLocation(), S.LookupOrdinaryName); 587 if (ObjectSetClass) { 588 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 589 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 590 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 591 "object_setClass(") 592 << FixItHint::CreateReplacement( 593 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 594 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 595 } 596 else 597 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 598 } else { 599 NamedDecl *ObjectGetClass = 600 S.LookupSingleName(S.TUScope, 601 &S.Context.Idents.get("object_getClass"), 602 SourceLocation(), S.LookupOrdinaryName); 603 if (ObjectGetClass) 604 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 605 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 606 "object_getClass(") 607 << FixItHint::CreateReplacement( 608 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 609 else 610 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 611 } 612 S.Diag(IV->getLocation(), diag::note_ivar_decl); 613 } 614 } 615 } 616 617 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 618 // Handle any placeholder expressions which made it here. 619 if (E->getType()->isPlaceholderType()) { 620 ExprResult result = CheckPlaceholderExpr(E); 621 if (result.isInvalid()) return ExprError(); 622 E = result.get(); 623 } 624 625 // C++ [conv.lval]p1: 626 // A glvalue of a non-function, non-array type T can be 627 // converted to a prvalue. 628 if (!E->isGLValue()) return E; 629 630 QualType T = E->getType(); 631 assert(!T.isNull() && "r-value conversion on typeless expression?"); 632 633 // lvalue-to-rvalue conversion cannot be applied to function or array types. 634 if (T->isFunctionType() || T->isArrayType()) 635 return E; 636 637 // We don't want to throw lvalue-to-rvalue casts on top of 638 // expressions of certain types in C++. 639 if (getLangOpts().CPlusPlus && 640 (E->getType() == Context.OverloadTy || 641 T->isDependentType() || 642 T->isRecordType())) 643 return E; 644 645 // The C standard is actually really unclear on this point, and 646 // DR106 tells us what the result should be but not why. It's 647 // generally best to say that void types just doesn't undergo 648 // lvalue-to-rvalue at all. Note that expressions of unqualified 649 // 'void' type are never l-values, but qualified void can be. 650 if (T->isVoidType()) 651 return E; 652 653 // OpenCL usually rejects direct accesses to values of 'half' type. 654 if (getLangOpts().OpenCL && 655 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 656 T->isHalfType()) { 657 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 658 << 0 << T; 659 return ExprError(); 660 } 661 662 CheckForNullPointerDereference(*this, E); 663 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 664 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 665 &Context.Idents.get("object_getClass"), 666 SourceLocation(), LookupOrdinaryName); 667 if (ObjectGetClass) 668 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 669 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 670 << FixItHint::CreateReplacement( 671 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 672 else 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 674 } 675 else if (const ObjCIvarRefExpr *OIRE = 676 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 677 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 678 679 // C++ [conv.lval]p1: 680 // [...] If T is a non-class type, the type of the prvalue is the 681 // cv-unqualified version of T. Otherwise, the type of the 682 // rvalue is T. 683 // 684 // C99 6.3.2.1p2: 685 // If the lvalue has qualified type, the value has the unqualified 686 // version of the type of the lvalue; otherwise, the value has the 687 // type of the lvalue. 688 if (T.hasQualifiers()) 689 T = T.getUnqualifiedType(); 690 691 // Under the MS ABI, lock down the inheritance model now. 692 if (T->isMemberPointerType() && 693 Context.getTargetInfo().getCXXABI().isMicrosoft()) 694 (void)isCompleteType(E->getExprLoc(), T); 695 696 ExprResult Res = CheckLValueToRValueConversionOperand(E); 697 if (Res.isInvalid()) 698 return Res; 699 E = Res.get(); 700 701 // Loading a __weak object implicitly retains the value, so we need a cleanup to 702 // balance that. 703 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 704 Cleanup.setExprNeedsCleanups(true); 705 706 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 707 Cleanup.setExprNeedsCleanups(true); 708 709 // C++ [conv.lval]p3: 710 // If T is cv std::nullptr_t, the result is a null pointer constant. 711 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 712 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 713 CurFPFeatureOverrides()); 714 715 // C11 6.3.2.1p2: 716 // ... if the lvalue has atomic type, the value has the non-atomic version 717 // of the type of the lvalue ... 718 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 719 T = Atomic->getValueType().getUnqualifiedType(); 720 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 721 nullptr, VK_PRValue, FPOptionsOverride()); 722 } 723 724 return Res; 725 } 726 727 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 728 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 729 if (Res.isInvalid()) 730 return ExprError(); 731 Res = DefaultLvalueConversion(Res.get()); 732 if (Res.isInvalid()) 733 return ExprError(); 734 return Res; 735 } 736 737 /// CallExprUnaryConversions - a special case of an unary conversion 738 /// performed on a function designator of a call expression. 739 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 740 QualType Ty = E->getType(); 741 ExprResult Res = E; 742 // Only do implicit cast for a function type, but not for a pointer 743 // to function type. 744 if (Ty->isFunctionType()) { 745 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 746 CK_FunctionToPointerDecay); 747 if (Res.isInvalid()) 748 return ExprError(); 749 } 750 Res = DefaultLvalueConversion(Res.get()); 751 if (Res.isInvalid()) 752 return ExprError(); 753 return Res.get(); 754 } 755 756 /// UsualUnaryConversions - Performs various conversions that are common to most 757 /// operators (C99 6.3). The conversions of array and function types are 758 /// sometimes suppressed. For example, the array->pointer conversion doesn't 759 /// apply if the array is an argument to the sizeof or address (&) operators. 760 /// In these instances, this routine should *not* be called. 761 ExprResult Sema::UsualUnaryConversions(Expr *E) { 762 // First, convert to an r-value. 763 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 764 if (Res.isInvalid()) 765 return ExprError(); 766 E = Res.get(); 767 768 QualType Ty = E->getType(); 769 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 770 771 // Half FP have to be promoted to float unless it is natively supported 772 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 773 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 774 775 // Try to perform integral promotions if the object has a theoretically 776 // promotable type. 777 if (Ty->isIntegralOrUnscopedEnumerationType()) { 778 // C99 6.3.1.1p2: 779 // 780 // The following may be used in an expression wherever an int or 781 // unsigned int may be used: 782 // - an object or expression with an integer type whose integer 783 // conversion rank is less than or equal to the rank of int 784 // and unsigned int. 785 // - A bit-field of type _Bool, int, signed int, or unsigned int. 786 // 787 // If an int can represent all values of the original type, the 788 // value is converted to an int; otherwise, it is converted to an 789 // unsigned int. These are called the integer promotions. All 790 // other types are unchanged by the integer promotions. 791 792 QualType PTy = Context.isPromotableBitField(E); 793 if (!PTy.isNull()) { 794 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 795 return E; 796 } 797 if (Ty->isPromotableIntegerType()) { 798 QualType PT = Context.getPromotedIntegerType(Ty); 799 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 800 return E; 801 } 802 } 803 return E; 804 } 805 806 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 807 /// do not have a prototype. Arguments that have type float or __fp16 808 /// are promoted to double. All other argument types are converted by 809 /// UsualUnaryConversions(). 810 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 811 QualType Ty = E->getType(); 812 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 813 814 ExprResult Res = UsualUnaryConversions(E); 815 if (Res.isInvalid()) 816 return ExprError(); 817 E = Res.get(); 818 819 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 820 // promote to double. 821 // Note that default argument promotion applies only to float (and 822 // half/fp16); it does not apply to _Float16. 823 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 824 if (BTy && (BTy->getKind() == BuiltinType::Half || 825 BTy->getKind() == BuiltinType::Float)) { 826 if (getLangOpts().OpenCL && 827 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 828 if (BTy->getKind() == BuiltinType::Half) { 829 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 830 } 831 } else { 832 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 833 } 834 } 835 if (BTy && 836 getLangOpts().getExtendIntArgs() == 837 LangOptions::ExtendArgsKind::ExtendTo64 && 838 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 839 Context.getTypeSizeInChars(BTy) < 840 Context.getTypeSizeInChars(Context.LongLongTy)) { 841 E = (Ty->isUnsignedIntegerType()) 842 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 843 .get() 844 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 845 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 846 "Unexpected typesize for LongLongTy"); 847 } 848 849 // C++ performs lvalue-to-rvalue conversion as a default argument 850 // promotion, even on class types, but note: 851 // C++11 [conv.lval]p2: 852 // When an lvalue-to-rvalue conversion occurs in an unevaluated 853 // operand or a subexpression thereof the value contained in the 854 // referenced object is not accessed. Otherwise, if the glvalue 855 // has a class type, the conversion copy-initializes a temporary 856 // of type T from the glvalue and the result of the conversion 857 // is a prvalue for the temporary. 858 // FIXME: add some way to gate this entire thing for correctness in 859 // potentially potentially evaluated contexts. 860 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 861 ExprResult Temp = PerformCopyInitialization( 862 InitializedEntity::InitializeTemporary(E->getType()), 863 E->getExprLoc(), E); 864 if (Temp.isInvalid()) 865 return ExprError(); 866 E = Temp.get(); 867 } 868 869 return E; 870 } 871 872 /// Determine the degree of POD-ness for an expression. 873 /// Incomplete types are considered POD, since this check can be performed 874 /// when we're in an unevaluated context. 875 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 876 if (Ty->isIncompleteType()) { 877 // C++11 [expr.call]p7: 878 // After these conversions, if the argument does not have arithmetic, 879 // enumeration, pointer, pointer to member, or class type, the program 880 // is ill-formed. 881 // 882 // Since we've already performed array-to-pointer and function-to-pointer 883 // decay, the only such type in C++ is cv void. This also handles 884 // initializer lists as variadic arguments. 885 if (Ty->isVoidType()) 886 return VAK_Invalid; 887 888 if (Ty->isObjCObjectType()) 889 return VAK_Invalid; 890 return VAK_Valid; 891 } 892 893 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 894 return VAK_Invalid; 895 896 if (Ty.isCXX98PODType(Context)) 897 return VAK_Valid; 898 899 // C++11 [expr.call]p7: 900 // Passing a potentially-evaluated argument of class type (Clause 9) 901 // having a non-trivial copy constructor, a non-trivial move constructor, 902 // or a non-trivial destructor, with no corresponding parameter, 903 // is conditionally-supported with implementation-defined semantics. 904 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 905 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 906 if (!Record->hasNonTrivialCopyConstructor() && 907 !Record->hasNonTrivialMoveConstructor() && 908 !Record->hasNonTrivialDestructor()) 909 return VAK_ValidInCXX11; 910 911 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 912 return VAK_Valid; 913 914 if (Ty->isObjCObjectType()) 915 return VAK_Invalid; 916 917 if (getLangOpts().MSVCCompat) 918 return VAK_MSVCUndefined; 919 920 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 921 // permitted to reject them. We should consider doing so. 922 return VAK_Undefined; 923 } 924 925 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 926 // Don't allow one to pass an Objective-C interface to a vararg. 927 const QualType &Ty = E->getType(); 928 VarArgKind VAK = isValidVarArgType(Ty); 929 930 // Complain about passing non-POD types through varargs. 931 switch (VAK) { 932 case VAK_ValidInCXX11: 933 DiagRuntimeBehavior( 934 E->getBeginLoc(), nullptr, 935 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 936 LLVM_FALLTHROUGH; 937 case VAK_Valid: 938 if (Ty->isRecordType()) { 939 // This is unlikely to be what the user intended. If the class has a 940 // 'c_str' member function, the user probably meant to call that. 941 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 942 PDiag(diag::warn_pass_class_arg_to_vararg) 943 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 944 } 945 break; 946 947 case VAK_Undefined: 948 case VAK_MSVCUndefined: 949 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 950 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 951 << getLangOpts().CPlusPlus11 << Ty << CT); 952 break; 953 954 case VAK_Invalid: 955 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 956 Diag(E->getBeginLoc(), 957 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 958 << Ty << CT; 959 else if (Ty->isObjCObjectType()) 960 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 961 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 962 << Ty << CT); 963 else 964 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 965 << isa<InitListExpr>(E) << Ty << CT; 966 break; 967 } 968 } 969 970 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 971 /// will create a trap if the resulting type is not a POD type. 972 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 973 FunctionDecl *FDecl) { 974 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 975 // Strip the unbridged-cast placeholder expression off, if applicable. 976 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 977 (CT == VariadicMethod || 978 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 979 E = stripARCUnbridgedCast(E); 980 981 // Otherwise, do normal placeholder checking. 982 } else { 983 ExprResult ExprRes = CheckPlaceholderExpr(E); 984 if (ExprRes.isInvalid()) 985 return ExprError(); 986 E = ExprRes.get(); 987 } 988 } 989 990 ExprResult ExprRes = DefaultArgumentPromotion(E); 991 if (ExprRes.isInvalid()) 992 return ExprError(); 993 994 // Copy blocks to the heap. 995 if (ExprRes.get()->getType()->isBlockPointerType()) 996 maybeExtendBlockObject(ExprRes); 997 998 E = ExprRes.get(); 999 1000 // Diagnostics regarding non-POD argument types are 1001 // emitted along with format string checking in Sema::CheckFunctionCall(). 1002 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1003 // Turn this into a trap. 1004 CXXScopeSpec SS; 1005 SourceLocation TemplateKWLoc; 1006 UnqualifiedId Name; 1007 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1008 E->getBeginLoc()); 1009 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1010 /*HasTrailingLParen=*/true, 1011 /*IsAddressOfOperand=*/false); 1012 if (TrapFn.isInvalid()) 1013 return ExprError(); 1014 1015 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1016 None, E->getEndLoc()); 1017 if (Call.isInvalid()) 1018 return ExprError(); 1019 1020 ExprResult Comma = 1021 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1022 if (Comma.isInvalid()) 1023 return ExprError(); 1024 return Comma.get(); 1025 } 1026 1027 if (!getLangOpts().CPlusPlus && 1028 RequireCompleteType(E->getExprLoc(), E->getType(), 1029 diag::err_call_incomplete_argument)) 1030 return ExprError(); 1031 1032 return E; 1033 } 1034 1035 /// Converts an integer to complex float type. Helper function of 1036 /// UsualArithmeticConversions() 1037 /// 1038 /// \return false if the integer expression is an integer type and is 1039 /// successfully converted to the complex type. 1040 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1041 ExprResult &ComplexExpr, 1042 QualType IntTy, 1043 QualType ComplexTy, 1044 bool SkipCast) { 1045 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1046 if (SkipCast) return false; 1047 if (IntTy->isIntegerType()) { 1048 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1049 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1050 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1051 CK_FloatingRealToComplex); 1052 } else { 1053 assert(IntTy->isComplexIntegerType()); 1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1055 CK_IntegralComplexToFloatingComplex); 1056 } 1057 return false; 1058 } 1059 1060 /// Handle arithmetic conversion with complex types. Helper function of 1061 /// UsualArithmeticConversions() 1062 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1063 ExprResult &RHS, QualType LHSType, 1064 QualType RHSType, 1065 bool IsCompAssign) { 1066 // if we have an integer operand, the result is the complex type. 1067 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1068 /*skipCast*/false)) 1069 return LHSType; 1070 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1071 /*skipCast*/IsCompAssign)) 1072 return RHSType; 1073 1074 // This handles complex/complex, complex/float, or float/complex. 1075 // When both operands are complex, the shorter operand is converted to the 1076 // type of the longer, and that is the type of the result. This corresponds 1077 // to what is done when combining two real floating-point operands. 1078 // The fun begins when size promotion occur across type domains. 1079 // From H&S 6.3.4: When one operand is complex and the other is a real 1080 // floating-point type, the less precise type is converted, within it's 1081 // real or complex domain, to the precision of the other type. For example, 1082 // when combining a "long double" with a "double _Complex", the 1083 // "double _Complex" is promoted to "long double _Complex". 1084 1085 // Compute the rank of the two types, regardless of whether they are complex. 1086 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1087 1088 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1089 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1090 QualType LHSElementType = 1091 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1092 QualType RHSElementType = 1093 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1094 1095 QualType ResultType = S.Context.getComplexType(LHSElementType); 1096 if (Order < 0) { 1097 // Promote the precision of the LHS if not an assignment. 1098 ResultType = S.Context.getComplexType(RHSElementType); 1099 if (!IsCompAssign) { 1100 if (LHSComplexType) 1101 LHS = 1102 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1103 else 1104 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1105 } 1106 } else if (Order > 0) { 1107 // Promote the precision of the RHS. 1108 if (RHSComplexType) 1109 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1110 else 1111 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1112 } 1113 return ResultType; 1114 } 1115 1116 /// Handle arithmetic conversion from integer to float. Helper function 1117 /// of UsualArithmeticConversions() 1118 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1119 ExprResult &IntExpr, 1120 QualType FloatTy, QualType IntTy, 1121 bool ConvertFloat, bool ConvertInt) { 1122 if (IntTy->isIntegerType()) { 1123 if (ConvertInt) 1124 // Convert intExpr to the lhs floating point type. 1125 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1126 CK_IntegralToFloating); 1127 return FloatTy; 1128 } 1129 1130 // Convert both sides to the appropriate complex float. 1131 assert(IntTy->isComplexIntegerType()); 1132 QualType result = S.Context.getComplexType(FloatTy); 1133 1134 // _Complex int -> _Complex float 1135 if (ConvertInt) 1136 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1137 CK_IntegralComplexToFloatingComplex); 1138 1139 // float -> _Complex float 1140 if (ConvertFloat) 1141 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1142 CK_FloatingRealToComplex); 1143 1144 return result; 1145 } 1146 1147 /// Handle arithmethic conversion with floating point types. Helper 1148 /// function of UsualArithmeticConversions() 1149 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1150 ExprResult &RHS, QualType LHSType, 1151 QualType RHSType, bool IsCompAssign) { 1152 bool LHSFloat = LHSType->isRealFloatingType(); 1153 bool RHSFloat = RHSType->isRealFloatingType(); 1154 1155 // N1169 4.1.4: If one of the operands has a floating type and the other 1156 // operand has a fixed-point type, the fixed-point operand 1157 // is converted to the floating type [...] 1158 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1159 if (LHSFloat) 1160 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1161 else if (!IsCompAssign) 1162 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1163 return LHSFloat ? LHSType : RHSType; 1164 } 1165 1166 // If we have two real floating types, convert the smaller operand 1167 // to the bigger result. 1168 if (LHSFloat && RHSFloat) { 1169 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1170 if (order > 0) { 1171 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1172 return LHSType; 1173 } 1174 1175 assert(order < 0 && "illegal float comparison"); 1176 if (!IsCompAssign) 1177 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1178 return RHSType; 1179 } 1180 1181 if (LHSFloat) { 1182 // Half FP has to be promoted to float unless it is natively supported 1183 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1184 LHSType = S.Context.FloatTy; 1185 1186 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1187 /*ConvertFloat=*/!IsCompAssign, 1188 /*ConvertInt=*/ true); 1189 } 1190 assert(RHSFloat); 1191 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1192 /*ConvertFloat=*/ true, 1193 /*ConvertInt=*/!IsCompAssign); 1194 } 1195 1196 /// Diagnose attempts to convert between __float128 and long double if 1197 /// there is no support for such conversion. Helper function of 1198 /// UsualArithmeticConversions(). 1199 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1200 QualType RHSType) { 1201 /* No issue converting if at least one of the types is not a floating point 1202 type or the two types have the same rank. 1203 */ 1204 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1205 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1206 return false; 1207 1208 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1209 "The remaining types must be floating point types."); 1210 1211 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1212 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1213 1214 QualType LHSElemType = LHSComplex ? 1215 LHSComplex->getElementType() : LHSType; 1216 QualType RHSElemType = RHSComplex ? 1217 RHSComplex->getElementType() : RHSType; 1218 1219 // No issue if the two types have the same representation 1220 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1221 &S.Context.getFloatTypeSemantics(RHSElemType)) 1222 return false; 1223 1224 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1225 RHSElemType == S.Context.LongDoubleTy); 1226 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1227 RHSElemType == S.Context.Float128Ty); 1228 1229 // We've handled the situation where __float128 and long double have the same 1230 // representation. We allow all conversions for all possible long double types 1231 // except PPC's double double. 1232 return Float128AndLongDouble && 1233 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1234 &llvm::APFloat::PPCDoubleDouble()); 1235 } 1236 1237 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1238 1239 namespace { 1240 /// These helper callbacks are placed in an anonymous namespace to 1241 /// permit their use as function template parameters. 1242 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1243 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1244 } 1245 1246 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1247 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1248 CK_IntegralComplexCast); 1249 } 1250 } 1251 1252 /// Handle integer arithmetic conversions. Helper function of 1253 /// UsualArithmeticConversions() 1254 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1255 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1256 ExprResult &RHS, QualType LHSType, 1257 QualType RHSType, bool IsCompAssign) { 1258 // The rules for this case are in C99 6.3.1.8 1259 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1260 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1261 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1262 if (LHSSigned == RHSSigned) { 1263 // Same signedness; use the higher-ranked type 1264 if (order >= 0) { 1265 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1266 return LHSType; 1267 } else if (!IsCompAssign) 1268 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1269 return RHSType; 1270 } else if (order != (LHSSigned ? 1 : -1)) { 1271 // The unsigned type has greater than or equal rank to the 1272 // signed type, so use the unsigned type 1273 if (RHSSigned) { 1274 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1275 return LHSType; 1276 } else if (!IsCompAssign) 1277 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1278 return RHSType; 1279 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1280 // The two types are different widths; if we are here, that 1281 // means the signed type is larger than the unsigned type, so 1282 // use the signed type. 1283 if (LHSSigned) { 1284 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1285 return LHSType; 1286 } else if (!IsCompAssign) 1287 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1288 return RHSType; 1289 } else { 1290 // The signed type is higher-ranked than the unsigned type, 1291 // but isn't actually any bigger (like unsigned int and long 1292 // on most 32-bit systems). Use the unsigned type corresponding 1293 // to the signed type. 1294 QualType result = 1295 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1296 RHS = (*doRHSCast)(S, RHS.get(), result); 1297 if (!IsCompAssign) 1298 LHS = (*doLHSCast)(S, LHS.get(), result); 1299 return result; 1300 } 1301 } 1302 1303 /// Handle conversions with GCC complex int extension. Helper function 1304 /// of UsualArithmeticConversions() 1305 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1306 ExprResult &RHS, QualType LHSType, 1307 QualType RHSType, 1308 bool IsCompAssign) { 1309 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1310 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1311 1312 if (LHSComplexInt && RHSComplexInt) { 1313 QualType LHSEltType = LHSComplexInt->getElementType(); 1314 QualType RHSEltType = RHSComplexInt->getElementType(); 1315 QualType ScalarType = 1316 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1317 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1318 1319 return S.Context.getComplexType(ScalarType); 1320 } 1321 1322 if (LHSComplexInt) { 1323 QualType LHSEltType = LHSComplexInt->getElementType(); 1324 QualType ScalarType = 1325 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1326 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1327 QualType ComplexType = S.Context.getComplexType(ScalarType); 1328 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1329 CK_IntegralRealToComplex); 1330 1331 return ComplexType; 1332 } 1333 1334 assert(RHSComplexInt); 1335 1336 QualType RHSEltType = RHSComplexInt->getElementType(); 1337 QualType ScalarType = 1338 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1339 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1340 QualType ComplexType = S.Context.getComplexType(ScalarType); 1341 1342 if (!IsCompAssign) 1343 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1344 CK_IntegralRealToComplex); 1345 return ComplexType; 1346 } 1347 1348 /// Return the rank of a given fixed point or integer type. The value itself 1349 /// doesn't matter, but the values must be increasing with proper increasing 1350 /// rank as described in N1169 4.1.1. 1351 static unsigned GetFixedPointRank(QualType Ty) { 1352 const auto *BTy = Ty->getAs<BuiltinType>(); 1353 assert(BTy && "Expected a builtin type."); 1354 1355 switch (BTy->getKind()) { 1356 case BuiltinType::ShortFract: 1357 case BuiltinType::UShortFract: 1358 case BuiltinType::SatShortFract: 1359 case BuiltinType::SatUShortFract: 1360 return 1; 1361 case BuiltinType::Fract: 1362 case BuiltinType::UFract: 1363 case BuiltinType::SatFract: 1364 case BuiltinType::SatUFract: 1365 return 2; 1366 case BuiltinType::LongFract: 1367 case BuiltinType::ULongFract: 1368 case BuiltinType::SatLongFract: 1369 case BuiltinType::SatULongFract: 1370 return 3; 1371 case BuiltinType::ShortAccum: 1372 case BuiltinType::UShortAccum: 1373 case BuiltinType::SatShortAccum: 1374 case BuiltinType::SatUShortAccum: 1375 return 4; 1376 case BuiltinType::Accum: 1377 case BuiltinType::UAccum: 1378 case BuiltinType::SatAccum: 1379 case BuiltinType::SatUAccum: 1380 return 5; 1381 case BuiltinType::LongAccum: 1382 case BuiltinType::ULongAccum: 1383 case BuiltinType::SatLongAccum: 1384 case BuiltinType::SatULongAccum: 1385 return 6; 1386 default: 1387 if (BTy->isInteger()) 1388 return 0; 1389 llvm_unreachable("Unexpected fixed point or integer type"); 1390 } 1391 } 1392 1393 /// handleFixedPointConversion - Fixed point operations between fixed 1394 /// point types and integers or other fixed point types do not fall under 1395 /// usual arithmetic conversion since these conversions could result in loss 1396 /// of precsision (N1169 4.1.4). These operations should be calculated with 1397 /// the full precision of their result type (N1169 4.1.6.2.1). 1398 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1399 QualType RHSTy) { 1400 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1401 "Expected at least one of the operands to be a fixed point type"); 1402 assert((LHSTy->isFixedPointOrIntegerType() || 1403 RHSTy->isFixedPointOrIntegerType()) && 1404 "Special fixed point arithmetic operation conversions are only " 1405 "applied to ints or other fixed point types"); 1406 1407 // If one operand has signed fixed-point type and the other operand has 1408 // unsigned fixed-point type, then the unsigned fixed-point operand is 1409 // converted to its corresponding signed fixed-point type and the resulting 1410 // type is the type of the converted operand. 1411 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1412 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1413 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1414 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1415 1416 // The result type is the type with the highest rank, whereby a fixed-point 1417 // conversion rank is always greater than an integer conversion rank; if the 1418 // type of either of the operands is a saturating fixedpoint type, the result 1419 // type shall be the saturating fixed-point type corresponding to the type 1420 // with the highest rank; the resulting value is converted (taking into 1421 // account rounding and overflow) to the precision of the resulting type. 1422 // Same ranks between signed and unsigned types are resolved earlier, so both 1423 // types are either signed or both unsigned at this point. 1424 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1425 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1426 1427 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1428 1429 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1430 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1431 1432 return ResultTy; 1433 } 1434 1435 /// Check that the usual arithmetic conversions can be performed on this pair of 1436 /// expressions that might be of enumeration type. 1437 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1438 SourceLocation Loc, 1439 Sema::ArithConvKind ACK) { 1440 // C++2a [expr.arith.conv]p1: 1441 // If one operand is of enumeration type and the other operand is of a 1442 // different enumeration type or a floating-point type, this behavior is 1443 // deprecated ([depr.arith.conv.enum]). 1444 // 1445 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1446 // Eventually we will presumably reject these cases (in C++23 onwards?). 1447 QualType L = LHS->getType(), R = RHS->getType(); 1448 bool LEnum = L->isUnscopedEnumerationType(), 1449 REnum = R->isUnscopedEnumerationType(); 1450 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1451 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1452 (REnum && L->isFloatingType())) { 1453 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1454 ? diag::warn_arith_conv_enum_float_cxx20 1455 : diag::warn_arith_conv_enum_float) 1456 << LHS->getSourceRange() << RHS->getSourceRange() 1457 << (int)ACK << LEnum << L << R; 1458 } else if (!IsCompAssign && LEnum && REnum && 1459 !S.Context.hasSameUnqualifiedType(L, R)) { 1460 unsigned DiagID; 1461 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1462 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1463 // If either enumeration type is unnamed, it's less likely that the 1464 // user cares about this, but this situation is still deprecated in 1465 // C++2a. Use a different warning group. 1466 DiagID = S.getLangOpts().CPlusPlus20 1467 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1468 : diag::warn_arith_conv_mixed_anon_enum_types; 1469 } else if (ACK == Sema::ACK_Conditional) { 1470 // Conditional expressions are separated out because they have 1471 // historically had a different warning flag. 1472 DiagID = S.getLangOpts().CPlusPlus20 1473 ? diag::warn_conditional_mixed_enum_types_cxx20 1474 : diag::warn_conditional_mixed_enum_types; 1475 } else if (ACK == Sema::ACK_Comparison) { 1476 // Comparison expressions are separated out because they have 1477 // historically had a different warning flag. 1478 DiagID = S.getLangOpts().CPlusPlus20 1479 ? diag::warn_comparison_mixed_enum_types_cxx20 1480 : diag::warn_comparison_mixed_enum_types; 1481 } else { 1482 DiagID = S.getLangOpts().CPlusPlus20 1483 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1484 : diag::warn_arith_conv_mixed_enum_types; 1485 } 1486 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1487 << (int)ACK << L << R; 1488 } 1489 } 1490 1491 /// UsualArithmeticConversions - Performs various conversions that are common to 1492 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1493 /// routine returns the first non-arithmetic type found. The client is 1494 /// responsible for emitting appropriate error diagnostics. 1495 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1496 SourceLocation Loc, 1497 ArithConvKind ACK) { 1498 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1499 1500 if (ACK != ACK_CompAssign) { 1501 LHS = UsualUnaryConversions(LHS.get()); 1502 if (LHS.isInvalid()) 1503 return QualType(); 1504 } 1505 1506 RHS = UsualUnaryConversions(RHS.get()); 1507 if (RHS.isInvalid()) 1508 return QualType(); 1509 1510 // For conversion purposes, we ignore any qualifiers. 1511 // For example, "const float" and "float" are equivalent. 1512 QualType LHSType = 1513 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1514 QualType RHSType = 1515 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1516 1517 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1518 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1519 LHSType = AtomicLHS->getValueType(); 1520 1521 // If both types are identical, no conversion is needed. 1522 if (LHSType == RHSType) 1523 return LHSType; 1524 1525 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1526 // The caller can deal with this (e.g. pointer + int). 1527 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1528 return QualType(); 1529 1530 // Apply unary and bitfield promotions to the LHS's type. 1531 QualType LHSUnpromotedType = LHSType; 1532 if (LHSType->isPromotableIntegerType()) 1533 LHSType = Context.getPromotedIntegerType(LHSType); 1534 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1535 if (!LHSBitfieldPromoteTy.isNull()) 1536 LHSType = LHSBitfieldPromoteTy; 1537 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1538 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1539 1540 // If both types are identical, no conversion is needed. 1541 if (LHSType == RHSType) 1542 return LHSType; 1543 1544 // ExtInt types aren't subject to conversions between them or normal integers, 1545 // so this fails. 1546 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1547 return QualType(); 1548 1549 // At this point, we have two different arithmetic types. 1550 1551 // Diagnose attempts to convert between __float128 and long double where 1552 // such conversions currently can't be handled. 1553 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1554 return QualType(); 1555 1556 // Handle complex types first (C99 6.3.1.8p1). 1557 if (LHSType->isComplexType() || RHSType->isComplexType()) 1558 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1559 ACK == ACK_CompAssign); 1560 1561 // Now handle "real" floating types (i.e. float, double, long double). 1562 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1563 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1564 ACK == ACK_CompAssign); 1565 1566 // Handle GCC complex int extension. 1567 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1568 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1569 ACK == ACK_CompAssign); 1570 1571 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1572 return handleFixedPointConversion(*this, LHSType, RHSType); 1573 1574 // Finally, we have two differing integer types. 1575 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1576 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1577 } 1578 1579 //===----------------------------------------------------------------------===// 1580 // Semantic Analysis for various Expression Types 1581 //===----------------------------------------------------------------------===// 1582 1583 1584 ExprResult 1585 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1586 SourceLocation DefaultLoc, 1587 SourceLocation RParenLoc, 1588 Expr *ControllingExpr, 1589 ArrayRef<ParsedType> ArgTypes, 1590 ArrayRef<Expr *> ArgExprs) { 1591 unsigned NumAssocs = ArgTypes.size(); 1592 assert(NumAssocs == ArgExprs.size()); 1593 1594 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1595 for (unsigned i = 0; i < NumAssocs; ++i) { 1596 if (ArgTypes[i]) 1597 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1598 else 1599 Types[i] = nullptr; 1600 } 1601 1602 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1603 ControllingExpr, 1604 llvm::makeArrayRef(Types, NumAssocs), 1605 ArgExprs); 1606 delete [] Types; 1607 return ER; 1608 } 1609 1610 ExprResult 1611 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1612 SourceLocation DefaultLoc, 1613 SourceLocation RParenLoc, 1614 Expr *ControllingExpr, 1615 ArrayRef<TypeSourceInfo *> Types, 1616 ArrayRef<Expr *> Exprs) { 1617 unsigned NumAssocs = Types.size(); 1618 assert(NumAssocs == Exprs.size()); 1619 1620 // Decay and strip qualifiers for the controlling expression type, and handle 1621 // placeholder type replacement. See committee discussion from WG14 DR423. 1622 { 1623 EnterExpressionEvaluationContext Unevaluated( 1624 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1625 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1626 if (R.isInvalid()) 1627 return ExprError(); 1628 ControllingExpr = R.get(); 1629 } 1630 1631 // The controlling expression is an unevaluated operand, so side effects are 1632 // likely unintended. 1633 if (!inTemplateInstantiation() && 1634 ControllingExpr->HasSideEffects(Context, false)) 1635 Diag(ControllingExpr->getExprLoc(), 1636 diag::warn_side_effects_unevaluated_context); 1637 1638 bool TypeErrorFound = false, 1639 IsResultDependent = ControllingExpr->isTypeDependent(), 1640 ContainsUnexpandedParameterPack 1641 = ControllingExpr->containsUnexpandedParameterPack(); 1642 1643 for (unsigned i = 0; i < NumAssocs; ++i) { 1644 if (Exprs[i]->containsUnexpandedParameterPack()) 1645 ContainsUnexpandedParameterPack = true; 1646 1647 if (Types[i]) { 1648 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1649 ContainsUnexpandedParameterPack = true; 1650 1651 if (Types[i]->getType()->isDependentType()) { 1652 IsResultDependent = true; 1653 } else { 1654 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1655 // complete object type other than a variably modified type." 1656 unsigned D = 0; 1657 if (Types[i]->getType()->isIncompleteType()) 1658 D = diag::err_assoc_type_incomplete; 1659 else if (!Types[i]->getType()->isObjectType()) 1660 D = diag::err_assoc_type_nonobject; 1661 else if (Types[i]->getType()->isVariablyModifiedType()) 1662 D = diag::err_assoc_type_variably_modified; 1663 1664 if (D != 0) { 1665 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1666 << Types[i]->getTypeLoc().getSourceRange() 1667 << Types[i]->getType(); 1668 TypeErrorFound = true; 1669 } 1670 1671 // C11 6.5.1.1p2 "No two generic associations in the same generic 1672 // selection shall specify compatible types." 1673 for (unsigned j = i+1; j < NumAssocs; ++j) 1674 if (Types[j] && !Types[j]->getType()->isDependentType() && 1675 Context.typesAreCompatible(Types[i]->getType(), 1676 Types[j]->getType())) { 1677 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1678 diag::err_assoc_compatible_types) 1679 << Types[j]->getTypeLoc().getSourceRange() 1680 << Types[j]->getType() 1681 << Types[i]->getType(); 1682 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1683 diag::note_compat_assoc) 1684 << Types[i]->getTypeLoc().getSourceRange() 1685 << Types[i]->getType(); 1686 TypeErrorFound = true; 1687 } 1688 } 1689 } 1690 } 1691 if (TypeErrorFound) 1692 return ExprError(); 1693 1694 // If we determined that the generic selection is result-dependent, don't 1695 // try to compute the result expression. 1696 if (IsResultDependent) 1697 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1698 Exprs, DefaultLoc, RParenLoc, 1699 ContainsUnexpandedParameterPack); 1700 1701 SmallVector<unsigned, 1> CompatIndices; 1702 unsigned DefaultIndex = -1U; 1703 for (unsigned i = 0; i < NumAssocs; ++i) { 1704 if (!Types[i]) 1705 DefaultIndex = i; 1706 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1707 Types[i]->getType())) 1708 CompatIndices.push_back(i); 1709 } 1710 1711 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1712 // type compatible with at most one of the types named in its generic 1713 // association list." 1714 if (CompatIndices.size() > 1) { 1715 // We strip parens here because the controlling expression is typically 1716 // parenthesized in macro definitions. 1717 ControllingExpr = ControllingExpr->IgnoreParens(); 1718 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1719 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1720 << (unsigned)CompatIndices.size(); 1721 for (unsigned I : CompatIndices) { 1722 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1723 diag::note_compat_assoc) 1724 << Types[I]->getTypeLoc().getSourceRange() 1725 << Types[I]->getType(); 1726 } 1727 return ExprError(); 1728 } 1729 1730 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1731 // its controlling expression shall have type compatible with exactly one of 1732 // the types named in its generic association list." 1733 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1734 // We strip parens here because the controlling expression is typically 1735 // parenthesized in macro definitions. 1736 ControllingExpr = ControllingExpr->IgnoreParens(); 1737 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1738 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1739 return ExprError(); 1740 } 1741 1742 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1743 // type name that is compatible with the type of the controlling expression, 1744 // then the result expression of the generic selection is the expression 1745 // in that generic association. Otherwise, the result expression of the 1746 // generic selection is the expression in the default generic association." 1747 unsigned ResultIndex = 1748 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1749 1750 return GenericSelectionExpr::Create( 1751 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1752 ContainsUnexpandedParameterPack, ResultIndex); 1753 } 1754 1755 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1756 /// location of the token and the offset of the ud-suffix within it. 1757 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1758 unsigned Offset) { 1759 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1760 S.getLangOpts()); 1761 } 1762 1763 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1764 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1765 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1766 IdentifierInfo *UDSuffix, 1767 SourceLocation UDSuffixLoc, 1768 ArrayRef<Expr*> Args, 1769 SourceLocation LitEndLoc) { 1770 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1771 1772 QualType ArgTy[2]; 1773 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1774 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1775 if (ArgTy[ArgIdx]->isArrayType()) 1776 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1777 } 1778 1779 DeclarationName OpName = 1780 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1781 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1782 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1783 1784 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1785 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1786 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1787 /*AllowStringTemplatePack*/ false, 1788 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1789 return ExprError(); 1790 1791 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1792 } 1793 1794 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1795 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1796 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1797 /// multiple tokens. However, the common case is that StringToks points to one 1798 /// string. 1799 /// 1800 ExprResult 1801 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1802 assert(!StringToks.empty() && "Must have at least one string!"); 1803 1804 StringLiteralParser Literal(StringToks, PP); 1805 if (Literal.hadError) 1806 return ExprError(); 1807 1808 SmallVector<SourceLocation, 4> StringTokLocs; 1809 for (const Token &Tok : StringToks) 1810 StringTokLocs.push_back(Tok.getLocation()); 1811 1812 QualType CharTy = Context.CharTy; 1813 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1814 if (Literal.isWide()) { 1815 CharTy = Context.getWideCharType(); 1816 Kind = StringLiteral::Wide; 1817 } else if (Literal.isUTF8()) { 1818 if (getLangOpts().Char8) 1819 CharTy = Context.Char8Ty; 1820 Kind = StringLiteral::UTF8; 1821 } else if (Literal.isUTF16()) { 1822 CharTy = Context.Char16Ty; 1823 Kind = StringLiteral::UTF16; 1824 } else if (Literal.isUTF32()) { 1825 CharTy = Context.Char32Ty; 1826 Kind = StringLiteral::UTF32; 1827 } else if (Literal.isPascal()) { 1828 CharTy = Context.UnsignedCharTy; 1829 } 1830 1831 // Warn on initializing an array of char from a u8 string literal; this 1832 // becomes ill-formed in C++2a. 1833 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1834 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1835 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1836 1837 // Create removals for all 'u8' prefixes in the string literal(s). This 1838 // ensures C++2a compatibility (but may change the program behavior when 1839 // built by non-Clang compilers for which the execution character set is 1840 // not always UTF-8). 1841 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1842 SourceLocation RemovalDiagLoc; 1843 for (const Token &Tok : StringToks) { 1844 if (Tok.getKind() == tok::utf8_string_literal) { 1845 if (RemovalDiagLoc.isInvalid()) 1846 RemovalDiagLoc = Tok.getLocation(); 1847 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1848 Tok.getLocation(), 1849 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1850 getSourceManager(), getLangOpts()))); 1851 } 1852 } 1853 Diag(RemovalDiagLoc, RemovalDiag); 1854 } 1855 1856 QualType StrTy = 1857 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1858 1859 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1860 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1861 Kind, Literal.Pascal, StrTy, 1862 &StringTokLocs[0], 1863 StringTokLocs.size()); 1864 if (Literal.getUDSuffix().empty()) 1865 return Lit; 1866 1867 // We're building a user-defined literal. 1868 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1869 SourceLocation UDSuffixLoc = 1870 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1871 Literal.getUDSuffixOffset()); 1872 1873 // Make sure we're allowed user-defined literals here. 1874 if (!UDLScope) 1875 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1876 1877 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1878 // operator "" X (str, len) 1879 QualType SizeType = Context.getSizeType(); 1880 1881 DeclarationName OpName = 1882 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1883 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1884 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1885 1886 QualType ArgTy[] = { 1887 Context.getArrayDecayedType(StrTy), SizeType 1888 }; 1889 1890 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1891 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1892 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1893 /*AllowStringTemplatePack*/ true, 1894 /*DiagnoseMissing*/ true, Lit)) { 1895 1896 case LOLR_Cooked: { 1897 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1898 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1899 StringTokLocs[0]); 1900 Expr *Args[] = { Lit, LenArg }; 1901 1902 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1903 } 1904 1905 case LOLR_Template: { 1906 TemplateArgumentListInfo ExplicitArgs; 1907 TemplateArgument Arg(Lit); 1908 TemplateArgumentLocInfo ArgInfo(Lit); 1909 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1910 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1911 &ExplicitArgs); 1912 } 1913 1914 case LOLR_StringTemplatePack: { 1915 TemplateArgumentListInfo ExplicitArgs; 1916 1917 unsigned CharBits = Context.getIntWidth(CharTy); 1918 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1919 llvm::APSInt Value(CharBits, CharIsUnsigned); 1920 1921 TemplateArgument TypeArg(CharTy); 1922 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1923 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1924 1925 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1926 Value = Lit->getCodeUnit(I); 1927 TemplateArgument Arg(Context, Value, CharTy); 1928 TemplateArgumentLocInfo ArgInfo; 1929 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1930 } 1931 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1932 &ExplicitArgs); 1933 } 1934 case LOLR_Raw: 1935 case LOLR_ErrorNoDiagnostic: 1936 llvm_unreachable("unexpected literal operator lookup result"); 1937 case LOLR_Error: 1938 return ExprError(); 1939 } 1940 llvm_unreachable("unexpected literal operator lookup result"); 1941 } 1942 1943 DeclRefExpr * 1944 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1945 SourceLocation Loc, 1946 const CXXScopeSpec *SS) { 1947 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1948 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1949 } 1950 1951 DeclRefExpr * 1952 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1953 const DeclarationNameInfo &NameInfo, 1954 const CXXScopeSpec *SS, NamedDecl *FoundD, 1955 SourceLocation TemplateKWLoc, 1956 const TemplateArgumentListInfo *TemplateArgs) { 1957 NestedNameSpecifierLoc NNS = 1958 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1959 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1960 TemplateArgs); 1961 } 1962 1963 // CUDA/HIP: Check whether a captured reference variable is referencing a 1964 // host variable in a device or host device lambda. 1965 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1966 VarDecl *VD) { 1967 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1968 return false; 1969 assert(VD->getType()->isReferenceType()); 1970 1971 // Check whether the reference variable is referencing a host variable. 1972 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1973 if (!DRE) 1974 return false; 1975 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1976 if (!Referee || !Referee->hasGlobalStorage() || 1977 Referee->hasAttr<CUDADeviceAttr>()) 1978 return false; 1979 1980 // Check whether the current function is a device or host device lambda. 1981 // Check whether the reference variable is a capture by getDeclContext() 1982 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1983 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1984 if (MD && MD->getParent()->isLambda() && 1985 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1986 VD->getDeclContext() != MD) 1987 return true; 1988 1989 return false; 1990 } 1991 1992 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1993 // A declaration named in an unevaluated operand never constitutes an odr-use. 1994 if (isUnevaluatedContext()) 1995 return NOUR_Unevaluated; 1996 1997 // C++2a [basic.def.odr]p4: 1998 // A variable x whose name appears as a potentially-evaluated expression e 1999 // is odr-used by e unless [...] x is a reference that is usable in 2000 // constant expressions. 2001 // CUDA/HIP: 2002 // If a reference variable referencing a host variable is captured in a 2003 // device or host device lambda, the value of the referee must be copied 2004 // to the capture and the reference variable must be treated as odr-use 2005 // since the value of the referee is not known at compile time and must 2006 // be loaded from the captured. 2007 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2008 if (VD->getType()->isReferenceType() && 2009 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2010 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2011 VD->isUsableInConstantExpressions(Context)) 2012 return NOUR_Constant; 2013 } 2014 2015 // All remaining non-variable cases constitute an odr-use. For variables, we 2016 // need to wait and see how the expression is used. 2017 return NOUR_None; 2018 } 2019 2020 /// BuildDeclRefExpr - Build an expression that references a 2021 /// declaration that does not require a closure capture. 2022 DeclRefExpr * 2023 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2024 const DeclarationNameInfo &NameInfo, 2025 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2026 SourceLocation TemplateKWLoc, 2027 const TemplateArgumentListInfo *TemplateArgs) { 2028 bool RefersToCapturedVariable = 2029 isa<VarDecl>(D) && 2030 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2031 2032 DeclRefExpr *E = DeclRefExpr::Create( 2033 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2034 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2035 MarkDeclRefReferenced(E); 2036 2037 // C++ [except.spec]p17: 2038 // An exception-specification is considered to be needed when: 2039 // - in an expression, the function is the unique lookup result or 2040 // the selected member of a set of overloaded functions. 2041 // 2042 // We delay doing this until after we've built the function reference and 2043 // marked it as used so that: 2044 // a) if the function is defaulted, we get errors from defining it before / 2045 // instead of errors from computing its exception specification, and 2046 // b) if the function is a defaulted comparison, we can use the body we 2047 // build when defining it as input to the exception specification 2048 // computation rather than computing a new body. 2049 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2050 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2051 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2052 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2053 } 2054 } 2055 2056 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2057 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2058 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2059 getCurFunction()->recordUseOfWeak(E); 2060 2061 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2062 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2063 FD = IFD->getAnonField(); 2064 if (FD) { 2065 UnusedPrivateFields.remove(FD); 2066 // Just in case we're building an illegal pointer-to-member. 2067 if (FD->isBitField()) 2068 E->setObjectKind(OK_BitField); 2069 } 2070 2071 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2072 // designates a bit-field. 2073 if (auto *BD = dyn_cast<BindingDecl>(D)) 2074 if (auto *BE = BD->getBinding()) 2075 E->setObjectKind(BE->getObjectKind()); 2076 2077 return E; 2078 } 2079 2080 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2081 /// possibly a list of template arguments. 2082 /// 2083 /// If this produces template arguments, it is permitted to call 2084 /// DecomposeTemplateName. 2085 /// 2086 /// This actually loses a lot of source location information for 2087 /// non-standard name kinds; we should consider preserving that in 2088 /// some way. 2089 void 2090 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2091 TemplateArgumentListInfo &Buffer, 2092 DeclarationNameInfo &NameInfo, 2093 const TemplateArgumentListInfo *&TemplateArgs) { 2094 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2095 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2096 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2097 2098 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2099 Id.TemplateId->NumArgs); 2100 translateTemplateArguments(TemplateArgsPtr, Buffer); 2101 2102 TemplateName TName = Id.TemplateId->Template.get(); 2103 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2104 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2105 TemplateArgs = &Buffer; 2106 } else { 2107 NameInfo = GetNameFromUnqualifiedId(Id); 2108 TemplateArgs = nullptr; 2109 } 2110 } 2111 2112 static void emitEmptyLookupTypoDiagnostic( 2113 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2114 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2115 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2116 DeclContext *Ctx = 2117 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2118 if (!TC) { 2119 // Emit a special diagnostic for failed member lookups. 2120 // FIXME: computing the declaration context might fail here (?) 2121 if (Ctx) 2122 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2123 << SS.getRange(); 2124 else 2125 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2126 return; 2127 } 2128 2129 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2130 bool DroppedSpecifier = 2131 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2132 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2133 ? diag::note_implicit_param_decl 2134 : diag::note_previous_decl; 2135 if (!Ctx) 2136 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2137 SemaRef.PDiag(NoteID)); 2138 else 2139 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2140 << Typo << Ctx << DroppedSpecifier 2141 << SS.getRange(), 2142 SemaRef.PDiag(NoteID)); 2143 } 2144 2145 /// Diagnose a lookup that found results in an enclosing class during error 2146 /// recovery. This usually indicates that the results were found in a dependent 2147 /// base class that could not be searched as part of a template definition. 2148 /// Always issues a diagnostic (though this may be only a warning in MS 2149 /// compatibility mode). 2150 /// 2151 /// Return \c true if the error is unrecoverable, or \c false if the caller 2152 /// should attempt to recover using these lookup results. 2153 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2154 // During a default argument instantiation the CurContext points 2155 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2156 // function parameter list, hence add an explicit check. 2157 bool isDefaultArgument = 2158 !CodeSynthesisContexts.empty() && 2159 CodeSynthesisContexts.back().Kind == 2160 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2161 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2162 bool isInstance = CurMethod && CurMethod->isInstance() && 2163 R.getNamingClass() == CurMethod->getParent() && 2164 !isDefaultArgument; 2165 2166 // There are two ways we can find a class-scope declaration during template 2167 // instantiation that we did not find in the template definition: if it is a 2168 // member of a dependent base class, or if it is declared after the point of 2169 // use in the same class. Distinguish these by comparing the class in which 2170 // the member was found to the naming class of the lookup. 2171 unsigned DiagID = diag::err_found_in_dependent_base; 2172 unsigned NoteID = diag::note_member_declared_at; 2173 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2174 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2175 : diag::err_found_later_in_class; 2176 } else if (getLangOpts().MSVCCompat) { 2177 DiagID = diag::ext_found_in_dependent_base; 2178 NoteID = diag::note_dependent_member_use; 2179 } 2180 2181 if (isInstance) { 2182 // Give a code modification hint to insert 'this->'. 2183 Diag(R.getNameLoc(), DiagID) 2184 << R.getLookupName() 2185 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2186 CheckCXXThisCapture(R.getNameLoc()); 2187 } else { 2188 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2189 // they're not shadowed). 2190 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2191 } 2192 2193 for (NamedDecl *D : R) 2194 Diag(D->getLocation(), NoteID); 2195 2196 // Return true if we are inside a default argument instantiation 2197 // and the found name refers to an instance member function, otherwise 2198 // the caller will try to create an implicit member call and this is wrong 2199 // for default arguments. 2200 // 2201 // FIXME: Is this special case necessary? We could allow the caller to 2202 // diagnose this. 2203 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2204 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2205 return true; 2206 } 2207 2208 // Tell the callee to try to recover. 2209 return false; 2210 } 2211 2212 /// Diagnose an empty lookup. 2213 /// 2214 /// \return false if new lookup candidates were found 2215 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2216 CorrectionCandidateCallback &CCC, 2217 TemplateArgumentListInfo *ExplicitTemplateArgs, 2218 ArrayRef<Expr *> Args, TypoExpr **Out) { 2219 DeclarationName Name = R.getLookupName(); 2220 2221 unsigned diagnostic = diag::err_undeclared_var_use; 2222 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2223 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2224 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2225 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2226 diagnostic = diag::err_undeclared_use; 2227 diagnostic_suggest = diag::err_undeclared_use_suggest; 2228 } 2229 2230 // If the original lookup was an unqualified lookup, fake an 2231 // unqualified lookup. This is useful when (for example) the 2232 // original lookup would not have found something because it was a 2233 // dependent name. 2234 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2235 while (DC) { 2236 if (isa<CXXRecordDecl>(DC)) { 2237 LookupQualifiedName(R, DC); 2238 2239 if (!R.empty()) { 2240 // Don't give errors about ambiguities in this lookup. 2241 R.suppressDiagnostics(); 2242 2243 // If there's a best viable function among the results, only mention 2244 // that one in the notes. 2245 OverloadCandidateSet Candidates(R.getNameLoc(), 2246 OverloadCandidateSet::CSK_Normal); 2247 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2248 OverloadCandidateSet::iterator Best; 2249 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2250 OR_Success) { 2251 R.clear(); 2252 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2253 R.resolveKind(); 2254 } 2255 2256 return DiagnoseDependentMemberLookup(R); 2257 } 2258 2259 R.clear(); 2260 } 2261 2262 DC = DC->getLookupParent(); 2263 } 2264 2265 // We didn't find anything, so try to correct for a typo. 2266 TypoCorrection Corrected; 2267 if (S && Out) { 2268 SourceLocation TypoLoc = R.getNameLoc(); 2269 assert(!ExplicitTemplateArgs && 2270 "Diagnosing an empty lookup with explicit template args!"); 2271 *Out = CorrectTypoDelayed( 2272 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2273 [=](const TypoCorrection &TC) { 2274 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2275 diagnostic, diagnostic_suggest); 2276 }, 2277 nullptr, CTK_ErrorRecovery); 2278 if (*Out) 2279 return true; 2280 } else if (S && 2281 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2282 S, &SS, CCC, CTK_ErrorRecovery))) { 2283 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2284 bool DroppedSpecifier = 2285 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2286 R.setLookupName(Corrected.getCorrection()); 2287 2288 bool AcceptableWithRecovery = false; 2289 bool AcceptableWithoutRecovery = false; 2290 NamedDecl *ND = Corrected.getFoundDecl(); 2291 if (ND) { 2292 if (Corrected.isOverloaded()) { 2293 OverloadCandidateSet OCS(R.getNameLoc(), 2294 OverloadCandidateSet::CSK_Normal); 2295 OverloadCandidateSet::iterator Best; 2296 for (NamedDecl *CD : Corrected) { 2297 if (FunctionTemplateDecl *FTD = 2298 dyn_cast<FunctionTemplateDecl>(CD)) 2299 AddTemplateOverloadCandidate( 2300 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2301 Args, OCS); 2302 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2303 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2304 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2305 Args, OCS); 2306 } 2307 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2308 case OR_Success: 2309 ND = Best->FoundDecl; 2310 Corrected.setCorrectionDecl(ND); 2311 break; 2312 default: 2313 // FIXME: Arbitrarily pick the first declaration for the note. 2314 Corrected.setCorrectionDecl(ND); 2315 break; 2316 } 2317 } 2318 R.addDecl(ND); 2319 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2320 CXXRecordDecl *Record = nullptr; 2321 if (Corrected.getCorrectionSpecifier()) { 2322 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2323 Record = Ty->getAsCXXRecordDecl(); 2324 } 2325 if (!Record) 2326 Record = cast<CXXRecordDecl>( 2327 ND->getDeclContext()->getRedeclContext()); 2328 R.setNamingClass(Record); 2329 } 2330 2331 auto *UnderlyingND = ND->getUnderlyingDecl(); 2332 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2333 isa<FunctionTemplateDecl>(UnderlyingND); 2334 // FIXME: If we ended up with a typo for a type name or 2335 // Objective-C class name, we're in trouble because the parser 2336 // is in the wrong place to recover. Suggest the typo 2337 // correction, but don't make it a fix-it since we're not going 2338 // to recover well anyway. 2339 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2340 getAsTypeTemplateDecl(UnderlyingND) || 2341 isa<ObjCInterfaceDecl>(UnderlyingND); 2342 } else { 2343 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2344 // because we aren't able to recover. 2345 AcceptableWithoutRecovery = true; 2346 } 2347 2348 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2349 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2350 ? diag::note_implicit_param_decl 2351 : diag::note_previous_decl; 2352 if (SS.isEmpty()) 2353 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2354 PDiag(NoteID), AcceptableWithRecovery); 2355 else 2356 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2357 << Name << computeDeclContext(SS, false) 2358 << DroppedSpecifier << SS.getRange(), 2359 PDiag(NoteID), AcceptableWithRecovery); 2360 2361 // Tell the callee whether to try to recover. 2362 return !AcceptableWithRecovery; 2363 } 2364 } 2365 R.clear(); 2366 2367 // Emit a special diagnostic for failed member lookups. 2368 // FIXME: computing the declaration context might fail here (?) 2369 if (!SS.isEmpty()) { 2370 Diag(R.getNameLoc(), diag::err_no_member) 2371 << Name << computeDeclContext(SS, false) 2372 << SS.getRange(); 2373 return true; 2374 } 2375 2376 // Give up, we can't recover. 2377 Diag(R.getNameLoc(), diagnostic) << Name; 2378 return true; 2379 } 2380 2381 /// In Microsoft mode, if we are inside a template class whose parent class has 2382 /// dependent base classes, and we can't resolve an unqualified identifier, then 2383 /// assume the identifier is a member of a dependent base class. We can only 2384 /// recover successfully in static methods, instance methods, and other contexts 2385 /// where 'this' is available. This doesn't precisely match MSVC's 2386 /// instantiation model, but it's close enough. 2387 static Expr * 2388 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2389 DeclarationNameInfo &NameInfo, 2390 SourceLocation TemplateKWLoc, 2391 const TemplateArgumentListInfo *TemplateArgs) { 2392 // Only try to recover from lookup into dependent bases in static methods or 2393 // contexts where 'this' is available. 2394 QualType ThisType = S.getCurrentThisType(); 2395 const CXXRecordDecl *RD = nullptr; 2396 if (!ThisType.isNull()) 2397 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2398 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2399 RD = MD->getParent(); 2400 if (!RD || !RD->hasAnyDependentBases()) 2401 return nullptr; 2402 2403 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2404 // is available, suggest inserting 'this->' as a fixit. 2405 SourceLocation Loc = NameInfo.getLoc(); 2406 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2407 DB << NameInfo.getName() << RD; 2408 2409 if (!ThisType.isNull()) { 2410 DB << FixItHint::CreateInsertion(Loc, "this->"); 2411 return CXXDependentScopeMemberExpr::Create( 2412 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2413 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2414 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2415 } 2416 2417 // Synthesize a fake NNS that points to the derived class. This will 2418 // perform name lookup during template instantiation. 2419 CXXScopeSpec SS; 2420 auto *NNS = 2421 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2422 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2423 return DependentScopeDeclRefExpr::Create( 2424 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2425 TemplateArgs); 2426 } 2427 2428 ExprResult 2429 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2430 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2431 bool HasTrailingLParen, bool IsAddressOfOperand, 2432 CorrectionCandidateCallback *CCC, 2433 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2434 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2435 "cannot be direct & operand and have a trailing lparen"); 2436 if (SS.isInvalid()) 2437 return ExprError(); 2438 2439 TemplateArgumentListInfo TemplateArgsBuffer; 2440 2441 // Decompose the UnqualifiedId into the following data. 2442 DeclarationNameInfo NameInfo; 2443 const TemplateArgumentListInfo *TemplateArgs; 2444 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2445 2446 DeclarationName Name = NameInfo.getName(); 2447 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2448 SourceLocation NameLoc = NameInfo.getLoc(); 2449 2450 if (II && II->isEditorPlaceholder()) { 2451 // FIXME: When typed placeholders are supported we can create a typed 2452 // placeholder expression node. 2453 return ExprError(); 2454 } 2455 2456 // C++ [temp.dep.expr]p3: 2457 // An id-expression is type-dependent if it contains: 2458 // -- an identifier that was declared with a dependent type, 2459 // (note: handled after lookup) 2460 // -- a template-id that is dependent, 2461 // (note: handled in BuildTemplateIdExpr) 2462 // -- a conversion-function-id that specifies a dependent type, 2463 // -- a nested-name-specifier that contains a class-name that 2464 // names a dependent type. 2465 // Determine whether this is a member of an unknown specialization; 2466 // we need to handle these differently. 2467 bool DependentID = false; 2468 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2469 Name.getCXXNameType()->isDependentType()) { 2470 DependentID = true; 2471 } else if (SS.isSet()) { 2472 if (DeclContext *DC = computeDeclContext(SS, false)) { 2473 if (RequireCompleteDeclContext(SS, DC)) 2474 return ExprError(); 2475 } else { 2476 DependentID = true; 2477 } 2478 } 2479 2480 if (DependentID) 2481 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2482 IsAddressOfOperand, TemplateArgs); 2483 2484 // Perform the required lookup. 2485 LookupResult R(*this, NameInfo, 2486 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2487 ? LookupObjCImplicitSelfParam 2488 : LookupOrdinaryName); 2489 if (TemplateKWLoc.isValid() || TemplateArgs) { 2490 // Lookup the template name again to correctly establish the context in 2491 // which it was found. This is really unfortunate as we already did the 2492 // lookup to determine that it was a template name in the first place. If 2493 // this becomes a performance hit, we can work harder to preserve those 2494 // results until we get here but it's likely not worth it. 2495 bool MemberOfUnknownSpecialization; 2496 AssumedTemplateKind AssumedTemplate; 2497 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2498 MemberOfUnknownSpecialization, TemplateKWLoc, 2499 &AssumedTemplate)) 2500 return ExprError(); 2501 2502 if (MemberOfUnknownSpecialization || 2503 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2504 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2505 IsAddressOfOperand, TemplateArgs); 2506 } else { 2507 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2508 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2509 2510 // If the result might be in a dependent base class, this is a dependent 2511 // id-expression. 2512 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2513 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2514 IsAddressOfOperand, TemplateArgs); 2515 2516 // If this reference is in an Objective-C method, then we need to do 2517 // some special Objective-C lookup, too. 2518 if (IvarLookupFollowUp) { 2519 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2520 if (E.isInvalid()) 2521 return ExprError(); 2522 2523 if (Expr *Ex = E.getAs<Expr>()) 2524 return Ex; 2525 } 2526 } 2527 2528 if (R.isAmbiguous()) 2529 return ExprError(); 2530 2531 // This could be an implicitly declared function reference (legal in C90, 2532 // extension in C99, forbidden in C++). 2533 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2534 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2535 if (D) R.addDecl(D); 2536 } 2537 2538 // Determine whether this name might be a candidate for 2539 // argument-dependent lookup. 2540 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2541 2542 if (R.empty() && !ADL) { 2543 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2544 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2545 TemplateKWLoc, TemplateArgs)) 2546 return E; 2547 } 2548 2549 // Don't diagnose an empty lookup for inline assembly. 2550 if (IsInlineAsmIdentifier) 2551 return ExprError(); 2552 2553 // If this name wasn't predeclared and if this is not a function 2554 // call, diagnose the problem. 2555 TypoExpr *TE = nullptr; 2556 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2557 : nullptr); 2558 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2559 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2560 "Typo correction callback misconfigured"); 2561 if (CCC) { 2562 // Make sure the callback knows what the typo being diagnosed is. 2563 CCC->setTypoName(II); 2564 if (SS.isValid()) 2565 CCC->setTypoNNS(SS.getScopeRep()); 2566 } 2567 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2568 // a template name, but we happen to have always already looked up the name 2569 // before we get here if it must be a template name. 2570 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2571 None, &TE)) { 2572 if (TE && KeywordReplacement) { 2573 auto &State = getTypoExprState(TE); 2574 auto BestTC = State.Consumer->getNextCorrection(); 2575 if (BestTC.isKeyword()) { 2576 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2577 if (State.DiagHandler) 2578 State.DiagHandler(BestTC); 2579 KeywordReplacement->startToken(); 2580 KeywordReplacement->setKind(II->getTokenID()); 2581 KeywordReplacement->setIdentifierInfo(II); 2582 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2583 // Clean up the state associated with the TypoExpr, since it has 2584 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2585 clearDelayedTypo(TE); 2586 // Signal that a correction to a keyword was performed by returning a 2587 // valid-but-null ExprResult. 2588 return (Expr*)nullptr; 2589 } 2590 State.Consumer->resetCorrectionStream(); 2591 } 2592 return TE ? TE : ExprError(); 2593 } 2594 2595 assert(!R.empty() && 2596 "DiagnoseEmptyLookup returned false but added no results"); 2597 2598 // If we found an Objective-C instance variable, let 2599 // LookupInObjCMethod build the appropriate expression to 2600 // reference the ivar. 2601 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2602 R.clear(); 2603 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2604 // In a hopelessly buggy code, Objective-C instance variable 2605 // lookup fails and no expression will be built to reference it. 2606 if (!E.isInvalid() && !E.get()) 2607 return ExprError(); 2608 return E; 2609 } 2610 } 2611 2612 // This is guaranteed from this point on. 2613 assert(!R.empty() || ADL); 2614 2615 // Check whether this might be a C++ implicit instance member access. 2616 // C++ [class.mfct.non-static]p3: 2617 // When an id-expression that is not part of a class member access 2618 // syntax and not used to form a pointer to member is used in the 2619 // body of a non-static member function of class X, if name lookup 2620 // resolves the name in the id-expression to a non-static non-type 2621 // member of some class C, the id-expression is transformed into a 2622 // class member access expression using (*this) as the 2623 // postfix-expression to the left of the . operator. 2624 // 2625 // But we don't actually need to do this for '&' operands if R 2626 // resolved to a function or overloaded function set, because the 2627 // expression is ill-formed if it actually works out to be a 2628 // non-static member function: 2629 // 2630 // C++ [expr.ref]p4: 2631 // Otherwise, if E1.E2 refers to a non-static member function. . . 2632 // [t]he expression can be used only as the left-hand operand of a 2633 // member function call. 2634 // 2635 // There are other safeguards against such uses, but it's important 2636 // to get this right here so that we don't end up making a 2637 // spuriously dependent expression if we're inside a dependent 2638 // instance method. 2639 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2640 bool MightBeImplicitMember; 2641 if (!IsAddressOfOperand) 2642 MightBeImplicitMember = true; 2643 else if (!SS.isEmpty()) 2644 MightBeImplicitMember = false; 2645 else if (R.isOverloadedResult()) 2646 MightBeImplicitMember = false; 2647 else if (R.isUnresolvableResult()) 2648 MightBeImplicitMember = true; 2649 else 2650 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2651 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2652 isa<MSPropertyDecl>(R.getFoundDecl()); 2653 2654 if (MightBeImplicitMember) 2655 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2656 R, TemplateArgs, S); 2657 } 2658 2659 if (TemplateArgs || TemplateKWLoc.isValid()) { 2660 2661 // In C++1y, if this is a variable template id, then check it 2662 // in BuildTemplateIdExpr(). 2663 // The single lookup result must be a variable template declaration. 2664 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2665 Id.TemplateId->Kind == TNK_Var_template) { 2666 assert(R.getAsSingle<VarTemplateDecl>() && 2667 "There should only be one declaration found."); 2668 } 2669 2670 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2671 } 2672 2673 return BuildDeclarationNameExpr(SS, R, ADL); 2674 } 2675 2676 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2677 /// declaration name, generally during template instantiation. 2678 /// There's a large number of things which don't need to be done along 2679 /// this path. 2680 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2681 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2682 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2683 DeclContext *DC = computeDeclContext(SS, false); 2684 if (!DC) 2685 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2686 NameInfo, /*TemplateArgs=*/nullptr); 2687 2688 if (RequireCompleteDeclContext(SS, DC)) 2689 return ExprError(); 2690 2691 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2692 LookupQualifiedName(R, DC); 2693 2694 if (R.isAmbiguous()) 2695 return ExprError(); 2696 2697 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2698 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2699 NameInfo, /*TemplateArgs=*/nullptr); 2700 2701 if (R.empty()) { 2702 // Don't diagnose problems with invalid record decl, the secondary no_member 2703 // diagnostic during template instantiation is likely bogus, e.g. if a class 2704 // is invalid because it's derived from an invalid base class, then missing 2705 // members were likely supposed to be inherited. 2706 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2707 if (CD->isInvalidDecl()) 2708 return ExprError(); 2709 Diag(NameInfo.getLoc(), diag::err_no_member) 2710 << NameInfo.getName() << DC << SS.getRange(); 2711 return ExprError(); 2712 } 2713 2714 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2715 // Diagnose a missing typename if this resolved unambiguously to a type in 2716 // a dependent context. If we can recover with a type, downgrade this to 2717 // a warning in Microsoft compatibility mode. 2718 unsigned DiagID = diag::err_typename_missing; 2719 if (RecoveryTSI && getLangOpts().MSVCCompat) 2720 DiagID = diag::ext_typename_missing; 2721 SourceLocation Loc = SS.getBeginLoc(); 2722 auto D = Diag(Loc, DiagID); 2723 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2724 << SourceRange(Loc, NameInfo.getEndLoc()); 2725 2726 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2727 // context. 2728 if (!RecoveryTSI) 2729 return ExprError(); 2730 2731 // Only issue the fixit if we're prepared to recover. 2732 D << FixItHint::CreateInsertion(Loc, "typename "); 2733 2734 // Recover by pretending this was an elaborated type. 2735 QualType Ty = Context.getTypeDeclType(TD); 2736 TypeLocBuilder TLB; 2737 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2738 2739 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2740 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2741 QTL.setElaboratedKeywordLoc(SourceLocation()); 2742 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2743 2744 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2745 2746 return ExprEmpty(); 2747 } 2748 2749 // Defend against this resolving to an implicit member access. We usually 2750 // won't get here if this might be a legitimate a class member (we end up in 2751 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2752 // a pointer-to-member or in an unevaluated context in C++11. 2753 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2754 return BuildPossibleImplicitMemberExpr(SS, 2755 /*TemplateKWLoc=*/SourceLocation(), 2756 R, /*TemplateArgs=*/nullptr, S); 2757 2758 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2759 } 2760 2761 /// The parser has read a name in, and Sema has detected that we're currently 2762 /// inside an ObjC method. Perform some additional checks and determine if we 2763 /// should form a reference to an ivar. 2764 /// 2765 /// Ideally, most of this would be done by lookup, but there's 2766 /// actually quite a lot of extra work involved. 2767 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2768 IdentifierInfo *II) { 2769 SourceLocation Loc = Lookup.getNameLoc(); 2770 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2771 2772 // Check for error condition which is already reported. 2773 if (!CurMethod) 2774 return DeclResult(true); 2775 2776 // There are two cases to handle here. 1) scoped lookup could have failed, 2777 // in which case we should look for an ivar. 2) scoped lookup could have 2778 // found a decl, but that decl is outside the current instance method (i.e. 2779 // a global variable). In these two cases, we do a lookup for an ivar with 2780 // this name, if the lookup sucedes, we replace it our current decl. 2781 2782 // If we're in a class method, we don't normally want to look for 2783 // ivars. But if we don't find anything else, and there's an 2784 // ivar, that's an error. 2785 bool IsClassMethod = CurMethod->isClassMethod(); 2786 2787 bool LookForIvars; 2788 if (Lookup.empty()) 2789 LookForIvars = true; 2790 else if (IsClassMethod) 2791 LookForIvars = false; 2792 else 2793 LookForIvars = (Lookup.isSingleResult() && 2794 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2795 ObjCInterfaceDecl *IFace = nullptr; 2796 if (LookForIvars) { 2797 IFace = CurMethod->getClassInterface(); 2798 ObjCInterfaceDecl *ClassDeclared; 2799 ObjCIvarDecl *IV = nullptr; 2800 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2801 // Diagnose using an ivar in a class method. 2802 if (IsClassMethod) { 2803 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2804 return DeclResult(true); 2805 } 2806 2807 // Diagnose the use of an ivar outside of the declaring class. 2808 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2809 !declaresSameEntity(ClassDeclared, IFace) && 2810 !getLangOpts().DebuggerSupport) 2811 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2812 2813 // Success. 2814 return IV; 2815 } 2816 } else if (CurMethod->isInstanceMethod()) { 2817 // We should warn if a local variable hides an ivar. 2818 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2819 ObjCInterfaceDecl *ClassDeclared; 2820 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2821 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2822 declaresSameEntity(IFace, ClassDeclared)) 2823 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2824 } 2825 } 2826 } else if (Lookup.isSingleResult() && 2827 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2828 // If accessing a stand-alone ivar in a class method, this is an error. 2829 if (const ObjCIvarDecl *IV = 2830 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2831 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2832 return DeclResult(true); 2833 } 2834 } 2835 2836 // Didn't encounter an error, didn't find an ivar. 2837 return DeclResult(false); 2838 } 2839 2840 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2841 ObjCIvarDecl *IV) { 2842 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2843 assert(CurMethod && CurMethod->isInstanceMethod() && 2844 "should not reference ivar from this context"); 2845 2846 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2847 assert(IFace && "should not reference ivar from this context"); 2848 2849 // If we're referencing an invalid decl, just return this as a silent 2850 // error node. The error diagnostic was already emitted on the decl. 2851 if (IV->isInvalidDecl()) 2852 return ExprError(); 2853 2854 // Check if referencing a field with __attribute__((deprecated)). 2855 if (DiagnoseUseOfDecl(IV, Loc)) 2856 return ExprError(); 2857 2858 // FIXME: This should use a new expr for a direct reference, don't 2859 // turn this into Self->ivar, just return a BareIVarExpr or something. 2860 IdentifierInfo &II = Context.Idents.get("self"); 2861 UnqualifiedId SelfName; 2862 SelfName.setImplicitSelfParam(&II); 2863 CXXScopeSpec SelfScopeSpec; 2864 SourceLocation TemplateKWLoc; 2865 ExprResult SelfExpr = 2866 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2867 /*HasTrailingLParen=*/false, 2868 /*IsAddressOfOperand=*/false); 2869 if (SelfExpr.isInvalid()) 2870 return ExprError(); 2871 2872 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2873 if (SelfExpr.isInvalid()) 2874 return ExprError(); 2875 2876 MarkAnyDeclReferenced(Loc, IV, true); 2877 2878 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2879 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2880 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2881 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2882 2883 ObjCIvarRefExpr *Result = new (Context) 2884 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2885 IV->getLocation(), SelfExpr.get(), true, true); 2886 2887 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2888 if (!isUnevaluatedContext() && 2889 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2890 getCurFunction()->recordUseOfWeak(Result); 2891 } 2892 if (getLangOpts().ObjCAutoRefCount) 2893 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2894 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2895 2896 return Result; 2897 } 2898 2899 /// The parser has read a name in, and Sema has detected that we're currently 2900 /// inside an ObjC method. Perform some additional checks and determine if we 2901 /// should form a reference to an ivar. If so, build an expression referencing 2902 /// that ivar. 2903 ExprResult 2904 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2905 IdentifierInfo *II, bool AllowBuiltinCreation) { 2906 // FIXME: Integrate this lookup step into LookupParsedName. 2907 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2908 if (Ivar.isInvalid()) 2909 return ExprError(); 2910 if (Ivar.isUsable()) 2911 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2912 cast<ObjCIvarDecl>(Ivar.get())); 2913 2914 if (Lookup.empty() && II && AllowBuiltinCreation) 2915 LookupBuiltin(Lookup); 2916 2917 // Sentinel value saying that we didn't do anything special. 2918 return ExprResult(false); 2919 } 2920 2921 /// Cast a base object to a member's actual type. 2922 /// 2923 /// There are two relevant checks: 2924 /// 2925 /// C++ [class.access.base]p7: 2926 /// 2927 /// If a class member access operator [...] is used to access a non-static 2928 /// data member or non-static member function, the reference is ill-formed if 2929 /// the left operand [...] cannot be implicitly converted to a pointer to the 2930 /// naming class of the right operand. 2931 /// 2932 /// C++ [expr.ref]p7: 2933 /// 2934 /// If E2 is a non-static data member or a non-static member function, the 2935 /// program is ill-formed if the class of which E2 is directly a member is an 2936 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2937 /// 2938 /// Note that the latter check does not consider access; the access of the 2939 /// "real" base class is checked as appropriate when checking the access of the 2940 /// member name. 2941 ExprResult 2942 Sema::PerformObjectMemberConversion(Expr *From, 2943 NestedNameSpecifier *Qualifier, 2944 NamedDecl *FoundDecl, 2945 NamedDecl *Member) { 2946 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2947 if (!RD) 2948 return From; 2949 2950 QualType DestRecordType; 2951 QualType DestType; 2952 QualType FromRecordType; 2953 QualType FromType = From->getType(); 2954 bool PointerConversions = false; 2955 if (isa<FieldDecl>(Member)) { 2956 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2957 auto FromPtrType = FromType->getAs<PointerType>(); 2958 DestRecordType = Context.getAddrSpaceQualType( 2959 DestRecordType, FromPtrType 2960 ? FromType->getPointeeType().getAddressSpace() 2961 : FromType.getAddressSpace()); 2962 2963 if (FromPtrType) { 2964 DestType = Context.getPointerType(DestRecordType); 2965 FromRecordType = FromPtrType->getPointeeType(); 2966 PointerConversions = true; 2967 } else { 2968 DestType = DestRecordType; 2969 FromRecordType = FromType; 2970 } 2971 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2972 if (Method->isStatic()) 2973 return From; 2974 2975 DestType = Method->getThisType(); 2976 DestRecordType = DestType->getPointeeType(); 2977 2978 if (FromType->getAs<PointerType>()) { 2979 FromRecordType = FromType->getPointeeType(); 2980 PointerConversions = true; 2981 } else { 2982 FromRecordType = FromType; 2983 DestType = DestRecordType; 2984 } 2985 2986 LangAS FromAS = FromRecordType.getAddressSpace(); 2987 LangAS DestAS = DestRecordType.getAddressSpace(); 2988 if (FromAS != DestAS) { 2989 QualType FromRecordTypeWithoutAS = 2990 Context.removeAddrSpaceQualType(FromRecordType); 2991 QualType FromTypeWithDestAS = 2992 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2993 if (PointerConversions) 2994 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2995 From = ImpCastExprToType(From, FromTypeWithDestAS, 2996 CK_AddressSpaceConversion, From->getValueKind()) 2997 .get(); 2998 } 2999 } else { 3000 // No conversion necessary. 3001 return From; 3002 } 3003 3004 if (DestType->isDependentType() || FromType->isDependentType()) 3005 return From; 3006 3007 // If the unqualified types are the same, no conversion is necessary. 3008 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3009 return From; 3010 3011 SourceRange FromRange = From->getSourceRange(); 3012 SourceLocation FromLoc = FromRange.getBegin(); 3013 3014 ExprValueKind VK = From->getValueKind(); 3015 3016 // C++ [class.member.lookup]p8: 3017 // [...] Ambiguities can often be resolved by qualifying a name with its 3018 // class name. 3019 // 3020 // If the member was a qualified name and the qualified referred to a 3021 // specific base subobject type, we'll cast to that intermediate type 3022 // first and then to the object in which the member is declared. That allows 3023 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3024 // 3025 // class Base { public: int x; }; 3026 // class Derived1 : public Base { }; 3027 // class Derived2 : public Base { }; 3028 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3029 // 3030 // void VeryDerived::f() { 3031 // x = 17; // error: ambiguous base subobjects 3032 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3033 // } 3034 if (Qualifier && Qualifier->getAsType()) { 3035 QualType QType = QualType(Qualifier->getAsType(), 0); 3036 assert(QType->isRecordType() && "lookup done with non-record type"); 3037 3038 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3039 3040 // In C++98, the qualifier type doesn't actually have to be a base 3041 // type of the object type, in which case we just ignore it. 3042 // Otherwise build the appropriate casts. 3043 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3044 CXXCastPath BasePath; 3045 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3046 FromLoc, FromRange, &BasePath)) 3047 return ExprError(); 3048 3049 if (PointerConversions) 3050 QType = Context.getPointerType(QType); 3051 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3052 VK, &BasePath).get(); 3053 3054 FromType = QType; 3055 FromRecordType = QRecordType; 3056 3057 // If the qualifier type was the same as the destination type, 3058 // we're done. 3059 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3060 return From; 3061 } 3062 } 3063 3064 CXXCastPath BasePath; 3065 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3066 FromLoc, FromRange, &BasePath, 3067 /*IgnoreAccess=*/true)) 3068 return ExprError(); 3069 3070 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3071 VK, &BasePath); 3072 } 3073 3074 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3075 const LookupResult &R, 3076 bool HasTrailingLParen) { 3077 // Only when used directly as the postfix-expression of a call. 3078 if (!HasTrailingLParen) 3079 return false; 3080 3081 // Never if a scope specifier was provided. 3082 if (SS.isSet()) 3083 return false; 3084 3085 // Only in C++ or ObjC++. 3086 if (!getLangOpts().CPlusPlus) 3087 return false; 3088 3089 // Turn off ADL when we find certain kinds of declarations during 3090 // normal lookup: 3091 for (NamedDecl *D : R) { 3092 // C++0x [basic.lookup.argdep]p3: 3093 // -- a declaration of a class member 3094 // Since using decls preserve this property, we check this on the 3095 // original decl. 3096 if (D->isCXXClassMember()) 3097 return false; 3098 3099 // C++0x [basic.lookup.argdep]p3: 3100 // -- a block-scope function declaration that is not a 3101 // using-declaration 3102 // NOTE: we also trigger this for function templates (in fact, we 3103 // don't check the decl type at all, since all other decl types 3104 // turn off ADL anyway). 3105 if (isa<UsingShadowDecl>(D)) 3106 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3107 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3108 return false; 3109 3110 // C++0x [basic.lookup.argdep]p3: 3111 // -- a declaration that is neither a function or a function 3112 // template 3113 // And also for builtin functions. 3114 if (isa<FunctionDecl>(D)) { 3115 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3116 3117 // But also builtin functions. 3118 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3119 return false; 3120 } else if (!isa<FunctionTemplateDecl>(D)) 3121 return false; 3122 } 3123 3124 return true; 3125 } 3126 3127 3128 /// Diagnoses obvious problems with the use of the given declaration 3129 /// as an expression. This is only actually called for lookups that 3130 /// were not overloaded, and it doesn't promise that the declaration 3131 /// will in fact be used. 3132 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3133 if (D->isInvalidDecl()) 3134 return true; 3135 3136 if (isa<TypedefNameDecl>(D)) { 3137 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3138 return true; 3139 } 3140 3141 if (isa<ObjCInterfaceDecl>(D)) { 3142 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3143 return true; 3144 } 3145 3146 if (isa<NamespaceDecl>(D)) { 3147 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3148 return true; 3149 } 3150 3151 return false; 3152 } 3153 3154 // Certain multiversion types should be treated as overloaded even when there is 3155 // only one result. 3156 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3157 assert(R.isSingleResult() && "Expected only a single result"); 3158 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3159 return FD && 3160 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3161 } 3162 3163 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3164 LookupResult &R, bool NeedsADL, 3165 bool AcceptInvalidDecl) { 3166 // If this is a single, fully-resolved result and we don't need ADL, 3167 // just build an ordinary singleton decl ref. 3168 if (!NeedsADL && R.isSingleResult() && 3169 !R.getAsSingle<FunctionTemplateDecl>() && 3170 !ShouldLookupResultBeMultiVersionOverload(R)) 3171 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3172 R.getRepresentativeDecl(), nullptr, 3173 AcceptInvalidDecl); 3174 3175 // We only need to check the declaration if there's exactly one 3176 // result, because in the overloaded case the results can only be 3177 // functions and function templates. 3178 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3179 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3180 return ExprError(); 3181 3182 // Otherwise, just build an unresolved lookup expression. Suppress 3183 // any lookup-related diagnostics; we'll hash these out later, when 3184 // we've picked a target. 3185 R.suppressDiagnostics(); 3186 3187 UnresolvedLookupExpr *ULE 3188 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3189 SS.getWithLocInContext(Context), 3190 R.getLookupNameInfo(), 3191 NeedsADL, R.isOverloadedResult(), 3192 R.begin(), R.end()); 3193 3194 return ULE; 3195 } 3196 3197 static void 3198 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3199 ValueDecl *var, DeclContext *DC); 3200 3201 /// Complete semantic analysis for a reference to the given declaration. 3202 ExprResult Sema::BuildDeclarationNameExpr( 3203 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3204 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3205 bool AcceptInvalidDecl) { 3206 assert(D && "Cannot refer to a NULL declaration"); 3207 assert(!isa<FunctionTemplateDecl>(D) && 3208 "Cannot refer unambiguously to a function template"); 3209 3210 SourceLocation Loc = NameInfo.getLoc(); 3211 if (CheckDeclInExpr(*this, Loc, D)) 3212 return ExprError(); 3213 3214 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3215 // Specifically diagnose references to class templates that are missing 3216 // a template argument list. 3217 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3218 return ExprError(); 3219 } 3220 3221 // Make sure that we're referring to a value. 3222 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3223 Diag(Loc, diag::err_ref_non_value) 3224 << D << SS.getRange(); 3225 Diag(D->getLocation(), diag::note_declared_at); 3226 return ExprError(); 3227 } 3228 3229 // Check whether this declaration can be used. Note that we suppress 3230 // this check when we're going to perform argument-dependent lookup 3231 // on this function name, because this might not be the function 3232 // that overload resolution actually selects. 3233 if (DiagnoseUseOfDecl(D, Loc)) 3234 return ExprError(); 3235 3236 auto *VD = cast<ValueDecl>(D); 3237 3238 // Only create DeclRefExpr's for valid Decl's. 3239 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3240 return ExprError(); 3241 3242 // Handle members of anonymous structs and unions. If we got here, 3243 // and the reference is to a class member indirect field, then this 3244 // must be the subject of a pointer-to-member expression. 3245 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3246 if (!indirectField->isCXXClassMember()) 3247 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3248 indirectField); 3249 3250 { 3251 QualType type = VD->getType(); 3252 if (type.isNull()) 3253 return ExprError(); 3254 ExprValueKind valueKind = VK_PRValue; 3255 3256 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3257 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3258 // is expanded by some outer '...' in the context of the use. 3259 type = type.getNonPackExpansionType(); 3260 3261 switch (D->getKind()) { 3262 // Ignore all the non-ValueDecl kinds. 3263 #define ABSTRACT_DECL(kind) 3264 #define VALUE(type, base) 3265 #define DECL(type, base) \ 3266 case Decl::type: 3267 #include "clang/AST/DeclNodes.inc" 3268 llvm_unreachable("invalid value decl kind"); 3269 3270 // These shouldn't make it here. 3271 case Decl::ObjCAtDefsField: 3272 llvm_unreachable("forming non-member reference to ivar?"); 3273 3274 // Enum constants are always r-values and never references. 3275 // Unresolved using declarations are dependent. 3276 case Decl::EnumConstant: 3277 case Decl::UnresolvedUsingValue: 3278 case Decl::OMPDeclareReduction: 3279 case Decl::OMPDeclareMapper: 3280 valueKind = VK_PRValue; 3281 break; 3282 3283 // Fields and indirect fields that got here must be for 3284 // pointer-to-member expressions; we just call them l-values for 3285 // internal consistency, because this subexpression doesn't really 3286 // exist in the high-level semantics. 3287 case Decl::Field: 3288 case Decl::IndirectField: 3289 case Decl::ObjCIvar: 3290 assert(getLangOpts().CPlusPlus && 3291 "building reference to field in C?"); 3292 3293 // These can't have reference type in well-formed programs, but 3294 // for internal consistency we do this anyway. 3295 type = type.getNonReferenceType(); 3296 valueKind = VK_LValue; 3297 break; 3298 3299 // Non-type template parameters are either l-values or r-values 3300 // depending on the type. 3301 case Decl::NonTypeTemplateParm: { 3302 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3303 type = reftype->getPointeeType(); 3304 valueKind = VK_LValue; // even if the parameter is an r-value reference 3305 break; 3306 } 3307 3308 // [expr.prim.id.unqual]p2: 3309 // If the entity is a template parameter object for a template 3310 // parameter of type T, the type of the expression is const T. 3311 // [...] The expression is an lvalue if the entity is a [...] template 3312 // parameter object. 3313 if (type->isRecordType()) { 3314 type = type.getUnqualifiedType().withConst(); 3315 valueKind = VK_LValue; 3316 break; 3317 } 3318 3319 // For non-references, we need to strip qualifiers just in case 3320 // the template parameter was declared as 'const int' or whatever. 3321 valueKind = VK_PRValue; 3322 type = type.getUnqualifiedType(); 3323 break; 3324 } 3325 3326 case Decl::Var: 3327 case Decl::VarTemplateSpecialization: 3328 case Decl::VarTemplatePartialSpecialization: 3329 case Decl::Decomposition: 3330 case Decl::OMPCapturedExpr: 3331 // In C, "extern void blah;" is valid and is an r-value. 3332 if (!getLangOpts().CPlusPlus && 3333 !type.hasQualifiers() && 3334 type->isVoidType()) { 3335 valueKind = VK_PRValue; 3336 break; 3337 } 3338 LLVM_FALLTHROUGH; 3339 3340 case Decl::ImplicitParam: 3341 case Decl::ParmVar: { 3342 // These are always l-values. 3343 valueKind = VK_LValue; 3344 type = type.getNonReferenceType(); 3345 3346 // FIXME: Does the addition of const really only apply in 3347 // potentially-evaluated contexts? Since the variable isn't actually 3348 // captured in an unevaluated context, it seems that the answer is no. 3349 if (!isUnevaluatedContext()) { 3350 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3351 if (!CapturedType.isNull()) 3352 type = CapturedType; 3353 } 3354 3355 break; 3356 } 3357 3358 case Decl::Binding: { 3359 // These are always lvalues. 3360 valueKind = VK_LValue; 3361 type = type.getNonReferenceType(); 3362 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3363 // decides how that's supposed to work. 3364 auto *BD = cast<BindingDecl>(VD); 3365 if (BD->getDeclContext() != CurContext) { 3366 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3367 if (DD && DD->hasLocalStorage()) 3368 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3369 } 3370 break; 3371 } 3372 3373 case Decl::Function: { 3374 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3375 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3376 type = Context.BuiltinFnTy; 3377 valueKind = VK_PRValue; 3378 break; 3379 } 3380 } 3381 3382 const FunctionType *fty = type->castAs<FunctionType>(); 3383 3384 // If we're referring to a function with an __unknown_anytype 3385 // result type, make the entire expression __unknown_anytype. 3386 if (fty->getReturnType() == Context.UnknownAnyTy) { 3387 type = Context.UnknownAnyTy; 3388 valueKind = VK_PRValue; 3389 break; 3390 } 3391 3392 // Functions are l-values in C++. 3393 if (getLangOpts().CPlusPlus) { 3394 valueKind = VK_LValue; 3395 break; 3396 } 3397 3398 // C99 DR 316 says that, if a function type comes from a 3399 // function definition (without a prototype), that type is only 3400 // used for checking compatibility. Therefore, when referencing 3401 // the function, we pretend that we don't have the full function 3402 // type. 3403 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3404 isa<FunctionProtoType>(fty)) 3405 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3406 fty->getExtInfo()); 3407 3408 // Functions are r-values in C. 3409 valueKind = VK_PRValue; 3410 break; 3411 } 3412 3413 case Decl::CXXDeductionGuide: 3414 llvm_unreachable("building reference to deduction guide"); 3415 3416 case Decl::MSProperty: 3417 case Decl::MSGuid: 3418 case Decl::TemplateParamObject: 3419 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3420 // capture in OpenMP, or duplicated between host and device? 3421 valueKind = VK_LValue; 3422 break; 3423 3424 case Decl::CXXMethod: 3425 // If we're referring to a method with an __unknown_anytype 3426 // result type, make the entire expression __unknown_anytype. 3427 // This should only be possible with a type written directly. 3428 if (const FunctionProtoType *proto 3429 = dyn_cast<FunctionProtoType>(VD->getType())) 3430 if (proto->getReturnType() == Context.UnknownAnyTy) { 3431 type = Context.UnknownAnyTy; 3432 valueKind = VK_PRValue; 3433 break; 3434 } 3435 3436 // C++ methods are l-values if static, r-values if non-static. 3437 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3438 valueKind = VK_LValue; 3439 break; 3440 } 3441 LLVM_FALLTHROUGH; 3442 3443 case Decl::CXXConversion: 3444 case Decl::CXXDestructor: 3445 case Decl::CXXConstructor: 3446 valueKind = VK_PRValue; 3447 break; 3448 } 3449 3450 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3451 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3452 TemplateArgs); 3453 } 3454 } 3455 3456 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3457 SmallString<32> &Target) { 3458 Target.resize(CharByteWidth * (Source.size() + 1)); 3459 char *ResultPtr = &Target[0]; 3460 const llvm::UTF8 *ErrorPtr; 3461 bool success = 3462 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3463 (void)success; 3464 assert(success); 3465 Target.resize(ResultPtr - &Target[0]); 3466 } 3467 3468 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3469 PredefinedExpr::IdentKind IK) { 3470 // Pick the current block, lambda, captured statement or function. 3471 Decl *currentDecl = nullptr; 3472 if (const BlockScopeInfo *BSI = getCurBlock()) 3473 currentDecl = BSI->TheDecl; 3474 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3475 currentDecl = LSI->CallOperator; 3476 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3477 currentDecl = CSI->TheCapturedDecl; 3478 else 3479 currentDecl = getCurFunctionOrMethodDecl(); 3480 3481 if (!currentDecl) { 3482 Diag(Loc, diag::ext_predef_outside_function); 3483 currentDecl = Context.getTranslationUnitDecl(); 3484 } 3485 3486 QualType ResTy; 3487 StringLiteral *SL = nullptr; 3488 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3489 ResTy = Context.DependentTy; 3490 else { 3491 // Pre-defined identifiers are of type char[x], where x is the length of 3492 // the string. 3493 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3494 unsigned Length = Str.length(); 3495 3496 llvm::APInt LengthI(32, Length + 1); 3497 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3498 ResTy = 3499 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3500 SmallString<32> RawChars; 3501 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3502 Str, RawChars); 3503 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3504 ArrayType::Normal, 3505 /*IndexTypeQuals*/ 0); 3506 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3507 /*Pascal*/ false, ResTy, Loc); 3508 } else { 3509 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3510 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3511 ArrayType::Normal, 3512 /*IndexTypeQuals*/ 0); 3513 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3514 /*Pascal*/ false, ResTy, Loc); 3515 } 3516 } 3517 3518 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3519 } 3520 3521 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3522 SourceLocation LParen, 3523 SourceLocation RParen, 3524 TypeSourceInfo *TSI) { 3525 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3526 } 3527 3528 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3529 SourceLocation LParen, 3530 SourceLocation RParen, 3531 ParsedType ParsedTy) { 3532 TypeSourceInfo *TSI = nullptr; 3533 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3534 3535 if (Ty.isNull()) 3536 return ExprError(); 3537 if (!TSI) 3538 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3539 3540 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3541 } 3542 3543 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3544 PredefinedExpr::IdentKind IK; 3545 3546 switch (Kind) { 3547 default: llvm_unreachable("Unknown simple primary expr!"); 3548 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3549 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3550 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3551 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3552 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3553 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3554 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3555 } 3556 3557 return BuildPredefinedExpr(Loc, IK); 3558 } 3559 3560 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3561 SmallString<16> CharBuffer; 3562 bool Invalid = false; 3563 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3564 if (Invalid) 3565 return ExprError(); 3566 3567 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3568 PP, Tok.getKind()); 3569 if (Literal.hadError()) 3570 return ExprError(); 3571 3572 QualType Ty; 3573 if (Literal.isWide()) 3574 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3575 else if (Literal.isUTF8() && getLangOpts().Char8) 3576 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3577 else if (Literal.isUTF16()) 3578 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3579 else if (Literal.isUTF32()) 3580 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3581 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3582 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3583 else 3584 Ty = Context.CharTy; // 'x' -> char in C++ 3585 3586 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3587 if (Literal.isWide()) 3588 Kind = CharacterLiteral::Wide; 3589 else if (Literal.isUTF16()) 3590 Kind = CharacterLiteral::UTF16; 3591 else if (Literal.isUTF32()) 3592 Kind = CharacterLiteral::UTF32; 3593 else if (Literal.isUTF8()) 3594 Kind = CharacterLiteral::UTF8; 3595 3596 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3597 Tok.getLocation()); 3598 3599 if (Literal.getUDSuffix().empty()) 3600 return Lit; 3601 3602 // We're building a user-defined literal. 3603 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3604 SourceLocation UDSuffixLoc = 3605 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3606 3607 // Make sure we're allowed user-defined literals here. 3608 if (!UDLScope) 3609 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3610 3611 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3612 // operator "" X (ch) 3613 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3614 Lit, Tok.getLocation()); 3615 } 3616 3617 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3618 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3619 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3620 Context.IntTy, Loc); 3621 } 3622 3623 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3624 QualType Ty, SourceLocation Loc) { 3625 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3626 3627 using llvm::APFloat; 3628 APFloat Val(Format); 3629 3630 APFloat::opStatus result = Literal.GetFloatValue(Val); 3631 3632 // Overflow is always an error, but underflow is only an error if 3633 // we underflowed to zero (APFloat reports denormals as underflow). 3634 if ((result & APFloat::opOverflow) || 3635 ((result & APFloat::opUnderflow) && Val.isZero())) { 3636 unsigned diagnostic; 3637 SmallString<20> buffer; 3638 if (result & APFloat::opOverflow) { 3639 diagnostic = diag::warn_float_overflow; 3640 APFloat::getLargest(Format).toString(buffer); 3641 } else { 3642 diagnostic = diag::warn_float_underflow; 3643 APFloat::getSmallest(Format).toString(buffer); 3644 } 3645 3646 S.Diag(Loc, diagnostic) 3647 << Ty 3648 << StringRef(buffer.data(), buffer.size()); 3649 } 3650 3651 bool isExact = (result == APFloat::opOK); 3652 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3653 } 3654 3655 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3656 assert(E && "Invalid expression"); 3657 3658 if (E->isValueDependent()) 3659 return false; 3660 3661 QualType QT = E->getType(); 3662 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3663 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3664 return true; 3665 } 3666 3667 llvm::APSInt ValueAPS; 3668 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3669 3670 if (R.isInvalid()) 3671 return true; 3672 3673 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3674 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3675 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3676 << toString(ValueAPS, 10) << ValueIsPositive; 3677 return true; 3678 } 3679 3680 return false; 3681 } 3682 3683 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3684 // Fast path for a single digit (which is quite common). A single digit 3685 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3686 if (Tok.getLength() == 1) { 3687 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3688 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3689 } 3690 3691 SmallString<128> SpellingBuffer; 3692 // NumericLiteralParser wants to overread by one character. Add padding to 3693 // the buffer in case the token is copied to the buffer. If getSpelling() 3694 // returns a StringRef to the memory buffer, it should have a null char at 3695 // the EOF, so it is also safe. 3696 SpellingBuffer.resize(Tok.getLength() + 1); 3697 3698 // Get the spelling of the token, which eliminates trigraphs, etc. 3699 bool Invalid = false; 3700 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3701 if (Invalid) 3702 return ExprError(); 3703 3704 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3705 PP.getSourceManager(), PP.getLangOpts(), 3706 PP.getTargetInfo(), PP.getDiagnostics()); 3707 if (Literal.hadError) 3708 return ExprError(); 3709 3710 if (Literal.hasUDSuffix()) { 3711 // We're building a user-defined literal. 3712 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3713 SourceLocation UDSuffixLoc = 3714 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3715 3716 // Make sure we're allowed user-defined literals here. 3717 if (!UDLScope) 3718 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3719 3720 QualType CookedTy; 3721 if (Literal.isFloatingLiteral()) { 3722 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3723 // long double, the literal is treated as a call of the form 3724 // operator "" X (f L) 3725 CookedTy = Context.LongDoubleTy; 3726 } else { 3727 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3728 // unsigned long long, the literal is treated as a call of the form 3729 // operator "" X (n ULL) 3730 CookedTy = Context.UnsignedLongLongTy; 3731 } 3732 3733 DeclarationName OpName = 3734 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3735 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3736 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3737 3738 SourceLocation TokLoc = Tok.getLocation(); 3739 3740 // Perform literal operator lookup to determine if we're building a raw 3741 // literal or a cooked one. 3742 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3743 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3744 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3745 /*AllowStringTemplatePack*/ false, 3746 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3747 case LOLR_ErrorNoDiagnostic: 3748 // Lookup failure for imaginary constants isn't fatal, there's still the 3749 // GNU extension producing _Complex types. 3750 break; 3751 case LOLR_Error: 3752 return ExprError(); 3753 case LOLR_Cooked: { 3754 Expr *Lit; 3755 if (Literal.isFloatingLiteral()) { 3756 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3757 } else { 3758 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3759 if (Literal.GetIntegerValue(ResultVal)) 3760 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3761 << /* Unsigned */ 1; 3762 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3763 Tok.getLocation()); 3764 } 3765 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3766 } 3767 3768 case LOLR_Raw: { 3769 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3770 // literal is treated as a call of the form 3771 // operator "" X ("n") 3772 unsigned Length = Literal.getUDSuffixOffset(); 3773 QualType StrTy = Context.getConstantArrayType( 3774 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3775 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3776 Expr *Lit = StringLiteral::Create( 3777 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3778 /*Pascal*/false, StrTy, &TokLoc, 1); 3779 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3780 } 3781 3782 case LOLR_Template: { 3783 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3784 // template), L is treated as a call fo the form 3785 // operator "" X <'c1', 'c2', ... 'ck'>() 3786 // where n is the source character sequence c1 c2 ... ck. 3787 TemplateArgumentListInfo ExplicitArgs; 3788 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3789 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3790 llvm::APSInt Value(CharBits, CharIsUnsigned); 3791 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3792 Value = TokSpelling[I]; 3793 TemplateArgument Arg(Context, Value, Context.CharTy); 3794 TemplateArgumentLocInfo ArgInfo; 3795 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3796 } 3797 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3798 &ExplicitArgs); 3799 } 3800 case LOLR_StringTemplatePack: 3801 llvm_unreachable("unexpected literal operator lookup result"); 3802 } 3803 } 3804 3805 Expr *Res; 3806 3807 if (Literal.isFixedPointLiteral()) { 3808 QualType Ty; 3809 3810 if (Literal.isAccum) { 3811 if (Literal.isHalf) { 3812 Ty = Context.ShortAccumTy; 3813 } else if (Literal.isLong) { 3814 Ty = Context.LongAccumTy; 3815 } else { 3816 Ty = Context.AccumTy; 3817 } 3818 } else if (Literal.isFract) { 3819 if (Literal.isHalf) { 3820 Ty = Context.ShortFractTy; 3821 } else if (Literal.isLong) { 3822 Ty = Context.LongFractTy; 3823 } else { 3824 Ty = Context.FractTy; 3825 } 3826 } 3827 3828 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3829 3830 bool isSigned = !Literal.isUnsigned; 3831 unsigned scale = Context.getFixedPointScale(Ty); 3832 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3833 3834 llvm::APInt Val(bit_width, 0, isSigned); 3835 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3836 bool ValIsZero = Val.isNullValue() && !Overflowed; 3837 3838 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3839 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3840 // Clause 6.4.4 - The value of a constant shall be in the range of 3841 // representable values for its type, with exception for constants of a 3842 // fract type with a value of exactly 1; such a constant shall denote 3843 // the maximal value for the type. 3844 --Val; 3845 else if (Val.ugt(MaxVal) || Overflowed) 3846 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3847 3848 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3849 Tok.getLocation(), scale); 3850 } else if (Literal.isFloatingLiteral()) { 3851 QualType Ty; 3852 if (Literal.isHalf){ 3853 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3854 Ty = Context.HalfTy; 3855 else { 3856 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3857 return ExprError(); 3858 } 3859 } else if (Literal.isFloat) 3860 Ty = Context.FloatTy; 3861 else if (Literal.isLong) 3862 Ty = Context.LongDoubleTy; 3863 else if (Literal.isFloat16) 3864 Ty = Context.Float16Ty; 3865 else if (Literal.isFloat128) 3866 Ty = Context.Float128Ty; 3867 else 3868 Ty = Context.DoubleTy; 3869 3870 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3871 3872 if (Ty == Context.DoubleTy) { 3873 if (getLangOpts().SinglePrecisionConstants) { 3874 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3875 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3876 } 3877 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3878 "cl_khr_fp64", getLangOpts())) { 3879 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3880 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3881 << (getLangOpts().OpenCLVersion >= 300); 3882 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3883 } 3884 } 3885 } else if (!Literal.isIntegerLiteral()) { 3886 return ExprError(); 3887 } else { 3888 QualType Ty; 3889 3890 // 'long long' is a C99 or C++11 feature. 3891 if (!getLangOpts().C99 && Literal.isLongLong) { 3892 if (getLangOpts().CPlusPlus) 3893 Diag(Tok.getLocation(), 3894 getLangOpts().CPlusPlus11 ? 3895 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3896 else 3897 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3898 } 3899 3900 // 'z/uz' literals are a C++2b feature. 3901 if (Literal.isSizeT) 3902 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3903 ? getLangOpts().CPlusPlus2b 3904 ? diag::warn_cxx20_compat_size_t_suffix 3905 : diag::ext_cxx2b_size_t_suffix 3906 : diag::err_cxx2b_size_t_suffix); 3907 3908 // Get the value in the widest-possible width. 3909 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3910 llvm::APInt ResultVal(MaxWidth, 0); 3911 3912 if (Literal.GetIntegerValue(ResultVal)) { 3913 // If this value didn't fit into uintmax_t, error and force to ull. 3914 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3915 << /* Unsigned */ 1; 3916 Ty = Context.UnsignedLongLongTy; 3917 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3918 "long long is not intmax_t?"); 3919 } else { 3920 // If this value fits into a ULL, try to figure out what else it fits into 3921 // according to the rules of C99 6.4.4.1p5. 3922 3923 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3924 // be an unsigned int. 3925 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3926 3927 // Check from smallest to largest, picking the smallest type we can. 3928 unsigned Width = 0; 3929 3930 // Microsoft specific integer suffixes are explicitly sized. 3931 if (Literal.MicrosoftInteger) { 3932 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3933 Width = 8; 3934 Ty = Context.CharTy; 3935 } else { 3936 Width = Literal.MicrosoftInteger; 3937 Ty = Context.getIntTypeForBitwidth(Width, 3938 /*Signed=*/!Literal.isUnsigned); 3939 } 3940 } 3941 3942 // Check C++2b size_t literals. 3943 if (Literal.isSizeT) { 3944 assert(!Literal.MicrosoftInteger && 3945 "size_t literals can't be Microsoft literals"); 3946 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3947 Context.getTargetInfo().getSizeType()); 3948 3949 // Does it fit in size_t? 3950 if (ResultVal.isIntN(SizeTSize)) { 3951 // Does it fit in ssize_t? 3952 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3953 Ty = Context.getSignedSizeType(); 3954 else if (AllowUnsigned) 3955 Ty = Context.getSizeType(); 3956 Width = SizeTSize; 3957 } 3958 } 3959 3960 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3961 !Literal.isSizeT) { 3962 // Are int/unsigned possibilities? 3963 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3964 3965 // Does it fit in a unsigned int? 3966 if (ResultVal.isIntN(IntSize)) { 3967 // Does it fit in a signed int? 3968 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3969 Ty = Context.IntTy; 3970 else if (AllowUnsigned) 3971 Ty = Context.UnsignedIntTy; 3972 Width = IntSize; 3973 } 3974 } 3975 3976 // Are long/unsigned long possibilities? 3977 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3978 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3979 3980 // Does it fit in a unsigned long? 3981 if (ResultVal.isIntN(LongSize)) { 3982 // Does it fit in a signed long? 3983 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3984 Ty = Context.LongTy; 3985 else if (AllowUnsigned) 3986 Ty = Context.UnsignedLongTy; 3987 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3988 // is compatible. 3989 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3990 const unsigned LongLongSize = 3991 Context.getTargetInfo().getLongLongWidth(); 3992 Diag(Tok.getLocation(), 3993 getLangOpts().CPlusPlus 3994 ? Literal.isLong 3995 ? diag::warn_old_implicitly_unsigned_long_cxx 3996 : /*C++98 UB*/ diag:: 3997 ext_old_implicitly_unsigned_long_cxx 3998 : diag::warn_old_implicitly_unsigned_long) 3999 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4000 : /*will be ill-formed*/ 1); 4001 Ty = Context.UnsignedLongTy; 4002 } 4003 Width = LongSize; 4004 } 4005 } 4006 4007 // Check long long if needed. 4008 if (Ty.isNull() && !Literal.isSizeT) { 4009 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4010 4011 // Does it fit in a unsigned long long? 4012 if (ResultVal.isIntN(LongLongSize)) { 4013 // Does it fit in a signed long long? 4014 // To be compatible with MSVC, hex integer literals ending with the 4015 // LL or i64 suffix are always signed in Microsoft mode. 4016 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4017 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4018 Ty = Context.LongLongTy; 4019 else if (AllowUnsigned) 4020 Ty = Context.UnsignedLongLongTy; 4021 Width = LongLongSize; 4022 } 4023 } 4024 4025 // If we still couldn't decide a type, we either have 'size_t' literal 4026 // that is out of range, or a decimal literal that does not fit in a 4027 // signed long long and has no U suffix. 4028 if (Ty.isNull()) { 4029 if (Literal.isSizeT) 4030 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4031 << Literal.isUnsigned; 4032 else 4033 Diag(Tok.getLocation(), 4034 diag::ext_integer_literal_too_large_for_signed); 4035 Ty = Context.UnsignedLongLongTy; 4036 Width = Context.getTargetInfo().getLongLongWidth(); 4037 } 4038 4039 if (ResultVal.getBitWidth() != Width) 4040 ResultVal = ResultVal.trunc(Width); 4041 } 4042 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4043 } 4044 4045 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4046 if (Literal.isImaginary) { 4047 Res = new (Context) ImaginaryLiteral(Res, 4048 Context.getComplexType(Res->getType())); 4049 4050 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4051 } 4052 return Res; 4053 } 4054 4055 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4056 assert(E && "ActOnParenExpr() missing expr"); 4057 QualType ExprTy = E->getType(); 4058 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4059 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4060 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4061 return new (Context) ParenExpr(L, R, E); 4062 } 4063 4064 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4065 SourceLocation Loc, 4066 SourceRange ArgRange) { 4067 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4068 // scalar or vector data type argument..." 4069 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4070 // type (C99 6.2.5p18) or void. 4071 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4072 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4073 << T << ArgRange; 4074 return true; 4075 } 4076 4077 assert((T->isVoidType() || !T->isIncompleteType()) && 4078 "Scalar types should always be complete"); 4079 return false; 4080 } 4081 4082 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4083 SourceLocation Loc, 4084 SourceRange ArgRange, 4085 UnaryExprOrTypeTrait TraitKind) { 4086 // Invalid types must be hard errors for SFINAE in C++. 4087 if (S.LangOpts.CPlusPlus) 4088 return true; 4089 4090 // C99 6.5.3.4p1: 4091 if (T->isFunctionType() && 4092 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4093 TraitKind == UETT_PreferredAlignOf)) { 4094 // sizeof(function)/alignof(function) is allowed as an extension. 4095 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4096 << getTraitSpelling(TraitKind) << ArgRange; 4097 return false; 4098 } 4099 4100 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4101 // this is an error (OpenCL v1.1 s6.3.k) 4102 if (T->isVoidType()) { 4103 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4104 : diag::ext_sizeof_alignof_void_type; 4105 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4106 return false; 4107 } 4108 4109 return true; 4110 } 4111 4112 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4113 SourceLocation Loc, 4114 SourceRange ArgRange, 4115 UnaryExprOrTypeTrait TraitKind) { 4116 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4117 // runtime doesn't allow it. 4118 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4119 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4120 << T << (TraitKind == UETT_SizeOf) 4121 << ArgRange; 4122 return true; 4123 } 4124 4125 return false; 4126 } 4127 4128 /// Check whether E is a pointer from a decayed array type (the decayed 4129 /// pointer type is equal to T) and emit a warning if it is. 4130 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4131 Expr *E) { 4132 // Don't warn if the operation changed the type. 4133 if (T != E->getType()) 4134 return; 4135 4136 // Now look for array decays. 4137 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4138 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4139 return; 4140 4141 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4142 << ICE->getType() 4143 << ICE->getSubExpr()->getType(); 4144 } 4145 4146 /// Check the constraints on expression operands to unary type expression 4147 /// and type traits. 4148 /// 4149 /// Completes any types necessary and validates the constraints on the operand 4150 /// expression. The logic mostly mirrors the type-based overload, but may modify 4151 /// the expression as it completes the type for that expression through template 4152 /// instantiation, etc. 4153 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4154 UnaryExprOrTypeTrait ExprKind) { 4155 QualType ExprTy = E->getType(); 4156 assert(!ExprTy->isReferenceType()); 4157 4158 bool IsUnevaluatedOperand = 4159 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4160 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4161 if (IsUnevaluatedOperand) { 4162 ExprResult Result = CheckUnevaluatedOperand(E); 4163 if (Result.isInvalid()) 4164 return true; 4165 E = Result.get(); 4166 } 4167 4168 // The operand for sizeof and alignof is in an unevaluated expression context, 4169 // so side effects could result in unintended consequences. 4170 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4171 // used to build SFINAE gadgets. 4172 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4173 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4174 !E->isInstantiationDependent() && 4175 E->HasSideEffects(Context, false)) 4176 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4177 4178 if (ExprKind == UETT_VecStep) 4179 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4180 E->getSourceRange()); 4181 4182 // Explicitly list some types as extensions. 4183 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4184 E->getSourceRange(), ExprKind)) 4185 return false; 4186 4187 // 'alignof' applied to an expression only requires the base element type of 4188 // the expression to be complete. 'sizeof' requires the expression's type to 4189 // be complete (and will attempt to complete it if it's an array of unknown 4190 // bound). 4191 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4192 if (RequireCompleteSizedType( 4193 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4194 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4195 getTraitSpelling(ExprKind), E->getSourceRange())) 4196 return true; 4197 } else { 4198 if (RequireCompleteSizedExprType( 4199 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4200 getTraitSpelling(ExprKind), E->getSourceRange())) 4201 return true; 4202 } 4203 4204 // Completing the expression's type may have changed it. 4205 ExprTy = E->getType(); 4206 assert(!ExprTy->isReferenceType()); 4207 4208 if (ExprTy->isFunctionType()) { 4209 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4210 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4211 return true; 4212 } 4213 4214 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4215 E->getSourceRange(), ExprKind)) 4216 return true; 4217 4218 if (ExprKind == UETT_SizeOf) { 4219 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4220 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4221 QualType OType = PVD->getOriginalType(); 4222 QualType Type = PVD->getType(); 4223 if (Type->isPointerType() && OType->isArrayType()) { 4224 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4225 << Type << OType; 4226 Diag(PVD->getLocation(), diag::note_declared_at); 4227 } 4228 } 4229 } 4230 4231 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4232 // decays into a pointer and returns an unintended result. This is most 4233 // likely a typo for "sizeof(array) op x". 4234 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4235 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4236 BO->getLHS()); 4237 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4238 BO->getRHS()); 4239 } 4240 } 4241 4242 return false; 4243 } 4244 4245 /// Check the constraints on operands to unary expression and type 4246 /// traits. 4247 /// 4248 /// This will complete any types necessary, and validate the various constraints 4249 /// on those operands. 4250 /// 4251 /// The UsualUnaryConversions() function is *not* called by this routine. 4252 /// C99 6.3.2.1p[2-4] all state: 4253 /// Except when it is the operand of the sizeof operator ... 4254 /// 4255 /// C++ [expr.sizeof]p4 4256 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4257 /// standard conversions are not applied to the operand of sizeof. 4258 /// 4259 /// This policy is followed for all of the unary trait expressions. 4260 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4261 SourceLocation OpLoc, 4262 SourceRange ExprRange, 4263 UnaryExprOrTypeTrait ExprKind) { 4264 if (ExprType->isDependentType()) 4265 return false; 4266 4267 // C++ [expr.sizeof]p2: 4268 // When applied to a reference or a reference type, the result 4269 // is the size of the referenced type. 4270 // C++11 [expr.alignof]p3: 4271 // When alignof is applied to a reference type, the result 4272 // shall be the alignment of the referenced type. 4273 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4274 ExprType = Ref->getPointeeType(); 4275 4276 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4277 // When alignof or _Alignof is applied to an array type, the result 4278 // is the alignment of the element type. 4279 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4280 ExprKind == UETT_OpenMPRequiredSimdAlign) 4281 ExprType = Context.getBaseElementType(ExprType); 4282 4283 if (ExprKind == UETT_VecStep) 4284 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4285 4286 // Explicitly list some types as extensions. 4287 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4288 ExprKind)) 4289 return false; 4290 4291 if (RequireCompleteSizedType( 4292 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4293 getTraitSpelling(ExprKind), ExprRange)) 4294 return true; 4295 4296 if (ExprType->isFunctionType()) { 4297 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4298 << getTraitSpelling(ExprKind) << ExprRange; 4299 return true; 4300 } 4301 4302 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4303 ExprKind)) 4304 return true; 4305 4306 return false; 4307 } 4308 4309 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4310 // Cannot know anything else if the expression is dependent. 4311 if (E->isTypeDependent()) 4312 return false; 4313 4314 if (E->getObjectKind() == OK_BitField) { 4315 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4316 << 1 << E->getSourceRange(); 4317 return true; 4318 } 4319 4320 ValueDecl *D = nullptr; 4321 Expr *Inner = E->IgnoreParens(); 4322 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4323 D = DRE->getDecl(); 4324 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4325 D = ME->getMemberDecl(); 4326 } 4327 4328 // If it's a field, require the containing struct to have a 4329 // complete definition so that we can compute the layout. 4330 // 4331 // This can happen in C++11 onwards, either by naming the member 4332 // in a way that is not transformed into a member access expression 4333 // (in an unevaluated operand, for instance), or by naming the member 4334 // in a trailing-return-type. 4335 // 4336 // For the record, since __alignof__ on expressions is a GCC 4337 // extension, GCC seems to permit this but always gives the 4338 // nonsensical answer 0. 4339 // 4340 // We don't really need the layout here --- we could instead just 4341 // directly check for all the appropriate alignment-lowing 4342 // attributes --- but that would require duplicating a lot of 4343 // logic that just isn't worth duplicating for such a marginal 4344 // use-case. 4345 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4346 // Fast path this check, since we at least know the record has a 4347 // definition if we can find a member of it. 4348 if (!FD->getParent()->isCompleteDefinition()) { 4349 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4350 << E->getSourceRange(); 4351 return true; 4352 } 4353 4354 // Otherwise, if it's a field, and the field doesn't have 4355 // reference type, then it must have a complete type (or be a 4356 // flexible array member, which we explicitly want to 4357 // white-list anyway), which makes the following checks trivial. 4358 if (!FD->getType()->isReferenceType()) 4359 return false; 4360 } 4361 4362 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4363 } 4364 4365 bool Sema::CheckVecStepExpr(Expr *E) { 4366 E = E->IgnoreParens(); 4367 4368 // Cannot know anything else if the expression is dependent. 4369 if (E->isTypeDependent()) 4370 return false; 4371 4372 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4373 } 4374 4375 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4376 CapturingScopeInfo *CSI) { 4377 assert(T->isVariablyModifiedType()); 4378 assert(CSI != nullptr); 4379 4380 // We're going to walk down into the type and look for VLA expressions. 4381 do { 4382 const Type *Ty = T.getTypePtr(); 4383 switch (Ty->getTypeClass()) { 4384 #define TYPE(Class, Base) 4385 #define ABSTRACT_TYPE(Class, Base) 4386 #define NON_CANONICAL_TYPE(Class, Base) 4387 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4388 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4389 #include "clang/AST/TypeNodes.inc" 4390 T = QualType(); 4391 break; 4392 // These types are never variably-modified. 4393 case Type::Builtin: 4394 case Type::Complex: 4395 case Type::Vector: 4396 case Type::ExtVector: 4397 case Type::ConstantMatrix: 4398 case Type::Record: 4399 case Type::Enum: 4400 case Type::Elaborated: 4401 case Type::TemplateSpecialization: 4402 case Type::ObjCObject: 4403 case Type::ObjCInterface: 4404 case Type::ObjCObjectPointer: 4405 case Type::ObjCTypeParam: 4406 case Type::Pipe: 4407 case Type::ExtInt: 4408 llvm_unreachable("type class is never variably-modified!"); 4409 case Type::Adjusted: 4410 T = cast<AdjustedType>(Ty)->getOriginalType(); 4411 break; 4412 case Type::Decayed: 4413 T = cast<DecayedType>(Ty)->getPointeeType(); 4414 break; 4415 case Type::Pointer: 4416 T = cast<PointerType>(Ty)->getPointeeType(); 4417 break; 4418 case Type::BlockPointer: 4419 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4420 break; 4421 case Type::LValueReference: 4422 case Type::RValueReference: 4423 T = cast<ReferenceType>(Ty)->getPointeeType(); 4424 break; 4425 case Type::MemberPointer: 4426 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4427 break; 4428 case Type::ConstantArray: 4429 case Type::IncompleteArray: 4430 // Losing element qualification here is fine. 4431 T = cast<ArrayType>(Ty)->getElementType(); 4432 break; 4433 case Type::VariableArray: { 4434 // Losing element qualification here is fine. 4435 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4436 4437 // Unknown size indication requires no size computation. 4438 // Otherwise, evaluate and record it. 4439 auto Size = VAT->getSizeExpr(); 4440 if (Size && !CSI->isVLATypeCaptured(VAT) && 4441 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4442 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4443 4444 T = VAT->getElementType(); 4445 break; 4446 } 4447 case Type::FunctionProto: 4448 case Type::FunctionNoProto: 4449 T = cast<FunctionType>(Ty)->getReturnType(); 4450 break; 4451 case Type::Paren: 4452 case Type::TypeOf: 4453 case Type::UnaryTransform: 4454 case Type::Attributed: 4455 case Type::SubstTemplateTypeParm: 4456 case Type::MacroQualified: 4457 // Keep walking after single level desugaring. 4458 T = T.getSingleStepDesugaredType(Context); 4459 break; 4460 case Type::Typedef: 4461 T = cast<TypedefType>(Ty)->desugar(); 4462 break; 4463 case Type::Decltype: 4464 T = cast<DecltypeType>(Ty)->desugar(); 4465 break; 4466 case Type::Auto: 4467 case Type::DeducedTemplateSpecialization: 4468 T = cast<DeducedType>(Ty)->getDeducedType(); 4469 break; 4470 case Type::TypeOfExpr: 4471 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4472 break; 4473 case Type::Atomic: 4474 T = cast<AtomicType>(Ty)->getValueType(); 4475 break; 4476 } 4477 } while (!T.isNull() && T->isVariablyModifiedType()); 4478 } 4479 4480 /// Build a sizeof or alignof expression given a type operand. 4481 ExprResult 4482 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4483 SourceLocation OpLoc, 4484 UnaryExprOrTypeTrait ExprKind, 4485 SourceRange R) { 4486 if (!TInfo) 4487 return ExprError(); 4488 4489 QualType T = TInfo->getType(); 4490 4491 if (!T->isDependentType() && 4492 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4493 return ExprError(); 4494 4495 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4496 if (auto *TT = T->getAs<TypedefType>()) { 4497 for (auto I = FunctionScopes.rbegin(), 4498 E = std::prev(FunctionScopes.rend()); 4499 I != E; ++I) { 4500 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4501 if (CSI == nullptr) 4502 break; 4503 DeclContext *DC = nullptr; 4504 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4505 DC = LSI->CallOperator; 4506 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4507 DC = CRSI->TheCapturedDecl; 4508 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4509 DC = BSI->TheDecl; 4510 if (DC) { 4511 if (DC->containsDecl(TT->getDecl())) 4512 break; 4513 captureVariablyModifiedType(Context, T, CSI); 4514 } 4515 } 4516 } 4517 } 4518 4519 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4520 return new (Context) UnaryExprOrTypeTraitExpr( 4521 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4522 } 4523 4524 /// Build a sizeof or alignof expression given an expression 4525 /// operand. 4526 ExprResult 4527 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4528 UnaryExprOrTypeTrait ExprKind) { 4529 ExprResult PE = CheckPlaceholderExpr(E); 4530 if (PE.isInvalid()) 4531 return ExprError(); 4532 4533 E = PE.get(); 4534 4535 // Verify that the operand is valid. 4536 bool isInvalid = false; 4537 if (E->isTypeDependent()) { 4538 // Delay type-checking for type-dependent expressions. 4539 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4540 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4541 } else if (ExprKind == UETT_VecStep) { 4542 isInvalid = CheckVecStepExpr(E); 4543 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4544 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4545 isInvalid = true; 4546 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4547 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4548 isInvalid = true; 4549 } else { 4550 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4551 } 4552 4553 if (isInvalid) 4554 return ExprError(); 4555 4556 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4557 PE = TransformToPotentiallyEvaluated(E); 4558 if (PE.isInvalid()) return ExprError(); 4559 E = PE.get(); 4560 } 4561 4562 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4563 return new (Context) UnaryExprOrTypeTraitExpr( 4564 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4565 } 4566 4567 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4568 /// expr and the same for @c alignof and @c __alignof 4569 /// Note that the ArgRange is invalid if isType is false. 4570 ExprResult 4571 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4572 UnaryExprOrTypeTrait ExprKind, bool IsType, 4573 void *TyOrEx, SourceRange ArgRange) { 4574 // If error parsing type, ignore. 4575 if (!TyOrEx) return ExprError(); 4576 4577 if (IsType) { 4578 TypeSourceInfo *TInfo; 4579 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4580 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4581 } 4582 4583 Expr *ArgEx = (Expr *)TyOrEx; 4584 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4585 return Result; 4586 } 4587 4588 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4589 bool IsReal) { 4590 if (V.get()->isTypeDependent()) 4591 return S.Context.DependentTy; 4592 4593 // _Real and _Imag are only l-values for normal l-values. 4594 if (V.get()->getObjectKind() != OK_Ordinary) { 4595 V = S.DefaultLvalueConversion(V.get()); 4596 if (V.isInvalid()) 4597 return QualType(); 4598 } 4599 4600 // These operators return the element type of a complex type. 4601 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4602 return CT->getElementType(); 4603 4604 // Otherwise they pass through real integer and floating point types here. 4605 if (V.get()->getType()->isArithmeticType()) 4606 return V.get()->getType(); 4607 4608 // Test for placeholders. 4609 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4610 if (PR.isInvalid()) return QualType(); 4611 if (PR.get() != V.get()) { 4612 V = PR; 4613 return CheckRealImagOperand(S, V, Loc, IsReal); 4614 } 4615 4616 // Reject anything else. 4617 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4618 << (IsReal ? "__real" : "__imag"); 4619 return QualType(); 4620 } 4621 4622 4623 4624 ExprResult 4625 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4626 tok::TokenKind Kind, Expr *Input) { 4627 UnaryOperatorKind Opc; 4628 switch (Kind) { 4629 default: llvm_unreachable("Unknown unary op!"); 4630 case tok::plusplus: Opc = UO_PostInc; break; 4631 case tok::minusminus: Opc = UO_PostDec; break; 4632 } 4633 4634 // Since this might is a postfix expression, get rid of ParenListExprs. 4635 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4636 if (Result.isInvalid()) return ExprError(); 4637 Input = Result.get(); 4638 4639 return BuildUnaryOp(S, OpLoc, Opc, Input); 4640 } 4641 4642 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4643 /// 4644 /// \return true on error 4645 static bool checkArithmeticOnObjCPointer(Sema &S, 4646 SourceLocation opLoc, 4647 Expr *op) { 4648 assert(op->getType()->isObjCObjectPointerType()); 4649 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4650 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4651 return false; 4652 4653 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4654 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4655 << op->getSourceRange(); 4656 return true; 4657 } 4658 4659 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4660 auto *BaseNoParens = Base->IgnoreParens(); 4661 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4662 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4663 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4664 } 4665 4666 ExprResult 4667 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4668 Expr *idx, SourceLocation rbLoc) { 4669 if (base && !base->getType().isNull() && 4670 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4671 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4672 SourceLocation(), /*Length*/ nullptr, 4673 /*Stride=*/nullptr, rbLoc); 4674 4675 // Since this might be a postfix expression, get rid of ParenListExprs. 4676 if (isa<ParenListExpr>(base)) { 4677 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4678 if (result.isInvalid()) return ExprError(); 4679 base = result.get(); 4680 } 4681 4682 // Check if base and idx form a MatrixSubscriptExpr. 4683 // 4684 // Helper to check for comma expressions, which are not allowed as indices for 4685 // matrix subscript expressions. 4686 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4687 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4688 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4689 << SourceRange(base->getBeginLoc(), rbLoc); 4690 return true; 4691 } 4692 return false; 4693 }; 4694 // The matrix subscript operator ([][])is considered a single operator. 4695 // Separating the index expressions by parenthesis is not allowed. 4696 if (base->getType()->isSpecificPlaceholderType( 4697 BuiltinType::IncompleteMatrixIdx) && 4698 !isa<MatrixSubscriptExpr>(base)) { 4699 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4700 << SourceRange(base->getBeginLoc(), rbLoc); 4701 return ExprError(); 4702 } 4703 // If the base is a MatrixSubscriptExpr, try to create a new 4704 // MatrixSubscriptExpr. 4705 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4706 if (matSubscriptE) { 4707 if (CheckAndReportCommaError(idx)) 4708 return ExprError(); 4709 4710 assert(matSubscriptE->isIncomplete() && 4711 "base has to be an incomplete matrix subscript"); 4712 return CreateBuiltinMatrixSubscriptExpr( 4713 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4714 } 4715 4716 // Handle any non-overload placeholder types in the base and index 4717 // expressions. We can't handle overloads here because the other 4718 // operand might be an overloadable type, in which case the overload 4719 // resolution for the operator overload should get the first crack 4720 // at the overload. 4721 bool IsMSPropertySubscript = false; 4722 if (base->getType()->isNonOverloadPlaceholderType()) { 4723 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4724 if (!IsMSPropertySubscript) { 4725 ExprResult result = CheckPlaceholderExpr(base); 4726 if (result.isInvalid()) 4727 return ExprError(); 4728 base = result.get(); 4729 } 4730 } 4731 4732 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4733 if (base->getType()->isMatrixType()) { 4734 if (CheckAndReportCommaError(idx)) 4735 return ExprError(); 4736 4737 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4738 } 4739 4740 // A comma-expression as the index is deprecated in C++2a onwards. 4741 if (getLangOpts().CPlusPlus20 && 4742 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4743 (isa<CXXOperatorCallExpr>(idx) && 4744 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4745 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4746 << SourceRange(base->getBeginLoc(), rbLoc); 4747 } 4748 4749 if (idx->getType()->isNonOverloadPlaceholderType()) { 4750 ExprResult result = CheckPlaceholderExpr(idx); 4751 if (result.isInvalid()) return ExprError(); 4752 idx = result.get(); 4753 } 4754 4755 // Build an unanalyzed expression if either operand is type-dependent. 4756 if (getLangOpts().CPlusPlus && 4757 (base->isTypeDependent() || idx->isTypeDependent())) { 4758 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4759 VK_LValue, OK_Ordinary, rbLoc); 4760 } 4761 4762 // MSDN, property (C++) 4763 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4764 // This attribute can also be used in the declaration of an empty array in a 4765 // class or structure definition. For example: 4766 // __declspec(property(get=GetX, put=PutX)) int x[]; 4767 // The above statement indicates that x[] can be used with one or more array 4768 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4769 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4770 if (IsMSPropertySubscript) { 4771 // Build MS property subscript expression if base is MS property reference 4772 // or MS property subscript. 4773 return new (Context) MSPropertySubscriptExpr( 4774 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4775 } 4776 4777 // Use C++ overloaded-operator rules if either operand has record 4778 // type. The spec says to do this if either type is *overloadable*, 4779 // but enum types can't declare subscript operators or conversion 4780 // operators, so there's nothing interesting for overload resolution 4781 // to do if there aren't any record types involved. 4782 // 4783 // ObjC pointers have their own subscripting logic that is not tied 4784 // to overload resolution and so should not take this path. 4785 if (getLangOpts().CPlusPlus && 4786 (base->getType()->isRecordType() || 4787 (!base->getType()->isObjCObjectPointerType() && 4788 idx->getType()->isRecordType()))) { 4789 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4790 } 4791 4792 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4793 4794 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4795 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4796 4797 return Res; 4798 } 4799 4800 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4801 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4802 InitializationKind Kind = 4803 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4804 InitializationSequence InitSeq(*this, Entity, Kind, E); 4805 return InitSeq.Perform(*this, Entity, Kind, E); 4806 } 4807 4808 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4809 Expr *ColumnIdx, 4810 SourceLocation RBLoc) { 4811 ExprResult BaseR = CheckPlaceholderExpr(Base); 4812 if (BaseR.isInvalid()) 4813 return BaseR; 4814 Base = BaseR.get(); 4815 4816 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4817 if (RowR.isInvalid()) 4818 return RowR; 4819 RowIdx = RowR.get(); 4820 4821 if (!ColumnIdx) 4822 return new (Context) MatrixSubscriptExpr( 4823 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4824 4825 // Build an unanalyzed expression if any of the operands is type-dependent. 4826 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4827 ColumnIdx->isTypeDependent()) 4828 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4829 Context.DependentTy, RBLoc); 4830 4831 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4832 if (ColumnR.isInvalid()) 4833 return ColumnR; 4834 ColumnIdx = ColumnR.get(); 4835 4836 // Check that IndexExpr is an integer expression. If it is a constant 4837 // expression, check that it is less than Dim (= the number of elements in the 4838 // corresponding dimension). 4839 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4840 bool IsColumnIdx) -> Expr * { 4841 if (!IndexExpr->getType()->isIntegerType() && 4842 !IndexExpr->isTypeDependent()) { 4843 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4844 << IsColumnIdx; 4845 return nullptr; 4846 } 4847 4848 if (Optional<llvm::APSInt> Idx = 4849 IndexExpr->getIntegerConstantExpr(Context)) { 4850 if ((*Idx < 0 || *Idx >= Dim)) { 4851 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4852 << IsColumnIdx << Dim; 4853 return nullptr; 4854 } 4855 } 4856 4857 ExprResult ConvExpr = 4858 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4859 assert(!ConvExpr.isInvalid() && 4860 "should be able to convert any integer type to size type"); 4861 return ConvExpr.get(); 4862 }; 4863 4864 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4865 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4866 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4867 if (!RowIdx || !ColumnIdx) 4868 return ExprError(); 4869 4870 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4871 MTy->getElementType(), RBLoc); 4872 } 4873 4874 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4875 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4876 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4877 4878 // For expressions like `&(*s).b`, the base is recorded and what should be 4879 // checked. 4880 const MemberExpr *Member = nullptr; 4881 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4882 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4883 4884 LastRecord.PossibleDerefs.erase(StrippedExpr); 4885 } 4886 4887 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4888 if (isUnevaluatedContext()) 4889 return; 4890 4891 QualType ResultTy = E->getType(); 4892 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4893 4894 // Bail if the element is an array since it is not memory access. 4895 if (isa<ArrayType>(ResultTy)) 4896 return; 4897 4898 if (ResultTy->hasAttr(attr::NoDeref)) { 4899 LastRecord.PossibleDerefs.insert(E); 4900 return; 4901 } 4902 4903 // Check if the base type is a pointer to a member access of a struct 4904 // marked with noderef. 4905 const Expr *Base = E->getBase(); 4906 QualType BaseTy = Base->getType(); 4907 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4908 // Not a pointer access 4909 return; 4910 4911 const MemberExpr *Member = nullptr; 4912 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4913 Member->isArrow()) 4914 Base = Member->getBase(); 4915 4916 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4917 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4918 LastRecord.PossibleDerefs.insert(E); 4919 } 4920 } 4921 4922 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4923 Expr *LowerBound, 4924 SourceLocation ColonLocFirst, 4925 SourceLocation ColonLocSecond, 4926 Expr *Length, Expr *Stride, 4927 SourceLocation RBLoc) { 4928 if (Base->getType()->isPlaceholderType() && 4929 !Base->getType()->isSpecificPlaceholderType( 4930 BuiltinType::OMPArraySection)) { 4931 ExprResult Result = CheckPlaceholderExpr(Base); 4932 if (Result.isInvalid()) 4933 return ExprError(); 4934 Base = Result.get(); 4935 } 4936 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4937 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4938 if (Result.isInvalid()) 4939 return ExprError(); 4940 Result = DefaultLvalueConversion(Result.get()); 4941 if (Result.isInvalid()) 4942 return ExprError(); 4943 LowerBound = Result.get(); 4944 } 4945 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4946 ExprResult Result = CheckPlaceholderExpr(Length); 4947 if (Result.isInvalid()) 4948 return ExprError(); 4949 Result = DefaultLvalueConversion(Result.get()); 4950 if (Result.isInvalid()) 4951 return ExprError(); 4952 Length = Result.get(); 4953 } 4954 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4955 ExprResult Result = CheckPlaceholderExpr(Stride); 4956 if (Result.isInvalid()) 4957 return ExprError(); 4958 Result = DefaultLvalueConversion(Result.get()); 4959 if (Result.isInvalid()) 4960 return ExprError(); 4961 Stride = Result.get(); 4962 } 4963 4964 // Build an unanalyzed expression if either operand is type-dependent. 4965 if (Base->isTypeDependent() || 4966 (LowerBound && 4967 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4968 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4969 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4970 return new (Context) OMPArraySectionExpr( 4971 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4972 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4973 } 4974 4975 // Perform default conversions. 4976 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4977 QualType ResultTy; 4978 if (OriginalTy->isAnyPointerType()) { 4979 ResultTy = OriginalTy->getPointeeType(); 4980 } else if (OriginalTy->isArrayType()) { 4981 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4982 } else { 4983 return ExprError( 4984 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4985 << Base->getSourceRange()); 4986 } 4987 // C99 6.5.2.1p1 4988 if (LowerBound) { 4989 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4990 LowerBound); 4991 if (Res.isInvalid()) 4992 return ExprError(Diag(LowerBound->getExprLoc(), 4993 diag::err_omp_typecheck_section_not_integer) 4994 << 0 << LowerBound->getSourceRange()); 4995 LowerBound = Res.get(); 4996 4997 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4998 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4999 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5000 << 0 << LowerBound->getSourceRange(); 5001 } 5002 if (Length) { 5003 auto Res = 5004 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5005 if (Res.isInvalid()) 5006 return ExprError(Diag(Length->getExprLoc(), 5007 diag::err_omp_typecheck_section_not_integer) 5008 << 1 << Length->getSourceRange()); 5009 Length = Res.get(); 5010 5011 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5012 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5013 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5014 << 1 << Length->getSourceRange(); 5015 } 5016 if (Stride) { 5017 ExprResult Res = 5018 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5019 if (Res.isInvalid()) 5020 return ExprError(Diag(Stride->getExprLoc(), 5021 diag::err_omp_typecheck_section_not_integer) 5022 << 1 << Stride->getSourceRange()); 5023 Stride = Res.get(); 5024 5025 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5026 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5027 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5028 << 1 << Stride->getSourceRange(); 5029 } 5030 5031 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5032 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5033 // type. Note that functions are not objects, and that (in C99 parlance) 5034 // incomplete types are not object types. 5035 if (ResultTy->isFunctionType()) { 5036 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5037 << ResultTy << Base->getSourceRange(); 5038 return ExprError(); 5039 } 5040 5041 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5042 diag::err_omp_section_incomplete_type, Base)) 5043 return ExprError(); 5044 5045 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5046 Expr::EvalResult Result; 5047 if (LowerBound->EvaluateAsInt(Result, Context)) { 5048 // OpenMP 5.0, [2.1.5 Array Sections] 5049 // The array section must be a subset of the original array. 5050 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5051 if (LowerBoundValue.isNegative()) { 5052 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5053 << LowerBound->getSourceRange(); 5054 return ExprError(); 5055 } 5056 } 5057 } 5058 5059 if (Length) { 5060 Expr::EvalResult Result; 5061 if (Length->EvaluateAsInt(Result, Context)) { 5062 // OpenMP 5.0, [2.1.5 Array Sections] 5063 // The length must evaluate to non-negative integers. 5064 llvm::APSInt LengthValue = Result.Val.getInt(); 5065 if (LengthValue.isNegative()) { 5066 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5067 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5068 << Length->getSourceRange(); 5069 return ExprError(); 5070 } 5071 } 5072 } else if (ColonLocFirst.isValid() && 5073 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5074 !OriginalTy->isVariableArrayType()))) { 5075 // OpenMP 5.0, [2.1.5 Array Sections] 5076 // When the size of the array dimension is not known, the length must be 5077 // specified explicitly. 5078 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5079 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5080 return ExprError(); 5081 } 5082 5083 if (Stride) { 5084 Expr::EvalResult Result; 5085 if (Stride->EvaluateAsInt(Result, Context)) { 5086 // OpenMP 5.0, [2.1.5 Array Sections] 5087 // The stride must evaluate to a positive integer. 5088 llvm::APSInt StrideValue = Result.Val.getInt(); 5089 if (!StrideValue.isStrictlyPositive()) { 5090 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5091 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5092 << Stride->getSourceRange(); 5093 return ExprError(); 5094 } 5095 } 5096 } 5097 5098 if (!Base->getType()->isSpecificPlaceholderType( 5099 BuiltinType::OMPArraySection)) { 5100 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5101 if (Result.isInvalid()) 5102 return ExprError(); 5103 Base = Result.get(); 5104 } 5105 return new (Context) OMPArraySectionExpr( 5106 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5107 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5108 } 5109 5110 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5111 SourceLocation RParenLoc, 5112 ArrayRef<Expr *> Dims, 5113 ArrayRef<SourceRange> Brackets) { 5114 if (Base->getType()->isPlaceholderType()) { 5115 ExprResult Result = CheckPlaceholderExpr(Base); 5116 if (Result.isInvalid()) 5117 return ExprError(); 5118 Result = DefaultLvalueConversion(Result.get()); 5119 if (Result.isInvalid()) 5120 return ExprError(); 5121 Base = Result.get(); 5122 } 5123 QualType BaseTy = Base->getType(); 5124 // Delay analysis of the types/expressions if instantiation/specialization is 5125 // required. 5126 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5127 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5128 LParenLoc, RParenLoc, Dims, Brackets); 5129 if (!BaseTy->isPointerType() || 5130 (!Base->isTypeDependent() && 5131 BaseTy->getPointeeType()->isIncompleteType())) 5132 return ExprError(Diag(Base->getExprLoc(), 5133 diag::err_omp_non_pointer_type_array_shaping_base) 5134 << Base->getSourceRange()); 5135 5136 SmallVector<Expr *, 4> NewDims; 5137 bool ErrorFound = false; 5138 for (Expr *Dim : Dims) { 5139 if (Dim->getType()->isPlaceholderType()) { 5140 ExprResult Result = CheckPlaceholderExpr(Dim); 5141 if (Result.isInvalid()) { 5142 ErrorFound = true; 5143 continue; 5144 } 5145 Result = DefaultLvalueConversion(Result.get()); 5146 if (Result.isInvalid()) { 5147 ErrorFound = true; 5148 continue; 5149 } 5150 Dim = Result.get(); 5151 } 5152 if (!Dim->isTypeDependent()) { 5153 ExprResult Result = 5154 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5155 if (Result.isInvalid()) { 5156 ErrorFound = true; 5157 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5158 << Dim->getSourceRange(); 5159 continue; 5160 } 5161 Dim = Result.get(); 5162 Expr::EvalResult EvResult; 5163 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5164 // OpenMP 5.0, [2.1.4 Array Shaping] 5165 // Each si is an integral type expression that must evaluate to a 5166 // positive integer. 5167 llvm::APSInt Value = EvResult.Val.getInt(); 5168 if (!Value.isStrictlyPositive()) { 5169 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5170 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5171 << Dim->getSourceRange(); 5172 ErrorFound = true; 5173 continue; 5174 } 5175 } 5176 } 5177 NewDims.push_back(Dim); 5178 } 5179 if (ErrorFound) 5180 return ExprError(); 5181 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5182 LParenLoc, RParenLoc, NewDims, Brackets); 5183 } 5184 5185 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5186 SourceLocation LLoc, SourceLocation RLoc, 5187 ArrayRef<OMPIteratorData> Data) { 5188 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5189 bool IsCorrect = true; 5190 for (const OMPIteratorData &D : Data) { 5191 TypeSourceInfo *TInfo = nullptr; 5192 SourceLocation StartLoc; 5193 QualType DeclTy; 5194 if (!D.Type.getAsOpaquePtr()) { 5195 // OpenMP 5.0, 2.1.6 Iterators 5196 // In an iterator-specifier, if the iterator-type is not specified then 5197 // the type of that iterator is of int type. 5198 DeclTy = Context.IntTy; 5199 StartLoc = D.DeclIdentLoc; 5200 } else { 5201 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5202 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5203 } 5204 5205 bool IsDeclTyDependent = DeclTy->isDependentType() || 5206 DeclTy->containsUnexpandedParameterPack() || 5207 DeclTy->isInstantiationDependentType(); 5208 if (!IsDeclTyDependent) { 5209 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5210 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5211 // The iterator-type must be an integral or pointer type. 5212 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5213 << DeclTy; 5214 IsCorrect = false; 5215 continue; 5216 } 5217 if (DeclTy.isConstant(Context)) { 5218 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5219 // The iterator-type must not be const qualified. 5220 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5221 << DeclTy; 5222 IsCorrect = false; 5223 continue; 5224 } 5225 } 5226 5227 // Iterator declaration. 5228 assert(D.DeclIdent && "Identifier expected."); 5229 // Always try to create iterator declarator to avoid extra error messages 5230 // about unknown declarations use. 5231 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5232 D.DeclIdent, DeclTy, TInfo, SC_None); 5233 VD->setImplicit(); 5234 if (S) { 5235 // Check for conflicting previous declaration. 5236 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5237 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5238 ForVisibleRedeclaration); 5239 Previous.suppressDiagnostics(); 5240 LookupName(Previous, S); 5241 5242 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5243 /*AllowInlineNamespace=*/false); 5244 if (!Previous.empty()) { 5245 NamedDecl *Old = Previous.getRepresentativeDecl(); 5246 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5247 Diag(Old->getLocation(), diag::note_previous_definition); 5248 } else { 5249 PushOnScopeChains(VD, S); 5250 } 5251 } else { 5252 CurContext->addDecl(VD); 5253 } 5254 Expr *Begin = D.Range.Begin; 5255 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5256 ExprResult BeginRes = 5257 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5258 Begin = BeginRes.get(); 5259 } 5260 Expr *End = D.Range.End; 5261 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5262 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5263 End = EndRes.get(); 5264 } 5265 Expr *Step = D.Range.Step; 5266 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5267 if (!Step->getType()->isIntegralType(Context)) { 5268 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5269 << Step << Step->getSourceRange(); 5270 IsCorrect = false; 5271 continue; 5272 } 5273 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5274 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5275 // If the step expression of a range-specification equals zero, the 5276 // behavior is unspecified. 5277 if (Result && Result->isNullValue()) { 5278 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5279 << Step << Step->getSourceRange(); 5280 IsCorrect = false; 5281 continue; 5282 } 5283 } 5284 if (!Begin || !End || !IsCorrect) { 5285 IsCorrect = false; 5286 continue; 5287 } 5288 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5289 IDElem.IteratorDecl = VD; 5290 IDElem.AssignmentLoc = D.AssignLoc; 5291 IDElem.Range.Begin = Begin; 5292 IDElem.Range.End = End; 5293 IDElem.Range.Step = Step; 5294 IDElem.ColonLoc = D.ColonLoc; 5295 IDElem.SecondColonLoc = D.SecColonLoc; 5296 } 5297 if (!IsCorrect) { 5298 // Invalidate all created iterator declarations if error is found. 5299 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5300 if (Decl *ID = D.IteratorDecl) 5301 ID->setInvalidDecl(); 5302 } 5303 return ExprError(); 5304 } 5305 SmallVector<OMPIteratorHelperData, 4> Helpers; 5306 if (!CurContext->isDependentContext()) { 5307 // Build number of ityeration for each iteration range. 5308 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5309 // ((Begini-Stepi-1-Endi) / -Stepi); 5310 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5311 // (Endi - Begini) 5312 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5313 D.Range.Begin); 5314 if(!Res.isUsable()) { 5315 IsCorrect = false; 5316 continue; 5317 } 5318 ExprResult St, St1; 5319 if (D.Range.Step) { 5320 St = D.Range.Step; 5321 // (Endi - Begini) + Stepi 5322 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5323 if (!Res.isUsable()) { 5324 IsCorrect = false; 5325 continue; 5326 } 5327 // (Endi - Begini) + Stepi - 1 5328 Res = 5329 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5330 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5331 if (!Res.isUsable()) { 5332 IsCorrect = false; 5333 continue; 5334 } 5335 // ((Endi - Begini) + Stepi - 1) / Stepi 5336 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5337 if (!Res.isUsable()) { 5338 IsCorrect = false; 5339 continue; 5340 } 5341 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5342 // (Begini - Endi) 5343 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5344 D.Range.Begin, D.Range.End); 5345 if (!Res1.isUsable()) { 5346 IsCorrect = false; 5347 continue; 5348 } 5349 // (Begini - Endi) - Stepi 5350 Res1 = 5351 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5352 if (!Res1.isUsable()) { 5353 IsCorrect = false; 5354 continue; 5355 } 5356 // (Begini - Endi) - Stepi - 1 5357 Res1 = 5358 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5359 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5360 if (!Res1.isUsable()) { 5361 IsCorrect = false; 5362 continue; 5363 } 5364 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5365 Res1 = 5366 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5367 if (!Res1.isUsable()) { 5368 IsCorrect = false; 5369 continue; 5370 } 5371 // Stepi > 0. 5372 ExprResult CmpRes = 5373 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5374 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5375 if (!CmpRes.isUsable()) { 5376 IsCorrect = false; 5377 continue; 5378 } 5379 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5380 Res.get(), Res1.get()); 5381 if (!Res.isUsable()) { 5382 IsCorrect = false; 5383 continue; 5384 } 5385 } 5386 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5387 if (!Res.isUsable()) { 5388 IsCorrect = false; 5389 continue; 5390 } 5391 5392 // Build counter update. 5393 // Build counter. 5394 auto *CounterVD = 5395 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5396 D.IteratorDecl->getBeginLoc(), nullptr, 5397 Res.get()->getType(), nullptr, SC_None); 5398 CounterVD->setImplicit(); 5399 ExprResult RefRes = 5400 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5401 D.IteratorDecl->getBeginLoc()); 5402 // Build counter update. 5403 // I = Begini + counter * Stepi; 5404 ExprResult UpdateRes; 5405 if (D.Range.Step) { 5406 UpdateRes = CreateBuiltinBinOp( 5407 D.AssignmentLoc, BO_Mul, 5408 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5409 } else { 5410 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5411 } 5412 if (!UpdateRes.isUsable()) { 5413 IsCorrect = false; 5414 continue; 5415 } 5416 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5417 UpdateRes.get()); 5418 if (!UpdateRes.isUsable()) { 5419 IsCorrect = false; 5420 continue; 5421 } 5422 ExprResult VDRes = 5423 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5424 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5425 D.IteratorDecl->getBeginLoc()); 5426 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5427 UpdateRes.get()); 5428 if (!UpdateRes.isUsable()) { 5429 IsCorrect = false; 5430 continue; 5431 } 5432 UpdateRes = 5433 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5434 if (!UpdateRes.isUsable()) { 5435 IsCorrect = false; 5436 continue; 5437 } 5438 ExprResult CounterUpdateRes = 5439 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5440 if (!CounterUpdateRes.isUsable()) { 5441 IsCorrect = false; 5442 continue; 5443 } 5444 CounterUpdateRes = 5445 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5446 if (!CounterUpdateRes.isUsable()) { 5447 IsCorrect = false; 5448 continue; 5449 } 5450 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5451 HD.CounterVD = CounterVD; 5452 HD.Upper = Res.get(); 5453 HD.Update = UpdateRes.get(); 5454 HD.CounterUpdate = CounterUpdateRes.get(); 5455 } 5456 } else { 5457 Helpers.assign(ID.size(), {}); 5458 } 5459 if (!IsCorrect) { 5460 // Invalidate all created iterator declarations if error is found. 5461 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5462 if (Decl *ID = D.IteratorDecl) 5463 ID->setInvalidDecl(); 5464 } 5465 return ExprError(); 5466 } 5467 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5468 LLoc, RLoc, ID, Helpers); 5469 } 5470 5471 ExprResult 5472 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5473 Expr *Idx, SourceLocation RLoc) { 5474 Expr *LHSExp = Base; 5475 Expr *RHSExp = Idx; 5476 5477 ExprValueKind VK = VK_LValue; 5478 ExprObjectKind OK = OK_Ordinary; 5479 5480 // Per C++ core issue 1213, the result is an xvalue if either operand is 5481 // a non-lvalue array, and an lvalue otherwise. 5482 if (getLangOpts().CPlusPlus11) { 5483 for (auto *Op : {LHSExp, RHSExp}) { 5484 Op = Op->IgnoreImplicit(); 5485 if (Op->getType()->isArrayType() && !Op->isLValue()) 5486 VK = VK_XValue; 5487 } 5488 } 5489 5490 // Perform default conversions. 5491 if (!LHSExp->getType()->getAs<VectorType>()) { 5492 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5493 if (Result.isInvalid()) 5494 return ExprError(); 5495 LHSExp = Result.get(); 5496 } 5497 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5498 if (Result.isInvalid()) 5499 return ExprError(); 5500 RHSExp = Result.get(); 5501 5502 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5503 5504 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5505 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5506 // in the subscript position. As a result, we need to derive the array base 5507 // and index from the expression types. 5508 Expr *BaseExpr, *IndexExpr; 5509 QualType ResultType; 5510 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5511 BaseExpr = LHSExp; 5512 IndexExpr = RHSExp; 5513 ResultType = Context.DependentTy; 5514 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5515 BaseExpr = LHSExp; 5516 IndexExpr = RHSExp; 5517 ResultType = PTy->getPointeeType(); 5518 } else if (const ObjCObjectPointerType *PTy = 5519 LHSTy->getAs<ObjCObjectPointerType>()) { 5520 BaseExpr = LHSExp; 5521 IndexExpr = RHSExp; 5522 5523 // Use custom logic if this should be the pseudo-object subscript 5524 // expression. 5525 if (!LangOpts.isSubscriptPointerArithmetic()) 5526 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5527 nullptr); 5528 5529 ResultType = PTy->getPointeeType(); 5530 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5531 // Handle the uncommon case of "123[Ptr]". 5532 BaseExpr = RHSExp; 5533 IndexExpr = LHSExp; 5534 ResultType = PTy->getPointeeType(); 5535 } else if (const ObjCObjectPointerType *PTy = 5536 RHSTy->getAs<ObjCObjectPointerType>()) { 5537 // Handle the uncommon case of "123[Ptr]". 5538 BaseExpr = RHSExp; 5539 IndexExpr = LHSExp; 5540 ResultType = PTy->getPointeeType(); 5541 if (!LangOpts.isSubscriptPointerArithmetic()) { 5542 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5543 << ResultType << BaseExpr->getSourceRange(); 5544 return ExprError(); 5545 } 5546 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5547 BaseExpr = LHSExp; // vectors: V[123] 5548 IndexExpr = RHSExp; 5549 // We apply C++ DR1213 to vector subscripting too. 5550 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_PRValue) { 5551 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5552 if (Materialized.isInvalid()) 5553 return ExprError(); 5554 LHSExp = Materialized.get(); 5555 } 5556 VK = LHSExp->getValueKind(); 5557 if (VK != VK_PRValue) 5558 OK = OK_VectorComponent; 5559 5560 ResultType = VTy->getElementType(); 5561 QualType BaseType = BaseExpr->getType(); 5562 Qualifiers BaseQuals = BaseType.getQualifiers(); 5563 Qualifiers MemberQuals = ResultType.getQualifiers(); 5564 Qualifiers Combined = BaseQuals + MemberQuals; 5565 if (Combined != MemberQuals) 5566 ResultType = Context.getQualifiedType(ResultType, Combined); 5567 } else if (LHSTy->isArrayType()) { 5568 // If we see an array that wasn't promoted by 5569 // DefaultFunctionArrayLvalueConversion, it must be an array that 5570 // wasn't promoted because of the C90 rule that doesn't 5571 // allow promoting non-lvalue arrays. Warn, then 5572 // force the promotion here. 5573 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5574 << LHSExp->getSourceRange(); 5575 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5576 CK_ArrayToPointerDecay).get(); 5577 LHSTy = LHSExp->getType(); 5578 5579 BaseExpr = LHSExp; 5580 IndexExpr = RHSExp; 5581 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5582 } else if (RHSTy->isArrayType()) { 5583 // Same as previous, except for 123[f().a] case 5584 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5585 << RHSExp->getSourceRange(); 5586 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5587 CK_ArrayToPointerDecay).get(); 5588 RHSTy = RHSExp->getType(); 5589 5590 BaseExpr = RHSExp; 5591 IndexExpr = LHSExp; 5592 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5593 } else { 5594 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5595 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5596 } 5597 // C99 6.5.2.1p1 5598 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5599 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5600 << IndexExpr->getSourceRange()); 5601 5602 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5603 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5604 && !IndexExpr->isTypeDependent()) 5605 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5606 5607 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5608 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5609 // type. Note that Functions are not objects, and that (in C99 parlance) 5610 // incomplete types are not object types. 5611 if (ResultType->isFunctionType()) { 5612 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5613 << ResultType << BaseExpr->getSourceRange(); 5614 return ExprError(); 5615 } 5616 5617 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5618 // GNU extension: subscripting on pointer to void 5619 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5620 << BaseExpr->getSourceRange(); 5621 5622 // C forbids expressions of unqualified void type from being l-values. 5623 // See IsCForbiddenLValueType. 5624 if (!ResultType.hasQualifiers()) 5625 VK = VK_PRValue; 5626 } else if (!ResultType->isDependentType() && 5627 RequireCompleteSizedType( 5628 LLoc, ResultType, 5629 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5630 return ExprError(); 5631 5632 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5633 !ResultType.isCForbiddenLValueType()); 5634 5635 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5636 FunctionScopes.size() > 1) { 5637 if (auto *TT = 5638 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5639 for (auto I = FunctionScopes.rbegin(), 5640 E = std::prev(FunctionScopes.rend()); 5641 I != E; ++I) { 5642 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5643 if (CSI == nullptr) 5644 break; 5645 DeclContext *DC = nullptr; 5646 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5647 DC = LSI->CallOperator; 5648 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5649 DC = CRSI->TheCapturedDecl; 5650 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5651 DC = BSI->TheDecl; 5652 if (DC) { 5653 if (DC->containsDecl(TT->getDecl())) 5654 break; 5655 captureVariablyModifiedType( 5656 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5657 } 5658 } 5659 } 5660 } 5661 5662 return new (Context) 5663 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5664 } 5665 5666 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5667 ParmVarDecl *Param) { 5668 if (Param->hasUnparsedDefaultArg()) { 5669 // If we've already cleared out the location for the default argument, 5670 // that means we're parsing it right now. 5671 if (!UnparsedDefaultArgLocs.count(Param)) { 5672 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5673 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5674 Param->setInvalidDecl(); 5675 return true; 5676 } 5677 5678 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5679 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5680 Diag(UnparsedDefaultArgLocs[Param], 5681 diag::note_default_argument_declared_here); 5682 return true; 5683 } 5684 5685 if (Param->hasUninstantiatedDefaultArg() && 5686 InstantiateDefaultArgument(CallLoc, FD, Param)) 5687 return true; 5688 5689 assert(Param->hasInit() && "default argument but no initializer?"); 5690 5691 // If the default expression creates temporaries, we need to 5692 // push them to the current stack of expression temporaries so they'll 5693 // be properly destroyed. 5694 // FIXME: We should really be rebuilding the default argument with new 5695 // bound temporaries; see the comment in PR5810. 5696 // We don't need to do that with block decls, though, because 5697 // blocks in default argument expression can never capture anything. 5698 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5699 // Set the "needs cleanups" bit regardless of whether there are 5700 // any explicit objects. 5701 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5702 5703 // Append all the objects to the cleanup list. Right now, this 5704 // should always be a no-op, because blocks in default argument 5705 // expressions should never be able to capture anything. 5706 assert(!Init->getNumObjects() && 5707 "default argument expression has capturing blocks?"); 5708 } 5709 5710 // We already type-checked the argument, so we know it works. 5711 // Just mark all of the declarations in this potentially-evaluated expression 5712 // as being "referenced". 5713 EnterExpressionEvaluationContext EvalContext( 5714 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5715 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5716 /*SkipLocalVariables=*/true); 5717 return false; 5718 } 5719 5720 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5721 FunctionDecl *FD, ParmVarDecl *Param) { 5722 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5723 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5724 return ExprError(); 5725 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5726 } 5727 5728 Sema::VariadicCallType 5729 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5730 Expr *Fn) { 5731 if (Proto && Proto->isVariadic()) { 5732 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5733 return VariadicConstructor; 5734 else if (Fn && Fn->getType()->isBlockPointerType()) 5735 return VariadicBlock; 5736 else if (FDecl) { 5737 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5738 if (Method->isInstance()) 5739 return VariadicMethod; 5740 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5741 return VariadicMethod; 5742 return VariadicFunction; 5743 } 5744 return VariadicDoesNotApply; 5745 } 5746 5747 namespace { 5748 class FunctionCallCCC final : public FunctionCallFilterCCC { 5749 public: 5750 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5751 unsigned NumArgs, MemberExpr *ME) 5752 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5753 FunctionName(FuncName) {} 5754 5755 bool ValidateCandidate(const TypoCorrection &candidate) override { 5756 if (!candidate.getCorrectionSpecifier() || 5757 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5758 return false; 5759 } 5760 5761 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5762 } 5763 5764 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5765 return std::make_unique<FunctionCallCCC>(*this); 5766 } 5767 5768 private: 5769 const IdentifierInfo *const FunctionName; 5770 }; 5771 } 5772 5773 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5774 FunctionDecl *FDecl, 5775 ArrayRef<Expr *> Args) { 5776 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5777 DeclarationName FuncName = FDecl->getDeclName(); 5778 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5779 5780 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5781 if (TypoCorrection Corrected = S.CorrectTypo( 5782 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5783 S.getScopeForContext(S.CurContext), nullptr, CCC, 5784 Sema::CTK_ErrorRecovery)) { 5785 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5786 if (Corrected.isOverloaded()) { 5787 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5788 OverloadCandidateSet::iterator Best; 5789 for (NamedDecl *CD : Corrected) { 5790 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5791 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5792 OCS); 5793 } 5794 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5795 case OR_Success: 5796 ND = Best->FoundDecl; 5797 Corrected.setCorrectionDecl(ND); 5798 break; 5799 default: 5800 break; 5801 } 5802 } 5803 ND = ND->getUnderlyingDecl(); 5804 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5805 return Corrected; 5806 } 5807 } 5808 return TypoCorrection(); 5809 } 5810 5811 /// ConvertArgumentsForCall - Converts the arguments specified in 5812 /// Args/NumArgs to the parameter types of the function FDecl with 5813 /// function prototype Proto. Call is the call expression itself, and 5814 /// Fn is the function expression. For a C++ member function, this 5815 /// routine does not attempt to convert the object argument. Returns 5816 /// true if the call is ill-formed. 5817 bool 5818 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5819 FunctionDecl *FDecl, 5820 const FunctionProtoType *Proto, 5821 ArrayRef<Expr *> Args, 5822 SourceLocation RParenLoc, 5823 bool IsExecConfig) { 5824 // Bail out early if calling a builtin with custom typechecking. 5825 if (FDecl) 5826 if (unsigned ID = FDecl->getBuiltinID()) 5827 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5828 return false; 5829 5830 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5831 // assignment, to the types of the corresponding parameter, ... 5832 unsigned NumParams = Proto->getNumParams(); 5833 bool Invalid = false; 5834 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5835 unsigned FnKind = Fn->getType()->isBlockPointerType() 5836 ? 1 /* block */ 5837 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5838 : 0 /* function */); 5839 5840 // If too few arguments are available (and we don't have default 5841 // arguments for the remaining parameters), don't make the call. 5842 if (Args.size() < NumParams) { 5843 if (Args.size() < MinArgs) { 5844 TypoCorrection TC; 5845 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5846 unsigned diag_id = 5847 MinArgs == NumParams && !Proto->isVariadic() 5848 ? diag::err_typecheck_call_too_few_args_suggest 5849 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5850 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5851 << static_cast<unsigned>(Args.size()) 5852 << TC.getCorrectionRange()); 5853 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5854 Diag(RParenLoc, 5855 MinArgs == NumParams && !Proto->isVariadic() 5856 ? diag::err_typecheck_call_too_few_args_one 5857 : diag::err_typecheck_call_too_few_args_at_least_one) 5858 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5859 else 5860 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5861 ? diag::err_typecheck_call_too_few_args 5862 : diag::err_typecheck_call_too_few_args_at_least) 5863 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5864 << Fn->getSourceRange(); 5865 5866 // Emit the location of the prototype. 5867 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5868 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5869 5870 return true; 5871 } 5872 // We reserve space for the default arguments when we create 5873 // the call expression, before calling ConvertArgumentsForCall. 5874 assert((Call->getNumArgs() == NumParams) && 5875 "We should have reserved space for the default arguments before!"); 5876 } 5877 5878 // If too many are passed and not variadic, error on the extras and drop 5879 // them. 5880 if (Args.size() > NumParams) { 5881 if (!Proto->isVariadic()) { 5882 TypoCorrection TC; 5883 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5884 unsigned diag_id = 5885 MinArgs == NumParams && !Proto->isVariadic() 5886 ? diag::err_typecheck_call_too_many_args_suggest 5887 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5888 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5889 << static_cast<unsigned>(Args.size()) 5890 << TC.getCorrectionRange()); 5891 } else if (NumParams == 1 && FDecl && 5892 FDecl->getParamDecl(0)->getDeclName()) 5893 Diag(Args[NumParams]->getBeginLoc(), 5894 MinArgs == NumParams 5895 ? diag::err_typecheck_call_too_many_args_one 5896 : diag::err_typecheck_call_too_many_args_at_most_one) 5897 << FnKind << FDecl->getParamDecl(0) 5898 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5899 << SourceRange(Args[NumParams]->getBeginLoc(), 5900 Args.back()->getEndLoc()); 5901 else 5902 Diag(Args[NumParams]->getBeginLoc(), 5903 MinArgs == NumParams 5904 ? diag::err_typecheck_call_too_many_args 5905 : diag::err_typecheck_call_too_many_args_at_most) 5906 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5907 << Fn->getSourceRange() 5908 << SourceRange(Args[NumParams]->getBeginLoc(), 5909 Args.back()->getEndLoc()); 5910 5911 // Emit the location of the prototype. 5912 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5913 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5914 5915 // This deletes the extra arguments. 5916 Call->shrinkNumArgs(NumParams); 5917 return true; 5918 } 5919 } 5920 SmallVector<Expr *, 8> AllArgs; 5921 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5922 5923 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5924 AllArgs, CallType); 5925 if (Invalid) 5926 return true; 5927 unsigned TotalNumArgs = AllArgs.size(); 5928 for (unsigned i = 0; i < TotalNumArgs; ++i) 5929 Call->setArg(i, AllArgs[i]); 5930 5931 Call->computeDependence(); 5932 return false; 5933 } 5934 5935 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5936 const FunctionProtoType *Proto, 5937 unsigned FirstParam, ArrayRef<Expr *> Args, 5938 SmallVectorImpl<Expr *> &AllArgs, 5939 VariadicCallType CallType, bool AllowExplicit, 5940 bool IsListInitialization) { 5941 unsigned NumParams = Proto->getNumParams(); 5942 bool Invalid = false; 5943 size_t ArgIx = 0; 5944 // Continue to check argument types (even if we have too few/many args). 5945 for (unsigned i = FirstParam; i < NumParams; i++) { 5946 QualType ProtoArgType = Proto->getParamType(i); 5947 5948 Expr *Arg; 5949 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5950 if (ArgIx < Args.size()) { 5951 Arg = Args[ArgIx++]; 5952 5953 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5954 diag::err_call_incomplete_argument, Arg)) 5955 return true; 5956 5957 // Strip the unbridged-cast placeholder expression off, if applicable. 5958 bool CFAudited = false; 5959 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5960 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5961 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5962 Arg = stripARCUnbridgedCast(Arg); 5963 else if (getLangOpts().ObjCAutoRefCount && 5964 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5965 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5966 CFAudited = true; 5967 5968 if (Proto->getExtParameterInfo(i).isNoEscape() && 5969 ProtoArgType->isBlockPointerType()) 5970 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5971 BE->getBlockDecl()->setDoesNotEscape(); 5972 5973 InitializedEntity Entity = 5974 Param ? InitializedEntity::InitializeParameter(Context, Param, 5975 ProtoArgType) 5976 : InitializedEntity::InitializeParameter( 5977 Context, ProtoArgType, Proto->isParamConsumed(i)); 5978 5979 // Remember that parameter belongs to a CF audited API. 5980 if (CFAudited) 5981 Entity.setParameterCFAudited(); 5982 5983 ExprResult ArgE = PerformCopyInitialization( 5984 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5985 if (ArgE.isInvalid()) 5986 return true; 5987 5988 Arg = ArgE.getAs<Expr>(); 5989 } else { 5990 assert(Param && "can't use default arguments without a known callee"); 5991 5992 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5993 if (ArgExpr.isInvalid()) 5994 return true; 5995 5996 Arg = ArgExpr.getAs<Expr>(); 5997 } 5998 5999 // Check for array bounds violations for each argument to the call. This 6000 // check only triggers warnings when the argument isn't a more complex Expr 6001 // with its own checking, such as a BinaryOperator. 6002 CheckArrayAccess(Arg); 6003 6004 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6005 CheckStaticArrayArgument(CallLoc, Param, Arg); 6006 6007 AllArgs.push_back(Arg); 6008 } 6009 6010 // If this is a variadic call, handle args passed through "...". 6011 if (CallType != VariadicDoesNotApply) { 6012 // Assume that extern "C" functions with variadic arguments that 6013 // return __unknown_anytype aren't *really* variadic. 6014 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6015 FDecl->isExternC()) { 6016 for (Expr *A : Args.slice(ArgIx)) { 6017 QualType paramType; // ignored 6018 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6019 Invalid |= arg.isInvalid(); 6020 AllArgs.push_back(arg.get()); 6021 } 6022 6023 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6024 } else { 6025 for (Expr *A : Args.slice(ArgIx)) { 6026 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6027 Invalid |= Arg.isInvalid(); 6028 AllArgs.push_back(Arg.get()); 6029 } 6030 } 6031 6032 // Check for array bounds violations. 6033 for (Expr *A : Args.slice(ArgIx)) 6034 CheckArrayAccess(A); 6035 } 6036 return Invalid; 6037 } 6038 6039 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6040 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6041 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6042 TL = DTL.getOriginalLoc(); 6043 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6044 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6045 << ATL.getLocalSourceRange(); 6046 } 6047 6048 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6049 /// array parameter, check that it is non-null, and that if it is formed by 6050 /// array-to-pointer decay, the underlying array is sufficiently large. 6051 /// 6052 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6053 /// array type derivation, then for each call to the function, the value of the 6054 /// corresponding actual argument shall provide access to the first element of 6055 /// an array with at least as many elements as specified by the size expression. 6056 void 6057 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6058 ParmVarDecl *Param, 6059 const Expr *ArgExpr) { 6060 // Static array parameters are not supported in C++. 6061 if (!Param || getLangOpts().CPlusPlus) 6062 return; 6063 6064 QualType OrigTy = Param->getOriginalType(); 6065 6066 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6067 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6068 return; 6069 6070 if (ArgExpr->isNullPointerConstant(Context, 6071 Expr::NPC_NeverValueDependent)) { 6072 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6073 DiagnoseCalleeStaticArrayParam(*this, Param); 6074 return; 6075 } 6076 6077 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6078 if (!CAT) 6079 return; 6080 6081 const ConstantArrayType *ArgCAT = 6082 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6083 if (!ArgCAT) 6084 return; 6085 6086 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6087 ArgCAT->getElementType())) { 6088 if (ArgCAT->getSize().ult(CAT->getSize())) { 6089 Diag(CallLoc, diag::warn_static_array_too_small) 6090 << ArgExpr->getSourceRange() 6091 << (unsigned)ArgCAT->getSize().getZExtValue() 6092 << (unsigned)CAT->getSize().getZExtValue() << 0; 6093 DiagnoseCalleeStaticArrayParam(*this, Param); 6094 } 6095 return; 6096 } 6097 6098 Optional<CharUnits> ArgSize = 6099 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6100 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6101 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6102 Diag(CallLoc, diag::warn_static_array_too_small) 6103 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6104 << (unsigned)ParmSize->getQuantity() << 1; 6105 DiagnoseCalleeStaticArrayParam(*this, Param); 6106 } 6107 } 6108 6109 /// Given a function expression of unknown-any type, try to rebuild it 6110 /// to have a function type. 6111 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6112 6113 /// Is the given type a placeholder that we need to lower out 6114 /// immediately during argument processing? 6115 static bool isPlaceholderToRemoveAsArg(QualType type) { 6116 // Placeholders are never sugared. 6117 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6118 if (!placeholder) return false; 6119 6120 switch (placeholder->getKind()) { 6121 // Ignore all the non-placeholder types. 6122 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6123 case BuiltinType::Id: 6124 #include "clang/Basic/OpenCLImageTypes.def" 6125 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6126 case BuiltinType::Id: 6127 #include "clang/Basic/OpenCLExtensionTypes.def" 6128 // In practice we'll never use this, since all SVE types are sugared 6129 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6130 #define SVE_TYPE(Name, Id, SingletonId) \ 6131 case BuiltinType::Id: 6132 #include "clang/Basic/AArch64SVEACLETypes.def" 6133 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6134 case BuiltinType::Id: 6135 #include "clang/Basic/PPCTypes.def" 6136 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6137 #include "clang/Basic/RISCVVTypes.def" 6138 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6139 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6140 #include "clang/AST/BuiltinTypes.def" 6141 return false; 6142 6143 // We cannot lower out overload sets; they might validly be resolved 6144 // by the call machinery. 6145 case BuiltinType::Overload: 6146 return false; 6147 6148 // Unbridged casts in ARC can be handled in some call positions and 6149 // should be left in place. 6150 case BuiltinType::ARCUnbridgedCast: 6151 return false; 6152 6153 // Pseudo-objects should be converted as soon as possible. 6154 case BuiltinType::PseudoObject: 6155 return true; 6156 6157 // The debugger mode could theoretically but currently does not try 6158 // to resolve unknown-typed arguments based on known parameter types. 6159 case BuiltinType::UnknownAny: 6160 return true; 6161 6162 // These are always invalid as call arguments and should be reported. 6163 case BuiltinType::BoundMember: 6164 case BuiltinType::BuiltinFn: 6165 case BuiltinType::IncompleteMatrixIdx: 6166 case BuiltinType::OMPArraySection: 6167 case BuiltinType::OMPArrayShaping: 6168 case BuiltinType::OMPIterator: 6169 return true; 6170 6171 } 6172 llvm_unreachable("bad builtin type kind"); 6173 } 6174 6175 /// Check an argument list for placeholders that we won't try to 6176 /// handle later. 6177 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6178 // Apply this processing to all the arguments at once instead of 6179 // dying at the first failure. 6180 bool hasInvalid = false; 6181 for (size_t i = 0, e = args.size(); i != e; i++) { 6182 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6183 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6184 if (result.isInvalid()) hasInvalid = true; 6185 else args[i] = result.get(); 6186 } 6187 } 6188 return hasInvalid; 6189 } 6190 6191 /// If a builtin function has a pointer argument with no explicit address 6192 /// space, then it should be able to accept a pointer to any address 6193 /// space as input. In order to do this, we need to replace the 6194 /// standard builtin declaration with one that uses the same address space 6195 /// as the call. 6196 /// 6197 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6198 /// it does not contain any pointer arguments without 6199 /// an address space qualifer. Otherwise the rewritten 6200 /// FunctionDecl is returned. 6201 /// TODO: Handle pointer return types. 6202 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6203 FunctionDecl *FDecl, 6204 MultiExprArg ArgExprs) { 6205 6206 QualType DeclType = FDecl->getType(); 6207 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6208 6209 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6210 ArgExprs.size() < FT->getNumParams()) 6211 return nullptr; 6212 6213 bool NeedsNewDecl = false; 6214 unsigned i = 0; 6215 SmallVector<QualType, 8> OverloadParams; 6216 6217 for (QualType ParamType : FT->param_types()) { 6218 6219 // Convert array arguments to pointer to simplify type lookup. 6220 ExprResult ArgRes = 6221 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6222 if (ArgRes.isInvalid()) 6223 return nullptr; 6224 Expr *Arg = ArgRes.get(); 6225 QualType ArgType = Arg->getType(); 6226 if (!ParamType->isPointerType() || 6227 ParamType.hasAddressSpace() || 6228 !ArgType->isPointerType() || 6229 !ArgType->getPointeeType().hasAddressSpace()) { 6230 OverloadParams.push_back(ParamType); 6231 continue; 6232 } 6233 6234 QualType PointeeType = ParamType->getPointeeType(); 6235 if (PointeeType.hasAddressSpace()) 6236 continue; 6237 6238 NeedsNewDecl = true; 6239 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6240 6241 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6242 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6243 } 6244 6245 if (!NeedsNewDecl) 6246 return nullptr; 6247 6248 FunctionProtoType::ExtProtoInfo EPI; 6249 EPI.Variadic = FT->isVariadic(); 6250 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6251 OverloadParams, EPI); 6252 DeclContext *Parent = FDecl->getParent(); 6253 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6254 FDecl->getLocation(), 6255 FDecl->getLocation(), 6256 FDecl->getIdentifier(), 6257 OverloadTy, 6258 /*TInfo=*/nullptr, 6259 SC_Extern, false, 6260 /*hasPrototype=*/true); 6261 SmallVector<ParmVarDecl*, 16> Params; 6262 FT = cast<FunctionProtoType>(OverloadTy); 6263 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6264 QualType ParamType = FT->getParamType(i); 6265 ParmVarDecl *Parm = 6266 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6267 SourceLocation(), nullptr, ParamType, 6268 /*TInfo=*/nullptr, SC_None, nullptr); 6269 Parm->setScopeInfo(0, i); 6270 Params.push_back(Parm); 6271 } 6272 OverloadDecl->setParams(Params); 6273 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6274 return OverloadDecl; 6275 } 6276 6277 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6278 FunctionDecl *Callee, 6279 MultiExprArg ArgExprs) { 6280 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6281 // similar attributes) really don't like it when functions are called with an 6282 // invalid number of args. 6283 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6284 /*PartialOverloading=*/false) && 6285 !Callee->isVariadic()) 6286 return; 6287 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6288 return; 6289 6290 if (const EnableIfAttr *Attr = 6291 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6292 S.Diag(Fn->getBeginLoc(), 6293 isa<CXXMethodDecl>(Callee) 6294 ? diag::err_ovl_no_viable_member_function_in_call 6295 : diag::err_ovl_no_viable_function_in_call) 6296 << Callee << Callee->getSourceRange(); 6297 S.Diag(Callee->getLocation(), 6298 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6299 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6300 return; 6301 } 6302 } 6303 6304 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6305 const UnresolvedMemberExpr *const UME, Sema &S) { 6306 6307 const auto GetFunctionLevelDCIfCXXClass = 6308 [](Sema &S) -> const CXXRecordDecl * { 6309 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6310 if (!DC || !DC->getParent()) 6311 return nullptr; 6312 6313 // If the call to some member function was made from within a member 6314 // function body 'M' return return 'M's parent. 6315 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6316 return MD->getParent()->getCanonicalDecl(); 6317 // else the call was made from within a default member initializer of a 6318 // class, so return the class. 6319 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6320 return RD->getCanonicalDecl(); 6321 return nullptr; 6322 }; 6323 // If our DeclContext is neither a member function nor a class (in the 6324 // case of a lambda in a default member initializer), we can't have an 6325 // enclosing 'this'. 6326 6327 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6328 if (!CurParentClass) 6329 return false; 6330 6331 // The naming class for implicit member functions call is the class in which 6332 // name lookup starts. 6333 const CXXRecordDecl *const NamingClass = 6334 UME->getNamingClass()->getCanonicalDecl(); 6335 assert(NamingClass && "Must have naming class even for implicit access"); 6336 6337 // If the unresolved member functions were found in a 'naming class' that is 6338 // related (either the same or derived from) to the class that contains the 6339 // member function that itself contained the implicit member access. 6340 6341 return CurParentClass == NamingClass || 6342 CurParentClass->isDerivedFrom(NamingClass); 6343 } 6344 6345 static void 6346 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6347 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6348 6349 if (!UME) 6350 return; 6351 6352 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6353 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6354 // already been captured, or if this is an implicit member function call (if 6355 // it isn't, an attempt to capture 'this' should already have been made). 6356 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6357 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6358 return; 6359 6360 // Check if the naming class in which the unresolved members were found is 6361 // related (same as or is a base of) to the enclosing class. 6362 6363 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6364 return; 6365 6366 6367 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6368 // If the enclosing function is not dependent, then this lambda is 6369 // capture ready, so if we can capture this, do so. 6370 if (!EnclosingFunctionCtx->isDependentContext()) { 6371 // If the current lambda and all enclosing lambdas can capture 'this' - 6372 // then go ahead and capture 'this' (since our unresolved overload set 6373 // contains at least one non-static member function). 6374 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6375 S.CheckCXXThisCapture(CallLoc); 6376 } else if (S.CurContext->isDependentContext()) { 6377 // ... since this is an implicit member reference, that might potentially 6378 // involve a 'this' capture, mark 'this' for potential capture in 6379 // enclosing lambdas. 6380 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6381 CurLSI->addPotentialThisCapture(CallLoc); 6382 } 6383 } 6384 6385 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6386 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6387 Expr *ExecConfig) { 6388 ExprResult Call = 6389 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6390 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6391 if (Call.isInvalid()) 6392 return Call; 6393 6394 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6395 // language modes. 6396 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6397 if (ULE->hasExplicitTemplateArgs() && 6398 ULE->decls_begin() == ULE->decls_end()) { 6399 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6400 ? diag::warn_cxx17_compat_adl_only_template_id 6401 : diag::ext_adl_only_template_id) 6402 << ULE->getName(); 6403 } 6404 } 6405 6406 if (LangOpts.OpenMP) 6407 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6408 ExecConfig); 6409 6410 return Call; 6411 } 6412 6413 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6414 /// This provides the location of the left/right parens and a list of comma 6415 /// locations. 6416 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6417 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6418 Expr *ExecConfig, bool IsExecConfig, 6419 bool AllowRecovery) { 6420 // Since this might be a postfix expression, get rid of ParenListExprs. 6421 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6422 if (Result.isInvalid()) return ExprError(); 6423 Fn = Result.get(); 6424 6425 if (checkArgsForPlaceholders(*this, ArgExprs)) 6426 return ExprError(); 6427 6428 if (getLangOpts().CPlusPlus) { 6429 // If this is a pseudo-destructor expression, build the call immediately. 6430 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6431 if (!ArgExprs.empty()) { 6432 // Pseudo-destructor calls should not have any arguments. 6433 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6434 << FixItHint::CreateRemoval( 6435 SourceRange(ArgExprs.front()->getBeginLoc(), 6436 ArgExprs.back()->getEndLoc())); 6437 } 6438 6439 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6440 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6441 } 6442 if (Fn->getType() == Context.PseudoObjectTy) { 6443 ExprResult result = CheckPlaceholderExpr(Fn); 6444 if (result.isInvalid()) return ExprError(); 6445 Fn = result.get(); 6446 } 6447 6448 // Determine whether this is a dependent call inside a C++ template, 6449 // in which case we won't do any semantic analysis now. 6450 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6451 if (ExecConfig) { 6452 return CUDAKernelCallExpr::Create(Context, Fn, 6453 cast<CallExpr>(ExecConfig), ArgExprs, 6454 Context.DependentTy, VK_PRValue, 6455 RParenLoc, CurFPFeatureOverrides()); 6456 } else { 6457 6458 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6459 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6460 Fn->getBeginLoc()); 6461 6462 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6463 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6464 } 6465 } 6466 6467 // Determine whether this is a call to an object (C++ [over.call.object]). 6468 if (Fn->getType()->isRecordType()) 6469 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6470 RParenLoc); 6471 6472 if (Fn->getType() == Context.UnknownAnyTy) { 6473 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6474 if (result.isInvalid()) return ExprError(); 6475 Fn = result.get(); 6476 } 6477 6478 if (Fn->getType() == Context.BoundMemberTy) { 6479 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6480 RParenLoc, AllowRecovery); 6481 } 6482 } 6483 6484 // Check for overloaded calls. This can happen even in C due to extensions. 6485 if (Fn->getType() == Context.OverloadTy) { 6486 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6487 6488 // We aren't supposed to apply this logic if there's an '&' involved. 6489 if (!find.HasFormOfMemberPointer) { 6490 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6491 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6492 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6493 OverloadExpr *ovl = find.Expression; 6494 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6495 return BuildOverloadedCallExpr( 6496 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6497 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6498 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6499 RParenLoc, AllowRecovery); 6500 } 6501 } 6502 6503 // If we're directly calling a function, get the appropriate declaration. 6504 if (Fn->getType() == Context.UnknownAnyTy) { 6505 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6506 if (result.isInvalid()) return ExprError(); 6507 Fn = result.get(); 6508 } 6509 6510 Expr *NakedFn = Fn->IgnoreParens(); 6511 6512 bool CallingNDeclIndirectly = false; 6513 NamedDecl *NDecl = nullptr; 6514 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6515 if (UnOp->getOpcode() == UO_AddrOf) { 6516 CallingNDeclIndirectly = true; 6517 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6518 } 6519 } 6520 6521 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6522 NDecl = DRE->getDecl(); 6523 6524 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6525 if (FDecl && FDecl->getBuiltinID()) { 6526 // Rewrite the function decl for this builtin by replacing parameters 6527 // with no explicit address space with the address space of the arguments 6528 // in ArgExprs. 6529 if ((FDecl = 6530 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6531 NDecl = FDecl; 6532 Fn = DeclRefExpr::Create( 6533 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6534 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6535 nullptr, DRE->isNonOdrUse()); 6536 } 6537 } 6538 } else if (isa<MemberExpr>(NakedFn)) 6539 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6540 6541 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6542 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6543 FD, /*Complain=*/true, Fn->getBeginLoc())) 6544 return ExprError(); 6545 6546 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6547 } 6548 6549 if (Context.isDependenceAllowed() && 6550 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6551 assert(!getLangOpts().CPlusPlus); 6552 assert((Fn->containsErrors() || 6553 llvm::any_of(ArgExprs, 6554 [](clang::Expr *E) { return E->containsErrors(); })) && 6555 "should only occur in error-recovery path."); 6556 QualType ReturnType = 6557 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6558 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6559 : Context.DependentTy; 6560 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6561 Expr::getValueKindForType(ReturnType), RParenLoc, 6562 CurFPFeatureOverrides()); 6563 } 6564 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6565 ExecConfig, IsExecConfig); 6566 } 6567 6568 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6569 // with the specified CallArgs 6570 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6571 MultiExprArg CallArgs) { 6572 StringRef Name = Context.BuiltinInfo.getName(Id); 6573 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6574 Sema::LookupOrdinaryName); 6575 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6576 6577 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6578 assert(BuiltInDecl && "failed to find builtin declaration"); 6579 6580 ExprResult DeclRef = 6581 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6582 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6583 6584 ExprResult Call = 6585 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6586 6587 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6588 return Call.get(); 6589 } 6590 6591 /// Parse a __builtin_astype expression. 6592 /// 6593 /// __builtin_astype( value, dst type ) 6594 /// 6595 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6596 SourceLocation BuiltinLoc, 6597 SourceLocation RParenLoc) { 6598 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6599 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6600 } 6601 6602 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6603 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6604 SourceLocation BuiltinLoc, 6605 SourceLocation RParenLoc) { 6606 ExprValueKind VK = VK_PRValue; 6607 ExprObjectKind OK = OK_Ordinary; 6608 QualType SrcTy = E->getType(); 6609 if (!SrcTy->isDependentType() && 6610 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6611 return ExprError( 6612 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6613 << DestTy << SrcTy << E->getSourceRange()); 6614 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6615 } 6616 6617 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6618 /// provided arguments. 6619 /// 6620 /// __builtin_convertvector( value, dst type ) 6621 /// 6622 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6623 SourceLocation BuiltinLoc, 6624 SourceLocation RParenLoc) { 6625 TypeSourceInfo *TInfo; 6626 GetTypeFromParser(ParsedDestTy, &TInfo); 6627 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6628 } 6629 6630 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6631 /// i.e. an expression not of \p OverloadTy. The expression should 6632 /// unary-convert to an expression of function-pointer or 6633 /// block-pointer type. 6634 /// 6635 /// \param NDecl the declaration being called, if available 6636 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6637 SourceLocation LParenLoc, 6638 ArrayRef<Expr *> Args, 6639 SourceLocation RParenLoc, Expr *Config, 6640 bool IsExecConfig, ADLCallKind UsesADL) { 6641 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6642 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6643 6644 // Functions with 'interrupt' attribute cannot be called directly. 6645 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6646 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6647 return ExprError(); 6648 } 6649 6650 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6651 // so there's some risk when calling out to non-interrupt handler functions 6652 // that the callee might not preserve them. This is easy to diagnose here, 6653 // but can be very challenging to debug. 6654 // Likewise, X86 interrupt handlers may only call routines with attribute 6655 // no_caller_saved_registers since there is no efficient way to 6656 // save and restore the non-GPR state. 6657 if (auto *Caller = getCurFunctionDecl()) { 6658 if (Caller->hasAttr<ARMInterruptAttr>()) { 6659 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6660 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6661 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6662 if (FDecl) 6663 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6664 } 6665 } 6666 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6667 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6668 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6669 if (FDecl) 6670 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6671 } 6672 } 6673 6674 // Promote the function operand. 6675 // We special-case function promotion here because we only allow promoting 6676 // builtin functions to function pointers in the callee of a call. 6677 ExprResult Result; 6678 QualType ResultTy; 6679 if (BuiltinID && 6680 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6681 // Extract the return type from the (builtin) function pointer type. 6682 // FIXME Several builtins still have setType in 6683 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6684 // Builtins.def to ensure they are correct before removing setType calls. 6685 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6686 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6687 ResultTy = FDecl->getCallResultType(); 6688 } else { 6689 Result = CallExprUnaryConversions(Fn); 6690 ResultTy = Context.BoolTy; 6691 } 6692 if (Result.isInvalid()) 6693 return ExprError(); 6694 Fn = Result.get(); 6695 6696 // Check for a valid function type, but only if it is not a builtin which 6697 // requires custom type checking. These will be handled by 6698 // CheckBuiltinFunctionCall below just after creation of the call expression. 6699 const FunctionType *FuncT = nullptr; 6700 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6701 retry: 6702 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6703 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6704 // have type pointer to function". 6705 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6706 if (!FuncT) 6707 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6708 << Fn->getType() << Fn->getSourceRange()); 6709 } else if (const BlockPointerType *BPT = 6710 Fn->getType()->getAs<BlockPointerType>()) { 6711 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6712 } else { 6713 // Handle calls to expressions of unknown-any type. 6714 if (Fn->getType() == Context.UnknownAnyTy) { 6715 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6716 if (rewrite.isInvalid()) 6717 return ExprError(); 6718 Fn = rewrite.get(); 6719 goto retry; 6720 } 6721 6722 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6723 << Fn->getType() << Fn->getSourceRange()); 6724 } 6725 } 6726 6727 // Get the number of parameters in the function prototype, if any. 6728 // We will allocate space for max(Args.size(), NumParams) arguments 6729 // in the call expression. 6730 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6731 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6732 6733 CallExpr *TheCall; 6734 if (Config) { 6735 assert(UsesADL == ADLCallKind::NotADL && 6736 "CUDAKernelCallExpr should not use ADL"); 6737 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6738 Args, ResultTy, VK_PRValue, RParenLoc, 6739 CurFPFeatureOverrides(), NumParams); 6740 } else { 6741 TheCall = 6742 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6743 CurFPFeatureOverrides(), NumParams, UsesADL); 6744 } 6745 6746 if (!Context.isDependenceAllowed()) { 6747 // Forget about the nulled arguments since typo correction 6748 // do not handle them well. 6749 TheCall->shrinkNumArgs(Args.size()); 6750 // C cannot always handle TypoExpr nodes in builtin calls and direct 6751 // function calls as their argument checking don't necessarily handle 6752 // dependent types properly, so make sure any TypoExprs have been 6753 // dealt with. 6754 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6755 if (!Result.isUsable()) return ExprError(); 6756 CallExpr *TheOldCall = TheCall; 6757 TheCall = dyn_cast<CallExpr>(Result.get()); 6758 bool CorrectedTypos = TheCall != TheOldCall; 6759 if (!TheCall) return Result; 6760 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6761 6762 // A new call expression node was created if some typos were corrected. 6763 // However it may not have been constructed with enough storage. In this 6764 // case, rebuild the node with enough storage. The waste of space is 6765 // immaterial since this only happens when some typos were corrected. 6766 if (CorrectedTypos && Args.size() < NumParams) { 6767 if (Config) 6768 TheCall = CUDAKernelCallExpr::Create( 6769 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6770 RParenLoc, CurFPFeatureOverrides(), NumParams); 6771 else 6772 TheCall = 6773 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6774 CurFPFeatureOverrides(), NumParams, UsesADL); 6775 } 6776 // We can now handle the nulled arguments for the default arguments. 6777 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6778 } 6779 6780 // Bail out early if calling a builtin with custom type checking. 6781 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6782 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6783 6784 if (getLangOpts().CUDA) { 6785 if (Config) { 6786 // CUDA: Kernel calls must be to global functions 6787 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6788 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6789 << FDecl << Fn->getSourceRange()); 6790 6791 // CUDA: Kernel function must have 'void' return type 6792 if (!FuncT->getReturnType()->isVoidType() && 6793 !FuncT->getReturnType()->getAs<AutoType>() && 6794 !FuncT->getReturnType()->isInstantiationDependentType()) 6795 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6796 << Fn->getType() << Fn->getSourceRange()); 6797 } else { 6798 // CUDA: Calls to global functions must be configured 6799 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6800 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6801 << FDecl << Fn->getSourceRange()); 6802 } 6803 } 6804 6805 // Check for a valid return type 6806 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6807 FDecl)) 6808 return ExprError(); 6809 6810 // We know the result type of the call, set it. 6811 TheCall->setType(FuncT->getCallResultType(Context)); 6812 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6813 6814 if (Proto) { 6815 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6816 IsExecConfig)) 6817 return ExprError(); 6818 } else { 6819 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6820 6821 if (FDecl) { 6822 // Check if we have too few/too many template arguments, based 6823 // on our knowledge of the function definition. 6824 const FunctionDecl *Def = nullptr; 6825 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6826 Proto = Def->getType()->getAs<FunctionProtoType>(); 6827 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6828 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6829 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6830 } 6831 6832 // If the function we're calling isn't a function prototype, but we have 6833 // a function prototype from a prior declaratiom, use that prototype. 6834 if (!FDecl->hasPrototype()) 6835 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6836 } 6837 6838 // Promote the arguments (C99 6.5.2.2p6). 6839 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6840 Expr *Arg = Args[i]; 6841 6842 if (Proto && i < Proto->getNumParams()) { 6843 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6844 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6845 ExprResult ArgE = 6846 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6847 if (ArgE.isInvalid()) 6848 return true; 6849 6850 Arg = ArgE.getAs<Expr>(); 6851 6852 } else { 6853 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6854 6855 if (ArgE.isInvalid()) 6856 return true; 6857 6858 Arg = ArgE.getAs<Expr>(); 6859 } 6860 6861 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6862 diag::err_call_incomplete_argument, Arg)) 6863 return ExprError(); 6864 6865 TheCall->setArg(i, Arg); 6866 } 6867 TheCall->computeDependence(); 6868 } 6869 6870 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6871 if (!Method->isStatic()) 6872 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6873 << Fn->getSourceRange()); 6874 6875 // Check for sentinels 6876 if (NDecl) 6877 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6878 6879 // Warn for unions passing across security boundary (CMSE). 6880 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6881 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6882 if (const auto *RT = 6883 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6884 if (RT->getDecl()->isOrContainsUnion()) 6885 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6886 << 0 << i; 6887 } 6888 } 6889 } 6890 6891 // Do special checking on direct calls to functions. 6892 if (FDecl) { 6893 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6894 return ExprError(); 6895 6896 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6897 6898 if (BuiltinID) 6899 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6900 } else if (NDecl) { 6901 if (CheckPointerCall(NDecl, TheCall, Proto)) 6902 return ExprError(); 6903 } else { 6904 if (CheckOtherCall(TheCall, Proto)) 6905 return ExprError(); 6906 } 6907 6908 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6909 } 6910 6911 ExprResult 6912 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6913 SourceLocation RParenLoc, Expr *InitExpr) { 6914 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6915 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6916 6917 TypeSourceInfo *TInfo; 6918 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6919 if (!TInfo) 6920 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6921 6922 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6923 } 6924 6925 ExprResult 6926 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6927 SourceLocation RParenLoc, Expr *LiteralExpr) { 6928 QualType literalType = TInfo->getType(); 6929 6930 if (literalType->isArrayType()) { 6931 if (RequireCompleteSizedType( 6932 LParenLoc, Context.getBaseElementType(literalType), 6933 diag::err_array_incomplete_or_sizeless_type, 6934 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6935 return ExprError(); 6936 if (literalType->isVariableArrayType()) { 6937 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6938 diag::err_variable_object_no_init)) { 6939 return ExprError(); 6940 } 6941 } 6942 } else if (!literalType->isDependentType() && 6943 RequireCompleteType(LParenLoc, literalType, 6944 diag::err_typecheck_decl_incomplete_type, 6945 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6946 return ExprError(); 6947 6948 InitializedEntity Entity 6949 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6950 InitializationKind Kind 6951 = InitializationKind::CreateCStyleCast(LParenLoc, 6952 SourceRange(LParenLoc, RParenLoc), 6953 /*InitList=*/true); 6954 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6955 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6956 &literalType); 6957 if (Result.isInvalid()) 6958 return ExprError(); 6959 LiteralExpr = Result.get(); 6960 6961 bool isFileScope = !CurContext->isFunctionOrMethod(); 6962 6963 // In C, compound literals are l-values for some reason. 6964 // For GCC compatibility, in C++, file-scope array compound literals with 6965 // constant initializers are also l-values, and compound literals are 6966 // otherwise prvalues. 6967 // 6968 // (GCC also treats C++ list-initialized file-scope array prvalues with 6969 // constant initializers as l-values, but that's non-conforming, so we don't 6970 // follow it there.) 6971 // 6972 // FIXME: It would be better to handle the lvalue cases as materializing and 6973 // lifetime-extending a temporary object, but our materialized temporaries 6974 // representation only supports lifetime extension from a variable, not "out 6975 // of thin air". 6976 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6977 // is bound to the result of applying array-to-pointer decay to the compound 6978 // literal. 6979 // FIXME: GCC supports compound literals of reference type, which should 6980 // obviously have a value kind derived from the kind of reference involved. 6981 ExprValueKind VK = 6982 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6983 ? VK_PRValue 6984 : VK_LValue; 6985 6986 if (isFileScope) 6987 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6988 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6989 Expr *Init = ILE->getInit(i); 6990 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6991 } 6992 6993 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6994 VK, LiteralExpr, isFileScope); 6995 if (isFileScope) { 6996 if (!LiteralExpr->isTypeDependent() && 6997 !LiteralExpr->isValueDependent() && 6998 !literalType->isDependentType()) // C99 6.5.2.5p3 6999 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7000 return ExprError(); 7001 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7002 literalType.getAddressSpace() != LangAS::Default) { 7003 // Embedded-C extensions to C99 6.5.2.5: 7004 // "If the compound literal occurs inside the body of a function, the 7005 // type name shall not be qualified by an address-space qualifier." 7006 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7007 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7008 return ExprError(); 7009 } 7010 7011 if (!isFileScope && !getLangOpts().CPlusPlus) { 7012 // Compound literals that have automatic storage duration are destroyed at 7013 // the end of the scope in C; in C++, they're just temporaries. 7014 7015 // Emit diagnostics if it is or contains a C union type that is non-trivial 7016 // to destruct. 7017 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7018 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7019 NTCUC_CompoundLiteral, NTCUK_Destruct); 7020 7021 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7022 if (literalType.isDestructedType()) { 7023 Cleanup.setExprNeedsCleanups(true); 7024 ExprCleanupObjects.push_back(E); 7025 getCurFunction()->setHasBranchProtectedScope(); 7026 } 7027 } 7028 7029 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7030 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7031 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7032 E->getInitializer()->getExprLoc()); 7033 7034 return MaybeBindToTemporary(E); 7035 } 7036 7037 ExprResult 7038 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7039 SourceLocation RBraceLoc) { 7040 // Only produce each kind of designated initialization diagnostic once. 7041 SourceLocation FirstDesignator; 7042 bool DiagnosedArrayDesignator = false; 7043 bool DiagnosedNestedDesignator = false; 7044 bool DiagnosedMixedDesignator = false; 7045 7046 // Check that any designated initializers are syntactically valid in the 7047 // current language mode. 7048 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7049 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7050 if (FirstDesignator.isInvalid()) 7051 FirstDesignator = DIE->getBeginLoc(); 7052 7053 if (!getLangOpts().CPlusPlus) 7054 break; 7055 7056 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7057 DiagnosedNestedDesignator = true; 7058 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7059 << DIE->getDesignatorsSourceRange(); 7060 } 7061 7062 for (auto &Desig : DIE->designators()) { 7063 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7064 DiagnosedArrayDesignator = true; 7065 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7066 << Desig.getSourceRange(); 7067 } 7068 } 7069 7070 if (!DiagnosedMixedDesignator && 7071 !isa<DesignatedInitExpr>(InitArgList[0])) { 7072 DiagnosedMixedDesignator = true; 7073 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7074 << DIE->getSourceRange(); 7075 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7076 << InitArgList[0]->getSourceRange(); 7077 } 7078 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7079 isa<DesignatedInitExpr>(InitArgList[0])) { 7080 DiagnosedMixedDesignator = true; 7081 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7082 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7083 << DIE->getSourceRange(); 7084 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7085 << InitArgList[I]->getSourceRange(); 7086 } 7087 } 7088 7089 if (FirstDesignator.isValid()) { 7090 // Only diagnose designated initiaization as a C++20 extension if we didn't 7091 // already diagnose use of (non-C++20) C99 designator syntax. 7092 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7093 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7094 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7095 ? diag::warn_cxx17_compat_designated_init 7096 : diag::ext_cxx_designated_init); 7097 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7098 Diag(FirstDesignator, diag::ext_designated_init); 7099 } 7100 } 7101 7102 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7103 } 7104 7105 ExprResult 7106 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7107 SourceLocation RBraceLoc) { 7108 // Semantic analysis for initializers is done by ActOnDeclarator() and 7109 // CheckInitializer() - it requires knowledge of the object being initialized. 7110 7111 // Immediately handle non-overload placeholders. Overloads can be 7112 // resolved contextually, but everything else here can't. 7113 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7114 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7115 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7116 7117 // Ignore failures; dropping the entire initializer list because 7118 // of one failure would be terrible for indexing/etc. 7119 if (result.isInvalid()) continue; 7120 7121 InitArgList[I] = result.get(); 7122 } 7123 } 7124 7125 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7126 RBraceLoc); 7127 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7128 return E; 7129 } 7130 7131 /// Do an explicit extend of the given block pointer if we're in ARC. 7132 void Sema::maybeExtendBlockObject(ExprResult &E) { 7133 assert(E.get()->getType()->isBlockPointerType()); 7134 assert(E.get()->isPRValue()); 7135 7136 // Only do this in an r-value context. 7137 if (!getLangOpts().ObjCAutoRefCount) return; 7138 7139 E = ImplicitCastExpr::Create( 7140 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7141 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7142 Cleanup.setExprNeedsCleanups(true); 7143 } 7144 7145 /// Prepare a conversion of the given expression to an ObjC object 7146 /// pointer type. 7147 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7148 QualType type = E.get()->getType(); 7149 if (type->isObjCObjectPointerType()) { 7150 return CK_BitCast; 7151 } else if (type->isBlockPointerType()) { 7152 maybeExtendBlockObject(E); 7153 return CK_BlockPointerToObjCPointerCast; 7154 } else { 7155 assert(type->isPointerType()); 7156 return CK_CPointerToObjCPointerCast; 7157 } 7158 } 7159 7160 /// Prepares for a scalar cast, performing all the necessary stages 7161 /// except the final cast and returning the kind required. 7162 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7163 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7164 // Also, callers should have filtered out the invalid cases with 7165 // pointers. Everything else should be possible. 7166 7167 QualType SrcTy = Src.get()->getType(); 7168 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7169 return CK_NoOp; 7170 7171 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7172 case Type::STK_MemberPointer: 7173 llvm_unreachable("member pointer type in C"); 7174 7175 case Type::STK_CPointer: 7176 case Type::STK_BlockPointer: 7177 case Type::STK_ObjCObjectPointer: 7178 switch (DestTy->getScalarTypeKind()) { 7179 case Type::STK_CPointer: { 7180 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7181 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7182 if (SrcAS != DestAS) 7183 return CK_AddressSpaceConversion; 7184 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7185 return CK_NoOp; 7186 return CK_BitCast; 7187 } 7188 case Type::STK_BlockPointer: 7189 return (SrcKind == Type::STK_BlockPointer 7190 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7191 case Type::STK_ObjCObjectPointer: 7192 if (SrcKind == Type::STK_ObjCObjectPointer) 7193 return CK_BitCast; 7194 if (SrcKind == Type::STK_CPointer) 7195 return CK_CPointerToObjCPointerCast; 7196 maybeExtendBlockObject(Src); 7197 return CK_BlockPointerToObjCPointerCast; 7198 case Type::STK_Bool: 7199 return CK_PointerToBoolean; 7200 case Type::STK_Integral: 7201 return CK_PointerToIntegral; 7202 case Type::STK_Floating: 7203 case Type::STK_FloatingComplex: 7204 case Type::STK_IntegralComplex: 7205 case Type::STK_MemberPointer: 7206 case Type::STK_FixedPoint: 7207 llvm_unreachable("illegal cast from pointer"); 7208 } 7209 llvm_unreachable("Should have returned before this"); 7210 7211 case Type::STK_FixedPoint: 7212 switch (DestTy->getScalarTypeKind()) { 7213 case Type::STK_FixedPoint: 7214 return CK_FixedPointCast; 7215 case Type::STK_Bool: 7216 return CK_FixedPointToBoolean; 7217 case Type::STK_Integral: 7218 return CK_FixedPointToIntegral; 7219 case Type::STK_Floating: 7220 return CK_FixedPointToFloating; 7221 case Type::STK_IntegralComplex: 7222 case Type::STK_FloatingComplex: 7223 Diag(Src.get()->getExprLoc(), 7224 diag::err_unimplemented_conversion_with_fixed_point_type) 7225 << DestTy; 7226 return CK_IntegralCast; 7227 case Type::STK_CPointer: 7228 case Type::STK_ObjCObjectPointer: 7229 case Type::STK_BlockPointer: 7230 case Type::STK_MemberPointer: 7231 llvm_unreachable("illegal cast to pointer type"); 7232 } 7233 llvm_unreachable("Should have returned before this"); 7234 7235 case Type::STK_Bool: // casting from bool is like casting from an integer 7236 case Type::STK_Integral: 7237 switch (DestTy->getScalarTypeKind()) { 7238 case Type::STK_CPointer: 7239 case Type::STK_ObjCObjectPointer: 7240 case Type::STK_BlockPointer: 7241 if (Src.get()->isNullPointerConstant(Context, 7242 Expr::NPC_ValueDependentIsNull)) 7243 return CK_NullToPointer; 7244 return CK_IntegralToPointer; 7245 case Type::STK_Bool: 7246 return CK_IntegralToBoolean; 7247 case Type::STK_Integral: 7248 return CK_IntegralCast; 7249 case Type::STK_Floating: 7250 return CK_IntegralToFloating; 7251 case Type::STK_IntegralComplex: 7252 Src = ImpCastExprToType(Src.get(), 7253 DestTy->castAs<ComplexType>()->getElementType(), 7254 CK_IntegralCast); 7255 return CK_IntegralRealToComplex; 7256 case Type::STK_FloatingComplex: 7257 Src = ImpCastExprToType(Src.get(), 7258 DestTy->castAs<ComplexType>()->getElementType(), 7259 CK_IntegralToFloating); 7260 return CK_FloatingRealToComplex; 7261 case Type::STK_MemberPointer: 7262 llvm_unreachable("member pointer type in C"); 7263 case Type::STK_FixedPoint: 7264 return CK_IntegralToFixedPoint; 7265 } 7266 llvm_unreachable("Should have returned before this"); 7267 7268 case Type::STK_Floating: 7269 switch (DestTy->getScalarTypeKind()) { 7270 case Type::STK_Floating: 7271 return CK_FloatingCast; 7272 case Type::STK_Bool: 7273 return CK_FloatingToBoolean; 7274 case Type::STK_Integral: 7275 return CK_FloatingToIntegral; 7276 case Type::STK_FloatingComplex: 7277 Src = ImpCastExprToType(Src.get(), 7278 DestTy->castAs<ComplexType>()->getElementType(), 7279 CK_FloatingCast); 7280 return CK_FloatingRealToComplex; 7281 case Type::STK_IntegralComplex: 7282 Src = ImpCastExprToType(Src.get(), 7283 DestTy->castAs<ComplexType>()->getElementType(), 7284 CK_FloatingToIntegral); 7285 return CK_IntegralRealToComplex; 7286 case Type::STK_CPointer: 7287 case Type::STK_ObjCObjectPointer: 7288 case Type::STK_BlockPointer: 7289 llvm_unreachable("valid float->pointer cast?"); 7290 case Type::STK_MemberPointer: 7291 llvm_unreachable("member pointer type in C"); 7292 case Type::STK_FixedPoint: 7293 return CK_FloatingToFixedPoint; 7294 } 7295 llvm_unreachable("Should have returned before this"); 7296 7297 case Type::STK_FloatingComplex: 7298 switch (DestTy->getScalarTypeKind()) { 7299 case Type::STK_FloatingComplex: 7300 return CK_FloatingComplexCast; 7301 case Type::STK_IntegralComplex: 7302 return CK_FloatingComplexToIntegralComplex; 7303 case Type::STK_Floating: { 7304 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7305 if (Context.hasSameType(ET, DestTy)) 7306 return CK_FloatingComplexToReal; 7307 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7308 return CK_FloatingCast; 7309 } 7310 case Type::STK_Bool: 7311 return CK_FloatingComplexToBoolean; 7312 case Type::STK_Integral: 7313 Src = ImpCastExprToType(Src.get(), 7314 SrcTy->castAs<ComplexType>()->getElementType(), 7315 CK_FloatingComplexToReal); 7316 return CK_FloatingToIntegral; 7317 case Type::STK_CPointer: 7318 case Type::STK_ObjCObjectPointer: 7319 case Type::STK_BlockPointer: 7320 llvm_unreachable("valid complex float->pointer cast?"); 7321 case Type::STK_MemberPointer: 7322 llvm_unreachable("member pointer type in C"); 7323 case Type::STK_FixedPoint: 7324 Diag(Src.get()->getExprLoc(), 7325 diag::err_unimplemented_conversion_with_fixed_point_type) 7326 << SrcTy; 7327 return CK_IntegralCast; 7328 } 7329 llvm_unreachable("Should have returned before this"); 7330 7331 case Type::STK_IntegralComplex: 7332 switch (DestTy->getScalarTypeKind()) { 7333 case Type::STK_FloatingComplex: 7334 return CK_IntegralComplexToFloatingComplex; 7335 case Type::STK_IntegralComplex: 7336 return CK_IntegralComplexCast; 7337 case Type::STK_Integral: { 7338 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7339 if (Context.hasSameType(ET, DestTy)) 7340 return CK_IntegralComplexToReal; 7341 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7342 return CK_IntegralCast; 7343 } 7344 case Type::STK_Bool: 7345 return CK_IntegralComplexToBoolean; 7346 case Type::STK_Floating: 7347 Src = ImpCastExprToType(Src.get(), 7348 SrcTy->castAs<ComplexType>()->getElementType(), 7349 CK_IntegralComplexToReal); 7350 return CK_IntegralToFloating; 7351 case Type::STK_CPointer: 7352 case Type::STK_ObjCObjectPointer: 7353 case Type::STK_BlockPointer: 7354 llvm_unreachable("valid complex int->pointer cast?"); 7355 case Type::STK_MemberPointer: 7356 llvm_unreachable("member pointer type in C"); 7357 case Type::STK_FixedPoint: 7358 Diag(Src.get()->getExprLoc(), 7359 diag::err_unimplemented_conversion_with_fixed_point_type) 7360 << SrcTy; 7361 return CK_IntegralCast; 7362 } 7363 llvm_unreachable("Should have returned before this"); 7364 } 7365 7366 llvm_unreachable("Unhandled scalar cast"); 7367 } 7368 7369 static bool breakDownVectorType(QualType type, uint64_t &len, 7370 QualType &eltType) { 7371 // Vectors are simple. 7372 if (const VectorType *vecType = type->getAs<VectorType>()) { 7373 len = vecType->getNumElements(); 7374 eltType = vecType->getElementType(); 7375 assert(eltType->isScalarType()); 7376 return true; 7377 } 7378 7379 // We allow lax conversion to and from non-vector types, but only if 7380 // they're real types (i.e. non-complex, non-pointer scalar types). 7381 if (!type->isRealType()) return false; 7382 7383 len = 1; 7384 eltType = type; 7385 return true; 7386 } 7387 7388 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7389 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7390 /// allowed? 7391 /// 7392 /// This will also return false if the two given types do not make sense from 7393 /// the perspective of SVE bitcasts. 7394 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7395 assert(srcTy->isVectorType() || destTy->isVectorType()); 7396 7397 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7398 if (!FirstType->isSizelessBuiltinType()) 7399 return false; 7400 7401 const auto *VecTy = SecondType->getAs<VectorType>(); 7402 return VecTy && 7403 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7404 }; 7405 7406 return ValidScalableConversion(srcTy, destTy) || 7407 ValidScalableConversion(destTy, srcTy); 7408 } 7409 7410 /// Are the two types matrix types and do they have the same dimensions i.e. 7411 /// do they have the same number of rows and the same number of columns? 7412 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7413 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7414 return false; 7415 7416 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7417 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7418 7419 return matSrcType->getNumRows() == matDestType->getNumRows() && 7420 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7421 } 7422 7423 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7424 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7425 7426 uint64_t SrcLen, DestLen; 7427 QualType SrcEltTy, DestEltTy; 7428 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7429 return false; 7430 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7431 return false; 7432 7433 // ASTContext::getTypeSize will return the size rounded up to a 7434 // power of 2, so instead of using that, we need to use the raw 7435 // element size multiplied by the element count. 7436 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7437 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7438 7439 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7440 } 7441 7442 /// Are the two types lax-compatible vector types? That is, given 7443 /// that one of them is a vector, do they have equal storage sizes, 7444 /// where the storage size is the number of elements times the element 7445 /// size? 7446 /// 7447 /// This will also return false if either of the types is neither a 7448 /// vector nor a real type. 7449 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7450 assert(destTy->isVectorType() || srcTy->isVectorType()); 7451 7452 // Disallow lax conversions between scalars and ExtVectors (these 7453 // conversions are allowed for other vector types because common headers 7454 // depend on them). Most scalar OP ExtVector cases are handled by the 7455 // splat path anyway, which does what we want (convert, not bitcast). 7456 // What this rules out for ExtVectors is crazy things like char4*float. 7457 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7458 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7459 7460 return areVectorTypesSameSize(srcTy, destTy); 7461 } 7462 7463 /// Is this a legal conversion between two types, one of which is 7464 /// known to be a vector type? 7465 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7466 assert(destTy->isVectorType() || srcTy->isVectorType()); 7467 7468 switch (Context.getLangOpts().getLaxVectorConversions()) { 7469 case LangOptions::LaxVectorConversionKind::None: 7470 return false; 7471 7472 case LangOptions::LaxVectorConversionKind::Integer: 7473 if (!srcTy->isIntegralOrEnumerationType()) { 7474 auto *Vec = srcTy->getAs<VectorType>(); 7475 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7476 return false; 7477 } 7478 if (!destTy->isIntegralOrEnumerationType()) { 7479 auto *Vec = destTy->getAs<VectorType>(); 7480 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7481 return false; 7482 } 7483 // OK, integer (vector) -> integer (vector) bitcast. 7484 break; 7485 7486 case LangOptions::LaxVectorConversionKind::All: 7487 break; 7488 } 7489 7490 return areLaxCompatibleVectorTypes(srcTy, destTy); 7491 } 7492 7493 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7494 CastKind &Kind) { 7495 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7496 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7497 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7498 << DestTy << SrcTy << R; 7499 } 7500 } else if (SrcTy->isMatrixType()) { 7501 return Diag(R.getBegin(), 7502 diag::err_invalid_conversion_between_matrix_and_type) 7503 << SrcTy << DestTy << R; 7504 } else if (DestTy->isMatrixType()) { 7505 return Diag(R.getBegin(), 7506 diag::err_invalid_conversion_between_matrix_and_type) 7507 << DestTy << SrcTy << R; 7508 } 7509 7510 Kind = CK_MatrixCast; 7511 return false; 7512 } 7513 7514 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7515 CastKind &Kind) { 7516 assert(VectorTy->isVectorType() && "Not a vector type!"); 7517 7518 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7519 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7520 return Diag(R.getBegin(), 7521 Ty->isVectorType() ? 7522 diag::err_invalid_conversion_between_vectors : 7523 diag::err_invalid_conversion_between_vector_and_integer) 7524 << VectorTy << Ty << R; 7525 } else 7526 return Diag(R.getBegin(), 7527 diag::err_invalid_conversion_between_vector_and_scalar) 7528 << VectorTy << Ty << R; 7529 7530 Kind = CK_BitCast; 7531 return false; 7532 } 7533 7534 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7535 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7536 7537 if (DestElemTy == SplattedExpr->getType()) 7538 return SplattedExpr; 7539 7540 assert(DestElemTy->isFloatingType() || 7541 DestElemTy->isIntegralOrEnumerationType()); 7542 7543 CastKind CK; 7544 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7545 // OpenCL requires that we convert `true` boolean expressions to -1, but 7546 // only when splatting vectors. 7547 if (DestElemTy->isFloatingType()) { 7548 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7549 // in two steps: boolean to signed integral, then to floating. 7550 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7551 CK_BooleanToSignedIntegral); 7552 SplattedExpr = CastExprRes.get(); 7553 CK = CK_IntegralToFloating; 7554 } else { 7555 CK = CK_BooleanToSignedIntegral; 7556 } 7557 } else { 7558 ExprResult CastExprRes = SplattedExpr; 7559 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7560 if (CastExprRes.isInvalid()) 7561 return ExprError(); 7562 SplattedExpr = CastExprRes.get(); 7563 } 7564 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7565 } 7566 7567 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7568 Expr *CastExpr, CastKind &Kind) { 7569 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7570 7571 QualType SrcTy = CastExpr->getType(); 7572 7573 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7574 // an ExtVectorType. 7575 // In OpenCL, casts between vectors of different types are not allowed. 7576 // (See OpenCL 6.2). 7577 if (SrcTy->isVectorType()) { 7578 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7579 (getLangOpts().OpenCL && 7580 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7581 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7582 << DestTy << SrcTy << R; 7583 return ExprError(); 7584 } 7585 Kind = CK_BitCast; 7586 return CastExpr; 7587 } 7588 7589 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7590 // conversion will take place first from scalar to elt type, and then 7591 // splat from elt type to vector. 7592 if (SrcTy->isPointerType()) 7593 return Diag(R.getBegin(), 7594 diag::err_invalid_conversion_between_vector_and_scalar) 7595 << DestTy << SrcTy << R; 7596 7597 Kind = CK_VectorSplat; 7598 return prepareVectorSplat(DestTy, CastExpr); 7599 } 7600 7601 ExprResult 7602 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7603 Declarator &D, ParsedType &Ty, 7604 SourceLocation RParenLoc, Expr *CastExpr) { 7605 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7606 "ActOnCastExpr(): missing type or expr"); 7607 7608 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7609 if (D.isInvalidType()) 7610 return ExprError(); 7611 7612 if (getLangOpts().CPlusPlus) { 7613 // Check that there are no default arguments (C++ only). 7614 CheckExtraCXXDefaultArguments(D); 7615 } else { 7616 // Make sure any TypoExprs have been dealt with. 7617 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7618 if (!Res.isUsable()) 7619 return ExprError(); 7620 CastExpr = Res.get(); 7621 } 7622 7623 checkUnusedDeclAttributes(D); 7624 7625 QualType castType = castTInfo->getType(); 7626 Ty = CreateParsedType(castType, castTInfo); 7627 7628 bool isVectorLiteral = false; 7629 7630 // Check for an altivec or OpenCL literal, 7631 // i.e. all the elements are integer constants. 7632 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7633 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7634 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7635 && castType->isVectorType() && (PE || PLE)) { 7636 if (PLE && PLE->getNumExprs() == 0) { 7637 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7638 return ExprError(); 7639 } 7640 if (PE || PLE->getNumExprs() == 1) { 7641 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7642 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7643 isVectorLiteral = true; 7644 } 7645 else 7646 isVectorLiteral = true; 7647 } 7648 7649 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7650 // then handle it as such. 7651 if (isVectorLiteral) 7652 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7653 7654 // If the Expr being casted is a ParenListExpr, handle it specially. 7655 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7656 // sequence of BinOp comma operators. 7657 if (isa<ParenListExpr>(CastExpr)) { 7658 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7659 if (Result.isInvalid()) return ExprError(); 7660 CastExpr = Result.get(); 7661 } 7662 7663 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7664 !getSourceManager().isInSystemMacro(LParenLoc)) 7665 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7666 7667 CheckTollFreeBridgeCast(castType, CastExpr); 7668 7669 CheckObjCBridgeRelatedCast(castType, CastExpr); 7670 7671 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7672 7673 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7674 } 7675 7676 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7677 SourceLocation RParenLoc, Expr *E, 7678 TypeSourceInfo *TInfo) { 7679 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7680 "Expected paren or paren list expression"); 7681 7682 Expr **exprs; 7683 unsigned numExprs; 7684 Expr *subExpr; 7685 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7686 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7687 LiteralLParenLoc = PE->getLParenLoc(); 7688 LiteralRParenLoc = PE->getRParenLoc(); 7689 exprs = PE->getExprs(); 7690 numExprs = PE->getNumExprs(); 7691 } else { // isa<ParenExpr> by assertion at function entrance 7692 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7693 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7694 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7695 exprs = &subExpr; 7696 numExprs = 1; 7697 } 7698 7699 QualType Ty = TInfo->getType(); 7700 assert(Ty->isVectorType() && "Expected vector type"); 7701 7702 SmallVector<Expr *, 8> initExprs; 7703 const VectorType *VTy = Ty->castAs<VectorType>(); 7704 unsigned numElems = VTy->getNumElements(); 7705 7706 // '(...)' form of vector initialization in AltiVec: the number of 7707 // initializers must be one or must match the size of the vector. 7708 // If a single value is specified in the initializer then it will be 7709 // replicated to all the components of the vector 7710 if (ShouldSplatAltivecScalarInCast(VTy)) { 7711 // The number of initializers must be one or must match the size of the 7712 // vector. If a single value is specified in the initializer then it will 7713 // be replicated to all the components of the vector 7714 if (numExprs == 1) { 7715 QualType ElemTy = VTy->getElementType(); 7716 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7717 if (Literal.isInvalid()) 7718 return ExprError(); 7719 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7720 PrepareScalarCast(Literal, ElemTy)); 7721 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7722 } 7723 else if (numExprs < numElems) { 7724 Diag(E->getExprLoc(), 7725 diag::err_incorrect_number_of_vector_initializers); 7726 return ExprError(); 7727 } 7728 else 7729 initExprs.append(exprs, exprs + numExprs); 7730 } 7731 else { 7732 // For OpenCL, when the number of initializers is a single value, 7733 // it will be replicated to all components of the vector. 7734 if (getLangOpts().OpenCL && 7735 VTy->getVectorKind() == VectorType::GenericVector && 7736 numExprs == 1) { 7737 QualType ElemTy = VTy->getElementType(); 7738 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7739 if (Literal.isInvalid()) 7740 return ExprError(); 7741 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7742 PrepareScalarCast(Literal, ElemTy)); 7743 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7744 } 7745 7746 initExprs.append(exprs, exprs + numExprs); 7747 } 7748 // FIXME: This means that pretty-printing the final AST will produce curly 7749 // braces instead of the original commas. 7750 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7751 initExprs, LiteralRParenLoc); 7752 initE->setType(Ty); 7753 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7754 } 7755 7756 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7757 /// the ParenListExpr into a sequence of comma binary operators. 7758 ExprResult 7759 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7760 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7761 if (!E) 7762 return OrigExpr; 7763 7764 ExprResult Result(E->getExpr(0)); 7765 7766 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7767 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7768 E->getExpr(i)); 7769 7770 if (Result.isInvalid()) return ExprError(); 7771 7772 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7773 } 7774 7775 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7776 SourceLocation R, 7777 MultiExprArg Val) { 7778 return ParenListExpr::Create(Context, L, Val, R); 7779 } 7780 7781 /// Emit a specialized diagnostic when one expression is a null pointer 7782 /// constant and the other is not a pointer. Returns true if a diagnostic is 7783 /// emitted. 7784 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7785 SourceLocation QuestionLoc) { 7786 Expr *NullExpr = LHSExpr; 7787 Expr *NonPointerExpr = RHSExpr; 7788 Expr::NullPointerConstantKind NullKind = 7789 NullExpr->isNullPointerConstant(Context, 7790 Expr::NPC_ValueDependentIsNotNull); 7791 7792 if (NullKind == Expr::NPCK_NotNull) { 7793 NullExpr = RHSExpr; 7794 NonPointerExpr = LHSExpr; 7795 NullKind = 7796 NullExpr->isNullPointerConstant(Context, 7797 Expr::NPC_ValueDependentIsNotNull); 7798 } 7799 7800 if (NullKind == Expr::NPCK_NotNull) 7801 return false; 7802 7803 if (NullKind == Expr::NPCK_ZeroExpression) 7804 return false; 7805 7806 if (NullKind == Expr::NPCK_ZeroLiteral) { 7807 // In this case, check to make sure that we got here from a "NULL" 7808 // string in the source code. 7809 NullExpr = NullExpr->IgnoreParenImpCasts(); 7810 SourceLocation loc = NullExpr->getExprLoc(); 7811 if (!findMacroSpelling(loc, "NULL")) 7812 return false; 7813 } 7814 7815 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7816 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7817 << NonPointerExpr->getType() << DiagType 7818 << NonPointerExpr->getSourceRange(); 7819 return true; 7820 } 7821 7822 /// Return false if the condition expression is valid, true otherwise. 7823 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7824 QualType CondTy = Cond->getType(); 7825 7826 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7827 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7828 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7829 << CondTy << Cond->getSourceRange(); 7830 return true; 7831 } 7832 7833 // C99 6.5.15p2 7834 if (CondTy->isScalarType()) return false; 7835 7836 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7837 << CondTy << Cond->getSourceRange(); 7838 return true; 7839 } 7840 7841 /// Handle when one or both operands are void type. 7842 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7843 ExprResult &RHS) { 7844 Expr *LHSExpr = LHS.get(); 7845 Expr *RHSExpr = RHS.get(); 7846 7847 if (!LHSExpr->getType()->isVoidType()) 7848 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7849 << RHSExpr->getSourceRange(); 7850 if (!RHSExpr->getType()->isVoidType()) 7851 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7852 << LHSExpr->getSourceRange(); 7853 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7854 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7855 return S.Context.VoidTy; 7856 } 7857 7858 /// Return false if the NullExpr can be promoted to PointerTy, 7859 /// true otherwise. 7860 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7861 QualType PointerTy) { 7862 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7863 !NullExpr.get()->isNullPointerConstant(S.Context, 7864 Expr::NPC_ValueDependentIsNull)) 7865 return true; 7866 7867 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7868 return false; 7869 } 7870 7871 /// Checks compatibility between two pointers and return the resulting 7872 /// type. 7873 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7874 ExprResult &RHS, 7875 SourceLocation Loc) { 7876 QualType LHSTy = LHS.get()->getType(); 7877 QualType RHSTy = RHS.get()->getType(); 7878 7879 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7880 // Two identical pointers types are always compatible. 7881 return LHSTy; 7882 } 7883 7884 QualType lhptee, rhptee; 7885 7886 // Get the pointee types. 7887 bool IsBlockPointer = false; 7888 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7889 lhptee = LHSBTy->getPointeeType(); 7890 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7891 IsBlockPointer = true; 7892 } else { 7893 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7894 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7895 } 7896 7897 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7898 // differently qualified versions of compatible types, the result type is 7899 // a pointer to an appropriately qualified version of the composite 7900 // type. 7901 7902 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7903 // clause doesn't make sense for our extensions. E.g. address space 2 should 7904 // be incompatible with address space 3: they may live on different devices or 7905 // anything. 7906 Qualifiers lhQual = lhptee.getQualifiers(); 7907 Qualifiers rhQual = rhptee.getQualifiers(); 7908 7909 LangAS ResultAddrSpace = LangAS::Default; 7910 LangAS LAddrSpace = lhQual.getAddressSpace(); 7911 LangAS RAddrSpace = rhQual.getAddressSpace(); 7912 7913 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7914 // spaces is disallowed. 7915 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7916 ResultAddrSpace = LAddrSpace; 7917 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7918 ResultAddrSpace = RAddrSpace; 7919 else { 7920 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7921 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7922 << RHS.get()->getSourceRange(); 7923 return QualType(); 7924 } 7925 7926 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7927 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7928 lhQual.removeCVRQualifiers(); 7929 rhQual.removeCVRQualifiers(); 7930 7931 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7932 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7933 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7934 // qual types are compatible iff 7935 // * corresponded types are compatible 7936 // * CVR qualifiers are equal 7937 // * address spaces are equal 7938 // Thus for conditional operator we merge CVR and address space unqualified 7939 // pointees and if there is a composite type we return a pointer to it with 7940 // merged qualifiers. 7941 LHSCastKind = 7942 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7943 RHSCastKind = 7944 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7945 lhQual.removeAddressSpace(); 7946 rhQual.removeAddressSpace(); 7947 7948 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7949 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7950 7951 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7952 7953 if (CompositeTy.isNull()) { 7954 // In this situation, we assume void* type. No especially good 7955 // reason, but this is what gcc does, and we do have to pick 7956 // to get a consistent AST. 7957 QualType incompatTy; 7958 incompatTy = S.Context.getPointerType( 7959 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7960 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7961 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7962 7963 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7964 // for casts between types with incompatible address space qualifiers. 7965 // For the following code the compiler produces casts between global and 7966 // local address spaces of the corresponded innermost pointees: 7967 // local int *global *a; 7968 // global int *global *b; 7969 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7970 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7971 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7972 << RHS.get()->getSourceRange(); 7973 7974 return incompatTy; 7975 } 7976 7977 // The pointer types are compatible. 7978 // In case of OpenCL ResultTy should have the address space qualifier 7979 // which is a superset of address spaces of both the 2nd and the 3rd 7980 // operands of the conditional operator. 7981 QualType ResultTy = [&, ResultAddrSpace]() { 7982 if (S.getLangOpts().OpenCL) { 7983 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7984 CompositeQuals.setAddressSpace(ResultAddrSpace); 7985 return S.Context 7986 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7987 .withCVRQualifiers(MergedCVRQual); 7988 } 7989 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7990 }(); 7991 if (IsBlockPointer) 7992 ResultTy = S.Context.getBlockPointerType(ResultTy); 7993 else 7994 ResultTy = S.Context.getPointerType(ResultTy); 7995 7996 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7997 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7998 return ResultTy; 7999 } 8000 8001 /// Return the resulting type when the operands are both block pointers. 8002 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8003 ExprResult &LHS, 8004 ExprResult &RHS, 8005 SourceLocation Loc) { 8006 QualType LHSTy = LHS.get()->getType(); 8007 QualType RHSTy = RHS.get()->getType(); 8008 8009 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8010 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8011 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8012 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8013 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8014 return destType; 8015 } 8016 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8017 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8018 << RHS.get()->getSourceRange(); 8019 return QualType(); 8020 } 8021 8022 // We have 2 block pointer types. 8023 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8024 } 8025 8026 /// Return the resulting type when the operands are both pointers. 8027 static QualType 8028 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8029 ExprResult &RHS, 8030 SourceLocation Loc) { 8031 // get the pointer types 8032 QualType LHSTy = LHS.get()->getType(); 8033 QualType RHSTy = RHS.get()->getType(); 8034 8035 // get the "pointed to" types 8036 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8037 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8038 8039 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8040 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8041 // Figure out necessary qualifiers (C99 6.5.15p6) 8042 QualType destPointee 8043 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8044 QualType destType = S.Context.getPointerType(destPointee); 8045 // Add qualifiers if necessary. 8046 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8047 // Promote to void*. 8048 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8049 return destType; 8050 } 8051 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8052 QualType destPointee 8053 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8054 QualType destType = S.Context.getPointerType(destPointee); 8055 // Add qualifiers if necessary. 8056 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8057 // Promote to void*. 8058 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8059 return destType; 8060 } 8061 8062 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8063 } 8064 8065 /// Return false if the first expression is not an integer and the second 8066 /// expression is not a pointer, true otherwise. 8067 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8068 Expr* PointerExpr, SourceLocation Loc, 8069 bool IsIntFirstExpr) { 8070 if (!PointerExpr->getType()->isPointerType() || 8071 !Int.get()->getType()->isIntegerType()) 8072 return false; 8073 8074 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8075 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8076 8077 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8078 << Expr1->getType() << Expr2->getType() 8079 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8080 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8081 CK_IntegralToPointer); 8082 return true; 8083 } 8084 8085 /// Simple conversion between integer and floating point types. 8086 /// 8087 /// Used when handling the OpenCL conditional operator where the 8088 /// condition is a vector while the other operands are scalar. 8089 /// 8090 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8091 /// types are either integer or floating type. Between the two 8092 /// operands, the type with the higher rank is defined as the "result 8093 /// type". The other operand needs to be promoted to the same type. No 8094 /// other type promotion is allowed. We cannot use 8095 /// UsualArithmeticConversions() for this purpose, since it always 8096 /// promotes promotable types. 8097 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8098 ExprResult &RHS, 8099 SourceLocation QuestionLoc) { 8100 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8101 if (LHS.isInvalid()) 8102 return QualType(); 8103 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8104 if (RHS.isInvalid()) 8105 return QualType(); 8106 8107 // For conversion purposes, we ignore any qualifiers. 8108 // For example, "const float" and "float" are equivalent. 8109 QualType LHSType = 8110 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8111 QualType RHSType = 8112 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8113 8114 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8115 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8116 << LHSType << LHS.get()->getSourceRange(); 8117 return QualType(); 8118 } 8119 8120 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8121 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8122 << RHSType << RHS.get()->getSourceRange(); 8123 return QualType(); 8124 } 8125 8126 // If both types are identical, no conversion is needed. 8127 if (LHSType == RHSType) 8128 return LHSType; 8129 8130 // Now handle "real" floating types (i.e. float, double, long double). 8131 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8132 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8133 /*IsCompAssign = */ false); 8134 8135 // Finally, we have two differing integer types. 8136 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8137 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8138 } 8139 8140 /// Convert scalar operands to a vector that matches the 8141 /// condition in length. 8142 /// 8143 /// Used when handling the OpenCL conditional operator where the 8144 /// condition is a vector while the other operands are scalar. 8145 /// 8146 /// We first compute the "result type" for the scalar operands 8147 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8148 /// into a vector of that type where the length matches the condition 8149 /// vector type. s6.11.6 requires that the element types of the result 8150 /// and the condition must have the same number of bits. 8151 static QualType 8152 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8153 QualType CondTy, SourceLocation QuestionLoc) { 8154 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8155 if (ResTy.isNull()) return QualType(); 8156 8157 const VectorType *CV = CondTy->getAs<VectorType>(); 8158 assert(CV); 8159 8160 // Determine the vector result type 8161 unsigned NumElements = CV->getNumElements(); 8162 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8163 8164 // Ensure that all types have the same number of bits 8165 if (S.Context.getTypeSize(CV->getElementType()) 8166 != S.Context.getTypeSize(ResTy)) { 8167 // Since VectorTy is created internally, it does not pretty print 8168 // with an OpenCL name. Instead, we just print a description. 8169 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8170 SmallString<64> Str; 8171 llvm::raw_svector_ostream OS(Str); 8172 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8173 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8174 << CondTy << OS.str(); 8175 return QualType(); 8176 } 8177 8178 // Convert operands to the vector result type 8179 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8180 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8181 8182 return VectorTy; 8183 } 8184 8185 /// Return false if this is a valid OpenCL condition vector 8186 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8187 SourceLocation QuestionLoc) { 8188 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8189 // integral type. 8190 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8191 assert(CondTy); 8192 QualType EleTy = CondTy->getElementType(); 8193 if (EleTy->isIntegerType()) return false; 8194 8195 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8196 << Cond->getType() << Cond->getSourceRange(); 8197 return true; 8198 } 8199 8200 /// Return false if the vector condition type and the vector 8201 /// result type are compatible. 8202 /// 8203 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8204 /// number of elements, and their element types have the same number 8205 /// of bits. 8206 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8207 SourceLocation QuestionLoc) { 8208 const VectorType *CV = CondTy->getAs<VectorType>(); 8209 const VectorType *RV = VecResTy->getAs<VectorType>(); 8210 assert(CV && RV); 8211 8212 if (CV->getNumElements() != RV->getNumElements()) { 8213 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8214 << CondTy << VecResTy; 8215 return true; 8216 } 8217 8218 QualType CVE = CV->getElementType(); 8219 QualType RVE = RV->getElementType(); 8220 8221 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8222 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8223 << CondTy << VecResTy; 8224 return true; 8225 } 8226 8227 return false; 8228 } 8229 8230 /// Return the resulting type for the conditional operator in 8231 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8232 /// s6.3.i) when the condition is a vector type. 8233 static QualType 8234 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8235 ExprResult &LHS, ExprResult &RHS, 8236 SourceLocation QuestionLoc) { 8237 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8238 if (Cond.isInvalid()) 8239 return QualType(); 8240 QualType CondTy = Cond.get()->getType(); 8241 8242 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8243 return QualType(); 8244 8245 // If either operand is a vector then find the vector type of the 8246 // result as specified in OpenCL v1.1 s6.3.i. 8247 if (LHS.get()->getType()->isVectorType() || 8248 RHS.get()->getType()->isVectorType()) { 8249 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8250 /*isCompAssign*/false, 8251 /*AllowBothBool*/true, 8252 /*AllowBoolConversions*/false); 8253 if (VecResTy.isNull()) return QualType(); 8254 // The result type must match the condition type as specified in 8255 // OpenCL v1.1 s6.11.6. 8256 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8257 return QualType(); 8258 return VecResTy; 8259 } 8260 8261 // Both operands are scalar. 8262 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8263 } 8264 8265 /// Return true if the Expr is block type 8266 static bool checkBlockType(Sema &S, const Expr *E) { 8267 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8268 QualType Ty = CE->getCallee()->getType(); 8269 if (Ty->isBlockPointerType()) { 8270 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8271 return true; 8272 } 8273 } 8274 return false; 8275 } 8276 8277 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8278 /// In that case, LHS = cond. 8279 /// C99 6.5.15 8280 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8281 ExprResult &RHS, ExprValueKind &VK, 8282 ExprObjectKind &OK, 8283 SourceLocation QuestionLoc) { 8284 8285 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8286 if (!LHSResult.isUsable()) return QualType(); 8287 LHS = LHSResult; 8288 8289 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8290 if (!RHSResult.isUsable()) return QualType(); 8291 RHS = RHSResult; 8292 8293 // C++ is sufficiently different to merit its own checker. 8294 if (getLangOpts().CPlusPlus) 8295 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8296 8297 VK = VK_PRValue; 8298 OK = OK_Ordinary; 8299 8300 if (Context.isDependenceAllowed() && 8301 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8302 RHS.get()->isTypeDependent())) { 8303 assert(!getLangOpts().CPlusPlus); 8304 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8305 RHS.get()->containsErrors()) && 8306 "should only occur in error-recovery path."); 8307 return Context.DependentTy; 8308 } 8309 8310 // The OpenCL operator with a vector condition is sufficiently 8311 // different to merit its own checker. 8312 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8313 Cond.get()->getType()->isExtVectorType()) 8314 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8315 8316 // First, check the condition. 8317 Cond = UsualUnaryConversions(Cond.get()); 8318 if (Cond.isInvalid()) 8319 return QualType(); 8320 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8321 return QualType(); 8322 8323 // Now check the two expressions. 8324 if (LHS.get()->getType()->isVectorType() || 8325 RHS.get()->getType()->isVectorType()) 8326 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8327 /*AllowBothBool*/true, 8328 /*AllowBoolConversions*/false); 8329 8330 QualType ResTy = 8331 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8332 if (LHS.isInvalid() || RHS.isInvalid()) 8333 return QualType(); 8334 8335 QualType LHSTy = LHS.get()->getType(); 8336 QualType RHSTy = RHS.get()->getType(); 8337 8338 // Diagnose attempts to convert between __float128 and long double where 8339 // such conversions currently can't be handled. 8340 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8341 Diag(QuestionLoc, 8342 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8343 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8344 return QualType(); 8345 } 8346 8347 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8348 // selection operator (?:). 8349 if (getLangOpts().OpenCL && 8350 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8351 return QualType(); 8352 } 8353 8354 // If both operands have arithmetic type, do the usual arithmetic conversions 8355 // to find a common type: C99 6.5.15p3,5. 8356 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8357 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8358 // different sizes, or between ExtInts and other types. 8359 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8360 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8361 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8362 << RHS.get()->getSourceRange(); 8363 return QualType(); 8364 } 8365 8366 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8367 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8368 8369 return ResTy; 8370 } 8371 8372 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8373 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8374 return LHSTy; 8375 } 8376 8377 // If both operands are the same structure or union type, the result is that 8378 // type. 8379 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8380 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8381 if (LHSRT->getDecl() == RHSRT->getDecl()) 8382 // "If both the operands have structure or union type, the result has 8383 // that type." This implies that CV qualifiers are dropped. 8384 return LHSTy.getUnqualifiedType(); 8385 // FIXME: Type of conditional expression must be complete in C mode. 8386 } 8387 8388 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8389 // The following || allows only one side to be void (a GCC-ism). 8390 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8391 return checkConditionalVoidType(*this, LHS, RHS); 8392 } 8393 8394 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8395 // the type of the other operand." 8396 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8397 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8398 8399 // All objective-c pointer type analysis is done here. 8400 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8401 QuestionLoc); 8402 if (LHS.isInvalid() || RHS.isInvalid()) 8403 return QualType(); 8404 if (!compositeType.isNull()) 8405 return compositeType; 8406 8407 8408 // Handle block pointer types. 8409 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8410 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8411 QuestionLoc); 8412 8413 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8414 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8415 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8416 QuestionLoc); 8417 8418 // GCC compatibility: soften pointer/integer mismatch. Note that 8419 // null pointers have been filtered out by this point. 8420 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8421 /*IsIntFirstExpr=*/true)) 8422 return RHSTy; 8423 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8424 /*IsIntFirstExpr=*/false)) 8425 return LHSTy; 8426 8427 // Allow ?: operations in which both operands have the same 8428 // built-in sizeless type. 8429 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8430 return LHSTy; 8431 8432 // Emit a better diagnostic if one of the expressions is a null pointer 8433 // constant and the other is not a pointer type. In this case, the user most 8434 // likely forgot to take the address of the other expression. 8435 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8436 return QualType(); 8437 8438 // Otherwise, the operands are not compatible. 8439 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8440 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8441 << RHS.get()->getSourceRange(); 8442 return QualType(); 8443 } 8444 8445 /// FindCompositeObjCPointerType - Helper method to find composite type of 8446 /// two objective-c pointer types of the two input expressions. 8447 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8448 SourceLocation QuestionLoc) { 8449 QualType LHSTy = LHS.get()->getType(); 8450 QualType RHSTy = RHS.get()->getType(); 8451 8452 // Handle things like Class and struct objc_class*. Here we case the result 8453 // to the pseudo-builtin, because that will be implicitly cast back to the 8454 // redefinition type if an attempt is made to access its fields. 8455 if (LHSTy->isObjCClassType() && 8456 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8457 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8458 return LHSTy; 8459 } 8460 if (RHSTy->isObjCClassType() && 8461 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8462 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8463 return RHSTy; 8464 } 8465 // And the same for struct objc_object* / id 8466 if (LHSTy->isObjCIdType() && 8467 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8468 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8469 return LHSTy; 8470 } 8471 if (RHSTy->isObjCIdType() && 8472 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8473 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8474 return RHSTy; 8475 } 8476 // And the same for struct objc_selector* / SEL 8477 if (Context.isObjCSelType(LHSTy) && 8478 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8479 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8480 return LHSTy; 8481 } 8482 if (Context.isObjCSelType(RHSTy) && 8483 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8484 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8485 return RHSTy; 8486 } 8487 // Check constraints for Objective-C object pointers types. 8488 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8489 8490 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8491 // Two identical object pointer types are always compatible. 8492 return LHSTy; 8493 } 8494 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8495 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8496 QualType compositeType = LHSTy; 8497 8498 // If both operands are interfaces and either operand can be 8499 // assigned to the other, use that type as the composite 8500 // type. This allows 8501 // xxx ? (A*) a : (B*) b 8502 // where B is a subclass of A. 8503 // 8504 // Additionally, as for assignment, if either type is 'id' 8505 // allow silent coercion. Finally, if the types are 8506 // incompatible then make sure to use 'id' as the composite 8507 // type so the result is acceptable for sending messages to. 8508 8509 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8510 // It could return the composite type. 8511 if (!(compositeType = 8512 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8513 // Nothing more to do. 8514 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8515 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8516 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8517 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8518 } else if ((LHSOPT->isObjCQualifiedIdType() || 8519 RHSOPT->isObjCQualifiedIdType()) && 8520 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8521 true)) { 8522 // Need to handle "id<xx>" explicitly. 8523 // GCC allows qualified id and any Objective-C type to devolve to 8524 // id. Currently localizing to here until clear this should be 8525 // part of ObjCQualifiedIdTypesAreCompatible. 8526 compositeType = Context.getObjCIdType(); 8527 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8528 compositeType = Context.getObjCIdType(); 8529 } else { 8530 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8531 << LHSTy << RHSTy 8532 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8533 QualType incompatTy = Context.getObjCIdType(); 8534 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8535 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8536 return incompatTy; 8537 } 8538 // The object pointer types are compatible. 8539 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8540 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8541 return compositeType; 8542 } 8543 // Check Objective-C object pointer types and 'void *' 8544 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8545 if (getLangOpts().ObjCAutoRefCount) { 8546 // ARC forbids the implicit conversion of object pointers to 'void *', 8547 // so these types are not compatible. 8548 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8549 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8550 LHS = RHS = true; 8551 return QualType(); 8552 } 8553 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8554 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8555 QualType destPointee 8556 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8557 QualType destType = Context.getPointerType(destPointee); 8558 // Add qualifiers if necessary. 8559 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8560 // Promote to void*. 8561 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8562 return destType; 8563 } 8564 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8565 if (getLangOpts().ObjCAutoRefCount) { 8566 // ARC forbids the implicit conversion of object pointers to 'void *', 8567 // so these types are not compatible. 8568 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8569 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8570 LHS = RHS = true; 8571 return QualType(); 8572 } 8573 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8574 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8575 QualType destPointee 8576 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8577 QualType destType = Context.getPointerType(destPointee); 8578 // Add qualifiers if necessary. 8579 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8580 // Promote to void*. 8581 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8582 return destType; 8583 } 8584 return QualType(); 8585 } 8586 8587 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8588 /// ParenRange in parentheses. 8589 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8590 const PartialDiagnostic &Note, 8591 SourceRange ParenRange) { 8592 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8593 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8594 EndLoc.isValid()) { 8595 Self.Diag(Loc, Note) 8596 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8597 << FixItHint::CreateInsertion(EndLoc, ")"); 8598 } else { 8599 // We can't display the parentheses, so just show the bare note. 8600 Self.Diag(Loc, Note) << ParenRange; 8601 } 8602 } 8603 8604 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8605 return BinaryOperator::isAdditiveOp(Opc) || 8606 BinaryOperator::isMultiplicativeOp(Opc) || 8607 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8608 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8609 // not any of the logical operators. Bitwise-xor is commonly used as a 8610 // logical-xor because there is no logical-xor operator. The logical 8611 // operators, including uses of xor, have a high false positive rate for 8612 // precedence warnings. 8613 } 8614 8615 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8616 /// expression, either using a built-in or overloaded operator, 8617 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8618 /// expression. 8619 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8620 Expr **RHSExprs) { 8621 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8622 E = E->IgnoreImpCasts(); 8623 E = E->IgnoreConversionOperatorSingleStep(); 8624 E = E->IgnoreImpCasts(); 8625 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8626 E = MTE->getSubExpr(); 8627 E = E->IgnoreImpCasts(); 8628 } 8629 8630 // Built-in binary operator. 8631 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8632 if (IsArithmeticOp(OP->getOpcode())) { 8633 *Opcode = OP->getOpcode(); 8634 *RHSExprs = OP->getRHS(); 8635 return true; 8636 } 8637 } 8638 8639 // Overloaded operator. 8640 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8641 if (Call->getNumArgs() != 2) 8642 return false; 8643 8644 // Make sure this is really a binary operator that is safe to pass into 8645 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8646 OverloadedOperatorKind OO = Call->getOperator(); 8647 if (OO < OO_Plus || OO > OO_Arrow || 8648 OO == OO_PlusPlus || OO == OO_MinusMinus) 8649 return false; 8650 8651 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8652 if (IsArithmeticOp(OpKind)) { 8653 *Opcode = OpKind; 8654 *RHSExprs = Call->getArg(1); 8655 return true; 8656 } 8657 } 8658 8659 return false; 8660 } 8661 8662 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8663 /// or is a logical expression such as (x==y) which has int type, but is 8664 /// commonly interpreted as boolean. 8665 static bool ExprLooksBoolean(Expr *E) { 8666 E = E->IgnoreParenImpCasts(); 8667 8668 if (E->getType()->isBooleanType()) 8669 return true; 8670 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8671 return OP->isComparisonOp() || OP->isLogicalOp(); 8672 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8673 return OP->getOpcode() == UO_LNot; 8674 if (E->getType()->isPointerType()) 8675 return true; 8676 // FIXME: What about overloaded operator calls returning "unspecified boolean 8677 // type"s (commonly pointer-to-members)? 8678 8679 return false; 8680 } 8681 8682 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8683 /// and binary operator are mixed in a way that suggests the programmer assumed 8684 /// the conditional operator has higher precedence, for example: 8685 /// "int x = a + someBinaryCondition ? 1 : 2". 8686 static void DiagnoseConditionalPrecedence(Sema &Self, 8687 SourceLocation OpLoc, 8688 Expr *Condition, 8689 Expr *LHSExpr, 8690 Expr *RHSExpr) { 8691 BinaryOperatorKind CondOpcode; 8692 Expr *CondRHS; 8693 8694 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8695 return; 8696 if (!ExprLooksBoolean(CondRHS)) 8697 return; 8698 8699 // The condition is an arithmetic binary expression, with a right- 8700 // hand side that looks boolean, so warn. 8701 8702 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8703 ? diag::warn_precedence_bitwise_conditional 8704 : diag::warn_precedence_conditional; 8705 8706 Self.Diag(OpLoc, DiagID) 8707 << Condition->getSourceRange() 8708 << BinaryOperator::getOpcodeStr(CondOpcode); 8709 8710 SuggestParentheses( 8711 Self, OpLoc, 8712 Self.PDiag(diag::note_precedence_silence) 8713 << BinaryOperator::getOpcodeStr(CondOpcode), 8714 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8715 8716 SuggestParentheses(Self, OpLoc, 8717 Self.PDiag(diag::note_precedence_conditional_first), 8718 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8719 } 8720 8721 /// Compute the nullability of a conditional expression. 8722 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8723 QualType LHSTy, QualType RHSTy, 8724 ASTContext &Ctx) { 8725 if (!ResTy->isAnyPointerType()) 8726 return ResTy; 8727 8728 auto GetNullability = [&Ctx](QualType Ty) { 8729 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8730 if (Kind) { 8731 // For our purposes, treat _Nullable_result as _Nullable. 8732 if (*Kind == NullabilityKind::NullableResult) 8733 return NullabilityKind::Nullable; 8734 return *Kind; 8735 } 8736 return NullabilityKind::Unspecified; 8737 }; 8738 8739 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8740 NullabilityKind MergedKind; 8741 8742 // Compute nullability of a binary conditional expression. 8743 if (IsBin) { 8744 if (LHSKind == NullabilityKind::NonNull) 8745 MergedKind = NullabilityKind::NonNull; 8746 else 8747 MergedKind = RHSKind; 8748 // Compute nullability of a normal conditional expression. 8749 } else { 8750 if (LHSKind == NullabilityKind::Nullable || 8751 RHSKind == NullabilityKind::Nullable) 8752 MergedKind = NullabilityKind::Nullable; 8753 else if (LHSKind == NullabilityKind::NonNull) 8754 MergedKind = RHSKind; 8755 else if (RHSKind == NullabilityKind::NonNull) 8756 MergedKind = LHSKind; 8757 else 8758 MergedKind = NullabilityKind::Unspecified; 8759 } 8760 8761 // Return if ResTy already has the correct nullability. 8762 if (GetNullability(ResTy) == MergedKind) 8763 return ResTy; 8764 8765 // Strip all nullability from ResTy. 8766 while (ResTy->getNullability(Ctx)) 8767 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8768 8769 // Create a new AttributedType with the new nullability kind. 8770 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8771 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8772 } 8773 8774 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8775 /// in the case of a the GNU conditional expr extension. 8776 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8777 SourceLocation ColonLoc, 8778 Expr *CondExpr, Expr *LHSExpr, 8779 Expr *RHSExpr) { 8780 if (!Context.isDependenceAllowed()) { 8781 // C cannot handle TypoExpr nodes in the condition because it 8782 // doesn't handle dependent types properly, so make sure any TypoExprs have 8783 // been dealt with before checking the operands. 8784 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8785 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8786 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8787 8788 if (!CondResult.isUsable()) 8789 return ExprError(); 8790 8791 if (LHSExpr) { 8792 if (!LHSResult.isUsable()) 8793 return ExprError(); 8794 } 8795 8796 if (!RHSResult.isUsable()) 8797 return ExprError(); 8798 8799 CondExpr = CondResult.get(); 8800 LHSExpr = LHSResult.get(); 8801 RHSExpr = RHSResult.get(); 8802 } 8803 8804 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8805 // was the condition. 8806 OpaqueValueExpr *opaqueValue = nullptr; 8807 Expr *commonExpr = nullptr; 8808 if (!LHSExpr) { 8809 commonExpr = CondExpr; 8810 // Lower out placeholder types first. This is important so that we don't 8811 // try to capture a placeholder. This happens in few cases in C++; such 8812 // as Objective-C++'s dictionary subscripting syntax. 8813 if (commonExpr->hasPlaceholderType()) { 8814 ExprResult result = CheckPlaceholderExpr(commonExpr); 8815 if (!result.isUsable()) return ExprError(); 8816 commonExpr = result.get(); 8817 } 8818 // We usually want to apply unary conversions *before* saving, except 8819 // in the special case of a C++ l-value conditional. 8820 if (!(getLangOpts().CPlusPlus 8821 && !commonExpr->isTypeDependent() 8822 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8823 && commonExpr->isGLValue() 8824 && commonExpr->isOrdinaryOrBitFieldObject() 8825 && RHSExpr->isOrdinaryOrBitFieldObject() 8826 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8827 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8828 if (commonRes.isInvalid()) 8829 return ExprError(); 8830 commonExpr = commonRes.get(); 8831 } 8832 8833 // If the common expression is a class or array prvalue, materialize it 8834 // so that we can safely refer to it multiple times. 8835 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8836 commonExpr->getType()->isArrayType())) { 8837 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8838 if (MatExpr.isInvalid()) 8839 return ExprError(); 8840 commonExpr = MatExpr.get(); 8841 } 8842 8843 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8844 commonExpr->getType(), 8845 commonExpr->getValueKind(), 8846 commonExpr->getObjectKind(), 8847 commonExpr); 8848 LHSExpr = CondExpr = opaqueValue; 8849 } 8850 8851 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8852 ExprValueKind VK = VK_PRValue; 8853 ExprObjectKind OK = OK_Ordinary; 8854 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8855 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8856 VK, OK, QuestionLoc); 8857 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8858 RHS.isInvalid()) 8859 return ExprError(); 8860 8861 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8862 RHS.get()); 8863 8864 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8865 8866 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8867 Context); 8868 8869 if (!commonExpr) 8870 return new (Context) 8871 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8872 RHS.get(), result, VK, OK); 8873 8874 return new (Context) BinaryConditionalOperator( 8875 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8876 ColonLoc, result, VK, OK); 8877 } 8878 8879 // Check if we have a conversion between incompatible cmse function pointer 8880 // types, that is, a conversion between a function pointer with the 8881 // cmse_nonsecure_call attribute and one without. 8882 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8883 QualType ToType) { 8884 if (const auto *ToFn = 8885 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8886 if (const auto *FromFn = 8887 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8888 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8889 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8890 8891 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8892 } 8893 } 8894 return false; 8895 } 8896 8897 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8898 // being closely modeled after the C99 spec:-). The odd characteristic of this 8899 // routine is it effectively iqnores the qualifiers on the top level pointee. 8900 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8901 // FIXME: add a couple examples in this comment. 8902 static Sema::AssignConvertType 8903 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8904 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8905 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8906 8907 // get the "pointed to" type (ignoring qualifiers at the top level) 8908 const Type *lhptee, *rhptee; 8909 Qualifiers lhq, rhq; 8910 std::tie(lhptee, lhq) = 8911 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8912 std::tie(rhptee, rhq) = 8913 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8914 8915 Sema::AssignConvertType ConvTy = Sema::Compatible; 8916 8917 // C99 6.5.16.1p1: This following citation is common to constraints 8918 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8919 // qualifiers of the type *pointed to* by the right; 8920 8921 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8922 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8923 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8924 // Ignore lifetime for further calculation. 8925 lhq.removeObjCLifetime(); 8926 rhq.removeObjCLifetime(); 8927 } 8928 8929 if (!lhq.compatiblyIncludes(rhq)) { 8930 // Treat address-space mismatches as fatal. 8931 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8932 return Sema::IncompatiblePointerDiscardsQualifiers; 8933 8934 // It's okay to add or remove GC or lifetime qualifiers when converting to 8935 // and from void*. 8936 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8937 .compatiblyIncludes( 8938 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8939 && (lhptee->isVoidType() || rhptee->isVoidType())) 8940 ; // keep old 8941 8942 // Treat lifetime mismatches as fatal. 8943 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8944 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8945 8946 // For GCC/MS compatibility, other qualifier mismatches are treated 8947 // as still compatible in C. 8948 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8949 } 8950 8951 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8952 // incomplete type and the other is a pointer to a qualified or unqualified 8953 // version of void... 8954 if (lhptee->isVoidType()) { 8955 if (rhptee->isIncompleteOrObjectType()) 8956 return ConvTy; 8957 8958 // As an extension, we allow cast to/from void* to function pointer. 8959 assert(rhptee->isFunctionType()); 8960 return Sema::FunctionVoidPointer; 8961 } 8962 8963 if (rhptee->isVoidType()) { 8964 if (lhptee->isIncompleteOrObjectType()) 8965 return ConvTy; 8966 8967 // As an extension, we allow cast to/from void* to function pointer. 8968 assert(lhptee->isFunctionType()); 8969 return Sema::FunctionVoidPointer; 8970 } 8971 8972 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8973 // unqualified versions of compatible types, ... 8974 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8975 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8976 // Check if the pointee types are compatible ignoring the sign. 8977 // We explicitly check for char so that we catch "char" vs 8978 // "unsigned char" on systems where "char" is unsigned. 8979 if (lhptee->isCharType()) 8980 ltrans = S.Context.UnsignedCharTy; 8981 else if (lhptee->hasSignedIntegerRepresentation()) 8982 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8983 8984 if (rhptee->isCharType()) 8985 rtrans = S.Context.UnsignedCharTy; 8986 else if (rhptee->hasSignedIntegerRepresentation()) 8987 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8988 8989 if (ltrans == rtrans) { 8990 // Types are compatible ignoring the sign. Qualifier incompatibility 8991 // takes priority over sign incompatibility because the sign 8992 // warning can be disabled. 8993 if (ConvTy != Sema::Compatible) 8994 return ConvTy; 8995 8996 return Sema::IncompatiblePointerSign; 8997 } 8998 8999 // If we are a multi-level pointer, it's possible that our issue is simply 9000 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9001 // the eventual target type is the same and the pointers have the same 9002 // level of indirection, this must be the issue. 9003 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9004 do { 9005 std::tie(lhptee, lhq) = 9006 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9007 std::tie(rhptee, rhq) = 9008 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9009 9010 // Inconsistent address spaces at this point is invalid, even if the 9011 // address spaces would be compatible. 9012 // FIXME: This doesn't catch address space mismatches for pointers of 9013 // different nesting levels, like: 9014 // __local int *** a; 9015 // int ** b = a; 9016 // It's not clear how to actually determine when such pointers are 9017 // invalidly incompatible. 9018 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9019 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9020 9021 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9022 9023 if (lhptee == rhptee) 9024 return Sema::IncompatibleNestedPointerQualifiers; 9025 } 9026 9027 // General pointer incompatibility takes priority over qualifiers. 9028 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9029 return Sema::IncompatibleFunctionPointer; 9030 return Sema::IncompatiblePointer; 9031 } 9032 if (!S.getLangOpts().CPlusPlus && 9033 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9034 return Sema::IncompatibleFunctionPointer; 9035 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9036 return Sema::IncompatibleFunctionPointer; 9037 return ConvTy; 9038 } 9039 9040 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9041 /// block pointer types are compatible or whether a block and normal pointer 9042 /// are compatible. It is more restrict than comparing two function pointer 9043 // types. 9044 static Sema::AssignConvertType 9045 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9046 QualType RHSType) { 9047 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9048 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9049 9050 QualType lhptee, rhptee; 9051 9052 // get the "pointed to" type (ignoring qualifiers at the top level) 9053 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9054 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9055 9056 // In C++, the types have to match exactly. 9057 if (S.getLangOpts().CPlusPlus) 9058 return Sema::IncompatibleBlockPointer; 9059 9060 Sema::AssignConvertType ConvTy = Sema::Compatible; 9061 9062 // For blocks we enforce that qualifiers are identical. 9063 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9064 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9065 if (S.getLangOpts().OpenCL) { 9066 LQuals.removeAddressSpace(); 9067 RQuals.removeAddressSpace(); 9068 } 9069 if (LQuals != RQuals) 9070 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9071 9072 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9073 // assignment. 9074 // The current behavior is similar to C++ lambdas. A block might be 9075 // assigned to a variable iff its return type and parameters are compatible 9076 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9077 // an assignment. Presumably it should behave in way that a function pointer 9078 // assignment does in C, so for each parameter and return type: 9079 // * CVR and address space of LHS should be a superset of CVR and address 9080 // space of RHS. 9081 // * unqualified types should be compatible. 9082 if (S.getLangOpts().OpenCL) { 9083 if (!S.Context.typesAreBlockPointerCompatible( 9084 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9085 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9086 return Sema::IncompatibleBlockPointer; 9087 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9088 return Sema::IncompatibleBlockPointer; 9089 9090 return ConvTy; 9091 } 9092 9093 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9094 /// for assignment compatibility. 9095 static Sema::AssignConvertType 9096 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9097 QualType RHSType) { 9098 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9099 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9100 9101 if (LHSType->isObjCBuiltinType()) { 9102 // Class is not compatible with ObjC object pointers. 9103 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9104 !RHSType->isObjCQualifiedClassType()) 9105 return Sema::IncompatiblePointer; 9106 return Sema::Compatible; 9107 } 9108 if (RHSType->isObjCBuiltinType()) { 9109 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9110 !LHSType->isObjCQualifiedClassType()) 9111 return Sema::IncompatiblePointer; 9112 return Sema::Compatible; 9113 } 9114 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9115 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9116 9117 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9118 // make an exception for id<P> 9119 !LHSType->isObjCQualifiedIdType()) 9120 return Sema::CompatiblePointerDiscardsQualifiers; 9121 9122 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9123 return Sema::Compatible; 9124 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9125 return Sema::IncompatibleObjCQualifiedId; 9126 return Sema::IncompatiblePointer; 9127 } 9128 9129 Sema::AssignConvertType 9130 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9131 QualType LHSType, QualType RHSType) { 9132 // Fake up an opaque expression. We don't actually care about what 9133 // cast operations are required, so if CheckAssignmentConstraints 9134 // adds casts to this they'll be wasted, but fortunately that doesn't 9135 // usually happen on valid code. 9136 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9137 ExprResult RHSPtr = &RHSExpr; 9138 CastKind K; 9139 9140 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9141 } 9142 9143 /// This helper function returns true if QT is a vector type that has element 9144 /// type ElementType. 9145 static bool isVector(QualType QT, QualType ElementType) { 9146 if (const VectorType *VT = QT->getAs<VectorType>()) 9147 return VT->getElementType().getCanonicalType() == ElementType; 9148 return false; 9149 } 9150 9151 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9152 /// has code to accommodate several GCC extensions when type checking 9153 /// pointers. Here are some objectionable examples that GCC considers warnings: 9154 /// 9155 /// int a, *pint; 9156 /// short *pshort; 9157 /// struct foo *pfoo; 9158 /// 9159 /// pint = pshort; // warning: assignment from incompatible pointer type 9160 /// a = pint; // warning: assignment makes integer from pointer without a cast 9161 /// pint = a; // warning: assignment makes pointer from integer without a cast 9162 /// pint = pfoo; // warning: assignment from incompatible pointer type 9163 /// 9164 /// As a result, the code for dealing with pointers is more complex than the 9165 /// C99 spec dictates. 9166 /// 9167 /// Sets 'Kind' for any result kind except Incompatible. 9168 Sema::AssignConvertType 9169 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9170 CastKind &Kind, bool ConvertRHS) { 9171 QualType RHSType = RHS.get()->getType(); 9172 QualType OrigLHSType = LHSType; 9173 9174 // Get canonical types. We're not formatting these types, just comparing 9175 // them. 9176 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9177 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9178 9179 // Common case: no conversion required. 9180 if (LHSType == RHSType) { 9181 Kind = CK_NoOp; 9182 return Compatible; 9183 } 9184 9185 // If we have an atomic type, try a non-atomic assignment, then just add an 9186 // atomic qualification step. 9187 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9188 Sema::AssignConvertType result = 9189 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9190 if (result != Compatible) 9191 return result; 9192 if (Kind != CK_NoOp && ConvertRHS) 9193 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9194 Kind = CK_NonAtomicToAtomic; 9195 return Compatible; 9196 } 9197 9198 // If the left-hand side is a reference type, then we are in a 9199 // (rare!) case where we've allowed the use of references in C, 9200 // e.g., as a parameter type in a built-in function. In this case, 9201 // just make sure that the type referenced is compatible with the 9202 // right-hand side type. The caller is responsible for adjusting 9203 // LHSType so that the resulting expression does not have reference 9204 // type. 9205 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9206 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9207 Kind = CK_LValueBitCast; 9208 return Compatible; 9209 } 9210 return Incompatible; 9211 } 9212 9213 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9214 // to the same ExtVector type. 9215 if (LHSType->isExtVectorType()) { 9216 if (RHSType->isExtVectorType()) 9217 return Incompatible; 9218 if (RHSType->isArithmeticType()) { 9219 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9220 if (ConvertRHS) 9221 RHS = prepareVectorSplat(LHSType, RHS.get()); 9222 Kind = CK_VectorSplat; 9223 return Compatible; 9224 } 9225 } 9226 9227 // Conversions to or from vector type. 9228 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9229 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9230 // Allow assignments of an AltiVec vector type to an equivalent GCC 9231 // vector type and vice versa 9232 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9233 Kind = CK_BitCast; 9234 return Compatible; 9235 } 9236 9237 // If we are allowing lax vector conversions, and LHS and RHS are both 9238 // vectors, the total size only needs to be the same. This is a bitcast; 9239 // no bits are changed but the result type is different. 9240 if (isLaxVectorConversion(RHSType, LHSType)) { 9241 Kind = CK_BitCast; 9242 return IncompatibleVectors; 9243 } 9244 } 9245 9246 // When the RHS comes from another lax conversion (e.g. binops between 9247 // scalars and vectors) the result is canonicalized as a vector. When the 9248 // LHS is also a vector, the lax is allowed by the condition above. Handle 9249 // the case where LHS is a scalar. 9250 if (LHSType->isScalarType()) { 9251 const VectorType *VecType = RHSType->getAs<VectorType>(); 9252 if (VecType && VecType->getNumElements() == 1 && 9253 isLaxVectorConversion(RHSType, LHSType)) { 9254 ExprResult *VecExpr = &RHS; 9255 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9256 Kind = CK_BitCast; 9257 return Compatible; 9258 } 9259 } 9260 9261 // Allow assignments between fixed-length and sizeless SVE vectors. 9262 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9263 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9264 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9265 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9266 Kind = CK_BitCast; 9267 return Compatible; 9268 } 9269 9270 return Incompatible; 9271 } 9272 9273 // Diagnose attempts to convert between __float128 and long double where 9274 // such conversions currently can't be handled. 9275 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9276 return Incompatible; 9277 9278 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9279 // discards the imaginary part. 9280 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9281 !LHSType->getAs<ComplexType>()) 9282 return Incompatible; 9283 9284 // Arithmetic conversions. 9285 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9286 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9287 if (ConvertRHS) 9288 Kind = PrepareScalarCast(RHS, LHSType); 9289 return Compatible; 9290 } 9291 9292 // Conversions to normal pointers. 9293 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9294 // U* -> T* 9295 if (isa<PointerType>(RHSType)) { 9296 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9297 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9298 if (AddrSpaceL != AddrSpaceR) 9299 Kind = CK_AddressSpaceConversion; 9300 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9301 Kind = CK_NoOp; 9302 else 9303 Kind = CK_BitCast; 9304 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9305 } 9306 9307 // int -> T* 9308 if (RHSType->isIntegerType()) { 9309 Kind = CK_IntegralToPointer; // FIXME: null? 9310 return IntToPointer; 9311 } 9312 9313 // C pointers are not compatible with ObjC object pointers, 9314 // with two exceptions: 9315 if (isa<ObjCObjectPointerType>(RHSType)) { 9316 // - conversions to void* 9317 if (LHSPointer->getPointeeType()->isVoidType()) { 9318 Kind = CK_BitCast; 9319 return Compatible; 9320 } 9321 9322 // - conversions from 'Class' to the redefinition type 9323 if (RHSType->isObjCClassType() && 9324 Context.hasSameType(LHSType, 9325 Context.getObjCClassRedefinitionType())) { 9326 Kind = CK_BitCast; 9327 return Compatible; 9328 } 9329 9330 Kind = CK_BitCast; 9331 return IncompatiblePointer; 9332 } 9333 9334 // U^ -> void* 9335 if (RHSType->getAs<BlockPointerType>()) { 9336 if (LHSPointer->getPointeeType()->isVoidType()) { 9337 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9338 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9339 ->getPointeeType() 9340 .getAddressSpace(); 9341 Kind = 9342 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9343 return Compatible; 9344 } 9345 } 9346 9347 return Incompatible; 9348 } 9349 9350 // Conversions to block pointers. 9351 if (isa<BlockPointerType>(LHSType)) { 9352 // U^ -> T^ 9353 if (RHSType->isBlockPointerType()) { 9354 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9355 ->getPointeeType() 9356 .getAddressSpace(); 9357 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9358 ->getPointeeType() 9359 .getAddressSpace(); 9360 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9361 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9362 } 9363 9364 // int or null -> T^ 9365 if (RHSType->isIntegerType()) { 9366 Kind = CK_IntegralToPointer; // FIXME: null 9367 return IntToBlockPointer; 9368 } 9369 9370 // id -> T^ 9371 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9372 Kind = CK_AnyPointerToBlockPointerCast; 9373 return Compatible; 9374 } 9375 9376 // void* -> T^ 9377 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9378 if (RHSPT->getPointeeType()->isVoidType()) { 9379 Kind = CK_AnyPointerToBlockPointerCast; 9380 return Compatible; 9381 } 9382 9383 return Incompatible; 9384 } 9385 9386 // Conversions to Objective-C pointers. 9387 if (isa<ObjCObjectPointerType>(LHSType)) { 9388 // A* -> B* 9389 if (RHSType->isObjCObjectPointerType()) { 9390 Kind = CK_BitCast; 9391 Sema::AssignConvertType result = 9392 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9393 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9394 result == Compatible && 9395 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9396 result = IncompatibleObjCWeakRef; 9397 return result; 9398 } 9399 9400 // int or null -> A* 9401 if (RHSType->isIntegerType()) { 9402 Kind = CK_IntegralToPointer; // FIXME: null 9403 return IntToPointer; 9404 } 9405 9406 // In general, C pointers are not compatible with ObjC object pointers, 9407 // with two exceptions: 9408 if (isa<PointerType>(RHSType)) { 9409 Kind = CK_CPointerToObjCPointerCast; 9410 9411 // - conversions from 'void*' 9412 if (RHSType->isVoidPointerType()) { 9413 return Compatible; 9414 } 9415 9416 // - conversions to 'Class' from its redefinition type 9417 if (LHSType->isObjCClassType() && 9418 Context.hasSameType(RHSType, 9419 Context.getObjCClassRedefinitionType())) { 9420 return Compatible; 9421 } 9422 9423 return IncompatiblePointer; 9424 } 9425 9426 // Only under strict condition T^ is compatible with an Objective-C pointer. 9427 if (RHSType->isBlockPointerType() && 9428 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9429 if (ConvertRHS) 9430 maybeExtendBlockObject(RHS); 9431 Kind = CK_BlockPointerToObjCPointerCast; 9432 return Compatible; 9433 } 9434 9435 return Incompatible; 9436 } 9437 9438 // Conversions from pointers that are not covered by the above. 9439 if (isa<PointerType>(RHSType)) { 9440 // T* -> _Bool 9441 if (LHSType == Context.BoolTy) { 9442 Kind = CK_PointerToBoolean; 9443 return Compatible; 9444 } 9445 9446 // T* -> int 9447 if (LHSType->isIntegerType()) { 9448 Kind = CK_PointerToIntegral; 9449 return PointerToInt; 9450 } 9451 9452 return Incompatible; 9453 } 9454 9455 // Conversions from Objective-C pointers that are not covered by the above. 9456 if (isa<ObjCObjectPointerType>(RHSType)) { 9457 // T* -> _Bool 9458 if (LHSType == Context.BoolTy) { 9459 Kind = CK_PointerToBoolean; 9460 return Compatible; 9461 } 9462 9463 // T* -> int 9464 if (LHSType->isIntegerType()) { 9465 Kind = CK_PointerToIntegral; 9466 return PointerToInt; 9467 } 9468 9469 return Incompatible; 9470 } 9471 9472 // struct A -> struct B 9473 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9474 if (Context.typesAreCompatible(LHSType, RHSType)) { 9475 Kind = CK_NoOp; 9476 return Compatible; 9477 } 9478 } 9479 9480 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9481 Kind = CK_IntToOCLSampler; 9482 return Compatible; 9483 } 9484 9485 return Incompatible; 9486 } 9487 9488 /// Constructs a transparent union from an expression that is 9489 /// used to initialize the transparent union. 9490 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9491 ExprResult &EResult, QualType UnionType, 9492 FieldDecl *Field) { 9493 // Build an initializer list that designates the appropriate member 9494 // of the transparent union. 9495 Expr *E = EResult.get(); 9496 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9497 E, SourceLocation()); 9498 Initializer->setType(UnionType); 9499 Initializer->setInitializedFieldInUnion(Field); 9500 9501 // Build a compound literal constructing a value of the transparent 9502 // union type from this initializer list. 9503 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9504 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9505 VK_PRValue, Initializer, false); 9506 } 9507 9508 Sema::AssignConvertType 9509 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9510 ExprResult &RHS) { 9511 QualType RHSType = RHS.get()->getType(); 9512 9513 // If the ArgType is a Union type, we want to handle a potential 9514 // transparent_union GCC extension. 9515 const RecordType *UT = ArgType->getAsUnionType(); 9516 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9517 return Incompatible; 9518 9519 // The field to initialize within the transparent union. 9520 RecordDecl *UD = UT->getDecl(); 9521 FieldDecl *InitField = nullptr; 9522 // It's compatible if the expression matches any of the fields. 9523 for (auto *it : UD->fields()) { 9524 if (it->getType()->isPointerType()) { 9525 // If the transparent union contains a pointer type, we allow: 9526 // 1) void pointer 9527 // 2) null pointer constant 9528 if (RHSType->isPointerType()) 9529 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9530 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9531 InitField = it; 9532 break; 9533 } 9534 9535 if (RHS.get()->isNullPointerConstant(Context, 9536 Expr::NPC_ValueDependentIsNull)) { 9537 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9538 CK_NullToPointer); 9539 InitField = it; 9540 break; 9541 } 9542 } 9543 9544 CastKind Kind; 9545 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9546 == Compatible) { 9547 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9548 InitField = it; 9549 break; 9550 } 9551 } 9552 9553 if (!InitField) 9554 return Incompatible; 9555 9556 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9557 return Compatible; 9558 } 9559 9560 Sema::AssignConvertType 9561 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9562 bool Diagnose, 9563 bool DiagnoseCFAudited, 9564 bool ConvertRHS) { 9565 // We need to be able to tell the caller whether we diagnosed a problem, if 9566 // they ask us to issue diagnostics. 9567 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9568 9569 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9570 // we can't avoid *all* modifications at the moment, so we need some somewhere 9571 // to put the updated value. 9572 ExprResult LocalRHS = CallerRHS; 9573 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9574 9575 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9576 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9577 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9578 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9579 Diag(RHS.get()->getExprLoc(), 9580 diag::warn_noderef_to_dereferenceable_pointer) 9581 << RHS.get()->getSourceRange(); 9582 } 9583 } 9584 } 9585 9586 if (getLangOpts().CPlusPlus) { 9587 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9588 // C++ 5.17p3: If the left operand is not of class type, the 9589 // expression is implicitly converted (C++ 4) to the 9590 // cv-unqualified type of the left operand. 9591 QualType RHSType = RHS.get()->getType(); 9592 if (Diagnose) { 9593 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9594 AA_Assigning); 9595 } else { 9596 ImplicitConversionSequence ICS = 9597 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9598 /*SuppressUserConversions=*/false, 9599 AllowedExplicit::None, 9600 /*InOverloadResolution=*/false, 9601 /*CStyle=*/false, 9602 /*AllowObjCWritebackConversion=*/false); 9603 if (ICS.isFailure()) 9604 return Incompatible; 9605 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9606 ICS, AA_Assigning); 9607 } 9608 if (RHS.isInvalid()) 9609 return Incompatible; 9610 Sema::AssignConvertType result = Compatible; 9611 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9612 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9613 result = IncompatibleObjCWeakRef; 9614 return result; 9615 } 9616 9617 // FIXME: Currently, we fall through and treat C++ classes like C 9618 // structures. 9619 // FIXME: We also fall through for atomics; not sure what should 9620 // happen there, though. 9621 } else if (RHS.get()->getType() == Context.OverloadTy) { 9622 // As a set of extensions to C, we support overloading on functions. These 9623 // functions need to be resolved here. 9624 DeclAccessPair DAP; 9625 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9626 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9627 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9628 else 9629 return Incompatible; 9630 } 9631 9632 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9633 // a null pointer constant. 9634 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9635 LHSType->isBlockPointerType()) && 9636 RHS.get()->isNullPointerConstant(Context, 9637 Expr::NPC_ValueDependentIsNull)) { 9638 if (Diagnose || ConvertRHS) { 9639 CastKind Kind; 9640 CXXCastPath Path; 9641 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9642 /*IgnoreBaseAccess=*/false, Diagnose); 9643 if (ConvertRHS) 9644 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9645 } 9646 return Compatible; 9647 } 9648 9649 // OpenCL queue_t type assignment. 9650 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9651 Context, Expr::NPC_ValueDependentIsNull)) { 9652 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9653 return Compatible; 9654 } 9655 9656 // This check seems unnatural, however it is necessary to ensure the proper 9657 // conversion of functions/arrays. If the conversion were done for all 9658 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9659 // expressions that suppress this implicit conversion (&, sizeof). 9660 // 9661 // Suppress this for references: C++ 8.5.3p5. 9662 if (!LHSType->isReferenceType()) { 9663 // FIXME: We potentially allocate here even if ConvertRHS is false. 9664 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9665 if (RHS.isInvalid()) 9666 return Incompatible; 9667 } 9668 CastKind Kind; 9669 Sema::AssignConvertType result = 9670 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9671 9672 // C99 6.5.16.1p2: The value of the right operand is converted to the 9673 // type of the assignment expression. 9674 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9675 // so that we can use references in built-in functions even in C. 9676 // The getNonReferenceType() call makes sure that the resulting expression 9677 // does not have reference type. 9678 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9679 QualType Ty = LHSType.getNonLValueExprType(Context); 9680 Expr *E = RHS.get(); 9681 9682 // Check for various Objective-C errors. If we are not reporting 9683 // diagnostics and just checking for errors, e.g., during overload 9684 // resolution, return Incompatible to indicate the failure. 9685 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9686 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9687 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9688 if (!Diagnose) 9689 return Incompatible; 9690 } 9691 if (getLangOpts().ObjC && 9692 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9693 E->getType(), E, Diagnose) || 9694 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9695 if (!Diagnose) 9696 return Incompatible; 9697 // Replace the expression with a corrected version and continue so we 9698 // can find further errors. 9699 RHS = E; 9700 return Compatible; 9701 } 9702 9703 if (ConvertRHS) 9704 RHS = ImpCastExprToType(E, Ty, Kind); 9705 } 9706 9707 return result; 9708 } 9709 9710 namespace { 9711 /// The original operand to an operator, prior to the application of the usual 9712 /// arithmetic conversions and converting the arguments of a builtin operator 9713 /// candidate. 9714 struct OriginalOperand { 9715 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9716 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9717 Op = MTE->getSubExpr(); 9718 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9719 Op = BTE->getSubExpr(); 9720 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9721 Orig = ICE->getSubExprAsWritten(); 9722 Conversion = ICE->getConversionFunction(); 9723 } 9724 } 9725 9726 QualType getType() const { return Orig->getType(); } 9727 9728 Expr *Orig; 9729 NamedDecl *Conversion; 9730 }; 9731 } 9732 9733 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9734 ExprResult &RHS) { 9735 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9736 9737 Diag(Loc, diag::err_typecheck_invalid_operands) 9738 << OrigLHS.getType() << OrigRHS.getType() 9739 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9740 9741 // If a user-defined conversion was applied to either of the operands prior 9742 // to applying the built-in operator rules, tell the user about it. 9743 if (OrigLHS.Conversion) { 9744 Diag(OrigLHS.Conversion->getLocation(), 9745 diag::note_typecheck_invalid_operands_converted) 9746 << 0 << LHS.get()->getType(); 9747 } 9748 if (OrigRHS.Conversion) { 9749 Diag(OrigRHS.Conversion->getLocation(), 9750 diag::note_typecheck_invalid_operands_converted) 9751 << 1 << RHS.get()->getType(); 9752 } 9753 9754 return QualType(); 9755 } 9756 9757 // Diagnose cases where a scalar was implicitly converted to a vector and 9758 // diagnose the underlying types. Otherwise, diagnose the error 9759 // as invalid vector logical operands for non-C++ cases. 9760 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9761 ExprResult &RHS) { 9762 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9763 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9764 9765 bool LHSNatVec = LHSType->isVectorType(); 9766 bool RHSNatVec = RHSType->isVectorType(); 9767 9768 if (!(LHSNatVec && RHSNatVec)) { 9769 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9770 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9771 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9772 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9773 << Vector->getSourceRange(); 9774 return QualType(); 9775 } 9776 9777 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9778 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9779 << RHS.get()->getSourceRange(); 9780 9781 return QualType(); 9782 } 9783 9784 /// Try to convert a value of non-vector type to a vector type by converting 9785 /// the type to the element type of the vector and then performing a splat. 9786 /// If the language is OpenCL, we only use conversions that promote scalar 9787 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9788 /// for float->int. 9789 /// 9790 /// OpenCL V2.0 6.2.6.p2: 9791 /// An error shall occur if any scalar operand type has greater rank 9792 /// than the type of the vector element. 9793 /// 9794 /// \param scalar - if non-null, actually perform the conversions 9795 /// \return true if the operation fails (but without diagnosing the failure) 9796 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9797 QualType scalarTy, 9798 QualType vectorEltTy, 9799 QualType vectorTy, 9800 unsigned &DiagID) { 9801 // The conversion to apply to the scalar before splatting it, 9802 // if necessary. 9803 CastKind scalarCast = CK_NoOp; 9804 9805 if (vectorEltTy->isIntegralType(S.Context)) { 9806 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9807 (scalarTy->isIntegerType() && 9808 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9809 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9810 return true; 9811 } 9812 if (!scalarTy->isIntegralType(S.Context)) 9813 return true; 9814 scalarCast = CK_IntegralCast; 9815 } else if (vectorEltTy->isRealFloatingType()) { 9816 if (scalarTy->isRealFloatingType()) { 9817 if (S.getLangOpts().OpenCL && 9818 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9819 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9820 return true; 9821 } 9822 scalarCast = CK_FloatingCast; 9823 } 9824 else if (scalarTy->isIntegralType(S.Context)) 9825 scalarCast = CK_IntegralToFloating; 9826 else 9827 return true; 9828 } else { 9829 return true; 9830 } 9831 9832 // Adjust scalar if desired. 9833 if (scalar) { 9834 if (scalarCast != CK_NoOp) 9835 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9836 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9837 } 9838 return false; 9839 } 9840 9841 /// Convert vector E to a vector with the same number of elements but different 9842 /// element type. 9843 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9844 const auto *VecTy = E->getType()->getAs<VectorType>(); 9845 assert(VecTy && "Expression E must be a vector"); 9846 QualType NewVecTy = S.Context.getVectorType(ElementType, 9847 VecTy->getNumElements(), 9848 VecTy->getVectorKind()); 9849 9850 // Look through the implicit cast. Return the subexpression if its type is 9851 // NewVecTy. 9852 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9853 if (ICE->getSubExpr()->getType() == NewVecTy) 9854 return ICE->getSubExpr(); 9855 9856 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9857 return S.ImpCastExprToType(E, NewVecTy, Cast); 9858 } 9859 9860 /// Test if a (constant) integer Int can be casted to another integer type 9861 /// IntTy without losing precision. 9862 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9863 QualType OtherIntTy) { 9864 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9865 9866 // Reject cases where the value of the Int is unknown as that would 9867 // possibly cause truncation, but accept cases where the scalar can be 9868 // demoted without loss of precision. 9869 Expr::EvalResult EVResult; 9870 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9871 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9872 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9873 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9874 9875 if (CstInt) { 9876 // If the scalar is constant and is of a higher order and has more active 9877 // bits that the vector element type, reject it. 9878 llvm::APSInt Result = EVResult.Val.getInt(); 9879 unsigned NumBits = IntSigned 9880 ? (Result.isNegative() ? Result.getMinSignedBits() 9881 : Result.getActiveBits()) 9882 : Result.getActiveBits(); 9883 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9884 return true; 9885 9886 // If the signedness of the scalar type and the vector element type 9887 // differs and the number of bits is greater than that of the vector 9888 // element reject it. 9889 return (IntSigned != OtherIntSigned && 9890 NumBits > S.Context.getIntWidth(OtherIntTy)); 9891 } 9892 9893 // Reject cases where the value of the scalar is not constant and it's 9894 // order is greater than that of the vector element type. 9895 return (Order < 0); 9896 } 9897 9898 /// Test if a (constant) integer Int can be casted to floating point type 9899 /// FloatTy without losing precision. 9900 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9901 QualType FloatTy) { 9902 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9903 9904 // Determine if the integer constant can be expressed as a floating point 9905 // number of the appropriate type. 9906 Expr::EvalResult EVResult; 9907 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9908 9909 uint64_t Bits = 0; 9910 if (CstInt) { 9911 // Reject constants that would be truncated if they were converted to 9912 // the floating point type. Test by simple to/from conversion. 9913 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9914 // could be avoided if there was a convertFromAPInt method 9915 // which could signal back if implicit truncation occurred. 9916 llvm::APSInt Result = EVResult.Val.getInt(); 9917 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9918 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9919 llvm::APFloat::rmTowardZero); 9920 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9921 !IntTy->hasSignedIntegerRepresentation()); 9922 bool Ignored = false; 9923 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9924 &Ignored); 9925 if (Result != ConvertBack) 9926 return true; 9927 } else { 9928 // Reject types that cannot be fully encoded into the mantissa of 9929 // the float. 9930 Bits = S.Context.getTypeSize(IntTy); 9931 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9932 S.Context.getFloatTypeSemantics(FloatTy)); 9933 if (Bits > FloatPrec) 9934 return true; 9935 } 9936 9937 return false; 9938 } 9939 9940 /// Attempt to convert and splat Scalar into a vector whose types matches 9941 /// Vector following GCC conversion rules. The rule is that implicit 9942 /// conversion can occur when Scalar can be casted to match Vector's element 9943 /// type without causing truncation of Scalar. 9944 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9945 ExprResult *Vector) { 9946 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9947 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9948 const VectorType *VT = VectorTy->getAs<VectorType>(); 9949 9950 assert(!isa<ExtVectorType>(VT) && 9951 "ExtVectorTypes should not be handled here!"); 9952 9953 QualType VectorEltTy = VT->getElementType(); 9954 9955 // Reject cases where the vector element type or the scalar element type are 9956 // not integral or floating point types. 9957 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9958 return true; 9959 9960 // The conversion to apply to the scalar before splatting it, 9961 // if necessary. 9962 CastKind ScalarCast = CK_NoOp; 9963 9964 // Accept cases where the vector elements are integers and the scalar is 9965 // an integer. 9966 // FIXME: Notionally if the scalar was a floating point value with a precise 9967 // integral representation, we could cast it to an appropriate integer 9968 // type and then perform the rest of the checks here. GCC will perform 9969 // this conversion in some cases as determined by the input language. 9970 // We should accept it on a language independent basis. 9971 if (VectorEltTy->isIntegralType(S.Context) && 9972 ScalarTy->isIntegralType(S.Context) && 9973 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9974 9975 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9976 return true; 9977 9978 ScalarCast = CK_IntegralCast; 9979 } else if (VectorEltTy->isIntegralType(S.Context) && 9980 ScalarTy->isRealFloatingType()) { 9981 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9982 ScalarCast = CK_FloatingToIntegral; 9983 else 9984 return true; 9985 } else if (VectorEltTy->isRealFloatingType()) { 9986 if (ScalarTy->isRealFloatingType()) { 9987 9988 // Reject cases where the scalar type is not a constant and has a higher 9989 // Order than the vector element type. 9990 llvm::APFloat Result(0.0); 9991 9992 // Determine whether this is a constant scalar. In the event that the 9993 // value is dependent (and thus cannot be evaluated by the constant 9994 // evaluator), skip the evaluation. This will then diagnose once the 9995 // expression is instantiated. 9996 bool CstScalar = Scalar->get()->isValueDependent() || 9997 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9998 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9999 if (!CstScalar && Order < 0) 10000 return true; 10001 10002 // If the scalar cannot be safely casted to the vector element type, 10003 // reject it. 10004 if (CstScalar) { 10005 bool Truncated = false; 10006 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10007 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10008 if (Truncated) 10009 return true; 10010 } 10011 10012 ScalarCast = CK_FloatingCast; 10013 } else if (ScalarTy->isIntegralType(S.Context)) { 10014 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10015 return true; 10016 10017 ScalarCast = CK_IntegralToFloating; 10018 } else 10019 return true; 10020 } else if (ScalarTy->isEnumeralType()) 10021 return true; 10022 10023 // Adjust scalar if desired. 10024 if (Scalar) { 10025 if (ScalarCast != CK_NoOp) 10026 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10027 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10028 } 10029 return false; 10030 } 10031 10032 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10033 SourceLocation Loc, bool IsCompAssign, 10034 bool AllowBothBool, 10035 bool AllowBoolConversions) { 10036 if (!IsCompAssign) { 10037 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10038 if (LHS.isInvalid()) 10039 return QualType(); 10040 } 10041 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10042 if (RHS.isInvalid()) 10043 return QualType(); 10044 10045 // For conversion purposes, we ignore any qualifiers. 10046 // For example, "const float" and "float" are equivalent. 10047 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10048 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10049 10050 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10051 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10052 assert(LHSVecType || RHSVecType); 10053 10054 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10055 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10056 return InvalidOperands(Loc, LHS, RHS); 10057 10058 // AltiVec-style "vector bool op vector bool" combinations are allowed 10059 // for some operators but not others. 10060 if (!AllowBothBool && 10061 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10062 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10063 return InvalidOperands(Loc, LHS, RHS); 10064 10065 // If the vector types are identical, return. 10066 if (Context.hasSameType(LHSType, RHSType)) 10067 return LHSType; 10068 10069 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10070 if (LHSVecType && RHSVecType && 10071 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10072 if (isa<ExtVectorType>(LHSVecType)) { 10073 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10074 return LHSType; 10075 } 10076 10077 if (!IsCompAssign) 10078 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10079 return RHSType; 10080 } 10081 10082 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10083 // can be mixed, with the result being the non-bool type. The non-bool 10084 // operand must have integer element type. 10085 if (AllowBoolConversions && LHSVecType && RHSVecType && 10086 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10087 (Context.getTypeSize(LHSVecType->getElementType()) == 10088 Context.getTypeSize(RHSVecType->getElementType()))) { 10089 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10090 LHSVecType->getElementType()->isIntegerType() && 10091 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10092 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10093 return LHSType; 10094 } 10095 if (!IsCompAssign && 10096 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10097 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10098 RHSVecType->getElementType()->isIntegerType()) { 10099 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10100 return RHSType; 10101 } 10102 } 10103 10104 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10105 // since the ambiguity can affect the ABI. 10106 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10107 const VectorType *VecType = SecondType->getAs<VectorType>(); 10108 return FirstType->isSizelessBuiltinType() && VecType && 10109 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10110 VecType->getVectorKind() == 10111 VectorType::SveFixedLengthPredicateVector); 10112 }; 10113 10114 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10115 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10116 return QualType(); 10117 } 10118 10119 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10120 // since the ambiguity can affect the ABI. 10121 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10122 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10123 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10124 10125 if (FirstVecType && SecondVecType) 10126 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10127 (SecondVecType->getVectorKind() == 10128 VectorType::SveFixedLengthDataVector || 10129 SecondVecType->getVectorKind() == 10130 VectorType::SveFixedLengthPredicateVector); 10131 10132 return FirstType->isSizelessBuiltinType() && SecondVecType && 10133 SecondVecType->getVectorKind() == VectorType::GenericVector; 10134 }; 10135 10136 if (IsSveGnuConversion(LHSType, RHSType) || 10137 IsSveGnuConversion(RHSType, LHSType)) { 10138 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10139 return QualType(); 10140 } 10141 10142 // If there's a vector type and a scalar, try to convert the scalar to 10143 // the vector element type and splat. 10144 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10145 if (!RHSVecType) { 10146 if (isa<ExtVectorType>(LHSVecType)) { 10147 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10148 LHSVecType->getElementType(), LHSType, 10149 DiagID)) 10150 return LHSType; 10151 } else { 10152 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10153 return LHSType; 10154 } 10155 } 10156 if (!LHSVecType) { 10157 if (isa<ExtVectorType>(RHSVecType)) { 10158 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10159 LHSType, RHSVecType->getElementType(), 10160 RHSType, DiagID)) 10161 return RHSType; 10162 } else { 10163 if (LHS.get()->getValueKind() == VK_LValue || 10164 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10165 return RHSType; 10166 } 10167 } 10168 10169 // FIXME: The code below also handles conversion between vectors and 10170 // non-scalars, we should break this down into fine grained specific checks 10171 // and emit proper diagnostics. 10172 QualType VecType = LHSVecType ? LHSType : RHSType; 10173 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10174 QualType OtherType = LHSVecType ? RHSType : LHSType; 10175 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10176 if (isLaxVectorConversion(OtherType, VecType)) { 10177 // If we're allowing lax vector conversions, only the total (data) size 10178 // needs to be the same. For non compound assignment, if one of the types is 10179 // scalar, the result is always the vector type. 10180 if (!IsCompAssign) { 10181 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10182 return VecType; 10183 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10184 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10185 // type. Note that this is already done by non-compound assignments in 10186 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10187 // <1 x T> -> T. The result is also a vector type. 10188 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10189 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10190 ExprResult *RHSExpr = &RHS; 10191 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10192 return VecType; 10193 } 10194 } 10195 10196 // Okay, the expression is invalid. 10197 10198 // If there's a non-vector, non-real operand, diagnose that. 10199 if ((!RHSVecType && !RHSType->isRealType()) || 10200 (!LHSVecType && !LHSType->isRealType())) { 10201 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10202 << LHSType << RHSType 10203 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10204 return QualType(); 10205 } 10206 10207 // OpenCL V1.1 6.2.6.p1: 10208 // If the operands are of more than one vector type, then an error shall 10209 // occur. Implicit conversions between vector types are not permitted, per 10210 // section 6.2.1. 10211 if (getLangOpts().OpenCL && 10212 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10213 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10214 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10215 << RHSType; 10216 return QualType(); 10217 } 10218 10219 10220 // If there is a vector type that is not a ExtVector and a scalar, we reach 10221 // this point if scalar could not be converted to the vector's element type 10222 // without truncation. 10223 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10224 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10225 QualType Scalar = LHSVecType ? RHSType : LHSType; 10226 QualType Vector = LHSVecType ? LHSType : RHSType; 10227 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10228 Diag(Loc, 10229 diag::err_typecheck_vector_not_convertable_implict_truncation) 10230 << ScalarOrVector << Scalar << Vector; 10231 10232 return QualType(); 10233 } 10234 10235 // Otherwise, use the generic diagnostic. 10236 Diag(Loc, DiagID) 10237 << LHSType << RHSType 10238 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10239 return QualType(); 10240 } 10241 10242 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10243 // expression. These are mainly cases where the null pointer is used as an 10244 // integer instead of a pointer. 10245 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10246 SourceLocation Loc, bool IsCompare) { 10247 // The canonical way to check for a GNU null is with isNullPointerConstant, 10248 // but we use a bit of a hack here for speed; this is a relatively 10249 // hot path, and isNullPointerConstant is slow. 10250 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10251 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10252 10253 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10254 10255 // Avoid analyzing cases where the result will either be invalid (and 10256 // diagnosed as such) or entirely valid and not something to warn about. 10257 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10258 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10259 return; 10260 10261 // Comparison operations would not make sense with a null pointer no matter 10262 // what the other expression is. 10263 if (!IsCompare) { 10264 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10265 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10266 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10267 return; 10268 } 10269 10270 // The rest of the operations only make sense with a null pointer 10271 // if the other expression is a pointer. 10272 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10273 NonNullType->canDecayToPointerType()) 10274 return; 10275 10276 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10277 << LHSNull /* LHS is NULL */ << NonNullType 10278 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10279 } 10280 10281 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10282 SourceLocation Loc) { 10283 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10284 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10285 if (!LUE || !RUE) 10286 return; 10287 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10288 RUE->getKind() != UETT_SizeOf) 10289 return; 10290 10291 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10292 QualType LHSTy = LHSArg->getType(); 10293 QualType RHSTy; 10294 10295 if (RUE->isArgumentType()) 10296 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10297 else 10298 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10299 10300 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10301 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10302 return; 10303 10304 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10305 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10306 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10307 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10308 << LHSArgDecl; 10309 } 10310 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10311 QualType ArrayElemTy = ArrayTy->getElementType(); 10312 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10313 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10314 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10315 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10316 return; 10317 S.Diag(Loc, diag::warn_division_sizeof_array) 10318 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10319 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10320 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10321 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10322 << LHSArgDecl; 10323 } 10324 10325 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10326 } 10327 } 10328 10329 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10330 ExprResult &RHS, 10331 SourceLocation Loc, bool IsDiv) { 10332 // Check for division/remainder by zero. 10333 Expr::EvalResult RHSValue; 10334 if (!RHS.get()->isValueDependent() && 10335 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10336 RHSValue.Val.getInt() == 0) 10337 S.DiagRuntimeBehavior(Loc, RHS.get(), 10338 S.PDiag(diag::warn_remainder_division_by_zero) 10339 << IsDiv << RHS.get()->getSourceRange()); 10340 } 10341 10342 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10343 SourceLocation Loc, 10344 bool IsCompAssign, bool IsDiv) { 10345 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10346 10347 QualType LHSTy = LHS.get()->getType(); 10348 QualType RHSTy = RHS.get()->getType(); 10349 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10350 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10351 /*AllowBothBool*/getLangOpts().AltiVec, 10352 /*AllowBoolConversions*/false); 10353 if (!IsDiv && 10354 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10355 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10356 // For division, only matrix-by-scalar is supported. Other combinations with 10357 // matrix types are invalid. 10358 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10359 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10360 10361 QualType compType = UsualArithmeticConversions( 10362 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10363 if (LHS.isInvalid() || RHS.isInvalid()) 10364 return QualType(); 10365 10366 10367 if (compType.isNull() || !compType->isArithmeticType()) 10368 return InvalidOperands(Loc, LHS, RHS); 10369 if (IsDiv) { 10370 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10371 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10372 } 10373 return compType; 10374 } 10375 10376 QualType Sema::CheckRemainderOperands( 10377 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10378 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10379 10380 if (LHS.get()->getType()->isVectorType() || 10381 RHS.get()->getType()->isVectorType()) { 10382 if (LHS.get()->getType()->hasIntegerRepresentation() && 10383 RHS.get()->getType()->hasIntegerRepresentation()) 10384 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10385 /*AllowBothBool*/getLangOpts().AltiVec, 10386 /*AllowBoolConversions*/false); 10387 return InvalidOperands(Loc, LHS, RHS); 10388 } 10389 10390 QualType compType = UsualArithmeticConversions( 10391 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10392 if (LHS.isInvalid() || RHS.isInvalid()) 10393 return QualType(); 10394 10395 if (compType.isNull() || !compType->isIntegerType()) 10396 return InvalidOperands(Loc, LHS, RHS); 10397 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10398 return compType; 10399 } 10400 10401 /// Diagnose invalid arithmetic on two void pointers. 10402 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10403 Expr *LHSExpr, Expr *RHSExpr) { 10404 S.Diag(Loc, S.getLangOpts().CPlusPlus 10405 ? diag::err_typecheck_pointer_arith_void_type 10406 : diag::ext_gnu_void_ptr) 10407 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10408 << RHSExpr->getSourceRange(); 10409 } 10410 10411 /// Diagnose invalid arithmetic on a void pointer. 10412 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10413 Expr *Pointer) { 10414 S.Diag(Loc, S.getLangOpts().CPlusPlus 10415 ? diag::err_typecheck_pointer_arith_void_type 10416 : diag::ext_gnu_void_ptr) 10417 << 0 /* one pointer */ << Pointer->getSourceRange(); 10418 } 10419 10420 /// Diagnose invalid arithmetic on a null pointer. 10421 /// 10422 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10423 /// idiom, which we recognize as a GNU extension. 10424 /// 10425 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10426 Expr *Pointer, bool IsGNUIdiom) { 10427 if (IsGNUIdiom) 10428 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10429 << Pointer->getSourceRange(); 10430 else 10431 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10432 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10433 } 10434 10435 /// Diagnose invalid subraction on a null pointer. 10436 /// 10437 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10438 Expr *Pointer, bool BothNull) { 10439 // Null - null is valid in C++ [expr.add]p7 10440 if (BothNull && S.getLangOpts().CPlusPlus) 10441 return; 10442 10443 // Is this s a macro from a system header? 10444 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10445 return; 10446 10447 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10448 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10449 } 10450 10451 /// Diagnose invalid arithmetic on two function pointers. 10452 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10453 Expr *LHS, Expr *RHS) { 10454 assert(LHS->getType()->isAnyPointerType()); 10455 assert(RHS->getType()->isAnyPointerType()); 10456 S.Diag(Loc, S.getLangOpts().CPlusPlus 10457 ? diag::err_typecheck_pointer_arith_function_type 10458 : diag::ext_gnu_ptr_func_arith) 10459 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10460 // We only show the second type if it differs from the first. 10461 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10462 RHS->getType()) 10463 << RHS->getType()->getPointeeType() 10464 << LHS->getSourceRange() << RHS->getSourceRange(); 10465 } 10466 10467 /// Diagnose invalid arithmetic on a function pointer. 10468 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10469 Expr *Pointer) { 10470 assert(Pointer->getType()->isAnyPointerType()); 10471 S.Diag(Loc, S.getLangOpts().CPlusPlus 10472 ? diag::err_typecheck_pointer_arith_function_type 10473 : diag::ext_gnu_ptr_func_arith) 10474 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10475 << 0 /* one pointer, so only one type */ 10476 << Pointer->getSourceRange(); 10477 } 10478 10479 /// Emit error if Operand is incomplete pointer type 10480 /// 10481 /// \returns True if pointer has incomplete type 10482 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10483 Expr *Operand) { 10484 QualType ResType = Operand->getType(); 10485 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10486 ResType = ResAtomicType->getValueType(); 10487 10488 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10489 QualType PointeeTy = ResType->getPointeeType(); 10490 return S.RequireCompleteSizedType( 10491 Loc, PointeeTy, 10492 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10493 Operand->getSourceRange()); 10494 } 10495 10496 /// Check the validity of an arithmetic pointer operand. 10497 /// 10498 /// If the operand has pointer type, this code will check for pointer types 10499 /// which are invalid in arithmetic operations. These will be diagnosed 10500 /// appropriately, including whether or not the use is supported as an 10501 /// extension. 10502 /// 10503 /// \returns True when the operand is valid to use (even if as an extension). 10504 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10505 Expr *Operand) { 10506 QualType ResType = Operand->getType(); 10507 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10508 ResType = ResAtomicType->getValueType(); 10509 10510 if (!ResType->isAnyPointerType()) return true; 10511 10512 QualType PointeeTy = ResType->getPointeeType(); 10513 if (PointeeTy->isVoidType()) { 10514 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10515 return !S.getLangOpts().CPlusPlus; 10516 } 10517 if (PointeeTy->isFunctionType()) { 10518 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10519 return !S.getLangOpts().CPlusPlus; 10520 } 10521 10522 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10523 10524 return true; 10525 } 10526 10527 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10528 /// operands. 10529 /// 10530 /// This routine will diagnose any invalid arithmetic on pointer operands much 10531 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10532 /// for emitting a single diagnostic even for operations where both LHS and RHS 10533 /// are (potentially problematic) pointers. 10534 /// 10535 /// \returns True when the operand is valid to use (even if as an extension). 10536 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10537 Expr *LHSExpr, Expr *RHSExpr) { 10538 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10539 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10540 if (!isLHSPointer && !isRHSPointer) return true; 10541 10542 QualType LHSPointeeTy, RHSPointeeTy; 10543 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10544 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10545 10546 // if both are pointers check if operation is valid wrt address spaces 10547 if (isLHSPointer && isRHSPointer) { 10548 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10549 S.Diag(Loc, 10550 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10551 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10552 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10553 return false; 10554 } 10555 } 10556 10557 // Check for arithmetic on pointers to incomplete types. 10558 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10559 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10560 if (isLHSVoidPtr || isRHSVoidPtr) { 10561 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10562 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10563 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10564 10565 return !S.getLangOpts().CPlusPlus; 10566 } 10567 10568 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10569 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10570 if (isLHSFuncPtr || isRHSFuncPtr) { 10571 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10572 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10573 RHSExpr); 10574 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10575 10576 return !S.getLangOpts().CPlusPlus; 10577 } 10578 10579 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10580 return false; 10581 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10582 return false; 10583 10584 return true; 10585 } 10586 10587 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10588 /// literal. 10589 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10590 Expr *LHSExpr, Expr *RHSExpr) { 10591 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10592 Expr* IndexExpr = RHSExpr; 10593 if (!StrExpr) { 10594 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10595 IndexExpr = LHSExpr; 10596 } 10597 10598 bool IsStringPlusInt = StrExpr && 10599 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10600 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10601 return; 10602 10603 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10604 Self.Diag(OpLoc, diag::warn_string_plus_int) 10605 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10606 10607 // Only print a fixit for "str" + int, not for int + "str". 10608 if (IndexExpr == RHSExpr) { 10609 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10610 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10611 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10612 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10613 << FixItHint::CreateInsertion(EndLoc, "]"); 10614 } else 10615 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10616 } 10617 10618 /// Emit a warning when adding a char literal to a string. 10619 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10620 Expr *LHSExpr, Expr *RHSExpr) { 10621 const Expr *StringRefExpr = LHSExpr; 10622 const CharacterLiteral *CharExpr = 10623 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10624 10625 if (!CharExpr) { 10626 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10627 StringRefExpr = RHSExpr; 10628 } 10629 10630 if (!CharExpr || !StringRefExpr) 10631 return; 10632 10633 const QualType StringType = StringRefExpr->getType(); 10634 10635 // Return if not a PointerType. 10636 if (!StringType->isAnyPointerType()) 10637 return; 10638 10639 // Return if not a CharacterType. 10640 if (!StringType->getPointeeType()->isAnyCharacterType()) 10641 return; 10642 10643 ASTContext &Ctx = Self.getASTContext(); 10644 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10645 10646 const QualType CharType = CharExpr->getType(); 10647 if (!CharType->isAnyCharacterType() && 10648 CharType->isIntegerType() && 10649 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10650 Self.Diag(OpLoc, diag::warn_string_plus_char) 10651 << DiagRange << Ctx.CharTy; 10652 } else { 10653 Self.Diag(OpLoc, diag::warn_string_plus_char) 10654 << DiagRange << CharExpr->getType(); 10655 } 10656 10657 // Only print a fixit for str + char, not for char + str. 10658 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10659 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10660 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10661 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10662 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10663 << FixItHint::CreateInsertion(EndLoc, "]"); 10664 } else { 10665 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10666 } 10667 } 10668 10669 /// Emit error when two pointers are incompatible. 10670 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10671 Expr *LHSExpr, Expr *RHSExpr) { 10672 assert(LHSExpr->getType()->isAnyPointerType()); 10673 assert(RHSExpr->getType()->isAnyPointerType()); 10674 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10675 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10676 << RHSExpr->getSourceRange(); 10677 } 10678 10679 // C99 6.5.6 10680 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10681 SourceLocation Loc, BinaryOperatorKind Opc, 10682 QualType* CompLHSTy) { 10683 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10684 10685 if (LHS.get()->getType()->isVectorType() || 10686 RHS.get()->getType()->isVectorType()) { 10687 QualType compType = CheckVectorOperands( 10688 LHS, RHS, Loc, CompLHSTy, 10689 /*AllowBothBool*/getLangOpts().AltiVec, 10690 /*AllowBoolConversions*/getLangOpts().ZVector); 10691 if (CompLHSTy) *CompLHSTy = compType; 10692 return compType; 10693 } 10694 10695 if (LHS.get()->getType()->isConstantMatrixType() || 10696 RHS.get()->getType()->isConstantMatrixType()) { 10697 QualType compType = 10698 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10699 if (CompLHSTy) 10700 *CompLHSTy = compType; 10701 return compType; 10702 } 10703 10704 QualType compType = UsualArithmeticConversions( 10705 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10706 if (LHS.isInvalid() || RHS.isInvalid()) 10707 return QualType(); 10708 10709 // Diagnose "string literal" '+' int and string '+' "char literal". 10710 if (Opc == BO_Add) { 10711 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10712 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10713 } 10714 10715 // handle the common case first (both operands are arithmetic). 10716 if (!compType.isNull() && compType->isArithmeticType()) { 10717 if (CompLHSTy) *CompLHSTy = compType; 10718 return compType; 10719 } 10720 10721 // Type-checking. Ultimately the pointer's going to be in PExp; 10722 // note that we bias towards the LHS being the pointer. 10723 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10724 10725 bool isObjCPointer; 10726 if (PExp->getType()->isPointerType()) { 10727 isObjCPointer = false; 10728 } else if (PExp->getType()->isObjCObjectPointerType()) { 10729 isObjCPointer = true; 10730 } else { 10731 std::swap(PExp, IExp); 10732 if (PExp->getType()->isPointerType()) { 10733 isObjCPointer = false; 10734 } else if (PExp->getType()->isObjCObjectPointerType()) { 10735 isObjCPointer = true; 10736 } else { 10737 return InvalidOperands(Loc, LHS, RHS); 10738 } 10739 } 10740 assert(PExp->getType()->isAnyPointerType()); 10741 10742 if (!IExp->getType()->isIntegerType()) 10743 return InvalidOperands(Loc, LHS, RHS); 10744 10745 // Adding to a null pointer results in undefined behavior. 10746 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10747 Context, Expr::NPC_ValueDependentIsNotNull)) { 10748 // In C++ adding zero to a null pointer is defined. 10749 Expr::EvalResult KnownVal; 10750 if (!getLangOpts().CPlusPlus || 10751 (!IExp->isValueDependent() && 10752 (!IExp->EvaluateAsInt(KnownVal, Context) || 10753 KnownVal.Val.getInt() != 0))) { 10754 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10755 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10756 Context, BO_Add, PExp, IExp); 10757 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10758 } 10759 } 10760 10761 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10762 return QualType(); 10763 10764 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10765 return QualType(); 10766 10767 // Check array bounds for pointer arithemtic 10768 CheckArrayAccess(PExp, IExp); 10769 10770 if (CompLHSTy) { 10771 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10772 if (LHSTy.isNull()) { 10773 LHSTy = LHS.get()->getType(); 10774 if (LHSTy->isPromotableIntegerType()) 10775 LHSTy = Context.getPromotedIntegerType(LHSTy); 10776 } 10777 *CompLHSTy = LHSTy; 10778 } 10779 10780 return PExp->getType(); 10781 } 10782 10783 // C99 6.5.6 10784 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10785 SourceLocation Loc, 10786 QualType* CompLHSTy) { 10787 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10788 10789 if (LHS.get()->getType()->isVectorType() || 10790 RHS.get()->getType()->isVectorType()) { 10791 QualType compType = CheckVectorOperands( 10792 LHS, RHS, Loc, CompLHSTy, 10793 /*AllowBothBool*/getLangOpts().AltiVec, 10794 /*AllowBoolConversions*/getLangOpts().ZVector); 10795 if (CompLHSTy) *CompLHSTy = compType; 10796 return compType; 10797 } 10798 10799 if (LHS.get()->getType()->isConstantMatrixType() || 10800 RHS.get()->getType()->isConstantMatrixType()) { 10801 QualType compType = 10802 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10803 if (CompLHSTy) 10804 *CompLHSTy = compType; 10805 return compType; 10806 } 10807 10808 QualType compType = UsualArithmeticConversions( 10809 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10810 if (LHS.isInvalid() || RHS.isInvalid()) 10811 return QualType(); 10812 10813 // Enforce type constraints: C99 6.5.6p3. 10814 10815 // Handle the common case first (both operands are arithmetic). 10816 if (!compType.isNull() && compType->isArithmeticType()) { 10817 if (CompLHSTy) *CompLHSTy = compType; 10818 return compType; 10819 } 10820 10821 // Either ptr - int or ptr - ptr. 10822 if (LHS.get()->getType()->isAnyPointerType()) { 10823 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10824 10825 // Diagnose bad cases where we step over interface counts. 10826 if (LHS.get()->getType()->isObjCObjectPointerType() && 10827 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10828 return QualType(); 10829 10830 // The result type of a pointer-int computation is the pointer type. 10831 if (RHS.get()->getType()->isIntegerType()) { 10832 // Subtracting from a null pointer should produce a warning. 10833 // The last argument to the diagnose call says this doesn't match the 10834 // GNU int-to-pointer idiom. 10835 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10836 Expr::NPC_ValueDependentIsNotNull)) { 10837 // In C++ adding zero to a null pointer is defined. 10838 Expr::EvalResult KnownVal; 10839 if (!getLangOpts().CPlusPlus || 10840 (!RHS.get()->isValueDependent() && 10841 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10842 KnownVal.Val.getInt() != 0))) { 10843 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10844 } 10845 } 10846 10847 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10848 return QualType(); 10849 10850 // Check array bounds for pointer arithemtic 10851 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10852 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10853 10854 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10855 return LHS.get()->getType(); 10856 } 10857 10858 // Handle pointer-pointer subtractions. 10859 if (const PointerType *RHSPTy 10860 = RHS.get()->getType()->getAs<PointerType>()) { 10861 QualType rpointee = RHSPTy->getPointeeType(); 10862 10863 if (getLangOpts().CPlusPlus) { 10864 // Pointee types must be the same: C++ [expr.add] 10865 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10866 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10867 } 10868 } else { 10869 // Pointee types must be compatible C99 6.5.6p3 10870 if (!Context.typesAreCompatible( 10871 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10872 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10873 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10874 return QualType(); 10875 } 10876 } 10877 10878 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10879 LHS.get(), RHS.get())) 10880 return QualType(); 10881 10882 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10883 Context, Expr::NPC_ValueDependentIsNotNull); 10884 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10885 Context, Expr::NPC_ValueDependentIsNotNull); 10886 10887 // Subtracting nullptr or from nullptr is suspect 10888 if (LHSIsNullPtr) 10889 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10890 if (RHSIsNullPtr) 10891 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10892 10893 // The pointee type may have zero size. As an extension, a structure or 10894 // union may have zero size or an array may have zero length. In this 10895 // case subtraction does not make sense. 10896 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10897 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10898 if (ElementSize.isZero()) { 10899 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10900 << rpointee.getUnqualifiedType() 10901 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10902 } 10903 } 10904 10905 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10906 return Context.getPointerDiffType(); 10907 } 10908 } 10909 10910 return InvalidOperands(Loc, LHS, RHS); 10911 } 10912 10913 static bool isScopedEnumerationType(QualType T) { 10914 if (const EnumType *ET = T->getAs<EnumType>()) 10915 return ET->getDecl()->isScoped(); 10916 return false; 10917 } 10918 10919 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10920 SourceLocation Loc, BinaryOperatorKind Opc, 10921 QualType LHSType) { 10922 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10923 // so skip remaining warnings as we don't want to modify values within Sema. 10924 if (S.getLangOpts().OpenCL) 10925 return; 10926 10927 // Check right/shifter operand 10928 Expr::EvalResult RHSResult; 10929 if (RHS.get()->isValueDependent() || 10930 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10931 return; 10932 llvm::APSInt Right = RHSResult.Val.getInt(); 10933 10934 if (Right.isNegative()) { 10935 S.DiagRuntimeBehavior(Loc, RHS.get(), 10936 S.PDiag(diag::warn_shift_negative) 10937 << RHS.get()->getSourceRange()); 10938 return; 10939 } 10940 10941 QualType LHSExprType = LHS.get()->getType(); 10942 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10943 if (LHSExprType->isExtIntType()) 10944 LeftSize = S.Context.getIntWidth(LHSExprType); 10945 else if (LHSExprType->isFixedPointType()) { 10946 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10947 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10948 } 10949 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10950 if (Right.uge(LeftBits)) { 10951 S.DiagRuntimeBehavior(Loc, RHS.get(), 10952 S.PDiag(diag::warn_shift_gt_typewidth) 10953 << RHS.get()->getSourceRange()); 10954 return; 10955 } 10956 10957 // FIXME: We probably need to handle fixed point types specially here. 10958 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10959 return; 10960 10961 // When left shifting an ICE which is signed, we can check for overflow which 10962 // according to C++ standards prior to C++2a has undefined behavior 10963 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10964 // more than the maximum value representable in the result type, so never 10965 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10966 // expression is still probably a bug.) 10967 Expr::EvalResult LHSResult; 10968 if (LHS.get()->isValueDependent() || 10969 LHSType->hasUnsignedIntegerRepresentation() || 10970 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10971 return; 10972 llvm::APSInt Left = LHSResult.Val.getInt(); 10973 10974 // If LHS does not have a signed type and non-negative value 10975 // then, the behavior is undefined before C++2a. Warn about it. 10976 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10977 !S.getLangOpts().CPlusPlus20) { 10978 S.DiagRuntimeBehavior(Loc, LHS.get(), 10979 S.PDiag(diag::warn_shift_lhs_negative) 10980 << LHS.get()->getSourceRange()); 10981 return; 10982 } 10983 10984 llvm::APInt ResultBits = 10985 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10986 if (LeftBits.uge(ResultBits)) 10987 return; 10988 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10989 Result = Result.shl(Right); 10990 10991 // Print the bit representation of the signed integer as an unsigned 10992 // hexadecimal number. 10993 SmallString<40> HexResult; 10994 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10995 10996 // If we are only missing a sign bit, this is less likely to result in actual 10997 // bugs -- if the result is cast back to an unsigned type, it will have the 10998 // expected value. Thus we place this behind a different warning that can be 10999 // turned off separately if needed. 11000 if (LeftBits == ResultBits - 1) { 11001 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11002 << HexResult << LHSType 11003 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11004 return; 11005 } 11006 11007 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11008 << HexResult.str() << Result.getMinSignedBits() << LHSType 11009 << Left.getBitWidth() << LHS.get()->getSourceRange() 11010 << RHS.get()->getSourceRange(); 11011 } 11012 11013 /// Return the resulting type when a vector is shifted 11014 /// by a scalar or vector shift amount. 11015 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11016 SourceLocation Loc, bool IsCompAssign) { 11017 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11018 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11019 !LHS.get()->getType()->isVectorType()) { 11020 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11021 << RHS.get()->getType() << LHS.get()->getType() 11022 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11023 return QualType(); 11024 } 11025 11026 if (!IsCompAssign) { 11027 LHS = S.UsualUnaryConversions(LHS.get()); 11028 if (LHS.isInvalid()) return QualType(); 11029 } 11030 11031 RHS = S.UsualUnaryConversions(RHS.get()); 11032 if (RHS.isInvalid()) return QualType(); 11033 11034 QualType LHSType = LHS.get()->getType(); 11035 // Note that LHS might be a scalar because the routine calls not only in 11036 // OpenCL case. 11037 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11038 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11039 11040 // Note that RHS might not be a vector. 11041 QualType RHSType = RHS.get()->getType(); 11042 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11043 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11044 11045 // The operands need to be integers. 11046 if (!LHSEleType->isIntegerType()) { 11047 S.Diag(Loc, diag::err_typecheck_expect_int) 11048 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11049 return QualType(); 11050 } 11051 11052 if (!RHSEleType->isIntegerType()) { 11053 S.Diag(Loc, diag::err_typecheck_expect_int) 11054 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11055 return QualType(); 11056 } 11057 11058 if (!LHSVecTy) { 11059 assert(RHSVecTy); 11060 if (IsCompAssign) 11061 return RHSType; 11062 if (LHSEleType != RHSEleType) { 11063 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11064 LHSEleType = RHSEleType; 11065 } 11066 QualType VecTy = 11067 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11068 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11069 LHSType = VecTy; 11070 } else if (RHSVecTy) { 11071 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11072 // are applied component-wise. So if RHS is a vector, then ensure 11073 // that the number of elements is the same as LHS... 11074 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11075 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11076 << LHS.get()->getType() << RHS.get()->getType() 11077 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11078 return QualType(); 11079 } 11080 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11081 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11082 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11083 if (LHSBT != RHSBT && 11084 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11085 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11086 << LHS.get()->getType() << RHS.get()->getType() 11087 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11088 } 11089 } 11090 } else { 11091 // ...else expand RHS to match the number of elements in LHS. 11092 QualType VecTy = 11093 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11094 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11095 } 11096 11097 return LHSType; 11098 } 11099 11100 // C99 6.5.7 11101 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11102 SourceLocation Loc, BinaryOperatorKind Opc, 11103 bool IsCompAssign) { 11104 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11105 11106 // Vector shifts promote their scalar inputs to vector type. 11107 if (LHS.get()->getType()->isVectorType() || 11108 RHS.get()->getType()->isVectorType()) { 11109 if (LangOpts.ZVector) { 11110 // The shift operators for the z vector extensions work basically 11111 // like general shifts, except that neither the LHS nor the RHS is 11112 // allowed to be a "vector bool". 11113 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11114 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11115 return InvalidOperands(Loc, LHS, RHS); 11116 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11117 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11118 return InvalidOperands(Loc, LHS, RHS); 11119 } 11120 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11121 } 11122 11123 // Shifts don't perform usual arithmetic conversions, they just do integer 11124 // promotions on each operand. C99 6.5.7p3 11125 11126 // For the LHS, do usual unary conversions, but then reset them away 11127 // if this is a compound assignment. 11128 ExprResult OldLHS = LHS; 11129 LHS = UsualUnaryConversions(LHS.get()); 11130 if (LHS.isInvalid()) 11131 return QualType(); 11132 QualType LHSType = LHS.get()->getType(); 11133 if (IsCompAssign) LHS = OldLHS; 11134 11135 // The RHS is simpler. 11136 RHS = UsualUnaryConversions(RHS.get()); 11137 if (RHS.isInvalid()) 11138 return QualType(); 11139 QualType RHSType = RHS.get()->getType(); 11140 11141 // C99 6.5.7p2: Each of the operands shall have integer type. 11142 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11143 if ((!LHSType->isFixedPointOrIntegerType() && 11144 !LHSType->hasIntegerRepresentation()) || 11145 !RHSType->hasIntegerRepresentation()) 11146 return InvalidOperands(Loc, LHS, RHS); 11147 11148 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11149 // hasIntegerRepresentation() above instead of this. 11150 if (isScopedEnumerationType(LHSType) || 11151 isScopedEnumerationType(RHSType)) { 11152 return InvalidOperands(Loc, LHS, RHS); 11153 } 11154 // Sanity-check shift operands 11155 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11156 11157 // "The type of the result is that of the promoted left operand." 11158 return LHSType; 11159 } 11160 11161 /// Diagnose bad pointer comparisons. 11162 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11163 ExprResult &LHS, ExprResult &RHS, 11164 bool IsError) { 11165 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11166 : diag::ext_typecheck_comparison_of_distinct_pointers) 11167 << LHS.get()->getType() << RHS.get()->getType() 11168 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11169 } 11170 11171 /// Returns false if the pointers are converted to a composite type, 11172 /// true otherwise. 11173 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11174 ExprResult &LHS, ExprResult &RHS) { 11175 // C++ [expr.rel]p2: 11176 // [...] Pointer conversions (4.10) and qualification 11177 // conversions (4.4) are performed on pointer operands (or on 11178 // a pointer operand and a null pointer constant) to bring 11179 // them to their composite pointer type. [...] 11180 // 11181 // C++ [expr.eq]p1 uses the same notion for (in)equality 11182 // comparisons of pointers. 11183 11184 QualType LHSType = LHS.get()->getType(); 11185 QualType RHSType = RHS.get()->getType(); 11186 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11187 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11188 11189 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11190 if (T.isNull()) { 11191 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11192 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11193 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11194 else 11195 S.InvalidOperands(Loc, LHS, RHS); 11196 return true; 11197 } 11198 11199 return false; 11200 } 11201 11202 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11203 ExprResult &LHS, 11204 ExprResult &RHS, 11205 bool IsError) { 11206 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11207 : diag::ext_typecheck_comparison_of_fptr_to_void) 11208 << LHS.get()->getType() << RHS.get()->getType() 11209 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11210 } 11211 11212 static bool isObjCObjectLiteral(ExprResult &E) { 11213 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11214 case Stmt::ObjCArrayLiteralClass: 11215 case Stmt::ObjCDictionaryLiteralClass: 11216 case Stmt::ObjCStringLiteralClass: 11217 case Stmt::ObjCBoxedExprClass: 11218 return true; 11219 default: 11220 // Note that ObjCBoolLiteral is NOT an object literal! 11221 return false; 11222 } 11223 } 11224 11225 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11226 const ObjCObjectPointerType *Type = 11227 LHS->getType()->getAs<ObjCObjectPointerType>(); 11228 11229 // If this is not actually an Objective-C object, bail out. 11230 if (!Type) 11231 return false; 11232 11233 // Get the LHS object's interface type. 11234 QualType InterfaceType = Type->getPointeeType(); 11235 11236 // If the RHS isn't an Objective-C object, bail out. 11237 if (!RHS->getType()->isObjCObjectPointerType()) 11238 return false; 11239 11240 // Try to find the -isEqual: method. 11241 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11242 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11243 InterfaceType, 11244 /*IsInstance=*/true); 11245 if (!Method) { 11246 if (Type->isObjCIdType()) { 11247 // For 'id', just check the global pool. 11248 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11249 /*receiverId=*/true); 11250 } else { 11251 // Check protocols. 11252 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11253 /*IsInstance=*/true); 11254 } 11255 } 11256 11257 if (!Method) 11258 return false; 11259 11260 QualType T = Method->parameters()[0]->getType(); 11261 if (!T->isObjCObjectPointerType()) 11262 return false; 11263 11264 QualType R = Method->getReturnType(); 11265 if (!R->isScalarType()) 11266 return false; 11267 11268 return true; 11269 } 11270 11271 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11272 FromE = FromE->IgnoreParenImpCasts(); 11273 switch (FromE->getStmtClass()) { 11274 default: 11275 break; 11276 case Stmt::ObjCStringLiteralClass: 11277 // "string literal" 11278 return LK_String; 11279 case Stmt::ObjCArrayLiteralClass: 11280 // "array literal" 11281 return LK_Array; 11282 case Stmt::ObjCDictionaryLiteralClass: 11283 // "dictionary literal" 11284 return LK_Dictionary; 11285 case Stmt::BlockExprClass: 11286 return LK_Block; 11287 case Stmt::ObjCBoxedExprClass: { 11288 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11289 switch (Inner->getStmtClass()) { 11290 case Stmt::IntegerLiteralClass: 11291 case Stmt::FloatingLiteralClass: 11292 case Stmt::CharacterLiteralClass: 11293 case Stmt::ObjCBoolLiteralExprClass: 11294 case Stmt::CXXBoolLiteralExprClass: 11295 // "numeric literal" 11296 return LK_Numeric; 11297 case Stmt::ImplicitCastExprClass: { 11298 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11299 // Boolean literals can be represented by implicit casts. 11300 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11301 return LK_Numeric; 11302 break; 11303 } 11304 default: 11305 break; 11306 } 11307 return LK_Boxed; 11308 } 11309 } 11310 return LK_None; 11311 } 11312 11313 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11314 ExprResult &LHS, ExprResult &RHS, 11315 BinaryOperator::Opcode Opc){ 11316 Expr *Literal; 11317 Expr *Other; 11318 if (isObjCObjectLiteral(LHS)) { 11319 Literal = LHS.get(); 11320 Other = RHS.get(); 11321 } else { 11322 Literal = RHS.get(); 11323 Other = LHS.get(); 11324 } 11325 11326 // Don't warn on comparisons against nil. 11327 Other = Other->IgnoreParenCasts(); 11328 if (Other->isNullPointerConstant(S.getASTContext(), 11329 Expr::NPC_ValueDependentIsNotNull)) 11330 return; 11331 11332 // This should be kept in sync with warn_objc_literal_comparison. 11333 // LK_String should always be after the other literals, since it has its own 11334 // warning flag. 11335 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11336 assert(LiteralKind != Sema::LK_Block); 11337 if (LiteralKind == Sema::LK_None) { 11338 llvm_unreachable("Unknown Objective-C object literal kind"); 11339 } 11340 11341 if (LiteralKind == Sema::LK_String) 11342 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11343 << Literal->getSourceRange(); 11344 else 11345 S.Diag(Loc, diag::warn_objc_literal_comparison) 11346 << LiteralKind << Literal->getSourceRange(); 11347 11348 if (BinaryOperator::isEqualityOp(Opc) && 11349 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11350 SourceLocation Start = LHS.get()->getBeginLoc(); 11351 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11352 CharSourceRange OpRange = 11353 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11354 11355 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11356 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11357 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11358 << FixItHint::CreateInsertion(End, "]"); 11359 } 11360 } 11361 11362 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11363 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11364 ExprResult &RHS, SourceLocation Loc, 11365 BinaryOperatorKind Opc) { 11366 // Check that left hand side is !something. 11367 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11368 if (!UO || UO->getOpcode() != UO_LNot) return; 11369 11370 // Only check if the right hand side is non-bool arithmetic type. 11371 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11372 11373 // Make sure that the something in !something is not bool. 11374 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11375 if (SubExpr->isKnownToHaveBooleanValue()) return; 11376 11377 // Emit warning. 11378 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11379 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11380 << Loc << IsBitwiseOp; 11381 11382 // First note suggest !(x < y) 11383 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11384 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11385 FirstClose = S.getLocForEndOfToken(FirstClose); 11386 if (FirstClose.isInvalid()) 11387 FirstOpen = SourceLocation(); 11388 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11389 << IsBitwiseOp 11390 << FixItHint::CreateInsertion(FirstOpen, "(") 11391 << FixItHint::CreateInsertion(FirstClose, ")"); 11392 11393 // Second note suggests (!x) < y 11394 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11395 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11396 SecondClose = S.getLocForEndOfToken(SecondClose); 11397 if (SecondClose.isInvalid()) 11398 SecondOpen = SourceLocation(); 11399 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11400 << FixItHint::CreateInsertion(SecondOpen, "(") 11401 << FixItHint::CreateInsertion(SecondClose, ")"); 11402 } 11403 11404 // Returns true if E refers to a non-weak array. 11405 static bool checkForArray(const Expr *E) { 11406 const ValueDecl *D = nullptr; 11407 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11408 D = DR->getDecl(); 11409 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11410 if (Mem->isImplicitAccess()) 11411 D = Mem->getMemberDecl(); 11412 } 11413 if (!D) 11414 return false; 11415 return D->getType()->isArrayType() && !D->isWeak(); 11416 } 11417 11418 /// Diagnose some forms of syntactically-obvious tautological comparison. 11419 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11420 Expr *LHS, Expr *RHS, 11421 BinaryOperatorKind Opc) { 11422 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11423 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11424 11425 QualType LHSType = LHS->getType(); 11426 QualType RHSType = RHS->getType(); 11427 if (LHSType->hasFloatingRepresentation() || 11428 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11429 S.inTemplateInstantiation()) 11430 return; 11431 11432 // Comparisons between two array types are ill-formed for operator<=>, so 11433 // we shouldn't emit any additional warnings about it. 11434 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11435 return; 11436 11437 // For non-floating point types, check for self-comparisons of the form 11438 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11439 // often indicate logic errors in the program. 11440 // 11441 // NOTE: Don't warn about comparison expressions resulting from macro 11442 // expansion. Also don't warn about comparisons which are only self 11443 // comparisons within a template instantiation. The warnings should catch 11444 // obvious cases in the definition of the template anyways. The idea is to 11445 // warn when the typed comparison operator will always evaluate to the same 11446 // result. 11447 11448 // Used for indexing into %select in warn_comparison_always 11449 enum { 11450 AlwaysConstant, 11451 AlwaysTrue, 11452 AlwaysFalse, 11453 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11454 }; 11455 11456 // C++2a [depr.array.comp]: 11457 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11458 // operands of array type are deprecated. 11459 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11460 RHSStripped->getType()->isArrayType()) { 11461 S.Diag(Loc, diag::warn_depr_array_comparison) 11462 << LHS->getSourceRange() << RHS->getSourceRange() 11463 << LHSStripped->getType() << RHSStripped->getType(); 11464 // Carry on to produce the tautological comparison warning, if this 11465 // expression is potentially-evaluated, we can resolve the array to a 11466 // non-weak declaration, and so on. 11467 } 11468 11469 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11470 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11471 unsigned Result; 11472 switch (Opc) { 11473 case BO_EQ: 11474 case BO_LE: 11475 case BO_GE: 11476 Result = AlwaysTrue; 11477 break; 11478 case BO_NE: 11479 case BO_LT: 11480 case BO_GT: 11481 Result = AlwaysFalse; 11482 break; 11483 case BO_Cmp: 11484 Result = AlwaysEqual; 11485 break; 11486 default: 11487 Result = AlwaysConstant; 11488 break; 11489 } 11490 S.DiagRuntimeBehavior(Loc, nullptr, 11491 S.PDiag(diag::warn_comparison_always) 11492 << 0 /*self-comparison*/ 11493 << Result); 11494 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11495 // What is it always going to evaluate to? 11496 unsigned Result; 11497 switch (Opc) { 11498 case BO_EQ: // e.g. array1 == array2 11499 Result = AlwaysFalse; 11500 break; 11501 case BO_NE: // e.g. array1 != array2 11502 Result = AlwaysTrue; 11503 break; 11504 default: // e.g. array1 <= array2 11505 // The best we can say is 'a constant' 11506 Result = AlwaysConstant; 11507 break; 11508 } 11509 S.DiagRuntimeBehavior(Loc, nullptr, 11510 S.PDiag(diag::warn_comparison_always) 11511 << 1 /*array comparison*/ 11512 << Result); 11513 } 11514 } 11515 11516 if (isa<CastExpr>(LHSStripped)) 11517 LHSStripped = LHSStripped->IgnoreParenCasts(); 11518 if (isa<CastExpr>(RHSStripped)) 11519 RHSStripped = RHSStripped->IgnoreParenCasts(); 11520 11521 // Warn about comparisons against a string constant (unless the other 11522 // operand is null); the user probably wants string comparison function. 11523 Expr *LiteralString = nullptr; 11524 Expr *LiteralStringStripped = nullptr; 11525 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11526 !RHSStripped->isNullPointerConstant(S.Context, 11527 Expr::NPC_ValueDependentIsNull)) { 11528 LiteralString = LHS; 11529 LiteralStringStripped = LHSStripped; 11530 } else if ((isa<StringLiteral>(RHSStripped) || 11531 isa<ObjCEncodeExpr>(RHSStripped)) && 11532 !LHSStripped->isNullPointerConstant(S.Context, 11533 Expr::NPC_ValueDependentIsNull)) { 11534 LiteralString = RHS; 11535 LiteralStringStripped = RHSStripped; 11536 } 11537 11538 if (LiteralString) { 11539 S.DiagRuntimeBehavior(Loc, nullptr, 11540 S.PDiag(diag::warn_stringcompare) 11541 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11542 << LiteralString->getSourceRange()); 11543 } 11544 } 11545 11546 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11547 switch (CK) { 11548 default: { 11549 #ifndef NDEBUG 11550 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11551 << "\n"; 11552 #endif 11553 llvm_unreachable("unhandled cast kind"); 11554 } 11555 case CK_UserDefinedConversion: 11556 return ICK_Identity; 11557 case CK_LValueToRValue: 11558 return ICK_Lvalue_To_Rvalue; 11559 case CK_ArrayToPointerDecay: 11560 return ICK_Array_To_Pointer; 11561 case CK_FunctionToPointerDecay: 11562 return ICK_Function_To_Pointer; 11563 case CK_IntegralCast: 11564 return ICK_Integral_Conversion; 11565 case CK_FloatingCast: 11566 return ICK_Floating_Conversion; 11567 case CK_IntegralToFloating: 11568 case CK_FloatingToIntegral: 11569 return ICK_Floating_Integral; 11570 case CK_IntegralComplexCast: 11571 case CK_FloatingComplexCast: 11572 case CK_FloatingComplexToIntegralComplex: 11573 case CK_IntegralComplexToFloatingComplex: 11574 return ICK_Complex_Conversion; 11575 case CK_FloatingComplexToReal: 11576 case CK_FloatingRealToComplex: 11577 case CK_IntegralComplexToReal: 11578 case CK_IntegralRealToComplex: 11579 return ICK_Complex_Real; 11580 } 11581 } 11582 11583 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11584 QualType FromType, 11585 SourceLocation Loc) { 11586 // Check for a narrowing implicit conversion. 11587 StandardConversionSequence SCS; 11588 SCS.setAsIdentityConversion(); 11589 SCS.setToType(0, FromType); 11590 SCS.setToType(1, ToType); 11591 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11592 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11593 11594 APValue PreNarrowingValue; 11595 QualType PreNarrowingType; 11596 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11597 PreNarrowingType, 11598 /*IgnoreFloatToIntegralConversion*/ true)) { 11599 case NK_Dependent_Narrowing: 11600 // Implicit conversion to a narrower type, but the expression is 11601 // value-dependent so we can't tell whether it's actually narrowing. 11602 case NK_Not_Narrowing: 11603 return false; 11604 11605 case NK_Constant_Narrowing: 11606 // Implicit conversion to a narrower type, and the value is not a constant 11607 // expression. 11608 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11609 << /*Constant*/ 1 11610 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11611 return true; 11612 11613 case NK_Variable_Narrowing: 11614 // Implicit conversion to a narrower type, and the value is not a constant 11615 // expression. 11616 case NK_Type_Narrowing: 11617 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11618 << /*Constant*/ 0 << FromType << ToType; 11619 // TODO: It's not a constant expression, but what if the user intended it 11620 // to be? Can we produce notes to help them figure out why it isn't? 11621 return true; 11622 } 11623 llvm_unreachable("unhandled case in switch"); 11624 } 11625 11626 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11627 ExprResult &LHS, 11628 ExprResult &RHS, 11629 SourceLocation Loc) { 11630 QualType LHSType = LHS.get()->getType(); 11631 QualType RHSType = RHS.get()->getType(); 11632 // Dig out the original argument type and expression before implicit casts 11633 // were applied. These are the types/expressions we need to check the 11634 // [expr.spaceship] requirements against. 11635 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11636 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11637 QualType LHSStrippedType = LHSStripped.get()->getType(); 11638 QualType RHSStrippedType = RHSStripped.get()->getType(); 11639 11640 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11641 // other is not, the program is ill-formed. 11642 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11643 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11644 return QualType(); 11645 } 11646 11647 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11648 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11649 RHSStrippedType->isEnumeralType(); 11650 if (NumEnumArgs == 1) { 11651 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11652 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11653 if (OtherTy->hasFloatingRepresentation()) { 11654 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11655 return QualType(); 11656 } 11657 } 11658 if (NumEnumArgs == 2) { 11659 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11660 // type E, the operator yields the result of converting the operands 11661 // to the underlying type of E and applying <=> to the converted operands. 11662 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11663 S.InvalidOperands(Loc, LHS, RHS); 11664 return QualType(); 11665 } 11666 QualType IntType = 11667 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11668 assert(IntType->isArithmeticType()); 11669 11670 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11671 // promote the boolean type, and all other promotable integer types, to 11672 // avoid this. 11673 if (IntType->isPromotableIntegerType()) 11674 IntType = S.Context.getPromotedIntegerType(IntType); 11675 11676 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11677 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11678 LHSType = RHSType = IntType; 11679 } 11680 11681 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11682 // usual arithmetic conversions are applied to the operands. 11683 QualType Type = 11684 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11685 if (LHS.isInvalid() || RHS.isInvalid()) 11686 return QualType(); 11687 if (Type.isNull()) 11688 return S.InvalidOperands(Loc, LHS, RHS); 11689 11690 Optional<ComparisonCategoryType> CCT = 11691 getComparisonCategoryForBuiltinCmp(Type); 11692 if (!CCT) 11693 return S.InvalidOperands(Loc, LHS, RHS); 11694 11695 bool HasNarrowing = checkThreeWayNarrowingConversion( 11696 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11697 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11698 RHS.get()->getBeginLoc()); 11699 if (HasNarrowing) 11700 return QualType(); 11701 11702 assert(!Type.isNull() && "composite type for <=> has not been set"); 11703 11704 return S.CheckComparisonCategoryType( 11705 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11706 } 11707 11708 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11709 ExprResult &RHS, 11710 SourceLocation Loc, 11711 BinaryOperatorKind Opc) { 11712 if (Opc == BO_Cmp) 11713 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11714 11715 // C99 6.5.8p3 / C99 6.5.9p4 11716 QualType Type = 11717 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11718 if (LHS.isInvalid() || RHS.isInvalid()) 11719 return QualType(); 11720 if (Type.isNull()) 11721 return S.InvalidOperands(Loc, LHS, RHS); 11722 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11723 11724 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11725 return S.InvalidOperands(Loc, LHS, RHS); 11726 11727 // Check for comparisons of floating point operands using != and ==. 11728 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11729 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11730 11731 // The result of comparisons is 'bool' in C++, 'int' in C. 11732 return S.Context.getLogicalOperationType(); 11733 } 11734 11735 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11736 if (!NullE.get()->getType()->isAnyPointerType()) 11737 return; 11738 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11739 if (!E.get()->getType()->isAnyPointerType() && 11740 E.get()->isNullPointerConstant(Context, 11741 Expr::NPC_ValueDependentIsNotNull) == 11742 Expr::NPCK_ZeroExpression) { 11743 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11744 if (CL->getValue() == 0) 11745 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11746 << NullValue 11747 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11748 NullValue ? "NULL" : "(void *)0"); 11749 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11750 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11751 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11752 if (T == Context.CharTy) 11753 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11754 << NullValue 11755 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11756 NullValue ? "NULL" : "(void *)0"); 11757 } 11758 } 11759 } 11760 11761 // C99 6.5.8, C++ [expr.rel] 11762 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11763 SourceLocation Loc, 11764 BinaryOperatorKind Opc) { 11765 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11766 bool IsThreeWay = Opc == BO_Cmp; 11767 bool IsOrdered = IsRelational || IsThreeWay; 11768 auto IsAnyPointerType = [](ExprResult E) { 11769 QualType Ty = E.get()->getType(); 11770 return Ty->isPointerType() || Ty->isMemberPointerType(); 11771 }; 11772 11773 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11774 // type, array-to-pointer, ..., conversions are performed on both operands to 11775 // bring them to their composite type. 11776 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11777 // any type-related checks. 11778 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11779 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11780 if (LHS.isInvalid()) 11781 return QualType(); 11782 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11783 if (RHS.isInvalid()) 11784 return QualType(); 11785 } else { 11786 LHS = DefaultLvalueConversion(LHS.get()); 11787 if (LHS.isInvalid()) 11788 return QualType(); 11789 RHS = DefaultLvalueConversion(RHS.get()); 11790 if (RHS.isInvalid()) 11791 return QualType(); 11792 } 11793 11794 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11795 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11796 CheckPtrComparisonWithNullChar(LHS, RHS); 11797 CheckPtrComparisonWithNullChar(RHS, LHS); 11798 } 11799 11800 // Handle vector comparisons separately. 11801 if (LHS.get()->getType()->isVectorType() || 11802 RHS.get()->getType()->isVectorType()) 11803 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11804 11805 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11806 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11807 11808 QualType LHSType = LHS.get()->getType(); 11809 QualType RHSType = RHS.get()->getType(); 11810 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11811 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11812 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11813 11814 const Expr::NullPointerConstantKind LHSNullKind = 11815 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11816 const Expr::NullPointerConstantKind RHSNullKind = 11817 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11818 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11819 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11820 11821 auto computeResultTy = [&]() { 11822 if (Opc != BO_Cmp) 11823 return Context.getLogicalOperationType(); 11824 assert(getLangOpts().CPlusPlus); 11825 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11826 11827 QualType CompositeTy = LHS.get()->getType(); 11828 assert(!CompositeTy->isReferenceType()); 11829 11830 Optional<ComparisonCategoryType> CCT = 11831 getComparisonCategoryForBuiltinCmp(CompositeTy); 11832 if (!CCT) 11833 return InvalidOperands(Loc, LHS, RHS); 11834 11835 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11836 // P0946R0: Comparisons between a null pointer constant and an object 11837 // pointer result in std::strong_equality, which is ill-formed under 11838 // P1959R0. 11839 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11840 << (LHSIsNull ? LHS.get()->getSourceRange() 11841 : RHS.get()->getSourceRange()); 11842 return QualType(); 11843 } 11844 11845 return CheckComparisonCategoryType( 11846 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11847 }; 11848 11849 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11850 bool IsEquality = Opc == BO_EQ; 11851 if (RHSIsNull) 11852 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11853 RHS.get()->getSourceRange()); 11854 else 11855 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11856 LHS.get()->getSourceRange()); 11857 } 11858 11859 if (IsOrdered && LHSType->isFunctionPointerType() && 11860 RHSType->isFunctionPointerType()) { 11861 // Valid unless a relational comparison of function pointers 11862 bool IsError = Opc == BO_Cmp; 11863 auto DiagID = 11864 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11865 : getLangOpts().CPlusPlus 11866 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11867 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11868 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11869 << RHS.get()->getSourceRange(); 11870 if (IsError) 11871 return QualType(); 11872 } 11873 11874 if ((LHSType->isIntegerType() && !LHSIsNull) || 11875 (RHSType->isIntegerType() && !RHSIsNull)) { 11876 // Skip normal pointer conversion checks in this case; we have better 11877 // diagnostics for this below. 11878 } else if (getLangOpts().CPlusPlus) { 11879 // Equality comparison of a function pointer to a void pointer is invalid, 11880 // but we allow it as an extension. 11881 // FIXME: If we really want to allow this, should it be part of composite 11882 // pointer type computation so it works in conditionals too? 11883 if (!IsOrdered && 11884 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11885 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11886 // This is a gcc extension compatibility comparison. 11887 // In a SFINAE context, we treat this as a hard error to maintain 11888 // conformance with the C++ standard. 11889 diagnoseFunctionPointerToVoidComparison( 11890 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11891 11892 if (isSFINAEContext()) 11893 return QualType(); 11894 11895 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11896 return computeResultTy(); 11897 } 11898 11899 // C++ [expr.eq]p2: 11900 // If at least one operand is a pointer [...] bring them to their 11901 // composite pointer type. 11902 // C++ [expr.spaceship]p6 11903 // If at least one of the operands is of pointer type, [...] bring them 11904 // to their composite pointer type. 11905 // C++ [expr.rel]p2: 11906 // If both operands are pointers, [...] bring them to their composite 11907 // pointer type. 11908 // For <=>, the only valid non-pointer types are arrays and functions, and 11909 // we already decayed those, so this is really the same as the relational 11910 // comparison rule. 11911 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11912 (IsOrdered ? 2 : 1) && 11913 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11914 RHSType->isObjCObjectPointerType()))) { 11915 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11916 return QualType(); 11917 return computeResultTy(); 11918 } 11919 } else if (LHSType->isPointerType() && 11920 RHSType->isPointerType()) { // C99 6.5.8p2 11921 // All of the following pointer-related warnings are GCC extensions, except 11922 // when handling null pointer constants. 11923 QualType LCanPointeeTy = 11924 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11925 QualType RCanPointeeTy = 11926 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11927 11928 // C99 6.5.9p2 and C99 6.5.8p2 11929 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11930 RCanPointeeTy.getUnqualifiedType())) { 11931 if (IsRelational) { 11932 // Pointers both need to point to complete or incomplete types 11933 if ((LCanPointeeTy->isIncompleteType() != 11934 RCanPointeeTy->isIncompleteType()) && 11935 !getLangOpts().C11) { 11936 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11937 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11938 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11939 << RCanPointeeTy->isIncompleteType(); 11940 } 11941 } 11942 } else if (!IsRelational && 11943 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11944 // Valid unless comparison between non-null pointer and function pointer 11945 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11946 && !LHSIsNull && !RHSIsNull) 11947 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11948 /*isError*/false); 11949 } else { 11950 // Invalid 11951 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11952 } 11953 if (LCanPointeeTy != RCanPointeeTy) { 11954 // Treat NULL constant as a special case in OpenCL. 11955 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11956 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11957 Diag(Loc, 11958 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11959 << LHSType << RHSType << 0 /* comparison */ 11960 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11961 } 11962 } 11963 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11964 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11965 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11966 : CK_BitCast; 11967 if (LHSIsNull && !RHSIsNull) 11968 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11969 else 11970 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11971 } 11972 return computeResultTy(); 11973 } 11974 11975 if (getLangOpts().CPlusPlus) { 11976 // C++ [expr.eq]p4: 11977 // Two operands of type std::nullptr_t or one operand of type 11978 // std::nullptr_t and the other a null pointer constant compare equal. 11979 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11980 if (LHSType->isNullPtrType()) { 11981 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11982 return computeResultTy(); 11983 } 11984 if (RHSType->isNullPtrType()) { 11985 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11986 return computeResultTy(); 11987 } 11988 } 11989 11990 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11991 // These aren't covered by the composite pointer type rules. 11992 if (!IsOrdered && RHSType->isNullPtrType() && 11993 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11994 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11995 return computeResultTy(); 11996 } 11997 if (!IsOrdered && LHSType->isNullPtrType() && 11998 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11999 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12000 return computeResultTy(); 12001 } 12002 12003 if (IsRelational && 12004 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12005 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12006 // HACK: Relational comparison of nullptr_t against a pointer type is 12007 // invalid per DR583, but we allow it within std::less<> and friends, 12008 // since otherwise common uses of it break. 12009 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12010 // friends to have std::nullptr_t overload candidates. 12011 DeclContext *DC = CurContext; 12012 if (isa<FunctionDecl>(DC)) 12013 DC = DC->getParent(); 12014 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12015 if (CTSD->isInStdNamespace() && 12016 llvm::StringSwitch<bool>(CTSD->getName()) 12017 .Cases("less", "less_equal", "greater", "greater_equal", true) 12018 .Default(false)) { 12019 if (RHSType->isNullPtrType()) 12020 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12021 else 12022 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12023 return computeResultTy(); 12024 } 12025 } 12026 } 12027 12028 // C++ [expr.eq]p2: 12029 // If at least one operand is a pointer to member, [...] bring them to 12030 // their composite pointer type. 12031 if (!IsOrdered && 12032 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12033 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12034 return QualType(); 12035 else 12036 return computeResultTy(); 12037 } 12038 } 12039 12040 // Handle block pointer types. 12041 if (!IsOrdered && LHSType->isBlockPointerType() && 12042 RHSType->isBlockPointerType()) { 12043 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12044 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12045 12046 if (!LHSIsNull && !RHSIsNull && 12047 !Context.typesAreCompatible(lpointee, rpointee)) { 12048 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12049 << LHSType << RHSType << LHS.get()->getSourceRange() 12050 << RHS.get()->getSourceRange(); 12051 } 12052 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12053 return computeResultTy(); 12054 } 12055 12056 // Allow block pointers to be compared with null pointer constants. 12057 if (!IsOrdered 12058 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12059 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12060 if (!LHSIsNull && !RHSIsNull) { 12061 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12062 ->getPointeeType()->isVoidType()) 12063 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12064 ->getPointeeType()->isVoidType()))) 12065 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12066 << LHSType << RHSType << LHS.get()->getSourceRange() 12067 << RHS.get()->getSourceRange(); 12068 } 12069 if (LHSIsNull && !RHSIsNull) 12070 LHS = ImpCastExprToType(LHS.get(), RHSType, 12071 RHSType->isPointerType() ? CK_BitCast 12072 : CK_AnyPointerToBlockPointerCast); 12073 else 12074 RHS = ImpCastExprToType(RHS.get(), LHSType, 12075 LHSType->isPointerType() ? CK_BitCast 12076 : CK_AnyPointerToBlockPointerCast); 12077 return computeResultTy(); 12078 } 12079 12080 if (LHSType->isObjCObjectPointerType() || 12081 RHSType->isObjCObjectPointerType()) { 12082 const PointerType *LPT = LHSType->getAs<PointerType>(); 12083 const PointerType *RPT = RHSType->getAs<PointerType>(); 12084 if (LPT || RPT) { 12085 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12086 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12087 12088 if (!LPtrToVoid && !RPtrToVoid && 12089 !Context.typesAreCompatible(LHSType, RHSType)) { 12090 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12091 /*isError*/false); 12092 } 12093 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12094 // the RHS, but we have test coverage for this behavior. 12095 // FIXME: Consider using convertPointersToCompositeType in C++. 12096 if (LHSIsNull && !RHSIsNull) { 12097 Expr *E = LHS.get(); 12098 if (getLangOpts().ObjCAutoRefCount) 12099 CheckObjCConversion(SourceRange(), RHSType, E, 12100 CCK_ImplicitConversion); 12101 LHS = ImpCastExprToType(E, RHSType, 12102 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12103 } 12104 else { 12105 Expr *E = RHS.get(); 12106 if (getLangOpts().ObjCAutoRefCount) 12107 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12108 /*Diagnose=*/true, 12109 /*DiagnoseCFAudited=*/false, Opc); 12110 RHS = ImpCastExprToType(E, LHSType, 12111 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12112 } 12113 return computeResultTy(); 12114 } 12115 if (LHSType->isObjCObjectPointerType() && 12116 RHSType->isObjCObjectPointerType()) { 12117 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12118 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12119 /*isError*/false); 12120 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12121 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12122 12123 if (LHSIsNull && !RHSIsNull) 12124 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12125 else 12126 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12127 return computeResultTy(); 12128 } 12129 12130 if (!IsOrdered && LHSType->isBlockPointerType() && 12131 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12132 LHS = ImpCastExprToType(LHS.get(), RHSType, 12133 CK_BlockPointerToObjCPointerCast); 12134 return computeResultTy(); 12135 } else if (!IsOrdered && 12136 LHSType->isBlockCompatibleObjCPointerType(Context) && 12137 RHSType->isBlockPointerType()) { 12138 RHS = ImpCastExprToType(RHS.get(), LHSType, 12139 CK_BlockPointerToObjCPointerCast); 12140 return computeResultTy(); 12141 } 12142 } 12143 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12144 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12145 unsigned DiagID = 0; 12146 bool isError = false; 12147 if (LangOpts.DebuggerSupport) { 12148 // Under a debugger, allow the comparison of pointers to integers, 12149 // since users tend to want to compare addresses. 12150 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12151 (RHSIsNull && RHSType->isIntegerType())) { 12152 if (IsOrdered) { 12153 isError = getLangOpts().CPlusPlus; 12154 DiagID = 12155 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12156 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12157 } 12158 } else if (getLangOpts().CPlusPlus) { 12159 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12160 isError = true; 12161 } else if (IsOrdered) 12162 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12163 else 12164 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12165 12166 if (DiagID) { 12167 Diag(Loc, DiagID) 12168 << LHSType << RHSType << LHS.get()->getSourceRange() 12169 << RHS.get()->getSourceRange(); 12170 if (isError) 12171 return QualType(); 12172 } 12173 12174 if (LHSType->isIntegerType()) 12175 LHS = ImpCastExprToType(LHS.get(), RHSType, 12176 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12177 else 12178 RHS = ImpCastExprToType(RHS.get(), LHSType, 12179 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12180 return computeResultTy(); 12181 } 12182 12183 // Handle block pointers. 12184 if (!IsOrdered && RHSIsNull 12185 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12186 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12187 return computeResultTy(); 12188 } 12189 if (!IsOrdered && LHSIsNull 12190 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12191 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12192 return computeResultTy(); 12193 } 12194 12195 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12196 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12197 return computeResultTy(); 12198 } 12199 12200 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12201 return computeResultTy(); 12202 } 12203 12204 if (LHSIsNull && RHSType->isQueueT()) { 12205 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12206 return computeResultTy(); 12207 } 12208 12209 if (LHSType->isQueueT() && RHSIsNull) { 12210 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12211 return computeResultTy(); 12212 } 12213 } 12214 12215 return InvalidOperands(Loc, LHS, RHS); 12216 } 12217 12218 // Return a signed ext_vector_type that is of identical size and number of 12219 // elements. For floating point vectors, return an integer type of identical 12220 // size and number of elements. In the non ext_vector_type case, search from 12221 // the largest type to the smallest type to avoid cases where long long == long, 12222 // where long gets picked over long long. 12223 QualType Sema::GetSignedVectorType(QualType V) { 12224 const VectorType *VTy = V->castAs<VectorType>(); 12225 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12226 12227 if (isa<ExtVectorType>(VTy)) { 12228 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12229 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12230 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12231 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12232 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12233 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12234 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12235 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12236 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12237 "Unhandled vector element size in vector compare"); 12238 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12239 } 12240 12241 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12242 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12243 VectorType::GenericVector); 12244 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12245 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12246 VectorType::GenericVector); 12247 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12248 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12249 VectorType::GenericVector); 12250 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12251 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12252 VectorType::GenericVector); 12253 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12254 "Unhandled vector element size in vector compare"); 12255 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12256 VectorType::GenericVector); 12257 } 12258 12259 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12260 /// operates on extended vector types. Instead of producing an IntTy result, 12261 /// like a scalar comparison, a vector comparison produces a vector of integer 12262 /// types. 12263 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12264 SourceLocation Loc, 12265 BinaryOperatorKind Opc) { 12266 if (Opc == BO_Cmp) { 12267 Diag(Loc, diag::err_three_way_vector_comparison); 12268 return QualType(); 12269 } 12270 12271 // Check to make sure we're operating on vectors of the same type and width, 12272 // Allowing one side to be a scalar of element type. 12273 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12274 /*AllowBothBool*/true, 12275 /*AllowBoolConversions*/getLangOpts().ZVector); 12276 if (vType.isNull()) 12277 return vType; 12278 12279 QualType LHSType = LHS.get()->getType(); 12280 12281 // Determine the return type of a vector compare. By default clang will return 12282 // a scalar for all vector compares except vector bool and vector pixel. 12283 // With the gcc compiler we will always return a vector type and with the xl 12284 // compiler we will always return a scalar type. This switch allows choosing 12285 // which behavior is prefered. 12286 if (getLangOpts().AltiVec) { 12287 switch (getLangOpts().getAltivecSrcCompat()) { 12288 case LangOptions::AltivecSrcCompatKind::Mixed: 12289 // If AltiVec, the comparison results in a numeric type, i.e. 12290 // bool for C++, int for C 12291 if (vType->castAs<VectorType>()->getVectorKind() == 12292 VectorType::AltiVecVector) 12293 return Context.getLogicalOperationType(); 12294 else 12295 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12296 break; 12297 case LangOptions::AltivecSrcCompatKind::GCC: 12298 // For GCC we always return the vector type. 12299 break; 12300 case LangOptions::AltivecSrcCompatKind::XL: 12301 return Context.getLogicalOperationType(); 12302 break; 12303 } 12304 } 12305 12306 // For non-floating point types, check for self-comparisons of the form 12307 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12308 // often indicate logic errors in the program. 12309 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12310 12311 // Check for comparisons of floating point operands using != and ==. 12312 if (BinaryOperator::isEqualityOp(Opc) && 12313 LHSType->hasFloatingRepresentation()) { 12314 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12315 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12316 } 12317 12318 // Return a signed type for the vector. 12319 return GetSignedVectorType(vType); 12320 } 12321 12322 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12323 const ExprResult &XorRHS, 12324 const SourceLocation Loc) { 12325 // Do not diagnose macros. 12326 if (Loc.isMacroID()) 12327 return; 12328 12329 // Do not diagnose if both LHS and RHS are macros. 12330 if (XorLHS.get()->getExprLoc().isMacroID() && 12331 XorRHS.get()->getExprLoc().isMacroID()) 12332 return; 12333 12334 bool Negative = false; 12335 bool ExplicitPlus = false; 12336 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12337 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12338 12339 if (!LHSInt) 12340 return; 12341 if (!RHSInt) { 12342 // Check negative literals. 12343 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12344 UnaryOperatorKind Opc = UO->getOpcode(); 12345 if (Opc != UO_Minus && Opc != UO_Plus) 12346 return; 12347 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12348 if (!RHSInt) 12349 return; 12350 Negative = (Opc == UO_Minus); 12351 ExplicitPlus = !Negative; 12352 } else { 12353 return; 12354 } 12355 } 12356 12357 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12358 llvm::APInt RightSideValue = RHSInt->getValue(); 12359 if (LeftSideValue != 2 && LeftSideValue != 10) 12360 return; 12361 12362 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12363 return; 12364 12365 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12366 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12367 llvm::StringRef ExprStr = 12368 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12369 12370 CharSourceRange XorRange = 12371 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12372 llvm::StringRef XorStr = 12373 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12374 // Do not diagnose if xor keyword/macro is used. 12375 if (XorStr == "xor") 12376 return; 12377 12378 std::string LHSStr = std::string(Lexer::getSourceText( 12379 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12380 S.getSourceManager(), S.getLangOpts())); 12381 std::string RHSStr = std::string(Lexer::getSourceText( 12382 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12383 S.getSourceManager(), S.getLangOpts())); 12384 12385 if (Negative) { 12386 RightSideValue = -RightSideValue; 12387 RHSStr = "-" + RHSStr; 12388 } else if (ExplicitPlus) { 12389 RHSStr = "+" + RHSStr; 12390 } 12391 12392 StringRef LHSStrRef = LHSStr; 12393 StringRef RHSStrRef = RHSStr; 12394 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12395 // literals. 12396 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12397 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12398 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12399 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12400 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12401 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12402 LHSStrRef.find('\'') != StringRef::npos || 12403 RHSStrRef.find('\'') != StringRef::npos) 12404 return; 12405 12406 bool SuggestXor = 12407 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12408 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12409 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12410 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12411 std::string SuggestedExpr = "1 << " + RHSStr; 12412 bool Overflow = false; 12413 llvm::APInt One = (LeftSideValue - 1); 12414 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12415 if (Overflow) { 12416 if (RightSideIntValue < 64) 12417 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12418 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12419 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12420 else if (RightSideIntValue == 64) 12421 S.Diag(Loc, diag::warn_xor_used_as_pow) 12422 << ExprStr << toString(XorValue, 10, true); 12423 else 12424 return; 12425 } else { 12426 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12427 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12428 << toString(PowValue, 10, true) 12429 << FixItHint::CreateReplacement( 12430 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12431 } 12432 12433 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12434 << ("0x2 ^ " + RHSStr) << SuggestXor; 12435 } else if (LeftSideValue == 10) { 12436 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12437 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12438 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12439 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12440 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12441 << ("0xA ^ " + RHSStr) << SuggestXor; 12442 } 12443 } 12444 12445 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12446 SourceLocation Loc) { 12447 // Ensure that either both operands are of the same vector type, or 12448 // one operand is of a vector type and the other is of its element type. 12449 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12450 /*AllowBothBool*/true, 12451 /*AllowBoolConversions*/false); 12452 if (vType.isNull()) 12453 return InvalidOperands(Loc, LHS, RHS); 12454 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12455 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12456 return InvalidOperands(Loc, LHS, RHS); 12457 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12458 // usage of the logical operators && and || with vectors in C. This 12459 // check could be notionally dropped. 12460 if (!getLangOpts().CPlusPlus && 12461 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12462 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12463 12464 return GetSignedVectorType(LHS.get()->getType()); 12465 } 12466 12467 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12468 SourceLocation Loc, 12469 bool IsCompAssign) { 12470 if (!IsCompAssign) { 12471 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12472 if (LHS.isInvalid()) 12473 return QualType(); 12474 } 12475 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12476 if (RHS.isInvalid()) 12477 return QualType(); 12478 12479 // For conversion purposes, we ignore any qualifiers. 12480 // For example, "const float" and "float" are equivalent. 12481 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12482 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12483 12484 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12485 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12486 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12487 12488 if (Context.hasSameType(LHSType, RHSType)) 12489 return LHSType; 12490 12491 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12492 // case we have to return InvalidOperands. 12493 ExprResult OriginalLHS = LHS; 12494 ExprResult OriginalRHS = RHS; 12495 if (LHSMatType && !RHSMatType) { 12496 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12497 if (!RHS.isInvalid()) 12498 return LHSType; 12499 12500 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12501 } 12502 12503 if (!LHSMatType && RHSMatType) { 12504 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12505 if (!LHS.isInvalid()) 12506 return RHSType; 12507 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12508 } 12509 12510 return InvalidOperands(Loc, LHS, RHS); 12511 } 12512 12513 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12514 SourceLocation Loc, 12515 bool IsCompAssign) { 12516 if (!IsCompAssign) { 12517 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12518 if (LHS.isInvalid()) 12519 return QualType(); 12520 } 12521 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12522 if (RHS.isInvalid()) 12523 return QualType(); 12524 12525 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12526 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12527 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12528 12529 if (LHSMatType && RHSMatType) { 12530 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12531 return InvalidOperands(Loc, LHS, RHS); 12532 12533 if (!Context.hasSameType(LHSMatType->getElementType(), 12534 RHSMatType->getElementType())) 12535 return InvalidOperands(Loc, LHS, RHS); 12536 12537 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12538 LHSMatType->getNumRows(), 12539 RHSMatType->getNumColumns()); 12540 } 12541 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12542 } 12543 12544 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12545 SourceLocation Loc, 12546 BinaryOperatorKind Opc) { 12547 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12548 12549 bool IsCompAssign = 12550 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12551 12552 if (LHS.get()->getType()->isVectorType() || 12553 RHS.get()->getType()->isVectorType()) { 12554 if (LHS.get()->getType()->hasIntegerRepresentation() && 12555 RHS.get()->getType()->hasIntegerRepresentation()) 12556 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12557 /*AllowBothBool*/true, 12558 /*AllowBoolConversions*/getLangOpts().ZVector); 12559 return InvalidOperands(Loc, LHS, RHS); 12560 } 12561 12562 if (Opc == BO_And) 12563 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12564 12565 if (LHS.get()->getType()->hasFloatingRepresentation() || 12566 RHS.get()->getType()->hasFloatingRepresentation()) 12567 return InvalidOperands(Loc, LHS, RHS); 12568 12569 ExprResult LHSResult = LHS, RHSResult = RHS; 12570 QualType compType = UsualArithmeticConversions( 12571 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12572 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12573 return QualType(); 12574 LHS = LHSResult.get(); 12575 RHS = RHSResult.get(); 12576 12577 if (Opc == BO_Xor) 12578 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12579 12580 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12581 return compType; 12582 return InvalidOperands(Loc, LHS, RHS); 12583 } 12584 12585 // C99 6.5.[13,14] 12586 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12587 SourceLocation Loc, 12588 BinaryOperatorKind Opc) { 12589 // Check vector operands differently. 12590 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12591 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12592 12593 bool EnumConstantInBoolContext = false; 12594 for (const ExprResult &HS : {LHS, RHS}) { 12595 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12596 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12597 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12598 EnumConstantInBoolContext = true; 12599 } 12600 } 12601 12602 if (EnumConstantInBoolContext) 12603 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12604 12605 // Diagnose cases where the user write a logical and/or but probably meant a 12606 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12607 // is a constant. 12608 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12609 !LHS.get()->getType()->isBooleanType() && 12610 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12611 // Don't warn in macros or template instantiations. 12612 !Loc.isMacroID() && !inTemplateInstantiation()) { 12613 // If the RHS can be constant folded, and if it constant folds to something 12614 // that isn't 0 or 1 (which indicate a potential logical operation that 12615 // happened to fold to true/false) then warn. 12616 // Parens on the RHS are ignored. 12617 Expr::EvalResult EVResult; 12618 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12619 llvm::APSInt Result = EVResult.Val.getInt(); 12620 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12621 !RHS.get()->getExprLoc().isMacroID()) || 12622 (Result != 0 && Result != 1)) { 12623 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12624 << RHS.get()->getSourceRange() 12625 << (Opc == BO_LAnd ? "&&" : "||"); 12626 // Suggest replacing the logical operator with the bitwise version 12627 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12628 << (Opc == BO_LAnd ? "&" : "|") 12629 << FixItHint::CreateReplacement(SourceRange( 12630 Loc, getLocForEndOfToken(Loc)), 12631 Opc == BO_LAnd ? "&" : "|"); 12632 if (Opc == BO_LAnd) 12633 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12634 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12635 << FixItHint::CreateRemoval( 12636 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12637 RHS.get()->getEndLoc())); 12638 } 12639 } 12640 } 12641 12642 if (!Context.getLangOpts().CPlusPlus) { 12643 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12644 // not operate on the built-in scalar and vector float types. 12645 if (Context.getLangOpts().OpenCL && 12646 Context.getLangOpts().OpenCLVersion < 120) { 12647 if (LHS.get()->getType()->isFloatingType() || 12648 RHS.get()->getType()->isFloatingType()) 12649 return InvalidOperands(Loc, LHS, RHS); 12650 } 12651 12652 LHS = UsualUnaryConversions(LHS.get()); 12653 if (LHS.isInvalid()) 12654 return QualType(); 12655 12656 RHS = UsualUnaryConversions(RHS.get()); 12657 if (RHS.isInvalid()) 12658 return QualType(); 12659 12660 if (!LHS.get()->getType()->isScalarType() || 12661 !RHS.get()->getType()->isScalarType()) 12662 return InvalidOperands(Loc, LHS, RHS); 12663 12664 return Context.IntTy; 12665 } 12666 12667 // The following is safe because we only use this method for 12668 // non-overloadable operands. 12669 12670 // C++ [expr.log.and]p1 12671 // C++ [expr.log.or]p1 12672 // The operands are both contextually converted to type bool. 12673 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12674 if (LHSRes.isInvalid()) 12675 return InvalidOperands(Loc, LHS, RHS); 12676 LHS = LHSRes; 12677 12678 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12679 if (RHSRes.isInvalid()) 12680 return InvalidOperands(Loc, LHS, RHS); 12681 RHS = RHSRes; 12682 12683 // C++ [expr.log.and]p2 12684 // C++ [expr.log.or]p2 12685 // The result is a bool. 12686 return Context.BoolTy; 12687 } 12688 12689 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12690 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12691 if (!ME) return false; 12692 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12693 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12694 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12695 if (!Base) return false; 12696 return Base->getMethodDecl() != nullptr; 12697 } 12698 12699 /// Is the given expression (which must be 'const') a reference to a 12700 /// variable which was originally non-const, but which has become 12701 /// 'const' due to being captured within a block? 12702 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12703 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12704 assert(E->isLValue() && E->getType().isConstQualified()); 12705 E = E->IgnoreParens(); 12706 12707 // Must be a reference to a declaration from an enclosing scope. 12708 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12709 if (!DRE) return NCCK_None; 12710 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12711 12712 // The declaration must be a variable which is not declared 'const'. 12713 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12714 if (!var) return NCCK_None; 12715 if (var->getType().isConstQualified()) return NCCK_None; 12716 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12717 12718 // Decide whether the first capture was for a block or a lambda. 12719 DeclContext *DC = S.CurContext, *Prev = nullptr; 12720 // Decide whether the first capture was for a block or a lambda. 12721 while (DC) { 12722 // For init-capture, it is possible that the variable belongs to the 12723 // template pattern of the current context. 12724 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12725 if (var->isInitCapture() && 12726 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12727 break; 12728 if (DC == var->getDeclContext()) 12729 break; 12730 Prev = DC; 12731 DC = DC->getParent(); 12732 } 12733 // Unless we have an init-capture, we've gone one step too far. 12734 if (!var->isInitCapture()) 12735 DC = Prev; 12736 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12737 } 12738 12739 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12740 Ty = Ty.getNonReferenceType(); 12741 if (IsDereference && Ty->isPointerType()) 12742 Ty = Ty->getPointeeType(); 12743 return !Ty.isConstQualified(); 12744 } 12745 12746 // Update err_typecheck_assign_const and note_typecheck_assign_const 12747 // when this enum is changed. 12748 enum { 12749 ConstFunction, 12750 ConstVariable, 12751 ConstMember, 12752 ConstMethod, 12753 NestedConstMember, 12754 ConstUnknown, // Keep as last element 12755 }; 12756 12757 /// Emit the "read-only variable not assignable" error and print notes to give 12758 /// more information about why the variable is not assignable, such as pointing 12759 /// to the declaration of a const variable, showing that a method is const, or 12760 /// that the function is returning a const reference. 12761 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12762 SourceLocation Loc) { 12763 SourceRange ExprRange = E->getSourceRange(); 12764 12765 // Only emit one error on the first const found. All other consts will emit 12766 // a note to the error. 12767 bool DiagnosticEmitted = false; 12768 12769 // Track if the current expression is the result of a dereference, and if the 12770 // next checked expression is the result of a dereference. 12771 bool IsDereference = false; 12772 bool NextIsDereference = false; 12773 12774 // Loop to process MemberExpr chains. 12775 while (true) { 12776 IsDereference = NextIsDereference; 12777 12778 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12779 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12780 NextIsDereference = ME->isArrow(); 12781 const ValueDecl *VD = ME->getMemberDecl(); 12782 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12783 // Mutable fields can be modified even if the class is const. 12784 if (Field->isMutable()) { 12785 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12786 break; 12787 } 12788 12789 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12790 if (!DiagnosticEmitted) { 12791 S.Diag(Loc, diag::err_typecheck_assign_const) 12792 << ExprRange << ConstMember << false /*static*/ << Field 12793 << Field->getType(); 12794 DiagnosticEmitted = true; 12795 } 12796 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12797 << ConstMember << false /*static*/ << Field << Field->getType() 12798 << Field->getSourceRange(); 12799 } 12800 E = ME->getBase(); 12801 continue; 12802 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12803 if (VDecl->getType().isConstQualified()) { 12804 if (!DiagnosticEmitted) { 12805 S.Diag(Loc, diag::err_typecheck_assign_const) 12806 << ExprRange << ConstMember << true /*static*/ << VDecl 12807 << VDecl->getType(); 12808 DiagnosticEmitted = true; 12809 } 12810 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12811 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12812 << VDecl->getSourceRange(); 12813 } 12814 // Static fields do not inherit constness from parents. 12815 break; 12816 } 12817 break; // End MemberExpr 12818 } else if (const ArraySubscriptExpr *ASE = 12819 dyn_cast<ArraySubscriptExpr>(E)) { 12820 E = ASE->getBase()->IgnoreParenImpCasts(); 12821 continue; 12822 } else if (const ExtVectorElementExpr *EVE = 12823 dyn_cast<ExtVectorElementExpr>(E)) { 12824 E = EVE->getBase()->IgnoreParenImpCasts(); 12825 continue; 12826 } 12827 break; 12828 } 12829 12830 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12831 // Function calls 12832 const FunctionDecl *FD = CE->getDirectCallee(); 12833 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12834 if (!DiagnosticEmitted) { 12835 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12836 << ConstFunction << FD; 12837 DiagnosticEmitted = true; 12838 } 12839 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12840 diag::note_typecheck_assign_const) 12841 << ConstFunction << FD << FD->getReturnType() 12842 << FD->getReturnTypeSourceRange(); 12843 } 12844 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12845 // Point to variable declaration. 12846 if (const ValueDecl *VD = DRE->getDecl()) { 12847 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12848 if (!DiagnosticEmitted) { 12849 S.Diag(Loc, diag::err_typecheck_assign_const) 12850 << ExprRange << ConstVariable << VD << VD->getType(); 12851 DiagnosticEmitted = true; 12852 } 12853 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12854 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12855 } 12856 } 12857 } else if (isa<CXXThisExpr>(E)) { 12858 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12859 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12860 if (MD->isConst()) { 12861 if (!DiagnosticEmitted) { 12862 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12863 << ConstMethod << MD; 12864 DiagnosticEmitted = true; 12865 } 12866 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12867 << ConstMethod << MD << MD->getSourceRange(); 12868 } 12869 } 12870 } 12871 } 12872 12873 if (DiagnosticEmitted) 12874 return; 12875 12876 // Can't determine a more specific message, so display the generic error. 12877 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12878 } 12879 12880 enum OriginalExprKind { 12881 OEK_Variable, 12882 OEK_Member, 12883 OEK_LValue 12884 }; 12885 12886 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12887 const RecordType *Ty, 12888 SourceLocation Loc, SourceRange Range, 12889 OriginalExprKind OEK, 12890 bool &DiagnosticEmitted) { 12891 std::vector<const RecordType *> RecordTypeList; 12892 RecordTypeList.push_back(Ty); 12893 unsigned NextToCheckIndex = 0; 12894 // We walk the record hierarchy breadth-first to ensure that we print 12895 // diagnostics in field nesting order. 12896 while (RecordTypeList.size() > NextToCheckIndex) { 12897 bool IsNested = NextToCheckIndex > 0; 12898 for (const FieldDecl *Field : 12899 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12900 // First, check every field for constness. 12901 QualType FieldTy = Field->getType(); 12902 if (FieldTy.isConstQualified()) { 12903 if (!DiagnosticEmitted) { 12904 S.Diag(Loc, diag::err_typecheck_assign_const) 12905 << Range << NestedConstMember << OEK << VD 12906 << IsNested << Field; 12907 DiagnosticEmitted = true; 12908 } 12909 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12910 << NestedConstMember << IsNested << Field 12911 << FieldTy << Field->getSourceRange(); 12912 } 12913 12914 // Then we append it to the list to check next in order. 12915 FieldTy = FieldTy.getCanonicalType(); 12916 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12917 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12918 RecordTypeList.push_back(FieldRecTy); 12919 } 12920 } 12921 ++NextToCheckIndex; 12922 } 12923 } 12924 12925 /// Emit an error for the case where a record we are trying to assign to has a 12926 /// const-qualified field somewhere in its hierarchy. 12927 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12928 SourceLocation Loc) { 12929 QualType Ty = E->getType(); 12930 assert(Ty->isRecordType() && "lvalue was not record?"); 12931 SourceRange Range = E->getSourceRange(); 12932 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12933 bool DiagEmitted = false; 12934 12935 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12936 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12937 Range, OEK_Member, DiagEmitted); 12938 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12939 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12940 Range, OEK_Variable, DiagEmitted); 12941 else 12942 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12943 Range, OEK_LValue, DiagEmitted); 12944 if (!DiagEmitted) 12945 DiagnoseConstAssignment(S, E, Loc); 12946 } 12947 12948 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12949 /// emit an error and return true. If so, return false. 12950 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12951 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12952 12953 S.CheckShadowingDeclModification(E, Loc); 12954 12955 SourceLocation OrigLoc = Loc; 12956 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12957 &Loc); 12958 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12959 IsLV = Expr::MLV_InvalidMessageExpression; 12960 if (IsLV == Expr::MLV_Valid) 12961 return false; 12962 12963 unsigned DiagID = 0; 12964 bool NeedType = false; 12965 switch (IsLV) { // C99 6.5.16p2 12966 case Expr::MLV_ConstQualified: 12967 // Use a specialized diagnostic when we're assigning to an object 12968 // from an enclosing function or block. 12969 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12970 if (NCCK == NCCK_Block) 12971 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12972 else 12973 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12974 break; 12975 } 12976 12977 // In ARC, use some specialized diagnostics for occasions where we 12978 // infer 'const'. These are always pseudo-strong variables. 12979 if (S.getLangOpts().ObjCAutoRefCount) { 12980 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12981 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12982 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12983 12984 // Use the normal diagnostic if it's pseudo-__strong but the 12985 // user actually wrote 'const'. 12986 if (var->isARCPseudoStrong() && 12987 (!var->getTypeSourceInfo() || 12988 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12989 // There are three pseudo-strong cases: 12990 // - self 12991 ObjCMethodDecl *method = S.getCurMethodDecl(); 12992 if (method && var == method->getSelfDecl()) { 12993 DiagID = method->isClassMethod() 12994 ? diag::err_typecheck_arc_assign_self_class_method 12995 : diag::err_typecheck_arc_assign_self; 12996 12997 // - Objective-C externally_retained attribute. 12998 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12999 isa<ParmVarDecl>(var)) { 13000 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13001 13002 // - fast enumeration variables 13003 } else { 13004 DiagID = diag::err_typecheck_arr_assign_enumeration; 13005 } 13006 13007 SourceRange Assign; 13008 if (Loc != OrigLoc) 13009 Assign = SourceRange(OrigLoc, OrigLoc); 13010 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13011 // We need to preserve the AST regardless, so migration tool 13012 // can do its job. 13013 return false; 13014 } 13015 } 13016 } 13017 13018 // If none of the special cases above are triggered, then this is a 13019 // simple const assignment. 13020 if (DiagID == 0) { 13021 DiagnoseConstAssignment(S, E, Loc); 13022 return true; 13023 } 13024 13025 break; 13026 case Expr::MLV_ConstAddrSpace: 13027 DiagnoseConstAssignment(S, E, Loc); 13028 return true; 13029 case Expr::MLV_ConstQualifiedField: 13030 DiagnoseRecursiveConstFields(S, E, Loc); 13031 return true; 13032 case Expr::MLV_ArrayType: 13033 case Expr::MLV_ArrayTemporary: 13034 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13035 NeedType = true; 13036 break; 13037 case Expr::MLV_NotObjectType: 13038 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13039 NeedType = true; 13040 break; 13041 case Expr::MLV_LValueCast: 13042 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13043 break; 13044 case Expr::MLV_Valid: 13045 llvm_unreachable("did not take early return for MLV_Valid"); 13046 case Expr::MLV_InvalidExpression: 13047 case Expr::MLV_MemberFunction: 13048 case Expr::MLV_ClassTemporary: 13049 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13050 break; 13051 case Expr::MLV_IncompleteType: 13052 case Expr::MLV_IncompleteVoidType: 13053 return S.RequireCompleteType(Loc, E->getType(), 13054 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13055 case Expr::MLV_DuplicateVectorComponents: 13056 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13057 break; 13058 case Expr::MLV_NoSetterProperty: 13059 llvm_unreachable("readonly properties should be processed differently"); 13060 case Expr::MLV_InvalidMessageExpression: 13061 DiagID = diag::err_readonly_message_assignment; 13062 break; 13063 case Expr::MLV_SubObjCPropertySetting: 13064 DiagID = diag::err_no_subobject_property_setting; 13065 break; 13066 } 13067 13068 SourceRange Assign; 13069 if (Loc != OrigLoc) 13070 Assign = SourceRange(OrigLoc, OrigLoc); 13071 if (NeedType) 13072 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13073 else 13074 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13075 return true; 13076 } 13077 13078 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13079 SourceLocation Loc, 13080 Sema &Sema) { 13081 if (Sema.inTemplateInstantiation()) 13082 return; 13083 if (Sema.isUnevaluatedContext()) 13084 return; 13085 if (Loc.isInvalid() || Loc.isMacroID()) 13086 return; 13087 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13088 return; 13089 13090 // C / C++ fields 13091 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13092 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13093 if (ML && MR) { 13094 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13095 return; 13096 const ValueDecl *LHSDecl = 13097 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13098 const ValueDecl *RHSDecl = 13099 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13100 if (LHSDecl != RHSDecl) 13101 return; 13102 if (LHSDecl->getType().isVolatileQualified()) 13103 return; 13104 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13105 if (RefTy->getPointeeType().isVolatileQualified()) 13106 return; 13107 13108 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13109 } 13110 13111 // Objective-C instance variables 13112 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13113 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13114 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13115 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13116 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13117 if (RL && RR && RL->getDecl() == RR->getDecl()) 13118 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13119 } 13120 } 13121 13122 // C99 6.5.16.1 13123 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13124 SourceLocation Loc, 13125 QualType CompoundType) { 13126 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13127 13128 // Verify that LHS is a modifiable lvalue, and emit error if not. 13129 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13130 return QualType(); 13131 13132 QualType LHSType = LHSExpr->getType(); 13133 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13134 CompoundType; 13135 // OpenCL v1.2 s6.1.1.1 p2: 13136 // The half data type can only be used to declare a pointer to a buffer that 13137 // contains half values 13138 if (getLangOpts().OpenCL && 13139 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13140 LHSType->isHalfType()) { 13141 Diag(Loc, diag::err_opencl_half_load_store) << 1 13142 << LHSType.getUnqualifiedType(); 13143 return QualType(); 13144 } 13145 13146 AssignConvertType ConvTy; 13147 if (CompoundType.isNull()) { 13148 Expr *RHSCheck = RHS.get(); 13149 13150 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13151 13152 QualType LHSTy(LHSType); 13153 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13154 if (RHS.isInvalid()) 13155 return QualType(); 13156 // Special case of NSObject attributes on c-style pointer types. 13157 if (ConvTy == IncompatiblePointer && 13158 ((Context.isObjCNSObjectType(LHSType) && 13159 RHSType->isObjCObjectPointerType()) || 13160 (Context.isObjCNSObjectType(RHSType) && 13161 LHSType->isObjCObjectPointerType()))) 13162 ConvTy = Compatible; 13163 13164 if (ConvTy == Compatible && 13165 LHSType->isObjCObjectType()) 13166 Diag(Loc, diag::err_objc_object_assignment) 13167 << LHSType; 13168 13169 // If the RHS is a unary plus or minus, check to see if they = and + are 13170 // right next to each other. If so, the user may have typo'd "x =+ 4" 13171 // instead of "x += 4". 13172 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13173 RHSCheck = ICE->getSubExpr(); 13174 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13175 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13176 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13177 // Only if the two operators are exactly adjacent. 13178 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13179 // And there is a space or other character before the subexpr of the 13180 // unary +/-. We don't want to warn on "x=-1". 13181 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13182 UO->getSubExpr()->getBeginLoc().isFileID()) { 13183 Diag(Loc, diag::warn_not_compound_assign) 13184 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13185 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13186 } 13187 } 13188 13189 if (ConvTy == Compatible) { 13190 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13191 // Warn about retain cycles where a block captures the LHS, but 13192 // not if the LHS is a simple variable into which the block is 13193 // being stored...unless that variable can be captured by reference! 13194 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13195 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13196 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13197 checkRetainCycles(LHSExpr, RHS.get()); 13198 } 13199 13200 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13201 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13202 // It is safe to assign a weak reference into a strong variable. 13203 // Although this code can still have problems: 13204 // id x = self.weakProp; 13205 // id y = self.weakProp; 13206 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13207 // paths through the function. This should be revisited if 13208 // -Wrepeated-use-of-weak is made flow-sensitive. 13209 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13210 // variable, which will be valid for the current autorelease scope. 13211 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13212 RHS.get()->getBeginLoc())) 13213 getCurFunction()->markSafeWeakUse(RHS.get()); 13214 13215 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13216 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13217 } 13218 } 13219 } else { 13220 // Compound assignment "x += y" 13221 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13222 } 13223 13224 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13225 RHS.get(), AA_Assigning)) 13226 return QualType(); 13227 13228 CheckForNullPointerDereference(*this, LHSExpr); 13229 13230 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13231 if (CompoundType.isNull()) { 13232 // C++2a [expr.ass]p5: 13233 // A simple-assignment whose left operand is of a volatile-qualified 13234 // type is deprecated unless the assignment is either a discarded-value 13235 // expression or an unevaluated operand 13236 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13237 } else { 13238 // C++2a [expr.ass]p6: 13239 // [Compound-assignment] expressions are deprecated if E1 has 13240 // volatile-qualified type 13241 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13242 } 13243 } 13244 13245 // C99 6.5.16p3: The type of an assignment expression is the type of the 13246 // left operand unless the left operand has qualified type, in which case 13247 // it is the unqualified version of the type of the left operand. 13248 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13249 // is converted to the type of the assignment expression (above). 13250 // C++ 5.17p1: the type of the assignment expression is that of its left 13251 // operand. 13252 return (getLangOpts().CPlusPlus 13253 ? LHSType : LHSType.getUnqualifiedType()); 13254 } 13255 13256 // Only ignore explicit casts to void. 13257 static bool IgnoreCommaOperand(const Expr *E) { 13258 E = E->IgnoreParens(); 13259 13260 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13261 if (CE->getCastKind() == CK_ToVoid) { 13262 return true; 13263 } 13264 13265 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13266 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13267 CE->getSubExpr()->getType()->isDependentType()) { 13268 return true; 13269 } 13270 } 13271 13272 return false; 13273 } 13274 13275 // Look for instances where it is likely the comma operator is confused with 13276 // another operator. There is an explicit list of acceptable expressions for 13277 // the left hand side of the comma operator, otherwise emit a warning. 13278 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13279 // No warnings in macros 13280 if (Loc.isMacroID()) 13281 return; 13282 13283 // Don't warn in template instantiations. 13284 if (inTemplateInstantiation()) 13285 return; 13286 13287 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13288 // instead, skip more than needed, then call back into here with the 13289 // CommaVisitor in SemaStmt.cpp. 13290 // The listed locations are the initialization and increment portions 13291 // of a for loop. The additional checks are on the condition of 13292 // if statements, do/while loops, and for loops. 13293 // Differences in scope flags for C89 mode requires the extra logic. 13294 const unsigned ForIncrementFlags = 13295 getLangOpts().C99 || getLangOpts().CPlusPlus 13296 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13297 : Scope::ContinueScope | Scope::BreakScope; 13298 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13299 const unsigned ScopeFlags = getCurScope()->getFlags(); 13300 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13301 (ScopeFlags & ForInitFlags) == ForInitFlags) 13302 return; 13303 13304 // If there are multiple comma operators used together, get the RHS of the 13305 // of the comma operator as the LHS. 13306 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13307 if (BO->getOpcode() != BO_Comma) 13308 break; 13309 LHS = BO->getRHS(); 13310 } 13311 13312 // Only allow some expressions on LHS to not warn. 13313 if (IgnoreCommaOperand(LHS)) 13314 return; 13315 13316 Diag(Loc, diag::warn_comma_operator); 13317 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13318 << LHS->getSourceRange() 13319 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13320 LangOpts.CPlusPlus ? "static_cast<void>(" 13321 : "(void)(") 13322 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13323 ")"); 13324 } 13325 13326 // C99 6.5.17 13327 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13328 SourceLocation Loc) { 13329 LHS = S.CheckPlaceholderExpr(LHS.get()); 13330 RHS = S.CheckPlaceholderExpr(RHS.get()); 13331 if (LHS.isInvalid() || RHS.isInvalid()) 13332 return QualType(); 13333 13334 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13335 // operands, but not unary promotions. 13336 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13337 13338 // So we treat the LHS as a ignored value, and in C++ we allow the 13339 // containing site to determine what should be done with the RHS. 13340 LHS = S.IgnoredValueConversions(LHS.get()); 13341 if (LHS.isInvalid()) 13342 return QualType(); 13343 13344 S.DiagnoseUnusedExprResult(LHS.get()); 13345 13346 if (!S.getLangOpts().CPlusPlus) { 13347 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13348 if (RHS.isInvalid()) 13349 return QualType(); 13350 if (!RHS.get()->getType()->isVoidType()) 13351 S.RequireCompleteType(Loc, RHS.get()->getType(), 13352 diag::err_incomplete_type); 13353 } 13354 13355 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13356 S.DiagnoseCommaOperator(LHS.get(), Loc); 13357 13358 return RHS.get()->getType(); 13359 } 13360 13361 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13362 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13363 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13364 ExprValueKind &VK, 13365 ExprObjectKind &OK, 13366 SourceLocation OpLoc, 13367 bool IsInc, bool IsPrefix) { 13368 if (Op->isTypeDependent()) 13369 return S.Context.DependentTy; 13370 13371 QualType ResType = Op->getType(); 13372 // Atomic types can be used for increment / decrement where the non-atomic 13373 // versions can, so ignore the _Atomic() specifier for the purpose of 13374 // checking. 13375 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13376 ResType = ResAtomicType->getValueType(); 13377 13378 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13379 13380 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13381 // Decrement of bool is not allowed. 13382 if (!IsInc) { 13383 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13384 return QualType(); 13385 } 13386 // Increment of bool sets it to true, but is deprecated. 13387 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13388 : diag::warn_increment_bool) 13389 << Op->getSourceRange(); 13390 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13391 // Error on enum increments and decrements in C++ mode 13392 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13393 return QualType(); 13394 } else if (ResType->isRealType()) { 13395 // OK! 13396 } else if (ResType->isPointerType()) { 13397 // C99 6.5.2.4p2, 6.5.6p2 13398 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13399 return QualType(); 13400 } else if (ResType->isObjCObjectPointerType()) { 13401 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13402 // Otherwise, we just need a complete type. 13403 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13404 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13405 return QualType(); 13406 } else if (ResType->isAnyComplexType()) { 13407 // C99 does not support ++/-- on complex types, we allow as an extension. 13408 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13409 << ResType << Op->getSourceRange(); 13410 } else if (ResType->isPlaceholderType()) { 13411 ExprResult PR = S.CheckPlaceholderExpr(Op); 13412 if (PR.isInvalid()) return QualType(); 13413 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13414 IsInc, IsPrefix); 13415 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13416 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13417 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13418 (ResType->castAs<VectorType>()->getVectorKind() != 13419 VectorType::AltiVecBool)) { 13420 // The z vector extensions allow ++ and -- for non-bool vectors. 13421 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13422 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13423 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13424 } else { 13425 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13426 << ResType << int(IsInc) << Op->getSourceRange(); 13427 return QualType(); 13428 } 13429 // At this point, we know we have a real, complex or pointer type. 13430 // Now make sure the operand is a modifiable lvalue. 13431 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13432 return QualType(); 13433 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13434 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13435 // An operand with volatile-qualified type is deprecated 13436 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13437 << IsInc << ResType; 13438 } 13439 // In C++, a prefix increment is the same type as the operand. Otherwise 13440 // (in C or with postfix), the increment is the unqualified type of the 13441 // operand. 13442 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13443 VK = VK_LValue; 13444 OK = Op->getObjectKind(); 13445 return ResType; 13446 } else { 13447 VK = VK_PRValue; 13448 return ResType.getUnqualifiedType(); 13449 } 13450 } 13451 13452 13453 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13454 /// This routine allows us to typecheck complex/recursive expressions 13455 /// where the declaration is needed for type checking. We only need to 13456 /// handle cases when the expression references a function designator 13457 /// or is an lvalue. Here are some examples: 13458 /// - &(x) => x 13459 /// - &*****f => f for f a function designator. 13460 /// - &s.xx => s 13461 /// - &s.zz[1].yy -> s, if zz is an array 13462 /// - *(x + 1) -> x, if x is an array 13463 /// - &"123"[2] -> 0 13464 /// - & __real__ x -> x 13465 /// 13466 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13467 /// members. 13468 static ValueDecl *getPrimaryDecl(Expr *E) { 13469 switch (E->getStmtClass()) { 13470 case Stmt::DeclRefExprClass: 13471 return cast<DeclRefExpr>(E)->getDecl(); 13472 case Stmt::MemberExprClass: 13473 // If this is an arrow operator, the address is an offset from 13474 // the base's value, so the object the base refers to is 13475 // irrelevant. 13476 if (cast<MemberExpr>(E)->isArrow()) 13477 return nullptr; 13478 // Otherwise, the expression refers to a part of the base 13479 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13480 case Stmt::ArraySubscriptExprClass: { 13481 // FIXME: This code shouldn't be necessary! We should catch the implicit 13482 // promotion of register arrays earlier. 13483 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13484 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13485 if (ICE->getSubExpr()->getType()->isArrayType()) 13486 return getPrimaryDecl(ICE->getSubExpr()); 13487 } 13488 return nullptr; 13489 } 13490 case Stmt::UnaryOperatorClass: { 13491 UnaryOperator *UO = cast<UnaryOperator>(E); 13492 13493 switch(UO->getOpcode()) { 13494 case UO_Real: 13495 case UO_Imag: 13496 case UO_Extension: 13497 return getPrimaryDecl(UO->getSubExpr()); 13498 default: 13499 return nullptr; 13500 } 13501 } 13502 case Stmt::ParenExprClass: 13503 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13504 case Stmt::ImplicitCastExprClass: 13505 // If the result of an implicit cast is an l-value, we care about 13506 // the sub-expression; otherwise, the result here doesn't matter. 13507 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13508 case Stmt::CXXUuidofExprClass: 13509 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13510 default: 13511 return nullptr; 13512 } 13513 } 13514 13515 namespace { 13516 enum { 13517 AO_Bit_Field = 0, 13518 AO_Vector_Element = 1, 13519 AO_Property_Expansion = 2, 13520 AO_Register_Variable = 3, 13521 AO_Matrix_Element = 4, 13522 AO_No_Error = 5 13523 }; 13524 } 13525 /// Diagnose invalid operand for address of operations. 13526 /// 13527 /// \param Type The type of operand which cannot have its address taken. 13528 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13529 Expr *E, unsigned Type) { 13530 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13531 } 13532 13533 /// CheckAddressOfOperand - The operand of & must be either a function 13534 /// designator or an lvalue designating an object. If it is an lvalue, the 13535 /// object cannot be declared with storage class register or be a bit field. 13536 /// Note: The usual conversions are *not* applied to the operand of the & 13537 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13538 /// In C++, the operand might be an overloaded function name, in which case 13539 /// we allow the '&' but retain the overloaded-function type. 13540 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13541 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13542 if (PTy->getKind() == BuiltinType::Overload) { 13543 Expr *E = OrigOp.get()->IgnoreParens(); 13544 if (!isa<OverloadExpr>(E)) { 13545 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13546 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13547 << OrigOp.get()->getSourceRange(); 13548 return QualType(); 13549 } 13550 13551 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13552 if (isa<UnresolvedMemberExpr>(Ovl)) 13553 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13554 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13555 << OrigOp.get()->getSourceRange(); 13556 return QualType(); 13557 } 13558 13559 return Context.OverloadTy; 13560 } 13561 13562 if (PTy->getKind() == BuiltinType::UnknownAny) 13563 return Context.UnknownAnyTy; 13564 13565 if (PTy->getKind() == BuiltinType::BoundMember) { 13566 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13567 << OrigOp.get()->getSourceRange(); 13568 return QualType(); 13569 } 13570 13571 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13572 if (OrigOp.isInvalid()) return QualType(); 13573 } 13574 13575 if (OrigOp.get()->isTypeDependent()) 13576 return Context.DependentTy; 13577 13578 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13579 13580 // Make sure to ignore parentheses in subsequent checks 13581 Expr *op = OrigOp.get()->IgnoreParens(); 13582 13583 // In OpenCL captures for blocks called as lambda functions 13584 // are located in the private address space. Blocks used in 13585 // enqueue_kernel can be located in a different address space 13586 // depending on a vendor implementation. Thus preventing 13587 // taking an address of the capture to avoid invalid AS casts. 13588 if (LangOpts.OpenCL) { 13589 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13590 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13591 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13592 return QualType(); 13593 } 13594 } 13595 13596 if (getLangOpts().C99) { 13597 // Implement C99-only parts of addressof rules. 13598 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13599 if (uOp->getOpcode() == UO_Deref) 13600 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13601 // (assuming the deref expression is valid). 13602 return uOp->getSubExpr()->getType(); 13603 } 13604 // Technically, there should be a check for array subscript 13605 // expressions here, but the result of one is always an lvalue anyway. 13606 } 13607 ValueDecl *dcl = getPrimaryDecl(op); 13608 13609 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13610 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13611 op->getBeginLoc())) 13612 return QualType(); 13613 13614 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13615 unsigned AddressOfError = AO_No_Error; 13616 13617 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13618 bool sfinae = (bool)isSFINAEContext(); 13619 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13620 : diag::ext_typecheck_addrof_temporary) 13621 << op->getType() << op->getSourceRange(); 13622 if (sfinae) 13623 return QualType(); 13624 // Materialize the temporary as an lvalue so that we can take its address. 13625 OrigOp = op = 13626 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13627 } else if (isa<ObjCSelectorExpr>(op)) { 13628 return Context.getPointerType(op->getType()); 13629 } else if (lval == Expr::LV_MemberFunction) { 13630 // If it's an instance method, make a member pointer. 13631 // The expression must have exactly the form &A::foo. 13632 13633 // If the underlying expression isn't a decl ref, give up. 13634 if (!isa<DeclRefExpr>(op)) { 13635 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13636 << OrigOp.get()->getSourceRange(); 13637 return QualType(); 13638 } 13639 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13640 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13641 13642 // The id-expression was parenthesized. 13643 if (OrigOp.get() != DRE) { 13644 Diag(OpLoc, diag::err_parens_pointer_member_function) 13645 << OrigOp.get()->getSourceRange(); 13646 13647 // The method was named without a qualifier. 13648 } else if (!DRE->getQualifier()) { 13649 if (MD->getParent()->getName().empty()) 13650 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13651 << op->getSourceRange(); 13652 else { 13653 SmallString<32> Str; 13654 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13655 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13656 << op->getSourceRange() 13657 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13658 } 13659 } 13660 13661 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13662 if (isa<CXXDestructorDecl>(MD)) 13663 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13664 13665 QualType MPTy = Context.getMemberPointerType( 13666 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13667 // Under the MS ABI, lock down the inheritance model now. 13668 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13669 (void)isCompleteType(OpLoc, MPTy); 13670 return MPTy; 13671 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13672 // C99 6.5.3.2p1 13673 // The operand must be either an l-value or a function designator 13674 if (!op->getType()->isFunctionType()) { 13675 // Use a special diagnostic for loads from property references. 13676 if (isa<PseudoObjectExpr>(op)) { 13677 AddressOfError = AO_Property_Expansion; 13678 } else { 13679 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13680 << op->getType() << op->getSourceRange(); 13681 return QualType(); 13682 } 13683 } 13684 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13685 // The operand cannot be a bit-field 13686 AddressOfError = AO_Bit_Field; 13687 } else if (op->getObjectKind() == OK_VectorComponent) { 13688 // The operand cannot be an element of a vector 13689 AddressOfError = AO_Vector_Element; 13690 } else if (op->getObjectKind() == OK_MatrixComponent) { 13691 // The operand cannot be an element of a matrix. 13692 AddressOfError = AO_Matrix_Element; 13693 } else if (dcl) { // C99 6.5.3.2p1 13694 // We have an lvalue with a decl. Make sure the decl is not declared 13695 // with the register storage-class specifier. 13696 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13697 // in C++ it is not error to take address of a register 13698 // variable (c++03 7.1.1P3) 13699 if (vd->getStorageClass() == SC_Register && 13700 !getLangOpts().CPlusPlus) { 13701 AddressOfError = AO_Register_Variable; 13702 } 13703 } else if (isa<MSPropertyDecl>(dcl)) { 13704 AddressOfError = AO_Property_Expansion; 13705 } else if (isa<FunctionTemplateDecl>(dcl)) { 13706 return Context.OverloadTy; 13707 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13708 // Okay: we can take the address of a field. 13709 // Could be a pointer to member, though, if there is an explicit 13710 // scope qualifier for the class. 13711 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13712 DeclContext *Ctx = dcl->getDeclContext(); 13713 if (Ctx && Ctx->isRecord()) { 13714 if (dcl->getType()->isReferenceType()) { 13715 Diag(OpLoc, 13716 diag::err_cannot_form_pointer_to_member_of_reference_type) 13717 << dcl->getDeclName() << dcl->getType(); 13718 return QualType(); 13719 } 13720 13721 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13722 Ctx = Ctx->getParent(); 13723 13724 QualType MPTy = Context.getMemberPointerType( 13725 op->getType(), 13726 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13727 // Under the MS ABI, lock down the inheritance model now. 13728 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13729 (void)isCompleteType(OpLoc, MPTy); 13730 return MPTy; 13731 } 13732 } 13733 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13734 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13735 llvm_unreachable("Unknown/unexpected decl type"); 13736 } 13737 13738 if (AddressOfError != AO_No_Error) { 13739 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13740 return QualType(); 13741 } 13742 13743 if (lval == Expr::LV_IncompleteVoidType) { 13744 // Taking the address of a void variable is technically illegal, but we 13745 // allow it in cases which are otherwise valid. 13746 // Example: "extern void x; void* y = &x;". 13747 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13748 } 13749 13750 // If the operand has type "type", the result has type "pointer to type". 13751 if (op->getType()->isObjCObjectType()) 13752 return Context.getObjCObjectPointerType(op->getType()); 13753 13754 CheckAddressOfPackedMember(op); 13755 13756 return Context.getPointerType(op->getType()); 13757 } 13758 13759 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13760 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13761 if (!DRE) 13762 return; 13763 const Decl *D = DRE->getDecl(); 13764 if (!D) 13765 return; 13766 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13767 if (!Param) 13768 return; 13769 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13770 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13771 return; 13772 if (FunctionScopeInfo *FD = S.getCurFunction()) 13773 if (!FD->ModifiedNonNullParams.count(Param)) 13774 FD->ModifiedNonNullParams.insert(Param); 13775 } 13776 13777 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13778 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13779 SourceLocation OpLoc) { 13780 if (Op->isTypeDependent()) 13781 return S.Context.DependentTy; 13782 13783 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13784 if (ConvResult.isInvalid()) 13785 return QualType(); 13786 Op = ConvResult.get(); 13787 QualType OpTy = Op->getType(); 13788 QualType Result; 13789 13790 if (isa<CXXReinterpretCastExpr>(Op)) { 13791 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13792 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13793 Op->getSourceRange()); 13794 } 13795 13796 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13797 { 13798 Result = PT->getPointeeType(); 13799 } 13800 else if (const ObjCObjectPointerType *OPT = 13801 OpTy->getAs<ObjCObjectPointerType>()) 13802 Result = OPT->getPointeeType(); 13803 else { 13804 ExprResult PR = S.CheckPlaceholderExpr(Op); 13805 if (PR.isInvalid()) return QualType(); 13806 if (PR.get() != Op) 13807 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13808 } 13809 13810 if (Result.isNull()) { 13811 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13812 << OpTy << Op->getSourceRange(); 13813 return QualType(); 13814 } 13815 13816 // Note that per both C89 and C99, indirection is always legal, even if Result 13817 // is an incomplete type or void. It would be possible to warn about 13818 // dereferencing a void pointer, but it's completely well-defined, and such a 13819 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13820 // for pointers to 'void' but is fine for any other pointer type: 13821 // 13822 // C++ [expr.unary.op]p1: 13823 // [...] the expression to which [the unary * operator] is applied shall 13824 // be a pointer to an object type, or a pointer to a function type 13825 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13826 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13827 << OpTy << Op->getSourceRange(); 13828 13829 // Dereferences are usually l-values... 13830 VK = VK_LValue; 13831 13832 // ...except that certain expressions are never l-values in C. 13833 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13834 VK = VK_PRValue; 13835 13836 return Result; 13837 } 13838 13839 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13840 BinaryOperatorKind Opc; 13841 switch (Kind) { 13842 default: llvm_unreachable("Unknown binop!"); 13843 case tok::periodstar: Opc = BO_PtrMemD; break; 13844 case tok::arrowstar: Opc = BO_PtrMemI; break; 13845 case tok::star: Opc = BO_Mul; break; 13846 case tok::slash: Opc = BO_Div; break; 13847 case tok::percent: Opc = BO_Rem; break; 13848 case tok::plus: Opc = BO_Add; break; 13849 case tok::minus: Opc = BO_Sub; break; 13850 case tok::lessless: Opc = BO_Shl; break; 13851 case tok::greatergreater: Opc = BO_Shr; break; 13852 case tok::lessequal: Opc = BO_LE; break; 13853 case tok::less: Opc = BO_LT; break; 13854 case tok::greaterequal: Opc = BO_GE; break; 13855 case tok::greater: Opc = BO_GT; break; 13856 case tok::exclaimequal: Opc = BO_NE; break; 13857 case tok::equalequal: Opc = BO_EQ; break; 13858 case tok::spaceship: Opc = BO_Cmp; break; 13859 case tok::amp: Opc = BO_And; break; 13860 case tok::caret: Opc = BO_Xor; break; 13861 case tok::pipe: Opc = BO_Or; break; 13862 case tok::ampamp: Opc = BO_LAnd; break; 13863 case tok::pipepipe: Opc = BO_LOr; break; 13864 case tok::equal: Opc = BO_Assign; break; 13865 case tok::starequal: Opc = BO_MulAssign; break; 13866 case tok::slashequal: Opc = BO_DivAssign; break; 13867 case tok::percentequal: Opc = BO_RemAssign; break; 13868 case tok::plusequal: Opc = BO_AddAssign; break; 13869 case tok::minusequal: Opc = BO_SubAssign; break; 13870 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13871 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13872 case tok::ampequal: Opc = BO_AndAssign; break; 13873 case tok::caretequal: Opc = BO_XorAssign; break; 13874 case tok::pipeequal: Opc = BO_OrAssign; break; 13875 case tok::comma: Opc = BO_Comma; break; 13876 } 13877 return Opc; 13878 } 13879 13880 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13881 tok::TokenKind Kind) { 13882 UnaryOperatorKind Opc; 13883 switch (Kind) { 13884 default: llvm_unreachable("Unknown unary op!"); 13885 case tok::plusplus: Opc = UO_PreInc; break; 13886 case tok::minusminus: Opc = UO_PreDec; break; 13887 case tok::amp: Opc = UO_AddrOf; break; 13888 case tok::star: Opc = UO_Deref; break; 13889 case tok::plus: Opc = UO_Plus; break; 13890 case tok::minus: Opc = UO_Minus; break; 13891 case tok::tilde: Opc = UO_Not; break; 13892 case tok::exclaim: Opc = UO_LNot; break; 13893 case tok::kw___real: Opc = UO_Real; break; 13894 case tok::kw___imag: Opc = UO_Imag; break; 13895 case tok::kw___extension__: Opc = UO_Extension; break; 13896 } 13897 return Opc; 13898 } 13899 13900 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13901 /// This warning suppressed in the event of macro expansions. 13902 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13903 SourceLocation OpLoc, bool IsBuiltin) { 13904 if (S.inTemplateInstantiation()) 13905 return; 13906 if (S.isUnevaluatedContext()) 13907 return; 13908 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13909 return; 13910 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13911 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13912 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13913 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13914 if (!LHSDeclRef || !RHSDeclRef || 13915 LHSDeclRef->getLocation().isMacroID() || 13916 RHSDeclRef->getLocation().isMacroID()) 13917 return; 13918 const ValueDecl *LHSDecl = 13919 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13920 const ValueDecl *RHSDecl = 13921 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13922 if (LHSDecl != RHSDecl) 13923 return; 13924 if (LHSDecl->getType().isVolatileQualified()) 13925 return; 13926 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13927 if (RefTy->getPointeeType().isVolatileQualified()) 13928 return; 13929 13930 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13931 : diag::warn_self_assignment_overloaded) 13932 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13933 << RHSExpr->getSourceRange(); 13934 } 13935 13936 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13937 /// is usually indicative of introspection within the Objective-C pointer. 13938 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13939 SourceLocation OpLoc) { 13940 if (!S.getLangOpts().ObjC) 13941 return; 13942 13943 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13944 const Expr *LHS = L.get(); 13945 const Expr *RHS = R.get(); 13946 13947 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13948 ObjCPointerExpr = LHS; 13949 OtherExpr = RHS; 13950 } 13951 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13952 ObjCPointerExpr = RHS; 13953 OtherExpr = LHS; 13954 } 13955 13956 // This warning is deliberately made very specific to reduce false 13957 // positives with logic that uses '&' for hashing. This logic mainly 13958 // looks for code trying to introspect into tagged pointers, which 13959 // code should generally never do. 13960 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13961 unsigned Diag = diag::warn_objc_pointer_masking; 13962 // Determine if we are introspecting the result of performSelectorXXX. 13963 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13964 // Special case messages to -performSelector and friends, which 13965 // can return non-pointer values boxed in a pointer value. 13966 // Some clients may wish to silence warnings in this subcase. 13967 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13968 Selector S = ME->getSelector(); 13969 StringRef SelArg0 = S.getNameForSlot(0); 13970 if (SelArg0.startswith("performSelector")) 13971 Diag = diag::warn_objc_pointer_masking_performSelector; 13972 } 13973 13974 S.Diag(OpLoc, Diag) 13975 << ObjCPointerExpr->getSourceRange(); 13976 } 13977 } 13978 13979 static NamedDecl *getDeclFromExpr(Expr *E) { 13980 if (!E) 13981 return nullptr; 13982 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13983 return DRE->getDecl(); 13984 if (auto *ME = dyn_cast<MemberExpr>(E)) 13985 return ME->getMemberDecl(); 13986 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13987 return IRE->getDecl(); 13988 return nullptr; 13989 } 13990 13991 // This helper function promotes a binary operator's operands (which are of a 13992 // half vector type) to a vector of floats and then truncates the result to 13993 // a vector of either half or short. 13994 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13995 BinaryOperatorKind Opc, QualType ResultTy, 13996 ExprValueKind VK, ExprObjectKind OK, 13997 bool IsCompAssign, SourceLocation OpLoc, 13998 FPOptionsOverride FPFeatures) { 13999 auto &Context = S.getASTContext(); 14000 assert((isVector(ResultTy, Context.HalfTy) || 14001 isVector(ResultTy, Context.ShortTy)) && 14002 "Result must be a vector of half or short"); 14003 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14004 isVector(RHS.get()->getType(), Context.HalfTy) && 14005 "both operands expected to be a half vector"); 14006 14007 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14008 QualType BinOpResTy = RHS.get()->getType(); 14009 14010 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14011 // change BinOpResTy to a vector of ints. 14012 if (isVector(ResultTy, Context.ShortTy)) 14013 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14014 14015 if (IsCompAssign) 14016 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14017 ResultTy, VK, OK, OpLoc, FPFeatures, 14018 BinOpResTy, BinOpResTy); 14019 14020 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14021 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14022 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14023 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14024 } 14025 14026 static std::pair<ExprResult, ExprResult> 14027 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14028 Expr *RHSExpr) { 14029 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14030 if (!S.Context.isDependenceAllowed()) { 14031 // C cannot handle TypoExpr nodes on either side of a binop because it 14032 // doesn't handle dependent types properly, so make sure any TypoExprs have 14033 // been dealt with before checking the operands. 14034 LHS = S.CorrectDelayedTyposInExpr(LHS); 14035 RHS = S.CorrectDelayedTyposInExpr( 14036 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14037 [Opc, LHS](Expr *E) { 14038 if (Opc != BO_Assign) 14039 return ExprResult(E); 14040 // Avoid correcting the RHS to the same Expr as the LHS. 14041 Decl *D = getDeclFromExpr(E); 14042 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14043 }); 14044 } 14045 return std::make_pair(LHS, RHS); 14046 } 14047 14048 /// Returns true if conversion between vectors of halfs and vectors of floats 14049 /// is needed. 14050 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14051 Expr *E0, Expr *E1 = nullptr) { 14052 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14053 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14054 return false; 14055 14056 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14057 QualType Ty = E->IgnoreImplicit()->getType(); 14058 14059 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14060 // to vectors of floats. Although the element type of the vectors is __fp16, 14061 // the vectors shouldn't be treated as storage-only types. See the 14062 // discussion here: https://reviews.llvm.org/rG825235c140e7 14063 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14064 if (VT->getVectorKind() == VectorType::NeonVector) 14065 return false; 14066 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14067 } 14068 return false; 14069 }; 14070 14071 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14072 } 14073 14074 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14075 /// operator @p Opc at location @c TokLoc. This routine only supports 14076 /// built-in operations; ActOnBinOp handles overloaded operators. 14077 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14078 BinaryOperatorKind Opc, 14079 Expr *LHSExpr, Expr *RHSExpr) { 14080 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14081 // The syntax only allows initializer lists on the RHS of assignment, 14082 // so we don't need to worry about accepting invalid code for 14083 // non-assignment operators. 14084 // C++11 5.17p9: 14085 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14086 // of x = {} is x = T(). 14087 InitializationKind Kind = InitializationKind::CreateDirectList( 14088 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14089 InitializedEntity Entity = 14090 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14091 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14092 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14093 if (Init.isInvalid()) 14094 return Init; 14095 RHSExpr = Init.get(); 14096 } 14097 14098 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14099 QualType ResultTy; // Result type of the binary operator. 14100 // The following two variables are used for compound assignment operators 14101 QualType CompLHSTy; // Type of LHS after promotions for computation 14102 QualType CompResultTy; // Type of computation result 14103 ExprValueKind VK = VK_PRValue; 14104 ExprObjectKind OK = OK_Ordinary; 14105 bool ConvertHalfVec = false; 14106 14107 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14108 if (!LHS.isUsable() || !RHS.isUsable()) 14109 return ExprError(); 14110 14111 if (getLangOpts().OpenCL) { 14112 QualType LHSTy = LHSExpr->getType(); 14113 QualType RHSTy = RHSExpr->getType(); 14114 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14115 // the ATOMIC_VAR_INIT macro. 14116 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14117 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14118 if (BO_Assign == Opc) 14119 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14120 else 14121 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14122 return ExprError(); 14123 } 14124 14125 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14126 // only with a builtin functions and therefore should be disallowed here. 14127 if (LHSTy->isImageType() || RHSTy->isImageType() || 14128 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14129 LHSTy->isPipeType() || RHSTy->isPipeType() || 14130 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14131 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14132 return ExprError(); 14133 } 14134 } 14135 14136 switch (Opc) { 14137 case BO_Assign: 14138 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14139 if (getLangOpts().CPlusPlus && 14140 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14141 VK = LHS.get()->getValueKind(); 14142 OK = LHS.get()->getObjectKind(); 14143 } 14144 if (!ResultTy.isNull()) { 14145 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14146 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14147 14148 // Avoid copying a block to the heap if the block is assigned to a local 14149 // auto variable that is declared in the same scope as the block. This 14150 // optimization is unsafe if the local variable is declared in an outer 14151 // scope. For example: 14152 // 14153 // BlockTy b; 14154 // { 14155 // b = ^{...}; 14156 // } 14157 // // It is unsafe to invoke the block here if it wasn't copied to the 14158 // // heap. 14159 // b(); 14160 14161 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14162 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14163 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14164 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14165 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14166 14167 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14168 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14169 NTCUC_Assignment, NTCUK_Copy); 14170 } 14171 RecordModifiableNonNullParam(*this, LHS.get()); 14172 break; 14173 case BO_PtrMemD: 14174 case BO_PtrMemI: 14175 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14176 Opc == BO_PtrMemI); 14177 break; 14178 case BO_Mul: 14179 case BO_Div: 14180 ConvertHalfVec = true; 14181 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14182 Opc == BO_Div); 14183 break; 14184 case BO_Rem: 14185 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14186 break; 14187 case BO_Add: 14188 ConvertHalfVec = true; 14189 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14190 break; 14191 case BO_Sub: 14192 ConvertHalfVec = true; 14193 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14194 break; 14195 case BO_Shl: 14196 case BO_Shr: 14197 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14198 break; 14199 case BO_LE: 14200 case BO_LT: 14201 case BO_GE: 14202 case BO_GT: 14203 ConvertHalfVec = true; 14204 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14205 break; 14206 case BO_EQ: 14207 case BO_NE: 14208 ConvertHalfVec = true; 14209 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14210 break; 14211 case BO_Cmp: 14212 ConvertHalfVec = true; 14213 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14214 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14215 break; 14216 case BO_And: 14217 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14218 LLVM_FALLTHROUGH; 14219 case BO_Xor: 14220 case BO_Or: 14221 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14222 break; 14223 case BO_LAnd: 14224 case BO_LOr: 14225 ConvertHalfVec = true; 14226 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14227 break; 14228 case BO_MulAssign: 14229 case BO_DivAssign: 14230 ConvertHalfVec = true; 14231 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14232 Opc == BO_DivAssign); 14233 CompLHSTy = CompResultTy; 14234 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14235 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14236 break; 14237 case BO_RemAssign: 14238 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14239 CompLHSTy = CompResultTy; 14240 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14241 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14242 break; 14243 case BO_AddAssign: 14244 ConvertHalfVec = true; 14245 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14246 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14247 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14248 break; 14249 case BO_SubAssign: 14250 ConvertHalfVec = true; 14251 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14252 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14253 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14254 break; 14255 case BO_ShlAssign: 14256 case BO_ShrAssign: 14257 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14258 CompLHSTy = CompResultTy; 14259 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14260 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14261 break; 14262 case BO_AndAssign: 14263 case BO_OrAssign: // fallthrough 14264 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14265 LLVM_FALLTHROUGH; 14266 case BO_XorAssign: 14267 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14268 CompLHSTy = CompResultTy; 14269 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14270 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14271 break; 14272 case BO_Comma: 14273 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14274 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14275 VK = RHS.get()->getValueKind(); 14276 OK = RHS.get()->getObjectKind(); 14277 } 14278 break; 14279 } 14280 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14281 return ExprError(); 14282 14283 // Some of the binary operations require promoting operands of half vector to 14284 // float vectors and truncating the result back to half vector. For now, we do 14285 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14286 // arm64). 14287 assert( 14288 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14289 isVector(LHS.get()->getType(), Context.HalfTy)) && 14290 "both sides are half vectors or neither sides are"); 14291 ConvertHalfVec = 14292 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14293 14294 // Check for array bounds violations for both sides of the BinaryOperator 14295 CheckArrayAccess(LHS.get()); 14296 CheckArrayAccess(RHS.get()); 14297 14298 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14299 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14300 &Context.Idents.get("object_setClass"), 14301 SourceLocation(), LookupOrdinaryName); 14302 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14303 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14304 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14305 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14306 "object_setClass(") 14307 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14308 ",") 14309 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14310 } 14311 else 14312 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14313 } 14314 else if (const ObjCIvarRefExpr *OIRE = 14315 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14316 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14317 14318 // Opc is not a compound assignment if CompResultTy is null. 14319 if (CompResultTy.isNull()) { 14320 if (ConvertHalfVec) 14321 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14322 OpLoc, CurFPFeatureOverrides()); 14323 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14324 VK, OK, OpLoc, CurFPFeatureOverrides()); 14325 } 14326 14327 // Handle compound assignments. 14328 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14329 OK_ObjCProperty) { 14330 VK = VK_LValue; 14331 OK = LHS.get()->getObjectKind(); 14332 } 14333 14334 // The LHS is not converted to the result type for fixed-point compound 14335 // assignment as the common type is computed on demand. Reset the CompLHSTy 14336 // to the LHS type we would have gotten after unary conversions. 14337 if (CompResultTy->isFixedPointType()) 14338 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14339 14340 if (ConvertHalfVec) 14341 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14342 OpLoc, CurFPFeatureOverrides()); 14343 14344 return CompoundAssignOperator::Create( 14345 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14346 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14347 } 14348 14349 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14350 /// operators are mixed in a way that suggests that the programmer forgot that 14351 /// comparison operators have higher precedence. The most typical example of 14352 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14353 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14354 SourceLocation OpLoc, Expr *LHSExpr, 14355 Expr *RHSExpr) { 14356 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14357 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14358 14359 // Check that one of the sides is a comparison operator and the other isn't. 14360 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14361 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14362 if (isLeftComp == isRightComp) 14363 return; 14364 14365 // Bitwise operations are sometimes used as eager logical ops. 14366 // Don't diagnose this. 14367 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14368 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14369 if (isLeftBitwise || isRightBitwise) 14370 return; 14371 14372 SourceRange DiagRange = isLeftComp 14373 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14374 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14375 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14376 SourceRange ParensRange = 14377 isLeftComp 14378 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14379 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14380 14381 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14382 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14383 SuggestParentheses(Self, OpLoc, 14384 Self.PDiag(diag::note_precedence_silence) << OpStr, 14385 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14386 SuggestParentheses(Self, OpLoc, 14387 Self.PDiag(diag::note_precedence_bitwise_first) 14388 << BinaryOperator::getOpcodeStr(Opc), 14389 ParensRange); 14390 } 14391 14392 /// It accepts a '&&' expr that is inside a '||' one. 14393 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14394 /// in parentheses. 14395 static void 14396 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14397 BinaryOperator *Bop) { 14398 assert(Bop->getOpcode() == BO_LAnd); 14399 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14400 << Bop->getSourceRange() << OpLoc; 14401 SuggestParentheses(Self, Bop->getOperatorLoc(), 14402 Self.PDiag(diag::note_precedence_silence) 14403 << Bop->getOpcodeStr(), 14404 Bop->getSourceRange()); 14405 } 14406 14407 /// Returns true if the given expression can be evaluated as a constant 14408 /// 'true'. 14409 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14410 bool Res; 14411 return !E->isValueDependent() && 14412 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14413 } 14414 14415 /// Returns true if the given expression can be evaluated as a constant 14416 /// 'false'. 14417 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14418 bool Res; 14419 return !E->isValueDependent() && 14420 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14421 } 14422 14423 /// Look for '&&' in the left hand of a '||' expr. 14424 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14425 Expr *LHSExpr, Expr *RHSExpr) { 14426 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14427 if (Bop->getOpcode() == BO_LAnd) { 14428 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14429 if (EvaluatesAsFalse(S, RHSExpr)) 14430 return; 14431 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14432 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14433 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14434 } else if (Bop->getOpcode() == BO_LOr) { 14435 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14436 // If it's "a || b && 1 || c" we didn't warn earlier for 14437 // "a || b && 1", but warn now. 14438 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14439 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14440 } 14441 } 14442 } 14443 } 14444 14445 /// Look for '&&' in the right hand of a '||' expr. 14446 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14447 Expr *LHSExpr, Expr *RHSExpr) { 14448 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14449 if (Bop->getOpcode() == BO_LAnd) { 14450 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14451 if (EvaluatesAsFalse(S, LHSExpr)) 14452 return; 14453 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14454 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14455 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14456 } 14457 } 14458 } 14459 14460 /// Look for bitwise op in the left or right hand of a bitwise op with 14461 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14462 /// the '&' expression in parentheses. 14463 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14464 SourceLocation OpLoc, Expr *SubExpr) { 14465 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14466 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14467 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14468 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14469 << Bop->getSourceRange() << OpLoc; 14470 SuggestParentheses(S, Bop->getOperatorLoc(), 14471 S.PDiag(diag::note_precedence_silence) 14472 << Bop->getOpcodeStr(), 14473 Bop->getSourceRange()); 14474 } 14475 } 14476 } 14477 14478 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14479 Expr *SubExpr, StringRef Shift) { 14480 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14481 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14482 StringRef Op = Bop->getOpcodeStr(); 14483 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14484 << Bop->getSourceRange() << OpLoc << Shift << Op; 14485 SuggestParentheses(S, Bop->getOperatorLoc(), 14486 S.PDiag(diag::note_precedence_silence) << Op, 14487 Bop->getSourceRange()); 14488 } 14489 } 14490 } 14491 14492 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14493 Expr *LHSExpr, Expr *RHSExpr) { 14494 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14495 if (!OCE) 14496 return; 14497 14498 FunctionDecl *FD = OCE->getDirectCallee(); 14499 if (!FD || !FD->isOverloadedOperator()) 14500 return; 14501 14502 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14503 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14504 return; 14505 14506 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14507 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14508 << (Kind == OO_LessLess); 14509 SuggestParentheses(S, OCE->getOperatorLoc(), 14510 S.PDiag(diag::note_precedence_silence) 14511 << (Kind == OO_LessLess ? "<<" : ">>"), 14512 OCE->getSourceRange()); 14513 SuggestParentheses( 14514 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14515 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14516 } 14517 14518 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14519 /// precedence. 14520 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14521 SourceLocation OpLoc, Expr *LHSExpr, 14522 Expr *RHSExpr){ 14523 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14524 if (BinaryOperator::isBitwiseOp(Opc)) 14525 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14526 14527 // Diagnose "arg1 & arg2 | arg3" 14528 if ((Opc == BO_Or || Opc == BO_Xor) && 14529 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14530 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14531 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14532 } 14533 14534 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14535 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14536 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14537 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14538 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14539 } 14540 14541 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14542 || Opc == BO_Shr) { 14543 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14544 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14545 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14546 } 14547 14548 // Warn on overloaded shift operators and comparisons, such as: 14549 // cout << 5 == 4; 14550 if (BinaryOperator::isComparisonOp(Opc)) 14551 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14552 } 14553 14554 // Binary Operators. 'Tok' is the token for the operator. 14555 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14556 tok::TokenKind Kind, 14557 Expr *LHSExpr, Expr *RHSExpr) { 14558 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14559 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14560 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14561 14562 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14563 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14564 14565 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14566 } 14567 14568 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14569 UnresolvedSetImpl &Functions) { 14570 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14571 if (OverOp != OO_None && OverOp != OO_Equal) 14572 LookupOverloadedOperatorName(OverOp, S, Functions); 14573 14574 // In C++20 onwards, we may have a second operator to look up. 14575 if (getLangOpts().CPlusPlus20) { 14576 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14577 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14578 } 14579 } 14580 14581 /// Build an overloaded binary operator expression in the given scope. 14582 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14583 BinaryOperatorKind Opc, 14584 Expr *LHS, Expr *RHS) { 14585 switch (Opc) { 14586 case BO_Assign: 14587 case BO_DivAssign: 14588 case BO_RemAssign: 14589 case BO_SubAssign: 14590 case BO_AndAssign: 14591 case BO_OrAssign: 14592 case BO_XorAssign: 14593 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14594 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14595 break; 14596 default: 14597 break; 14598 } 14599 14600 // Find all of the overloaded operators visible from this point. 14601 UnresolvedSet<16> Functions; 14602 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14603 14604 // Build the (potentially-overloaded, potentially-dependent) 14605 // binary operation. 14606 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14607 } 14608 14609 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14610 BinaryOperatorKind Opc, 14611 Expr *LHSExpr, Expr *RHSExpr) { 14612 ExprResult LHS, RHS; 14613 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14614 if (!LHS.isUsable() || !RHS.isUsable()) 14615 return ExprError(); 14616 LHSExpr = LHS.get(); 14617 RHSExpr = RHS.get(); 14618 14619 // We want to end up calling one of checkPseudoObjectAssignment 14620 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14621 // both expressions are overloadable or either is type-dependent), 14622 // or CreateBuiltinBinOp (in any other case). We also want to get 14623 // any placeholder types out of the way. 14624 14625 // Handle pseudo-objects in the LHS. 14626 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14627 // Assignments with a pseudo-object l-value need special analysis. 14628 if (pty->getKind() == BuiltinType::PseudoObject && 14629 BinaryOperator::isAssignmentOp(Opc)) 14630 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14631 14632 // Don't resolve overloads if the other type is overloadable. 14633 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14634 // We can't actually test that if we still have a placeholder, 14635 // though. Fortunately, none of the exceptions we see in that 14636 // code below are valid when the LHS is an overload set. Note 14637 // that an overload set can be dependently-typed, but it never 14638 // instantiates to having an overloadable type. 14639 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14640 if (resolvedRHS.isInvalid()) return ExprError(); 14641 RHSExpr = resolvedRHS.get(); 14642 14643 if (RHSExpr->isTypeDependent() || 14644 RHSExpr->getType()->isOverloadableType()) 14645 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14646 } 14647 14648 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14649 // template, diagnose the missing 'template' keyword instead of diagnosing 14650 // an invalid use of a bound member function. 14651 // 14652 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14653 // to C++1z [over.over]/1.4, but we already checked for that case above. 14654 if (Opc == BO_LT && inTemplateInstantiation() && 14655 (pty->getKind() == BuiltinType::BoundMember || 14656 pty->getKind() == BuiltinType::Overload)) { 14657 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14658 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14659 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14660 return isa<FunctionTemplateDecl>(ND); 14661 })) { 14662 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14663 : OE->getNameLoc(), 14664 diag::err_template_kw_missing) 14665 << OE->getName().getAsString() << ""; 14666 return ExprError(); 14667 } 14668 } 14669 14670 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14671 if (LHS.isInvalid()) return ExprError(); 14672 LHSExpr = LHS.get(); 14673 } 14674 14675 // Handle pseudo-objects in the RHS. 14676 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14677 // An overload in the RHS can potentially be resolved by the type 14678 // being assigned to. 14679 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14680 if (getLangOpts().CPlusPlus && 14681 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14682 LHSExpr->getType()->isOverloadableType())) 14683 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14684 14685 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14686 } 14687 14688 // Don't resolve overloads if the other type is overloadable. 14689 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14690 LHSExpr->getType()->isOverloadableType()) 14691 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14692 14693 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14694 if (!resolvedRHS.isUsable()) return ExprError(); 14695 RHSExpr = resolvedRHS.get(); 14696 } 14697 14698 if (getLangOpts().CPlusPlus) { 14699 // If either expression is type-dependent, always build an 14700 // overloaded op. 14701 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14702 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14703 14704 // Otherwise, build an overloaded op if either expression has an 14705 // overloadable type. 14706 if (LHSExpr->getType()->isOverloadableType() || 14707 RHSExpr->getType()->isOverloadableType()) 14708 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14709 } 14710 14711 if (getLangOpts().RecoveryAST && 14712 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14713 assert(!getLangOpts().CPlusPlus); 14714 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14715 "Should only occur in error-recovery path."); 14716 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14717 // C [6.15.16] p3: 14718 // An assignment expression has the value of the left operand after the 14719 // assignment, but is not an lvalue. 14720 return CompoundAssignOperator::Create( 14721 Context, LHSExpr, RHSExpr, Opc, 14722 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14723 OpLoc, CurFPFeatureOverrides()); 14724 QualType ResultType; 14725 switch (Opc) { 14726 case BO_Assign: 14727 ResultType = LHSExpr->getType().getUnqualifiedType(); 14728 break; 14729 case BO_LT: 14730 case BO_GT: 14731 case BO_LE: 14732 case BO_GE: 14733 case BO_EQ: 14734 case BO_NE: 14735 case BO_LAnd: 14736 case BO_LOr: 14737 // These operators have a fixed result type regardless of operands. 14738 ResultType = Context.IntTy; 14739 break; 14740 case BO_Comma: 14741 ResultType = RHSExpr->getType(); 14742 break; 14743 default: 14744 ResultType = Context.DependentTy; 14745 break; 14746 } 14747 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14748 VK_PRValue, OK_Ordinary, OpLoc, 14749 CurFPFeatureOverrides()); 14750 } 14751 14752 // Build a built-in binary operation. 14753 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14754 } 14755 14756 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14757 if (T.isNull() || T->isDependentType()) 14758 return false; 14759 14760 if (!T->isPromotableIntegerType()) 14761 return true; 14762 14763 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14764 } 14765 14766 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14767 UnaryOperatorKind Opc, 14768 Expr *InputExpr) { 14769 ExprResult Input = InputExpr; 14770 ExprValueKind VK = VK_PRValue; 14771 ExprObjectKind OK = OK_Ordinary; 14772 QualType resultType; 14773 bool CanOverflow = false; 14774 14775 bool ConvertHalfVec = false; 14776 if (getLangOpts().OpenCL) { 14777 QualType Ty = InputExpr->getType(); 14778 // The only legal unary operation for atomics is '&'. 14779 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14780 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14781 // only with a builtin functions and therefore should be disallowed here. 14782 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14783 || Ty->isBlockPointerType())) { 14784 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14785 << InputExpr->getType() 14786 << Input.get()->getSourceRange()); 14787 } 14788 } 14789 14790 switch (Opc) { 14791 case UO_PreInc: 14792 case UO_PreDec: 14793 case UO_PostInc: 14794 case UO_PostDec: 14795 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14796 OpLoc, 14797 Opc == UO_PreInc || 14798 Opc == UO_PostInc, 14799 Opc == UO_PreInc || 14800 Opc == UO_PreDec); 14801 CanOverflow = isOverflowingIntegerType(Context, resultType); 14802 break; 14803 case UO_AddrOf: 14804 resultType = CheckAddressOfOperand(Input, OpLoc); 14805 CheckAddressOfNoDeref(InputExpr); 14806 RecordModifiableNonNullParam(*this, InputExpr); 14807 break; 14808 case UO_Deref: { 14809 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14810 if (Input.isInvalid()) return ExprError(); 14811 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14812 break; 14813 } 14814 case UO_Plus: 14815 case UO_Minus: 14816 CanOverflow = Opc == UO_Minus && 14817 isOverflowingIntegerType(Context, Input.get()->getType()); 14818 Input = UsualUnaryConversions(Input.get()); 14819 if (Input.isInvalid()) return ExprError(); 14820 // Unary plus and minus require promoting an operand of half vector to a 14821 // float vector and truncating the result back to a half vector. For now, we 14822 // do this only when HalfArgsAndReturns is set (that is, when the target is 14823 // arm or arm64). 14824 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14825 14826 // If the operand is a half vector, promote it to a float vector. 14827 if (ConvertHalfVec) 14828 Input = convertVector(Input.get(), Context.FloatTy, *this); 14829 resultType = Input.get()->getType(); 14830 if (resultType->isDependentType()) 14831 break; 14832 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14833 break; 14834 else if (resultType->isVectorType() && 14835 // The z vector extensions don't allow + or - with bool vectors. 14836 (!Context.getLangOpts().ZVector || 14837 resultType->castAs<VectorType>()->getVectorKind() != 14838 VectorType::AltiVecBool)) 14839 break; 14840 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14841 Opc == UO_Plus && 14842 resultType->isPointerType()) 14843 break; 14844 14845 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14846 << resultType << Input.get()->getSourceRange()); 14847 14848 case UO_Not: // bitwise complement 14849 Input = UsualUnaryConversions(Input.get()); 14850 if (Input.isInvalid()) 14851 return ExprError(); 14852 resultType = Input.get()->getType(); 14853 if (resultType->isDependentType()) 14854 break; 14855 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14856 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14857 // C99 does not support '~' for complex conjugation. 14858 Diag(OpLoc, diag::ext_integer_complement_complex) 14859 << resultType << Input.get()->getSourceRange(); 14860 else if (resultType->hasIntegerRepresentation()) 14861 break; 14862 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14863 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14864 // on vector float types. 14865 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14866 if (!T->isIntegerType()) 14867 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14868 << resultType << Input.get()->getSourceRange()); 14869 } else { 14870 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14871 << resultType << Input.get()->getSourceRange()); 14872 } 14873 break; 14874 14875 case UO_LNot: // logical negation 14876 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14877 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14878 if (Input.isInvalid()) return ExprError(); 14879 resultType = Input.get()->getType(); 14880 14881 // Though we still have to promote half FP to float... 14882 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14883 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14884 resultType = Context.FloatTy; 14885 } 14886 14887 if (resultType->isDependentType()) 14888 break; 14889 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14890 // C99 6.5.3.3p1: ok, fallthrough; 14891 if (Context.getLangOpts().CPlusPlus) { 14892 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14893 // operand contextually converted to bool. 14894 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14895 ScalarTypeToBooleanCastKind(resultType)); 14896 } else if (Context.getLangOpts().OpenCL && 14897 Context.getLangOpts().OpenCLVersion < 120) { 14898 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14899 // operate on scalar float types. 14900 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14901 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14902 << resultType << Input.get()->getSourceRange()); 14903 } 14904 } else if (resultType->isExtVectorType()) { 14905 if (Context.getLangOpts().OpenCL && 14906 Context.getLangOpts().OpenCLVersion < 120 && 14907 !Context.getLangOpts().OpenCLCPlusPlus) { 14908 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14909 // operate on vector float types. 14910 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14911 if (!T->isIntegerType()) 14912 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14913 << resultType << Input.get()->getSourceRange()); 14914 } 14915 // Vector logical not returns the signed variant of the operand type. 14916 resultType = GetSignedVectorType(resultType); 14917 break; 14918 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14919 const VectorType *VTy = resultType->castAs<VectorType>(); 14920 if (VTy->getVectorKind() != VectorType::GenericVector) 14921 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14922 << resultType << Input.get()->getSourceRange()); 14923 14924 // Vector logical not returns the signed variant of the operand type. 14925 resultType = GetSignedVectorType(resultType); 14926 break; 14927 } else { 14928 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14929 << resultType << Input.get()->getSourceRange()); 14930 } 14931 14932 // LNot always has type int. C99 6.5.3.3p5. 14933 // In C++, it's bool. C++ 5.3.1p8 14934 resultType = Context.getLogicalOperationType(); 14935 break; 14936 case UO_Real: 14937 case UO_Imag: 14938 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14939 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14940 // complex l-values to ordinary l-values and all other values to r-values. 14941 if (Input.isInvalid()) return ExprError(); 14942 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14943 if (Input.get()->getValueKind() != VK_PRValue && 14944 Input.get()->getObjectKind() == OK_Ordinary) 14945 VK = Input.get()->getValueKind(); 14946 } else if (!getLangOpts().CPlusPlus) { 14947 // In C, a volatile scalar is read by __imag. In C++, it is not. 14948 Input = DefaultLvalueConversion(Input.get()); 14949 } 14950 break; 14951 case UO_Extension: 14952 resultType = Input.get()->getType(); 14953 VK = Input.get()->getValueKind(); 14954 OK = Input.get()->getObjectKind(); 14955 break; 14956 case UO_Coawait: 14957 // It's unnecessary to represent the pass-through operator co_await in the 14958 // AST; just return the input expression instead. 14959 assert(!Input.get()->getType()->isDependentType() && 14960 "the co_await expression must be non-dependant before " 14961 "building operator co_await"); 14962 return Input; 14963 } 14964 if (resultType.isNull() || Input.isInvalid()) 14965 return ExprError(); 14966 14967 // Check for array bounds violations in the operand of the UnaryOperator, 14968 // except for the '*' and '&' operators that have to be handled specially 14969 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14970 // that are explicitly defined as valid by the standard). 14971 if (Opc != UO_AddrOf && Opc != UO_Deref) 14972 CheckArrayAccess(Input.get()); 14973 14974 auto *UO = 14975 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14976 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14977 14978 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14979 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14980 !isUnevaluatedContext()) 14981 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14982 14983 // Convert the result back to a half vector. 14984 if (ConvertHalfVec) 14985 return convertVector(UO, Context.HalfTy, *this); 14986 return UO; 14987 } 14988 14989 /// Determine whether the given expression is a qualified member 14990 /// access expression, of a form that could be turned into a pointer to member 14991 /// with the address-of operator. 14992 bool Sema::isQualifiedMemberAccess(Expr *E) { 14993 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14994 if (!DRE->getQualifier()) 14995 return false; 14996 14997 ValueDecl *VD = DRE->getDecl(); 14998 if (!VD->isCXXClassMember()) 14999 return false; 15000 15001 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15002 return true; 15003 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15004 return Method->isInstance(); 15005 15006 return false; 15007 } 15008 15009 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15010 if (!ULE->getQualifier()) 15011 return false; 15012 15013 for (NamedDecl *D : ULE->decls()) { 15014 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15015 if (Method->isInstance()) 15016 return true; 15017 } else { 15018 // Overload set does not contain methods. 15019 break; 15020 } 15021 } 15022 15023 return false; 15024 } 15025 15026 return false; 15027 } 15028 15029 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15030 UnaryOperatorKind Opc, Expr *Input) { 15031 // First things first: handle placeholders so that the 15032 // overloaded-operator check considers the right type. 15033 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15034 // Increment and decrement of pseudo-object references. 15035 if (pty->getKind() == BuiltinType::PseudoObject && 15036 UnaryOperator::isIncrementDecrementOp(Opc)) 15037 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15038 15039 // extension is always a builtin operator. 15040 if (Opc == UO_Extension) 15041 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15042 15043 // & gets special logic for several kinds of placeholder. 15044 // The builtin code knows what to do. 15045 if (Opc == UO_AddrOf && 15046 (pty->getKind() == BuiltinType::Overload || 15047 pty->getKind() == BuiltinType::UnknownAny || 15048 pty->getKind() == BuiltinType::BoundMember)) 15049 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15050 15051 // Anything else needs to be handled now. 15052 ExprResult Result = CheckPlaceholderExpr(Input); 15053 if (Result.isInvalid()) return ExprError(); 15054 Input = Result.get(); 15055 } 15056 15057 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15058 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15059 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15060 // Find all of the overloaded operators visible from this point. 15061 UnresolvedSet<16> Functions; 15062 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15063 if (S && OverOp != OO_None) 15064 LookupOverloadedOperatorName(OverOp, S, Functions); 15065 15066 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15067 } 15068 15069 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15070 } 15071 15072 // Unary Operators. 'Tok' is the token for the operator. 15073 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15074 tok::TokenKind Op, Expr *Input) { 15075 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15076 } 15077 15078 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15079 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15080 LabelDecl *TheDecl) { 15081 TheDecl->markUsed(Context); 15082 // Create the AST node. The address of a label always has type 'void*'. 15083 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15084 Context.getPointerType(Context.VoidTy)); 15085 } 15086 15087 void Sema::ActOnStartStmtExpr() { 15088 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15089 } 15090 15091 void Sema::ActOnStmtExprError() { 15092 // Note that function is also called by TreeTransform when leaving a 15093 // StmtExpr scope without rebuilding anything. 15094 15095 DiscardCleanupsInEvaluationContext(); 15096 PopExpressionEvaluationContext(); 15097 } 15098 15099 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15100 SourceLocation RPLoc) { 15101 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15102 } 15103 15104 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15105 SourceLocation RPLoc, unsigned TemplateDepth) { 15106 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15107 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15108 15109 if (hasAnyUnrecoverableErrorsInThisFunction()) 15110 DiscardCleanupsInEvaluationContext(); 15111 assert(!Cleanup.exprNeedsCleanups() && 15112 "cleanups within StmtExpr not correctly bound!"); 15113 PopExpressionEvaluationContext(); 15114 15115 // FIXME: there are a variety of strange constraints to enforce here, for 15116 // example, it is not possible to goto into a stmt expression apparently. 15117 // More semantic analysis is needed. 15118 15119 // If there are sub-stmts in the compound stmt, take the type of the last one 15120 // as the type of the stmtexpr. 15121 QualType Ty = Context.VoidTy; 15122 bool StmtExprMayBindToTemp = false; 15123 if (!Compound->body_empty()) { 15124 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15125 if (const auto *LastStmt = 15126 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15127 if (const Expr *Value = LastStmt->getExprStmt()) { 15128 StmtExprMayBindToTemp = true; 15129 Ty = Value->getType(); 15130 } 15131 } 15132 } 15133 15134 // FIXME: Check that expression type is complete/non-abstract; statement 15135 // expressions are not lvalues. 15136 Expr *ResStmtExpr = 15137 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15138 if (StmtExprMayBindToTemp) 15139 return MaybeBindToTemporary(ResStmtExpr); 15140 return ResStmtExpr; 15141 } 15142 15143 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15144 if (ER.isInvalid()) 15145 return ExprError(); 15146 15147 // Do function/array conversion on the last expression, but not 15148 // lvalue-to-rvalue. However, initialize an unqualified type. 15149 ER = DefaultFunctionArrayConversion(ER.get()); 15150 if (ER.isInvalid()) 15151 return ExprError(); 15152 Expr *E = ER.get(); 15153 15154 if (E->isTypeDependent()) 15155 return E; 15156 15157 // In ARC, if the final expression ends in a consume, splice 15158 // the consume out and bind it later. In the alternate case 15159 // (when dealing with a retainable type), the result 15160 // initialization will create a produce. In both cases the 15161 // result will be +1, and we'll need to balance that out with 15162 // a bind. 15163 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15164 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15165 return Cast->getSubExpr(); 15166 15167 // FIXME: Provide a better location for the initialization. 15168 return PerformCopyInitialization( 15169 InitializedEntity::InitializeStmtExprResult( 15170 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15171 SourceLocation(), E); 15172 } 15173 15174 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15175 TypeSourceInfo *TInfo, 15176 ArrayRef<OffsetOfComponent> Components, 15177 SourceLocation RParenLoc) { 15178 QualType ArgTy = TInfo->getType(); 15179 bool Dependent = ArgTy->isDependentType(); 15180 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15181 15182 // We must have at least one component that refers to the type, and the first 15183 // one is known to be a field designator. Verify that the ArgTy represents 15184 // a struct/union/class. 15185 if (!Dependent && !ArgTy->isRecordType()) 15186 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15187 << ArgTy << TypeRange); 15188 15189 // Type must be complete per C99 7.17p3 because a declaring a variable 15190 // with an incomplete type would be ill-formed. 15191 if (!Dependent 15192 && RequireCompleteType(BuiltinLoc, ArgTy, 15193 diag::err_offsetof_incomplete_type, TypeRange)) 15194 return ExprError(); 15195 15196 bool DidWarnAboutNonPOD = false; 15197 QualType CurrentType = ArgTy; 15198 SmallVector<OffsetOfNode, 4> Comps; 15199 SmallVector<Expr*, 4> Exprs; 15200 for (const OffsetOfComponent &OC : Components) { 15201 if (OC.isBrackets) { 15202 // Offset of an array sub-field. TODO: Should we allow vector elements? 15203 if (!CurrentType->isDependentType()) { 15204 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15205 if(!AT) 15206 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15207 << CurrentType); 15208 CurrentType = AT->getElementType(); 15209 } else 15210 CurrentType = Context.DependentTy; 15211 15212 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15213 if (IdxRval.isInvalid()) 15214 return ExprError(); 15215 Expr *Idx = IdxRval.get(); 15216 15217 // The expression must be an integral expression. 15218 // FIXME: An integral constant expression? 15219 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15220 !Idx->getType()->isIntegerType()) 15221 return ExprError( 15222 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15223 << Idx->getSourceRange()); 15224 15225 // Record this array index. 15226 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15227 Exprs.push_back(Idx); 15228 continue; 15229 } 15230 15231 // Offset of a field. 15232 if (CurrentType->isDependentType()) { 15233 // We have the offset of a field, but we can't look into the dependent 15234 // type. Just record the identifier of the field. 15235 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15236 CurrentType = Context.DependentTy; 15237 continue; 15238 } 15239 15240 // We need to have a complete type to look into. 15241 if (RequireCompleteType(OC.LocStart, CurrentType, 15242 diag::err_offsetof_incomplete_type)) 15243 return ExprError(); 15244 15245 // Look for the designated field. 15246 const RecordType *RC = CurrentType->getAs<RecordType>(); 15247 if (!RC) 15248 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15249 << CurrentType); 15250 RecordDecl *RD = RC->getDecl(); 15251 15252 // C++ [lib.support.types]p5: 15253 // The macro offsetof accepts a restricted set of type arguments in this 15254 // International Standard. type shall be a POD structure or a POD union 15255 // (clause 9). 15256 // C++11 [support.types]p4: 15257 // If type is not a standard-layout class (Clause 9), the results are 15258 // undefined. 15259 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15260 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15261 unsigned DiagID = 15262 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15263 : diag::ext_offsetof_non_pod_type; 15264 15265 if (!IsSafe && !DidWarnAboutNonPOD && 15266 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15267 PDiag(DiagID) 15268 << SourceRange(Components[0].LocStart, OC.LocEnd) 15269 << CurrentType)) 15270 DidWarnAboutNonPOD = true; 15271 } 15272 15273 // Look for the field. 15274 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15275 LookupQualifiedName(R, RD); 15276 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15277 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15278 if (!MemberDecl) { 15279 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15280 MemberDecl = IndirectMemberDecl->getAnonField(); 15281 } 15282 15283 if (!MemberDecl) 15284 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15285 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15286 OC.LocEnd)); 15287 15288 // C99 7.17p3: 15289 // (If the specified member is a bit-field, the behavior is undefined.) 15290 // 15291 // We diagnose this as an error. 15292 if (MemberDecl->isBitField()) { 15293 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15294 << MemberDecl->getDeclName() 15295 << SourceRange(BuiltinLoc, RParenLoc); 15296 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15297 return ExprError(); 15298 } 15299 15300 RecordDecl *Parent = MemberDecl->getParent(); 15301 if (IndirectMemberDecl) 15302 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15303 15304 // If the member was found in a base class, introduce OffsetOfNodes for 15305 // the base class indirections. 15306 CXXBasePaths Paths; 15307 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15308 Paths)) { 15309 if (Paths.getDetectedVirtual()) { 15310 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15311 << MemberDecl->getDeclName() 15312 << SourceRange(BuiltinLoc, RParenLoc); 15313 return ExprError(); 15314 } 15315 15316 CXXBasePath &Path = Paths.front(); 15317 for (const CXXBasePathElement &B : Path) 15318 Comps.push_back(OffsetOfNode(B.Base)); 15319 } 15320 15321 if (IndirectMemberDecl) { 15322 for (auto *FI : IndirectMemberDecl->chain()) { 15323 assert(isa<FieldDecl>(FI)); 15324 Comps.push_back(OffsetOfNode(OC.LocStart, 15325 cast<FieldDecl>(FI), OC.LocEnd)); 15326 } 15327 } else 15328 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15329 15330 CurrentType = MemberDecl->getType().getNonReferenceType(); 15331 } 15332 15333 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15334 Comps, Exprs, RParenLoc); 15335 } 15336 15337 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15338 SourceLocation BuiltinLoc, 15339 SourceLocation TypeLoc, 15340 ParsedType ParsedArgTy, 15341 ArrayRef<OffsetOfComponent> Components, 15342 SourceLocation RParenLoc) { 15343 15344 TypeSourceInfo *ArgTInfo; 15345 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15346 if (ArgTy.isNull()) 15347 return ExprError(); 15348 15349 if (!ArgTInfo) 15350 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15351 15352 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15353 } 15354 15355 15356 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15357 Expr *CondExpr, 15358 Expr *LHSExpr, Expr *RHSExpr, 15359 SourceLocation RPLoc) { 15360 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15361 15362 ExprValueKind VK = VK_PRValue; 15363 ExprObjectKind OK = OK_Ordinary; 15364 QualType resType; 15365 bool CondIsTrue = false; 15366 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15367 resType = Context.DependentTy; 15368 } else { 15369 // The conditional expression is required to be a constant expression. 15370 llvm::APSInt condEval(32); 15371 ExprResult CondICE = VerifyIntegerConstantExpression( 15372 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15373 if (CondICE.isInvalid()) 15374 return ExprError(); 15375 CondExpr = CondICE.get(); 15376 CondIsTrue = condEval.getZExtValue(); 15377 15378 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15379 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15380 15381 resType = ActiveExpr->getType(); 15382 VK = ActiveExpr->getValueKind(); 15383 OK = ActiveExpr->getObjectKind(); 15384 } 15385 15386 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15387 resType, VK, OK, RPLoc, CondIsTrue); 15388 } 15389 15390 //===----------------------------------------------------------------------===// 15391 // Clang Extensions. 15392 //===----------------------------------------------------------------------===// 15393 15394 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15395 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15396 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15397 15398 if (LangOpts.CPlusPlus) { 15399 MangleNumberingContext *MCtx; 15400 Decl *ManglingContextDecl; 15401 std::tie(MCtx, ManglingContextDecl) = 15402 getCurrentMangleNumberContext(Block->getDeclContext()); 15403 if (MCtx) { 15404 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15405 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15406 } 15407 } 15408 15409 PushBlockScope(CurScope, Block); 15410 CurContext->addDecl(Block); 15411 if (CurScope) 15412 PushDeclContext(CurScope, Block); 15413 else 15414 CurContext = Block; 15415 15416 getCurBlock()->HasImplicitReturnType = true; 15417 15418 // Enter a new evaluation context to insulate the block from any 15419 // cleanups from the enclosing full-expression. 15420 PushExpressionEvaluationContext( 15421 ExpressionEvaluationContext::PotentiallyEvaluated); 15422 } 15423 15424 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15425 Scope *CurScope) { 15426 assert(ParamInfo.getIdentifier() == nullptr && 15427 "block-id should have no identifier!"); 15428 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15429 BlockScopeInfo *CurBlock = getCurBlock(); 15430 15431 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15432 QualType T = Sig->getType(); 15433 15434 // FIXME: We should allow unexpanded parameter packs here, but that would, 15435 // in turn, make the block expression contain unexpanded parameter packs. 15436 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15437 // Drop the parameters. 15438 FunctionProtoType::ExtProtoInfo EPI; 15439 EPI.HasTrailingReturn = false; 15440 EPI.TypeQuals.addConst(); 15441 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15442 Sig = Context.getTrivialTypeSourceInfo(T); 15443 } 15444 15445 // GetTypeForDeclarator always produces a function type for a block 15446 // literal signature. Furthermore, it is always a FunctionProtoType 15447 // unless the function was written with a typedef. 15448 assert(T->isFunctionType() && 15449 "GetTypeForDeclarator made a non-function block signature"); 15450 15451 // Look for an explicit signature in that function type. 15452 FunctionProtoTypeLoc ExplicitSignature; 15453 15454 if ((ExplicitSignature = Sig->getTypeLoc() 15455 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15456 15457 // Check whether that explicit signature was synthesized by 15458 // GetTypeForDeclarator. If so, don't save that as part of the 15459 // written signature. 15460 if (ExplicitSignature.getLocalRangeBegin() == 15461 ExplicitSignature.getLocalRangeEnd()) { 15462 // This would be much cheaper if we stored TypeLocs instead of 15463 // TypeSourceInfos. 15464 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15465 unsigned Size = Result.getFullDataSize(); 15466 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15467 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15468 15469 ExplicitSignature = FunctionProtoTypeLoc(); 15470 } 15471 } 15472 15473 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15474 CurBlock->FunctionType = T; 15475 15476 const auto *Fn = T->castAs<FunctionType>(); 15477 QualType RetTy = Fn->getReturnType(); 15478 bool isVariadic = 15479 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15480 15481 CurBlock->TheDecl->setIsVariadic(isVariadic); 15482 15483 // Context.DependentTy is used as a placeholder for a missing block 15484 // return type. TODO: what should we do with declarators like: 15485 // ^ * { ... } 15486 // If the answer is "apply template argument deduction".... 15487 if (RetTy != Context.DependentTy) { 15488 CurBlock->ReturnType = RetTy; 15489 CurBlock->TheDecl->setBlockMissingReturnType(false); 15490 CurBlock->HasImplicitReturnType = false; 15491 } 15492 15493 // Push block parameters from the declarator if we had them. 15494 SmallVector<ParmVarDecl*, 8> Params; 15495 if (ExplicitSignature) { 15496 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15497 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15498 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15499 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15500 // Diagnose this as an extension in C17 and earlier. 15501 if (!getLangOpts().C2x) 15502 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15503 } 15504 Params.push_back(Param); 15505 } 15506 15507 // Fake up parameter variables if we have a typedef, like 15508 // ^ fntype { ... } 15509 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15510 for (const auto &I : Fn->param_types()) { 15511 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15512 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15513 Params.push_back(Param); 15514 } 15515 } 15516 15517 // Set the parameters on the block decl. 15518 if (!Params.empty()) { 15519 CurBlock->TheDecl->setParams(Params); 15520 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15521 /*CheckParameterNames=*/false); 15522 } 15523 15524 // Finally we can process decl attributes. 15525 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15526 15527 // Put the parameter variables in scope. 15528 for (auto AI : CurBlock->TheDecl->parameters()) { 15529 AI->setOwningFunction(CurBlock->TheDecl); 15530 15531 // If this has an identifier, add it to the scope stack. 15532 if (AI->getIdentifier()) { 15533 CheckShadow(CurBlock->TheScope, AI); 15534 15535 PushOnScopeChains(AI, CurBlock->TheScope); 15536 } 15537 } 15538 } 15539 15540 /// ActOnBlockError - If there is an error parsing a block, this callback 15541 /// is invoked to pop the information about the block from the action impl. 15542 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15543 // Leave the expression-evaluation context. 15544 DiscardCleanupsInEvaluationContext(); 15545 PopExpressionEvaluationContext(); 15546 15547 // Pop off CurBlock, handle nested blocks. 15548 PopDeclContext(); 15549 PopFunctionScopeInfo(); 15550 } 15551 15552 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15553 /// literal was successfully completed. ^(int x){...} 15554 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15555 Stmt *Body, Scope *CurScope) { 15556 // If blocks are disabled, emit an error. 15557 if (!LangOpts.Blocks) 15558 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15559 15560 // Leave the expression-evaluation context. 15561 if (hasAnyUnrecoverableErrorsInThisFunction()) 15562 DiscardCleanupsInEvaluationContext(); 15563 assert(!Cleanup.exprNeedsCleanups() && 15564 "cleanups within block not correctly bound!"); 15565 PopExpressionEvaluationContext(); 15566 15567 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15568 BlockDecl *BD = BSI->TheDecl; 15569 15570 if (BSI->HasImplicitReturnType) 15571 deduceClosureReturnType(*BSI); 15572 15573 QualType RetTy = Context.VoidTy; 15574 if (!BSI->ReturnType.isNull()) 15575 RetTy = BSI->ReturnType; 15576 15577 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15578 QualType BlockTy; 15579 15580 // If the user wrote a function type in some form, try to use that. 15581 if (!BSI->FunctionType.isNull()) { 15582 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15583 15584 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15585 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15586 15587 // Turn protoless block types into nullary block types. 15588 if (isa<FunctionNoProtoType>(FTy)) { 15589 FunctionProtoType::ExtProtoInfo EPI; 15590 EPI.ExtInfo = Ext; 15591 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15592 15593 // Otherwise, if we don't need to change anything about the function type, 15594 // preserve its sugar structure. 15595 } else if (FTy->getReturnType() == RetTy && 15596 (!NoReturn || FTy->getNoReturnAttr())) { 15597 BlockTy = BSI->FunctionType; 15598 15599 // Otherwise, make the minimal modifications to the function type. 15600 } else { 15601 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15602 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15603 EPI.TypeQuals = Qualifiers(); 15604 EPI.ExtInfo = Ext; 15605 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15606 } 15607 15608 // If we don't have a function type, just build one from nothing. 15609 } else { 15610 FunctionProtoType::ExtProtoInfo EPI; 15611 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15612 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15613 } 15614 15615 DiagnoseUnusedParameters(BD->parameters()); 15616 BlockTy = Context.getBlockPointerType(BlockTy); 15617 15618 // If needed, diagnose invalid gotos and switches in the block. 15619 if (getCurFunction()->NeedsScopeChecking() && 15620 !PP.isCodeCompletionEnabled()) 15621 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15622 15623 BD->setBody(cast<CompoundStmt>(Body)); 15624 15625 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15626 DiagnoseUnguardedAvailabilityViolations(BD); 15627 15628 // Try to apply the named return value optimization. We have to check again 15629 // if we can do this, though, because blocks keep return statements around 15630 // to deduce an implicit return type. 15631 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15632 !BD->isDependentContext()) 15633 computeNRVO(Body, BSI); 15634 15635 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15636 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15637 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15638 NTCUK_Destruct|NTCUK_Copy); 15639 15640 PopDeclContext(); 15641 15642 // Set the captured variables on the block. 15643 SmallVector<BlockDecl::Capture, 4> Captures; 15644 for (Capture &Cap : BSI->Captures) { 15645 if (Cap.isInvalid() || Cap.isThisCapture()) 15646 continue; 15647 15648 VarDecl *Var = Cap.getVariable(); 15649 Expr *CopyExpr = nullptr; 15650 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15651 if (const RecordType *Record = 15652 Cap.getCaptureType()->getAs<RecordType>()) { 15653 // The capture logic needs the destructor, so make sure we mark it. 15654 // Usually this is unnecessary because most local variables have 15655 // their destructors marked at declaration time, but parameters are 15656 // an exception because it's technically only the call site that 15657 // actually requires the destructor. 15658 if (isa<ParmVarDecl>(Var)) 15659 FinalizeVarWithDestructor(Var, Record); 15660 15661 // Enter a separate potentially-evaluated context while building block 15662 // initializers to isolate their cleanups from those of the block 15663 // itself. 15664 // FIXME: Is this appropriate even when the block itself occurs in an 15665 // unevaluated operand? 15666 EnterExpressionEvaluationContext EvalContext( 15667 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15668 15669 SourceLocation Loc = Cap.getLocation(); 15670 15671 ExprResult Result = BuildDeclarationNameExpr( 15672 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15673 15674 // According to the blocks spec, the capture of a variable from 15675 // the stack requires a const copy constructor. This is not true 15676 // of the copy/move done to move a __block variable to the heap. 15677 if (!Result.isInvalid() && 15678 !Result.get()->getType().isConstQualified()) { 15679 Result = ImpCastExprToType(Result.get(), 15680 Result.get()->getType().withConst(), 15681 CK_NoOp, VK_LValue); 15682 } 15683 15684 if (!Result.isInvalid()) { 15685 Result = PerformCopyInitialization( 15686 InitializedEntity::InitializeBlock(Var->getLocation(), 15687 Cap.getCaptureType(), false), 15688 Loc, Result.get()); 15689 } 15690 15691 // Build a full-expression copy expression if initialization 15692 // succeeded and used a non-trivial constructor. Recover from 15693 // errors by pretending that the copy isn't necessary. 15694 if (!Result.isInvalid() && 15695 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15696 ->isTrivial()) { 15697 Result = MaybeCreateExprWithCleanups(Result); 15698 CopyExpr = Result.get(); 15699 } 15700 } 15701 } 15702 15703 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15704 CopyExpr); 15705 Captures.push_back(NewCap); 15706 } 15707 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15708 15709 // Pop the block scope now but keep it alive to the end of this function. 15710 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15711 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15712 15713 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15714 15715 // If the block isn't obviously global, i.e. it captures anything at 15716 // all, then we need to do a few things in the surrounding context: 15717 if (Result->getBlockDecl()->hasCaptures()) { 15718 // First, this expression has a new cleanup object. 15719 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15720 Cleanup.setExprNeedsCleanups(true); 15721 15722 // It also gets a branch-protected scope if any of the captured 15723 // variables needs destruction. 15724 for (const auto &CI : Result->getBlockDecl()->captures()) { 15725 const VarDecl *var = CI.getVariable(); 15726 if (var->getType().isDestructedType() != QualType::DK_none) { 15727 setFunctionHasBranchProtectedScope(); 15728 break; 15729 } 15730 } 15731 } 15732 15733 if (getCurFunction()) 15734 getCurFunction()->addBlock(BD); 15735 15736 return Result; 15737 } 15738 15739 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15740 SourceLocation RPLoc) { 15741 TypeSourceInfo *TInfo; 15742 GetTypeFromParser(Ty, &TInfo); 15743 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15744 } 15745 15746 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15747 Expr *E, TypeSourceInfo *TInfo, 15748 SourceLocation RPLoc) { 15749 Expr *OrigExpr = E; 15750 bool IsMS = false; 15751 15752 // CUDA device code does not support varargs. 15753 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15754 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15755 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15756 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15757 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15758 } 15759 } 15760 15761 // NVPTX does not support va_arg expression. 15762 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15763 Context.getTargetInfo().getTriple().isNVPTX()) 15764 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15765 15766 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15767 // as Microsoft ABI on an actual Microsoft platform, where 15768 // __builtin_ms_va_list and __builtin_va_list are the same.) 15769 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15770 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15771 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15772 if (Context.hasSameType(MSVaListType, E->getType())) { 15773 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15774 return ExprError(); 15775 IsMS = true; 15776 } 15777 } 15778 15779 // Get the va_list type 15780 QualType VaListType = Context.getBuiltinVaListType(); 15781 if (!IsMS) { 15782 if (VaListType->isArrayType()) { 15783 // Deal with implicit array decay; for example, on x86-64, 15784 // va_list is an array, but it's supposed to decay to 15785 // a pointer for va_arg. 15786 VaListType = Context.getArrayDecayedType(VaListType); 15787 // Make sure the input expression also decays appropriately. 15788 ExprResult Result = UsualUnaryConversions(E); 15789 if (Result.isInvalid()) 15790 return ExprError(); 15791 E = Result.get(); 15792 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15793 // If va_list is a record type and we are compiling in C++ mode, 15794 // check the argument using reference binding. 15795 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15796 Context, Context.getLValueReferenceType(VaListType), false); 15797 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15798 if (Init.isInvalid()) 15799 return ExprError(); 15800 E = Init.getAs<Expr>(); 15801 } else { 15802 // Otherwise, the va_list argument must be an l-value because 15803 // it is modified by va_arg. 15804 if (!E->isTypeDependent() && 15805 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15806 return ExprError(); 15807 } 15808 } 15809 15810 if (!IsMS && !E->isTypeDependent() && 15811 !Context.hasSameType(VaListType, E->getType())) 15812 return ExprError( 15813 Diag(E->getBeginLoc(), 15814 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15815 << OrigExpr->getType() << E->getSourceRange()); 15816 15817 if (!TInfo->getType()->isDependentType()) { 15818 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15819 diag::err_second_parameter_to_va_arg_incomplete, 15820 TInfo->getTypeLoc())) 15821 return ExprError(); 15822 15823 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15824 TInfo->getType(), 15825 diag::err_second_parameter_to_va_arg_abstract, 15826 TInfo->getTypeLoc())) 15827 return ExprError(); 15828 15829 if (!TInfo->getType().isPODType(Context)) { 15830 Diag(TInfo->getTypeLoc().getBeginLoc(), 15831 TInfo->getType()->isObjCLifetimeType() 15832 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15833 : diag::warn_second_parameter_to_va_arg_not_pod) 15834 << TInfo->getType() 15835 << TInfo->getTypeLoc().getSourceRange(); 15836 } 15837 15838 // Check for va_arg where arguments of the given type will be promoted 15839 // (i.e. this va_arg is guaranteed to have undefined behavior). 15840 QualType PromoteType; 15841 if (TInfo->getType()->isPromotableIntegerType()) { 15842 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15843 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15844 // and C2x 7.16.1.1p2 says, in part: 15845 // If type is not compatible with the type of the actual next argument 15846 // (as promoted according to the default argument promotions), the 15847 // behavior is undefined, except for the following cases: 15848 // - both types are pointers to qualified or unqualified versions of 15849 // compatible types; 15850 // - one type is a signed integer type, the other type is the 15851 // corresponding unsigned integer type, and the value is 15852 // representable in both types; 15853 // - one type is pointer to qualified or unqualified void and the 15854 // other is a pointer to a qualified or unqualified character type. 15855 // Given that type compatibility is the primary requirement (ignoring 15856 // qualifications), you would think we could call typesAreCompatible() 15857 // directly to test this. However, in C++, that checks for *same type*, 15858 // which causes false positives when passing an enumeration type to 15859 // va_arg. Instead, get the underlying type of the enumeration and pass 15860 // that. 15861 QualType UnderlyingType = TInfo->getType(); 15862 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15863 UnderlyingType = ET->getDecl()->getIntegerType(); 15864 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15865 /*CompareUnqualified*/ true)) 15866 PromoteType = QualType(); 15867 15868 // If the types are still not compatible, we need to test whether the 15869 // promoted type and the underlying type are the same except for 15870 // signedness. Ask the AST for the correctly corresponding type and see 15871 // if that's compatible. 15872 if (!PromoteType.isNull() && 15873 PromoteType->isUnsignedIntegerType() != 15874 UnderlyingType->isUnsignedIntegerType()) { 15875 UnderlyingType = 15876 UnderlyingType->isUnsignedIntegerType() 15877 ? Context.getCorrespondingSignedType(UnderlyingType) 15878 : Context.getCorrespondingUnsignedType(UnderlyingType); 15879 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15880 /*CompareUnqualified*/ true)) 15881 PromoteType = QualType(); 15882 } 15883 } 15884 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15885 PromoteType = Context.DoubleTy; 15886 if (!PromoteType.isNull()) 15887 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15888 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15889 << TInfo->getType() 15890 << PromoteType 15891 << TInfo->getTypeLoc().getSourceRange()); 15892 } 15893 15894 QualType T = TInfo->getType().getNonLValueExprType(Context); 15895 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15896 } 15897 15898 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15899 // The type of __null will be int or long, depending on the size of 15900 // pointers on the target. 15901 QualType Ty; 15902 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15903 if (pw == Context.getTargetInfo().getIntWidth()) 15904 Ty = Context.IntTy; 15905 else if (pw == Context.getTargetInfo().getLongWidth()) 15906 Ty = Context.LongTy; 15907 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15908 Ty = Context.LongLongTy; 15909 else { 15910 llvm_unreachable("I don't know size of pointer!"); 15911 } 15912 15913 return new (Context) GNUNullExpr(Ty, TokenLoc); 15914 } 15915 15916 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15917 SourceLocation BuiltinLoc, 15918 SourceLocation RPLoc) { 15919 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15920 } 15921 15922 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15923 SourceLocation BuiltinLoc, 15924 SourceLocation RPLoc, 15925 DeclContext *ParentContext) { 15926 return new (Context) 15927 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15928 } 15929 15930 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15931 bool Diagnose) { 15932 if (!getLangOpts().ObjC) 15933 return false; 15934 15935 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15936 if (!PT) 15937 return false; 15938 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15939 15940 // Ignore any parens, implicit casts (should only be 15941 // array-to-pointer decays), and not-so-opaque values. The last is 15942 // important for making this trigger for property assignments. 15943 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15944 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15945 if (OV->getSourceExpr()) 15946 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15947 15948 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15949 if (!PT->isObjCIdType() && 15950 !(ID && ID->getIdentifier()->isStr("NSString"))) 15951 return false; 15952 if (!SL->isAscii()) 15953 return false; 15954 15955 if (Diagnose) { 15956 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15957 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15958 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15959 } 15960 return true; 15961 } 15962 15963 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15964 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15965 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15966 !SrcExpr->isNullPointerConstant( 15967 getASTContext(), Expr::NPC_NeverValueDependent)) { 15968 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15969 return false; 15970 if (Diagnose) { 15971 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15972 << /*number*/1 15973 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15974 Expr *NumLit = 15975 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15976 if (NumLit) 15977 Exp = NumLit; 15978 } 15979 return true; 15980 } 15981 15982 return false; 15983 } 15984 15985 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15986 const Expr *SrcExpr) { 15987 if (!DstType->isFunctionPointerType() || 15988 !SrcExpr->getType()->isFunctionType()) 15989 return false; 15990 15991 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15992 if (!DRE) 15993 return false; 15994 15995 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15996 if (!FD) 15997 return false; 15998 15999 return !S.checkAddressOfFunctionIsAvailable(FD, 16000 /*Complain=*/true, 16001 SrcExpr->getBeginLoc()); 16002 } 16003 16004 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16005 SourceLocation Loc, 16006 QualType DstType, QualType SrcType, 16007 Expr *SrcExpr, AssignmentAction Action, 16008 bool *Complained) { 16009 if (Complained) 16010 *Complained = false; 16011 16012 // Decode the result (notice that AST's are still created for extensions). 16013 bool CheckInferredResultType = false; 16014 bool isInvalid = false; 16015 unsigned DiagKind = 0; 16016 ConversionFixItGenerator ConvHints; 16017 bool MayHaveConvFixit = false; 16018 bool MayHaveFunctionDiff = false; 16019 const ObjCInterfaceDecl *IFace = nullptr; 16020 const ObjCProtocolDecl *PDecl = nullptr; 16021 16022 switch (ConvTy) { 16023 case Compatible: 16024 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16025 return false; 16026 16027 case PointerToInt: 16028 if (getLangOpts().CPlusPlus) { 16029 DiagKind = diag::err_typecheck_convert_pointer_int; 16030 isInvalid = true; 16031 } else { 16032 DiagKind = diag::ext_typecheck_convert_pointer_int; 16033 } 16034 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16035 MayHaveConvFixit = true; 16036 break; 16037 case IntToPointer: 16038 if (getLangOpts().CPlusPlus) { 16039 DiagKind = diag::err_typecheck_convert_int_pointer; 16040 isInvalid = true; 16041 } else { 16042 DiagKind = diag::ext_typecheck_convert_int_pointer; 16043 } 16044 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16045 MayHaveConvFixit = true; 16046 break; 16047 case IncompatibleFunctionPointer: 16048 if (getLangOpts().CPlusPlus) { 16049 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16050 isInvalid = true; 16051 } else { 16052 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16053 } 16054 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16055 MayHaveConvFixit = true; 16056 break; 16057 case IncompatiblePointer: 16058 if (Action == AA_Passing_CFAudited) { 16059 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16060 } else if (getLangOpts().CPlusPlus) { 16061 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16062 isInvalid = true; 16063 } else { 16064 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16065 } 16066 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16067 SrcType->isObjCObjectPointerType(); 16068 if (!CheckInferredResultType) { 16069 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16070 } else if (CheckInferredResultType) { 16071 SrcType = SrcType.getUnqualifiedType(); 16072 DstType = DstType.getUnqualifiedType(); 16073 } 16074 MayHaveConvFixit = true; 16075 break; 16076 case IncompatiblePointerSign: 16077 if (getLangOpts().CPlusPlus) { 16078 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16079 isInvalid = true; 16080 } else { 16081 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16082 } 16083 break; 16084 case FunctionVoidPointer: 16085 if (getLangOpts().CPlusPlus) { 16086 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16087 isInvalid = true; 16088 } else { 16089 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16090 } 16091 break; 16092 case IncompatiblePointerDiscardsQualifiers: { 16093 // Perform array-to-pointer decay if necessary. 16094 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16095 16096 isInvalid = true; 16097 16098 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16099 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16100 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16101 DiagKind = diag::err_typecheck_incompatible_address_space; 16102 break; 16103 16104 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16105 DiagKind = diag::err_typecheck_incompatible_ownership; 16106 break; 16107 } 16108 16109 llvm_unreachable("unknown error case for discarding qualifiers!"); 16110 // fallthrough 16111 } 16112 case CompatiblePointerDiscardsQualifiers: 16113 // If the qualifiers lost were because we were applying the 16114 // (deprecated) C++ conversion from a string literal to a char* 16115 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16116 // Ideally, this check would be performed in 16117 // checkPointerTypesForAssignment. However, that would require a 16118 // bit of refactoring (so that the second argument is an 16119 // expression, rather than a type), which should be done as part 16120 // of a larger effort to fix checkPointerTypesForAssignment for 16121 // C++ semantics. 16122 if (getLangOpts().CPlusPlus && 16123 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16124 return false; 16125 if (getLangOpts().CPlusPlus) { 16126 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16127 isInvalid = true; 16128 } else { 16129 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16130 } 16131 16132 break; 16133 case IncompatibleNestedPointerQualifiers: 16134 if (getLangOpts().CPlusPlus) { 16135 isInvalid = true; 16136 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16137 } else { 16138 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16139 } 16140 break; 16141 case IncompatibleNestedPointerAddressSpaceMismatch: 16142 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16143 isInvalid = true; 16144 break; 16145 case IntToBlockPointer: 16146 DiagKind = diag::err_int_to_block_pointer; 16147 isInvalid = true; 16148 break; 16149 case IncompatibleBlockPointer: 16150 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16151 isInvalid = true; 16152 break; 16153 case IncompatibleObjCQualifiedId: { 16154 if (SrcType->isObjCQualifiedIdType()) { 16155 const ObjCObjectPointerType *srcOPT = 16156 SrcType->castAs<ObjCObjectPointerType>(); 16157 for (auto *srcProto : srcOPT->quals()) { 16158 PDecl = srcProto; 16159 break; 16160 } 16161 if (const ObjCInterfaceType *IFaceT = 16162 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16163 IFace = IFaceT->getDecl(); 16164 } 16165 else if (DstType->isObjCQualifiedIdType()) { 16166 const ObjCObjectPointerType *dstOPT = 16167 DstType->castAs<ObjCObjectPointerType>(); 16168 for (auto *dstProto : dstOPT->quals()) { 16169 PDecl = dstProto; 16170 break; 16171 } 16172 if (const ObjCInterfaceType *IFaceT = 16173 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16174 IFace = IFaceT->getDecl(); 16175 } 16176 if (getLangOpts().CPlusPlus) { 16177 DiagKind = diag::err_incompatible_qualified_id; 16178 isInvalid = true; 16179 } else { 16180 DiagKind = diag::warn_incompatible_qualified_id; 16181 } 16182 break; 16183 } 16184 case IncompatibleVectors: 16185 if (getLangOpts().CPlusPlus) { 16186 DiagKind = diag::err_incompatible_vectors; 16187 isInvalid = true; 16188 } else { 16189 DiagKind = diag::warn_incompatible_vectors; 16190 } 16191 break; 16192 case IncompatibleObjCWeakRef: 16193 DiagKind = diag::err_arc_weak_unavailable_assign; 16194 isInvalid = true; 16195 break; 16196 case Incompatible: 16197 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16198 if (Complained) 16199 *Complained = true; 16200 return true; 16201 } 16202 16203 DiagKind = diag::err_typecheck_convert_incompatible; 16204 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16205 MayHaveConvFixit = true; 16206 isInvalid = true; 16207 MayHaveFunctionDiff = true; 16208 break; 16209 } 16210 16211 QualType FirstType, SecondType; 16212 switch (Action) { 16213 case AA_Assigning: 16214 case AA_Initializing: 16215 // The destination type comes first. 16216 FirstType = DstType; 16217 SecondType = SrcType; 16218 break; 16219 16220 case AA_Returning: 16221 case AA_Passing: 16222 case AA_Passing_CFAudited: 16223 case AA_Converting: 16224 case AA_Sending: 16225 case AA_Casting: 16226 // The source type comes first. 16227 FirstType = SrcType; 16228 SecondType = DstType; 16229 break; 16230 } 16231 16232 PartialDiagnostic FDiag = PDiag(DiagKind); 16233 if (Action == AA_Passing_CFAudited) 16234 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16235 else 16236 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16237 16238 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16239 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16240 auto isPlainChar = [](const clang::Type *Type) { 16241 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16242 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16243 }; 16244 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16245 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16246 } 16247 16248 // If we can fix the conversion, suggest the FixIts. 16249 if (!ConvHints.isNull()) { 16250 for (FixItHint &H : ConvHints.Hints) 16251 FDiag << H; 16252 } 16253 16254 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16255 16256 if (MayHaveFunctionDiff) 16257 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16258 16259 Diag(Loc, FDiag); 16260 if ((DiagKind == diag::warn_incompatible_qualified_id || 16261 DiagKind == diag::err_incompatible_qualified_id) && 16262 PDecl && IFace && !IFace->hasDefinition()) 16263 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16264 << IFace << PDecl; 16265 16266 if (SecondType == Context.OverloadTy) 16267 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16268 FirstType, /*TakingAddress=*/true); 16269 16270 if (CheckInferredResultType) 16271 EmitRelatedResultTypeNote(SrcExpr); 16272 16273 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16274 EmitRelatedResultTypeNoteForReturn(DstType); 16275 16276 if (Complained) 16277 *Complained = true; 16278 return isInvalid; 16279 } 16280 16281 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16282 llvm::APSInt *Result, 16283 AllowFoldKind CanFold) { 16284 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16285 public: 16286 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16287 QualType T) override { 16288 return S.Diag(Loc, diag::err_ice_not_integral) 16289 << T << S.LangOpts.CPlusPlus; 16290 } 16291 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16292 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16293 } 16294 } Diagnoser; 16295 16296 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16297 } 16298 16299 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16300 llvm::APSInt *Result, 16301 unsigned DiagID, 16302 AllowFoldKind CanFold) { 16303 class IDDiagnoser : public VerifyICEDiagnoser { 16304 unsigned DiagID; 16305 16306 public: 16307 IDDiagnoser(unsigned DiagID) 16308 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16309 16310 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16311 return S.Diag(Loc, DiagID); 16312 } 16313 } Diagnoser(DiagID); 16314 16315 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16316 } 16317 16318 Sema::SemaDiagnosticBuilder 16319 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16320 QualType T) { 16321 return diagnoseNotICE(S, Loc); 16322 } 16323 16324 Sema::SemaDiagnosticBuilder 16325 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16326 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16327 } 16328 16329 ExprResult 16330 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16331 VerifyICEDiagnoser &Diagnoser, 16332 AllowFoldKind CanFold) { 16333 SourceLocation DiagLoc = E->getBeginLoc(); 16334 16335 if (getLangOpts().CPlusPlus11) { 16336 // C++11 [expr.const]p5: 16337 // If an expression of literal class type is used in a context where an 16338 // integral constant expression is required, then that class type shall 16339 // have a single non-explicit conversion function to an integral or 16340 // unscoped enumeration type 16341 ExprResult Converted; 16342 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16343 VerifyICEDiagnoser &BaseDiagnoser; 16344 public: 16345 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16346 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16347 BaseDiagnoser.Suppress, true), 16348 BaseDiagnoser(BaseDiagnoser) {} 16349 16350 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16351 QualType T) override { 16352 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16353 } 16354 16355 SemaDiagnosticBuilder diagnoseIncomplete( 16356 Sema &S, SourceLocation Loc, QualType T) override { 16357 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16358 } 16359 16360 SemaDiagnosticBuilder diagnoseExplicitConv( 16361 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16362 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16363 } 16364 16365 SemaDiagnosticBuilder noteExplicitConv( 16366 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16367 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16368 << ConvTy->isEnumeralType() << ConvTy; 16369 } 16370 16371 SemaDiagnosticBuilder diagnoseAmbiguous( 16372 Sema &S, SourceLocation Loc, QualType T) override { 16373 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16374 } 16375 16376 SemaDiagnosticBuilder noteAmbiguous( 16377 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16378 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16379 << ConvTy->isEnumeralType() << ConvTy; 16380 } 16381 16382 SemaDiagnosticBuilder diagnoseConversion( 16383 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16384 llvm_unreachable("conversion functions are permitted"); 16385 } 16386 } ConvertDiagnoser(Diagnoser); 16387 16388 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16389 ConvertDiagnoser); 16390 if (Converted.isInvalid()) 16391 return Converted; 16392 E = Converted.get(); 16393 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16394 return ExprError(); 16395 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16396 // An ICE must be of integral or unscoped enumeration type. 16397 if (!Diagnoser.Suppress) 16398 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16399 << E->getSourceRange(); 16400 return ExprError(); 16401 } 16402 16403 ExprResult RValueExpr = DefaultLvalueConversion(E); 16404 if (RValueExpr.isInvalid()) 16405 return ExprError(); 16406 16407 E = RValueExpr.get(); 16408 16409 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16410 // in the non-ICE case. 16411 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16412 if (Result) 16413 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16414 if (!isa<ConstantExpr>(E)) 16415 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16416 : ConstantExpr::Create(Context, E); 16417 return E; 16418 } 16419 16420 Expr::EvalResult EvalResult; 16421 SmallVector<PartialDiagnosticAt, 8> Notes; 16422 EvalResult.Diag = &Notes; 16423 16424 // Try to evaluate the expression, and produce diagnostics explaining why it's 16425 // not a constant expression as a side-effect. 16426 bool Folded = 16427 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16428 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16429 16430 if (!isa<ConstantExpr>(E)) 16431 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16432 16433 // In C++11, we can rely on diagnostics being produced for any expression 16434 // which is not a constant expression. If no diagnostics were produced, then 16435 // this is a constant expression. 16436 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16437 if (Result) 16438 *Result = EvalResult.Val.getInt(); 16439 return E; 16440 } 16441 16442 // If our only note is the usual "invalid subexpression" note, just point 16443 // the caret at its location rather than producing an essentially 16444 // redundant note. 16445 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16446 diag::note_invalid_subexpr_in_const_expr) { 16447 DiagLoc = Notes[0].first; 16448 Notes.clear(); 16449 } 16450 16451 if (!Folded || !CanFold) { 16452 if (!Diagnoser.Suppress) { 16453 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16454 for (const PartialDiagnosticAt &Note : Notes) 16455 Diag(Note.first, Note.second); 16456 } 16457 16458 return ExprError(); 16459 } 16460 16461 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16462 for (const PartialDiagnosticAt &Note : Notes) 16463 Diag(Note.first, Note.second); 16464 16465 if (Result) 16466 *Result = EvalResult.Val.getInt(); 16467 return E; 16468 } 16469 16470 namespace { 16471 // Handle the case where we conclude a expression which we speculatively 16472 // considered to be unevaluated is actually evaluated. 16473 class TransformToPE : public TreeTransform<TransformToPE> { 16474 typedef TreeTransform<TransformToPE> BaseTransform; 16475 16476 public: 16477 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16478 16479 // Make sure we redo semantic analysis 16480 bool AlwaysRebuild() { return true; } 16481 bool ReplacingOriginal() { return true; } 16482 16483 // We need to special-case DeclRefExprs referring to FieldDecls which 16484 // are not part of a member pointer formation; normal TreeTransforming 16485 // doesn't catch this case because of the way we represent them in the AST. 16486 // FIXME: This is a bit ugly; is it really the best way to handle this 16487 // case? 16488 // 16489 // Error on DeclRefExprs referring to FieldDecls. 16490 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16491 if (isa<FieldDecl>(E->getDecl()) && 16492 !SemaRef.isUnevaluatedContext()) 16493 return SemaRef.Diag(E->getLocation(), 16494 diag::err_invalid_non_static_member_use) 16495 << E->getDecl() << E->getSourceRange(); 16496 16497 return BaseTransform::TransformDeclRefExpr(E); 16498 } 16499 16500 // Exception: filter out member pointer formation 16501 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16502 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16503 return E; 16504 16505 return BaseTransform::TransformUnaryOperator(E); 16506 } 16507 16508 // The body of a lambda-expression is in a separate expression evaluation 16509 // context so never needs to be transformed. 16510 // FIXME: Ideally we wouldn't transform the closure type either, and would 16511 // just recreate the capture expressions and lambda expression. 16512 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16513 return SkipLambdaBody(E, Body); 16514 } 16515 }; 16516 } 16517 16518 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16519 assert(isUnevaluatedContext() && 16520 "Should only transform unevaluated expressions"); 16521 ExprEvalContexts.back().Context = 16522 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16523 if (isUnevaluatedContext()) 16524 return E; 16525 return TransformToPE(*this).TransformExpr(E); 16526 } 16527 16528 void 16529 Sema::PushExpressionEvaluationContext( 16530 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16531 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16532 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16533 LambdaContextDecl, ExprContext); 16534 Cleanup.reset(); 16535 if (!MaybeODRUseExprs.empty()) 16536 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16537 } 16538 16539 void 16540 Sema::PushExpressionEvaluationContext( 16541 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16542 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16543 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16544 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16545 } 16546 16547 namespace { 16548 16549 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16550 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16551 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16552 if (E->getOpcode() == UO_Deref) 16553 return CheckPossibleDeref(S, E->getSubExpr()); 16554 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16555 return CheckPossibleDeref(S, E->getBase()); 16556 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16557 return CheckPossibleDeref(S, E->getBase()); 16558 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16559 QualType Inner; 16560 QualType Ty = E->getType(); 16561 if (const auto *Ptr = Ty->getAs<PointerType>()) 16562 Inner = Ptr->getPointeeType(); 16563 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16564 Inner = Arr->getElementType(); 16565 else 16566 return nullptr; 16567 16568 if (Inner->hasAttr(attr::NoDeref)) 16569 return E; 16570 } 16571 return nullptr; 16572 } 16573 16574 } // namespace 16575 16576 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16577 for (const Expr *E : Rec.PossibleDerefs) { 16578 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16579 if (DeclRef) { 16580 const ValueDecl *Decl = DeclRef->getDecl(); 16581 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16582 << Decl->getName() << E->getSourceRange(); 16583 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16584 } else { 16585 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16586 << E->getSourceRange(); 16587 } 16588 } 16589 Rec.PossibleDerefs.clear(); 16590 } 16591 16592 /// Check whether E, which is either a discarded-value expression or an 16593 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16594 /// and if so, remove it from the list of volatile-qualified assignments that 16595 /// we are going to warn are deprecated. 16596 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16597 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16598 return; 16599 16600 // Note: ignoring parens here is not justified by the standard rules, but 16601 // ignoring parentheses seems like a more reasonable approach, and this only 16602 // drives a deprecation warning so doesn't affect conformance. 16603 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16604 if (BO->getOpcode() == BO_Assign) { 16605 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16606 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16607 LHSs.end()); 16608 } 16609 } 16610 } 16611 16612 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16613 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16614 RebuildingImmediateInvocation) 16615 return E; 16616 16617 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16618 /// It's OK if this fails; we'll also remove this in 16619 /// HandleImmediateInvocations, but catching it here allows us to avoid 16620 /// walking the AST looking for it in simple cases. 16621 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16622 if (auto *DeclRef = 16623 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16624 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16625 16626 E = MaybeCreateExprWithCleanups(E); 16627 16628 ConstantExpr *Res = ConstantExpr::Create( 16629 getASTContext(), E.get(), 16630 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16631 getASTContext()), 16632 /*IsImmediateInvocation*/ true); 16633 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16634 return Res; 16635 } 16636 16637 static void EvaluateAndDiagnoseImmediateInvocation( 16638 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16639 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16640 Expr::EvalResult Eval; 16641 Eval.Diag = &Notes; 16642 ConstantExpr *CE = Candidate.getPointer(); 16643 bool Result = CE->EvaluateAsConstantExpr( 16644 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16645 if (!Result || !Notes.empty()) { 16646 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16647 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16648 InnerExpr = FunctionalCast->getSubExpr(); 16649 FunctionDecl *FD = nullptr; 16650 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16651 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16652 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16653 FD = Call->getConstructor(); 16654 else 16655 llvm_unreachable("unhandled decl kind"); 16656 assert(FD->isConsteval()); 16657 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16658 for (auto &Note : Notes) 16659 SemaRef.Diag(Note.first, Note.second); 16660 return; 16661 } 16662 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16663 } 16664 16665 static void RemoveNestedImmediateInvocation( 16666 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16667 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16668 struct ComplexRemove : TreeTransform<ComplexRemove> { 16669 using Base = TreeTransform<ComplexRemove>; 16670 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16671 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16672 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16673 CurrentII; 16674 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16675 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16676 SmallVector<Sema::ImmediateInvocationCandidate, 16677 4>::reverse_iterator Current) 16678 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16679 void RemoveImmediateInvocation(ConstantExpr* E) { 16680 auto It = std::find_if(CurrentII, IISet.rend(), 16681 [E](Sema::ImmediateInvocationCandidate Elem) { 16682 return Elem.getPointer() == E; 16683 }); 16684 assert(It != IISet.rend() && 16685 "ConstantExpr marked IsImmediateInvocation should " 16686 "be present"); 16687 It->setInt(1); // Mark as deleted 16688 } 16689 ExprResult TransformConstantExpr(ConstantExpr *E) { 16690 if (!E->isImmediateInvocation()) 16691 return Base::TransformConstantExpr(E); 16692 RemoveImmediateInvocation(E); 16693 return Base::TransformExpr(E->getSubExpr()); 16694 } 16695 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16696 /// we need to remove its DeclRefExpr from the DRSet. 16697 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16698 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16699 return Base::TransformCXXOperatorCallExpr(E); 16700 } 16701 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16702 /// here. 16703 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16704 if (!Init) 16705 return Init; 16706 /// ConstantExpr are the first layer of implicit node to be removed so if 16707 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16708 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16709 if (CE->isImmediateInvocation()) 16710 RemoveImmediateInvocation(CE); 16711 return Base::TransformInitializer(Init, NotCopyInit); 16712 } 16713 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16714 DRSet.erase(E); 16715 return E; 16716 } 16717 bool AlwaysRebuild() { return false; } 16718 bool ReplacingOriginal() { return true; } 16719 bool AllowSkippingCXXConstructExpr() { 16720 bool Res = AllowSkippingFirstCXXConstructExpr; 16721 AllowSkippingFirstCXXConstructExpr = true; 16722 return Res; 16723 } 16724 bool AllowSkippingFirstCXXConstructExpr = true; 16725 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16726 Rec.ImmediateInvocationCandidates, It); 16727 16728 /// CXXConstructExpr with a single argument are getting skipped by 16729 /// TreeTransform in some situtation because they could be implicit. This 16730 /// can only occur for the top-level CXXConstructExpr because it is used 16731 /// nowhere in the expression being transformed therefore will not be rebuilt. 16732 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16733 /// skipping the first CXXConstructExpr. 16734 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16735 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16736 16737 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16738 assert(Res.isUsable()); 16739 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16740 It->getPointer()->setSubExpr(Res.get()); 16741 } 16742 16743 static void 16744 HandleImmediateInvocations(Sema &SemaRef, 16745 Sema::ExpressionEvaluationContextRecord &Rec) { 16746 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16747 Rec.ReferenceToConsteval.size() == 0) || 16748 SemaRef.RebuildingImmediateInvocation) 16749 return; 16750 16751 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16752 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16753 /// need to remove ReferenceToConsteval in the immediate invocation. 16754 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16755 16756 /// Prevent sema calls during the tree transform from adding pointers that 16757 /// are already in the sets. 16758 llvm::SaveAndRestore<bool> DisableIITracking( 16759 SemaRef.RebuildingImmediateInvocation, true); 16760 16761 /// Prevent diagnostic during tree transfrom as they are duplicates 16762 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16763 16764 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16765 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16766 if (!It->getInt()) 16767 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16768 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16769 Rec.ReferenceToConsteval.size()) { 16770 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16771 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16772 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16773 bool VisitDeclRefExpr(DeclRefExpr *E) { 16774 DRSet.erase(E); 16775 return DRSet.size(); 16776 } 16777 } Visitor(Rec.ReferenceToConsteval); 16778 Visitor.TraverseStmt( 16779 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16780 } 16781 for (auto CE : Rec.ImmediateInvocationCandidates) 16782 if (!CE.getInt()) 16783 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16784 for (auto DR : Rec.ReferenceToConsteval) { 16785 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16786 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16787 << FD; 16788 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16789 } 16790 } 16791 16792 void Sema::PopExpressionEvaluationContext() { 16793 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16794 unsigned NumTypos = Rec.NumTypos; 16795 16796 if (!Rec.Lambdas.empty()) { 16797 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16798 if (!getLangOpts().CPlusPlus20 && 16799 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16800 Rec.isUnevaluated() || 16801 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16802 unsigned D; 16803 if (Rec.isUnevaluated()) { 16804 // C++11 [expr.prim.lambda]p2: 16805 // A lambda-expression shall not appear in an unevaluated operand 16806 // (Clause 5). 16807 D = diag::err_lambda_unevaluated_operand; 16808 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16809 // C++1y [expr.const]p2: 16810 // A conditional-expression e is a core constant expression unless the 16811 // evaluation of e, following the rules of the abstract machine, would 16812 // evaluate [...] a lambda-expression. 16813 D = diag::err_lambda_in_constant_expression; 16814 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16815 // C++17 [expr.prim.lamda]p2: 16816 // A lambda-expression shall not appear [...] in a template-argument. 16817 D = diag::err_lambda_in_invalid_context; 16818 } else 16819 llvm_unreachable("Couldn't infer lambda error message."); 16820 16821 for (const auto *L : Rec.Lambdas) 16822 Diag(L->getBeginLoc(), D); 16823 } 16824 } 16825 16826 WarnOnPendingNoDerefs(Rec); 16827 HandleImmediateInvocations(*this, Rec); 16828 16829 // Warn on any volatile-qualified simple-assignments that are not discarded- 16830 // value expressions nor unevaluated operands (those cases get removed from 16831 // this list by CheckUnusedVolatileAssignment). 16832 for (auto *BO : Rec.VolatileAssignmentLHSs) 16833 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16834 << BO->getType(); 16835 16836 // When are coming out of an unevaluated context, clear out any 16837 // temporaries that we may have created as part of the evaluation of 16838 // the expression in that context: they aren't relevant because they 16839 // will never be constructed. 16840 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16841 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16842 ExprCleanupObjects.end()); 16843 Cleanup = Rec.ParentCleanup; 16844 CleanupVarDeclMarking(); 16845 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16846 // Otherwise, merge the contexts together. 16847 } else { 16848 Cleanup.mergeFrom(Rec.ParentCleanup); 16849 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16850 Rec.SavedMaybeODRUseExprs.end()); 16851 } 16852 16853 // Pop the current expression evaluation context off the stack. 16854 ExprEvalContexts.pop_back(); 16855 16856 // The global expression evaluation context record is never popped. 16857 ExprEvalContexts.back().NumTypos += NumTypos; 16858 } 16859 16860 void Sema::DiscardCleanupsInEvaluationContext() { 16861 ExprCleanupObjects.erase( 16862 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16863 ExprCleanupObjects.end()); 16864 Cleanup.reset(); 16865 MaybeODRUseExprs.clear(); 16866 } 16867 16868 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16869 ExprResult Result = CheckPlaceholderExpr(E); 16870 if (Result.isInvalid()) 16871 return ExprError(); 16872 E = Result.get(); 16873 if (!E->getType()->isVariablyModifiedType()) 16874 return E; 16875 return TransformToPotentiallyEvaluated(E); 16876 } 16877 16878 /// Are we in a context that is potentially constant evaluated per C++20 16879 /// [expr.const]p12? 16880 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16881 /// C++2a [expr.const]p12: 16882 // An expression or conversion is potentially constant evaluated if it is 16883 switch (SemaRef.ExprEvalContexts.back().Context) { 16884 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16885 // -- a manifestly constant-evaluated expression, 16886 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16887 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16888 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16889 // -- a potentially-evaluated expression, 16890 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16891 // -- an immediate subexpression of a braced-init-list, 16892 16893 // -- [FIXME] an expression of the form & cast-expression that occurs 16894 // within a templated entity 16895 // -- a subexpression of one of the above that is not a subexpression of 16896 // a nested unevaluated operand. 16897 return true; 16898 16899 case Sema::ExpressionEvaluationContext::Unevaluated: 16900 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16901 // Expressions in this context are never evaluated. 16902 return false; 16903 } 16904 llvm_unreachable("Invalid context"); 16905 } 16906 16907 /// Return true if this function has a calling convention that requires mangling 16908 /// in the size of the parameter pack. 16909 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16910 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16911 // we don't need parameter type sizes. 16912 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16913 if (!TT.isOSWindows() || !TT.isX86()) 16914 return false; 16915 16916 // If this is C++ and this isn't an extern "C" function, parameters do not 16917 // need to be complete. In this case, C++ mangling will apply, which doesn't 16918 // use the size of the parameters. 16919 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16920 return false; 16921 16922 // Stdcall, fastcall, and vectorcall need this special treatment. 16923 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16924 switch (CC) { 16925 case CC_X86StdCall: 16926 case CC_X86FastCall: 16927 case CC_X86VectorCall: 16928 return true; 16929 default: 16930 break; 16931 } 16932 return false; 16933 } 16934 16935 /// Require that all of the parameter types of function be complete. Normally, 16936 /// parameter types are only required to be complete when a function is called 16937 /// or defined, but to mangle functions with certain calling conventions, the 16938 /// mangler needs to know the size of the parameter list. In this situation, 16939 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16940 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16941 /// result in a linker error. Clang doesn't implement this behavior, and instead 16942 /// attempts to error at compile time. 16943 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16944 SourceLocation Loc) { 16945 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16946 FunctionDecl *FD; 16947 ParmVarDecl *Param; 16948 16949 public: 16950 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16951 : FD(FD), Param(Param) {} 16952 16953 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16954 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16955 StringRef CCName; 16956 switch (CC) { 16957 case CC_X86StdCall: 16958 CCName = "stdcall"; 16959 break; 16960 case CC_X86FastCall: 16961 CCName = "fastcall"; 16962 break; 16963 case CC_X86VectorCall: 16964 CCName = "vectorcall"; 16965 break; 16966 default: 16967 llvm_unreachable("CC does not need mangling"); 16968 } 16969 16970 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16971 << Param->getDeclName() << FD->getDeclName() << CCName; 16972 } 16973 }; 16974 16975 for (ParmVarDecl *Param : FD->parameters()) { 16976 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16977 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16978 } 16979 } 16980 16981 namespace { 16982 enum class OdrUseContext { 16983 /// Declarations in this context are not odr-used. 16984 None, 16985 /// Declarations in this context are formally odr-used, but this is a 16986 /// dependent context. 16987 Dependent, 16988 /// Declarations in this context are odr-used but not actually used (yet). 16989 FormallyOdrUsed, 16990 /// Declarations in this context are used. 16991 Used 16992 }; 16993 } 16994 16995 /// Are we within a context in which references to resolved functions or to 16996 /// variables result in odr-use? 16997 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16998 OdrUseContext Result; 16999 17000 switch (SemaRef.ExprEvalContexts.back().Context) { 17001 case Sema::ExpressionEvaluationContext::Unevaluated: 17002 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17003 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17004 return OdrUseContext::None; 17005 17006 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17007 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17008 Result = OdrUseContext::Used; 17009 break; 17010 17011 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17012 Result = OdrUseContext::FormallyOdrUsed; 17013 break; 17014 17015 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17016 // A default argument formally results in odr-use, but doesn't actually 17017 // result in a use in any real sense until it itself is used. 17018 Result = OdrUseContext::FormallyOdrUsed; 17019 break; 17020 } 17021 17022 if (SemaRef.CurContext->isDependentContext()) 17023 return OdrUseContext::Dependent; 17024 17025 return Result; 17026 } 17027 17028 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17029 if (!Func->isConstexpr()) 17030 return false; 17031 17032 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17033 return true; 17034 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17035 return CCD && CCD->getInheritedConstructor(); 17036 } 17037 17038 /// Mark a function referenced, and check whether it is odr-used 17039 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17040 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17041 bool MightBeOdrUse) { 17042 assert(Func && "No function?"); 17043 17044 Func->setReferenced(); 17045 17046 // Recursive functions aren't really used until they're used from some other 17047 // context. 17048 bool IsRecursiveCall = CurContext == Func; 17049 17050 // C++11 [basic.def.odr]p3: 17051 // A function whose name appears as a potentially-evaluated expression is 17052 // odr-used if it is the unique lookup result or the selected member of a 17053 // set of overloaded functions [...]. 17054 // 17055 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17056 // can just check that here. 17057 OdrUseContext OdrUse = 17058 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17059 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17060 OdrUse = OdrUseContext::FormallyOdrUsed; 17061 17062 // Trivial default constructors and destructors are never actually used. 17063 // FIXME: What about other special members? 17064 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17065 OdrUse == OdrUseContext::Used) { 17066 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17067 if (Constructor->isDefaultConstructor()) 17068 OdrUse = OdrUseContext::FormallyOdrUsed; 17069 if (isa<CXXDestructorDecl>(Func)) 17070 OdrUse = OdrUseContext::FormallyOdrUsed; 17071 } 17072 17073 // C++20 [expr.const]p12: 17074 // A function [...] is needed for constant evaluation if it is [...] a 17075 // constexpr function that is named by an expression that is potentially 17076 // constant evaluated 17077 bool NeededForConstantEvaluation = 17078 isPotentiallyConstantEvaluatedContext(*this) && 17079 isImplicitlyDefinableConstexprFunction(Func); 17080 17081 // Determine whether we require a function definition to exist, per 17082 // C++11 [temp.inst]p3: 17083 // Unless a function template specialization has been explicitly 17084 // instantiated or explicitly specialized, the function template 17085 // specialization is implicitly instantiated when the specialization is 17086 // referenced in a context that requires a function definition to exist. 17087 // C++20 [temp.inst]p7: 17088 // The existence of a definition of a [...] function is considered to 17089 // affect the semantics of the program if the [...] function is needed for 17090 // constant evaluation by an expression 17091 // C++20 [basic.def.odr]p10: 17092 // Every program shall contain exactly one definition of every non-inline 17093 // function or variable that is odr-used in that program outside of a 17094 // discarded statement 17095 // C++20 [special]p1: 17096 // The implementation will implicitly define [defaulted special members] 17097 // if they are odr-used or needed for constant evaluation. 17098 // 17099 // Note that we skip the implicit instantiation of templates that are only 17100 // used in unused default arguments or by recursive calls to themselves. 17101 // This is formally non-conforming, but seems reasonable in practice. 17102 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17103 NeededForConstantEvaluation); 17104 17105 // C++14 [temp.expl.spec]p6: 17106 // If a template [...] is explicitly specialized then that specialization 17107 // shall be declared before the first use of that specialization that would 17108 // cause an implicit instantiation to take place, in every translation unit 17109 // in which such a use occurs 17110 if (NeedDefinition && 17111 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17112 Func->getMemberSpecializationInfo())) 17113 checkSpecializationVisibility(Loc, Func); 17114 17115 if (getLangOpts().CUDA) 17116 CheckCUDACall(Loc, Func); 17117 17118 if (getLangOpts().SYCLIsDevice) 17119 checkSYCLDeviceFunction(Loc, Func); 17120 17121 // If we need a definition, try to create one. 17122 if (NeedDefinition && !Func->getBody()) { 17123 runWithSufficientStackSpace(Loc, [&] { 17124 if (CXXConstructorDecl *Constructor = 17125 dyn_cast<CXXConstructorDecl>(Func)) { 17126 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17127 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17128 if (Constructor->isDefaultConstructor()) { 17129 if (Constructor->isTrivial() && 17130 !Constructor->hasAttr<DLLExportAttr>()) 17131 return; 17132 DefineImplicitDefaultConstructor(Loc, Constructor); 17133 } else if (Constructor->isCopyConstructor()) { 17134 DefineImplicitCopyConstructor(Loc, Constructor); 17135 } else if (Constructor->isMoveConstructor()) { 17136 DefineImplicitMoveConstructor(Loc, Constructor); 17137 } 17138 } else if (Constructor->getInheritedConstructor()) { 17139 DefineInheritingConstructor(Loc, Constructor); 17140 } 17141 } else if (CXXDestructorDecl *Destructor = 17142 dyn_cast<CXXDestructorDecl>(Func)) { 17143 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17144 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17145 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17146 return; 17147 DefineImplicitDestructor(Loc, Destructor); 17148 } 17149 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17150 MarkVTableUsed(Loc, Destructor->getParent()); 17151 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17152 if (MethodDecl->isOverloadedOperator() && 17153 MethodDecl->getOverloadedOperator() == OO_Equal) { 17154 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17155 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17156 if (MethodDecl->isCopyAssignmentOperator()) 17157 DefineImplicitCopyAssignment(Loc, MethodDecl); 17158 else if (MethodDecl->isMoveAssignmentOperator()) 17159 DefineImplicitMoveAssignment(Loc, MethodDecl); 17160 } 17161 } else if (isa<CXXConversionDecl>(MethodDecl) && 17162 MethodDecl->getParent()->isLambda()) { 17163 CXXConversionDecl *Conversion = 17164 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17165 if (Conversion->isLambdaToBlockPointerConversion()) 17166 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17167 else 17168 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17169 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17170 MarkVTableUsed(Loc, MethodDecl->getParent()); 17171 } 17172 17173 if (Func->isDefaulted() && !Func->isDeleted()) { 17174 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17175 if (DCK != DefaultedComparisonKind::None) 17176 DefineDefaultedComparison(Loc, Func, DCK); 17177 } 17178 17179 // Implicit instantiation of function templates and member functions of 17180 // class templates. 17181 if (Func->isImplicitlyInstantiable()) { 17182 TemplateSpecializationKind TSK = 17183 Func->getTemplateSpecializationKindForInstantiation(); 17184 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17185 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17186 if (FirstInstantiation) { 17187 PointOfInstantiation = Loc; 17188 if (auto *MSI = Func->getMemberSpecializationInfo()) 17189 MSI->setPointOfInstantiation(Loc); 17190 // FIXME: Notify listener. 17191 else 17192 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17193 } else if (TSK != TSK_ImplicitInstantiation) { 17194 // Use the point of use as the point of instantiation, instead of the 17195 // point of explicit instantiation (which we track as the actual point 17196 // of instantiation). This gives better backtraces in diagnostics. 17197 PointOfInstantiation = Loc; 17198 } 17199 17200 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17201 Func->isConstexpr()) { 17202 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17203 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17204 CodeSynthesisContexts.size()) 17205 PendingLocalImplicitInstantiations.push_back( 17206 std::make_pair(Func, PointOfInstantiation)); 17207 else if (Func->isConstexpr()) 17208 // Do not defer instantiations of constexpr functions, to avoid the 17209 // expression evaluator needing to call back into Sema if it sees a 17210 // call to such a function. 17211 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17212 else { 17213 Func->setInstantiationIsPending(true); 17214 PendingInstantiations.push_back( 17215 std::make_pair(Func, PointOfInstantiation)); 17216 // Notify the consumer that a function was implicitly instantiated. 17217 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17218 } 17219 } 17220 } else { 17221 // Walk redefinitions, as some of them may be instantiable. 17222 for (auto i : Func->redecls()) { 17223 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17224 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17225 } 17226 } 17227 }); 17228 } 17229 17230 // C++14 [except.spec]p17: 17231 // An exception-specification is considered to be needed when: 17232 // - the function is odr-used or, if it appears in an unevaluated operand, 17233 // would be odr-used if the expression were potentially-evaluated; 17234 // 17235 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17236 // function is a pure virtual function we're calling, and in that case the 17237 // function was selected by overload resolution and we need to resolve its 17238 // exception specification for a different reason. 17239 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17240 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17241 ResolveExceptionSpec(Loc, FPT); 17242 17243 // If this is the first "real" use, act on that. 17244 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17245 // Keep track of used but undefined functions. 17246 if (!Func->isDefined()) { 17247 if (mightHaveNonExternalLinkage(Func)) 17248 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17249 else if (Func->getMostRecentDecl()->isInlined() && 17250 !LangOpts.GNUInline && 17251 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17252 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17253 else if (isExternalWithNoLinkageType(Func)) 17254 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17255 } 17256 17257 // Some x86 Windows calling conventions mangle the size of the parameter 17258 // pack into the name. Computing the size of the parameters requires the 17259 // parameter types to be complete. Check that now. 17260 if (funcHasParameterSizeMangling(*this, Func)) 17261 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17262 17263 // In the MS C++ ABI, the compiler emits destructor variants where they are 17264 // used. If the destructor is used here but defined elsewhere, mark the 17265 // virtual base destructors referenced. If those virtual base destructors 17266 // are inline, this will ensure they are defined when emitting the complete 17267 // destructor variant. This checking may be redundant if the destructor is 17268 // provided later in this TU. 17269 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17270 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17271 CXXRecordDecl *Parent = Dtor->getParent(); 17272 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17273 CheckCompleteDestructorVariant(Loc, Dtor); 17274 } 17275 } 17276 17277 Func->markUsed(Context); 17278 } 17279 } 17280 17281 /// Directly mark a variable odr-used. Given a choice, prefer to use 17282 /// MarkVariableReferenced since it does additional checks and then 17283 /// calls MarkVarDeclODRUsed. 17284 /// If the variable must be captured: 17285 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17286 /// - else capture it in the DeclContext that maps to the 17287 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17288 static void 17289 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17290 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17291 // Keep track of used but undefined variables. 17292 // FIXME: We shouldn't suppress this warning for static data members. 17293 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17294 (!Var->isExternallyVisible() || Var->isInline() || 17295 SemaRef.isExternalWithNoLinkageType(Var)) && 17296 !(Var->isStaticDataMember() && Var->hasInit())) { 17297 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17298 if (old.isInvalid()) 17299 old = Loc; 17300 } 17301 QualType CaptureType, DeclRefType; 17302 if (SemaRef.LangOpts.OpenMP) 17303 SemaRef.tryCaptureOpenMPLambdas(Var); 17304 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17305 /*EllipsisLoc*/ SourceLocation(), 17306 /*BuildAndDiagnose*/ true, 17307 CaptureType, DeclRefType, 17308 FunctionScopeIndexToStopAt); 17309 17310 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17311 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17312 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17313 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17314 if (VarTarget == Sema::CVT_Host && 17315 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17316 UserTarget == Sema::CFT_Global)) { 17317 // Diagnose ODR-use of host global variables in device functions. 17318 // Reference of device global variables in host functions is allowed 17319 // through shadow variables therefore it is not diagnosed. 17320 if (SemaRef.LangOpts.CUDAIsDevice) { 17321 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17322 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17323 SemaRef.targetDiag(Var->getLocation(), 17324 Var->getType().isConstQualified() 17325 ? diag::note_cuda_const_var_unpromoted 17326 : diag::note_cuda_host_var); 17327 } 17328 } else if (VarTarget == Sema::CVT_Device && 17329 (UserTarget == Sema::CFT_Host || 17330 UserTarget == Sema::CFT_HostDevice) && 17331 !Var->hasExternalStorage()) { 17332 // Record a CUDA/HIP device side variable if it is ODR-used 17333 // by host code. This is done conservatively, when the variable is 17334 // referenced in any of the following contexts: 17335 // - a non-function context 17336 // - a host function 17337 // - a host device function 17338 // This makes the ODR-use of the device side variable by host code to 17339 // be visible in the device compilation for the compiler to be able to 17340 // emit template variables instantiated by host code only and to 17341 // externalize the static device side variable ODR-used by host code. 17342 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17343 } 17344 } 17345 17346 Var->markUsed(SemaRef.Context); 17347 } 17348 17349 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17350 SourceLocation Loc, 17351 unsigned CapturingScopeIndex) { 17352 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17353 } 17354 17355 static void 17356 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17357 ValueDecl *var, DeclContext *DC) { 17358 DeclContext *VarDC = var->getDeclContext(); 17359 17360 // If the parameter still belongs to the translation unit, then 17361 // we're actually just using one parameter in the declaration of 17362 // the next. 17363 if (isa<ParmVarDecl>(var) && 17364 isa<TranslationUnitDecl>(VarDC)) 17365 return; 17366 17367 // For C code, don't diagnose about capture if we're not actually in code 17368 // right now; it's impossible to write a non-constant expression outside of 17369 // function context, so we'll get other (more useful) diagnostics later. 17370 // 17371 // For C++, things get a bit more nasty... it would be nice to suppress this 17372 // diagnostic for certain cases like using a local variable in an array bound 17373 // for a member of a local class, but the correct predicate is not obvious. 17374 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17375 return; 17376 17377 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17378 unsigned ContextKind = 3; // unknown 17379 if (isa<CXXMethodDecl>(VarDC) && 17380 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17381 ContextKind = 2; 17382 } else if (isa<FunctionDecl>(VarDC)) { 17383 ContextKind = 0; 17384 } else if (isa<BlockDecl>(VarDC)) { 17385 ContextKind = 1; 17386 } 17387 17388 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17389 << var << ValueKind << ContextKind << VarDC; 17390 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17391 << var; 17392 17393 // FIXME: Add additional diagnostic info about class etc. which prevents 17394 // capture. 17395 } 17396 17397 17398 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17399 bool &SubCapturesAreNested, 17400 QualType &CaptureType, 17401 QualType &DeclRefType) { 17402 // Check whether we've already captured it. 17403 if (CSI->CaptureMap.count(Var)) { 17404 // If we found a capture, any subcaptures are nested. 17405 SubCapturesAreNested = true; 17406 17407 // Retrieve the capture type for this variable. 17408 CaptureType = CSI->getCapture(Var).getCaptureType(); 17409 17410 // Compute the type of an expression that refers to this variable. 17411 DeclRefType = CaptureType.getNonReferenceType(); 17412 17413 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17414 // are mutable in the sense that user can change their value - they are 17415 // private instances of the captured declarations. 17416 const Capture &Cap = CSI->getCapture(Var); 17417 if (Cap.isCopyCapture() && 17418 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17419 !(isa<CapturedRegionScopeInfo>(CSI) && 17420 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17421 DeclRefType.addConst(); 17422 return true; 17423 } 17424 return false; 17425 } 17426 17427 // Only block literals, captured statements, and lambda expressions can 17428 // capture; other scopes don't work. 17429 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17430 SourceLocation Loc, 17431 const bool Diagnose, Sema &S) { 17432 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17433 return getLambdaAwareParentOfDeclContext(DC); 17434 else if (Var->hasLocalStorage()) { 17435 if (Diagnose) 17436 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17437 } 17438 return nullptr; 17439 } 17440 17441 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17442 // certain types of variables (unnamed, variably modified types etc.) 17443 // so check for eligibility. 17444 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17445 SourceLocation Loc, 17446 const bool Diagnose, Sema &S) { 17447 17448 bool IsBlock = isa<BlockScopeInfo>(CSI); 17449 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17450 17451 // Lambdas are not allowed to capture unnamed variables 17452 // (e.g. anonymous unions). 17453 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17454 // assuming that's the intent. 17455 if (IsLambda && !Var->getDeclName()) { 17456 if (Diagnose) { 17457 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17458 S.Diag(Var->getLocation(), diag::note_declared_at); 17459 } 17460 return false; 17461 } 17462 17463 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17464 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17465 if (Diagnose) { 17466 S.Diag(Loc, diag::err_ref_vm_type); 17467 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17468 } 17469 return false; 17470 } 17471 // Prohibit structs with flexible array members too. 17472 // We cannot capture what is in the tail end of the struct. 17473 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17474 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17475 if (Diagnose) { 17476 if (IsBlock) 17477 S.Diag(Loc, diag::err_ref_flexarray_type); 17478 else 17479 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17480 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17481 } 17482 return false; 17483 } 17484 } 17485 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17486 // Lambdas and captured statements are not allowed to capture __block 17487 // variables; they don't support the expected semantics. 17488 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17489 if (Diagnose) { 17490 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17491 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17492 } 17493 return false; 17494 } 17495 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17496 if (S.getLangOpts().OpenCL && IsBlock && 17497 Var->getType()->isBlockPointerType()) { 17498 if (Diagnose) 17499 S.Diag(Loc, diag::err_opencl_block_ref_block); 17500 return false; 17501 } 17502 17503 return true; 17504 } 17505 17506 // Returns true if the capture by block was successful. 17507 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17508 SourceLocation Loc, 17509 const bool BuildAndDiagnose, 17510 QualType &CaptureType, 17511 QualType &DeclRefType, 17512 const bool Nested, 17513 Sema &S, bool Invalid) { 17514 bool ByRef = false; 17515 17516 // Blocks are not allowed to capture arrays, excepting OpenCL. 17517 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17518 // (decayed to pointers). 17519 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17520 if (BuildAndDiagnose) { 17521 S.Diag(Loc, diag::err_ref_array_type); 17522 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17523 Invalid = true; 17524 } else { 17525 return false; 17526 } 17527 } 17528 17529 // Forbid the block-capture of autoreleasing variables. 17530 if (!Invalid && 17531 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17532 if (BuildAndDiagnose) { 17533 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17534 << /*block*/ 0; 17535 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17536 Invalid = true; 17537 } else { 17538 return false; 17539 } 17540 } 17541 17542 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17543 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17544 QualType PointeeTy = PT->getPointeeType(); 17545 17546 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17547 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17548 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17549 if (BuildAndDiagnose) { 17550 SourceLocation VarLoc = Var->getLocation(); 17551 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17552 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17553 } 17554 } 17555 } 17556 17557 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17558 if (HasBlocksAttr || CaptureType->isReferenceType() || 17559 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17560 // Block capture by reference does not change the capture or 17561 // declaration reference types. 17562 ByRef = true; 17563 } else { 17564 // Block capture by copy introduces 'const'. 17565 CaptureType = CaptureType.getNonReferenceType().withConst(); 17566 DeclRefType = CaptureType; 17567 } 17568 17569 // Actually capture the variable. 17570 if (BuildAndDiagnose) 17571 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17572 CaptureType, Invalid); 17573 17574 return !Invalid; 17575 } 17576 17577 17578 /// Capture the given variable in the captured region. 17579 static bool captureInCapturedRegion( 17580 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17581 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17582 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17583 bool IsTopScope, Sema &S, bool Invalid) { 17584 // By default, capture variables by reference. 17585 bool ByRef = true; 17586 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17587 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17588 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17589 // Using an LValue reference type is consistent with Lambdas (see below). 17590 if (S.isOpenMPCapturedDecl(Var)) { 17591 bool HasConst = DeclRefType.isConstQualified(); 17592 DeclRefType = DeclRefType.getUnqualifiedType(); 17593 // Don't lose diagnostics about assignments to const. 17594 if (HasConst) 17595 DeclRefType.addConst(); 17596 } 17597 // Do not capture firstprivates in tasks. 17598 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17599 OMPC_unknown) 17600 return true; 17601 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17602 RSI->OpenMPCaptureLevel); 17603 } 17604 17605 if (ByRef) 17606 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17607 else 17608 CaptureType = DeclRefType; 17609 17610 // Actually capture the variable. 17611 if (BuildAndDiagnose) 17612 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17613 Loc, SourceLocation(), CaptureType, Invalid); 17614 17615 return !Invalid; 17616 } 17617 17618 /// Capture the given variable in the lambda. 17619 static bool captureInLambda(LambdaScopeInfo *LSI, 17620 VarDecl *Var, 17621 SourceLocation Loc, 17622 const bool BuildAndDiagnose, 17623 QualType &CaptureType, 17624 QualType &DeclRefType, 17625 const bool RefersToCapturedVariable, 17626 const Sema::TryCaptureKind Kind, 17627 SourceLocation EllipsisLoc, 17628 const bool IsTopScope, 17629 Sema &S, bool Invalid) { 17630 // Determine whether we are capturing by reference or by value. 17631 bool ByRef = false; 17632 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17633 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17634 } else { 17635 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17636 } 17637 17638 // Compute the type of the field that will capture this variable. 17639 if (ByRef) { 17640 // C++11 [expr.prim.lambda]p15: 17641 // An entity is captured by reference if it is implicitly or 17642 // explicitly captured but not captured by copy. It is 17643 // unspecified whether additional unnamed non-static data 17644 // members are declared in the closure type for entities 17645 // captured by reference. 17646 // 17647 // FIXME: It is not clear whether we want to build an lvalue reference 17648 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17649 // to do the former, while EDG does the latter. Core issue 1249 will 17650 // clarify, but for now we follow GCC because it's a more permissive and 17651 // easily defensible position. 17652 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17653 } else { 17654 // C++11 [expr.prim.lambda]p14: 17655 // For each entity captured by copy, an unnamed non-static 17656 // data member is declared in the closure type. The 17657 // declaration order of these members is unspecified. The type 17658 // of such a data member is the type of the corresponding 17659 // captured entity if the entity is not a reference to an 17660 // object, or the referenced type otherwise. [Note: If the 17661 // captured entity is a reference to a function, the 17662 // corresponding data member is also a reference to a 17663 // function. - end note ] 17664 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17665 if (!RefType->getPointeeType()->isFunctionType()) 17666 CaptureType = RefType->getPointeeType(); 17667 } 17668 17669 // Forbid the lambda copy-capture of autoreleasing variables. 17670 if (!Invalid && 17671 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17672 if (BuildAndDiagnose) { 17673 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17674 S.Diag(Var->getLocation(), diag::note_previous_decl) 17675 << Var->getDeclName(); 17676 Invalid = true; 17677 } else { 17678 return false; 17679 } 17680 } 17681 17682 // Make sure that by-copy captures are of a complete and non-abstract type. 17683 if (!Invalid && BuildAndDiagnose) { 17684 if (!CaptureType->isDependentType() && 17685 S.RequireCompleteSizedType( 17686 Loc, CaptureType, 17687 diag::err_capture_of_incomplete_or_sizeless_type, 17688 Var->getDeclName())) 17689 Invalid = true; 17690 else if (S.RequireNonAbstractType(Loc, CaptureType, 17691 diag::err_capture_of_abstract_type)) 17692 Invalid = true; 17693 } 17694 } 17695 17696 // Compute the type of a reference to this captured variable. 17697 if (ByRef) 17698 DeclRefType = CaptureType.getNonReferenceType(); 17699 else { 17700 // C++ [expr.prim.lambda]p5: 17701 // The closure type for a lambda-expression has a public inline 17702 // function call operator [...]. This function call operator is 17703 // declared const (9.3.1) if and only if the lambda-expression's 17704 // parameter-declaration-clause is not followed by mutable. 17705 DeclRefType = CaptureType.getNonReferenceType(); 17706 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17707 DeclRefType.addConst(); 17708 } 17709 17710 // Add the capture. 17711 if (BuildAndDiagnose) 17712 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17713 Loc, EllipsisLoc, CaptureType, Invalid); 17714 17715 return !Invalid; 17716 } 17717 17718 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17719 // Offer a Copy fix even if the type is dependent. 17720 if (Var->getType()->isDependentType()) 17721 return true; 17722 QualType T = Var->getType().getNonReferenceType(); 17723 if (T.isTriviallyCopyableType(Context)) 17724 return true; 17725 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17726 17727 if (!(RD = RD->getDefinition())) 17728 return false; 17729 if (RD->hasSimpleCopyConstructor()) 17730 return true; 17731 if (RD->hasUserDeclaredCopyConstructor()) 17732 for (CXXConstructorDecl *Ctor : RD->ctors()) 17733 if (Ctor->isCopyConstructor()) 17734 return !Ctor->isDeleted(); 17735 } 17736 return false; 17737 } 17738 17739 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17740 /// default capture. Fixes may be omitted if they aren't allowed by the 17741 /// standard, for example we can't emit a default copy capture fix-it if we 17742 /// already explicitly copy capture capture another variable. 17743 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17744 VarDecl *Var) { 17745 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17746 // Don't offer Capture by copy of default capture by copy fixes if Var is 17747 // known not to be copy constructible. 17748 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17749 17750 SmallString<32> FixBuffer; 17751 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17752 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17753 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17754 if (ShouldOfferCopyFix) { 17755 // Offer fixes to insert an explicit capture for the variable. 17756 // [] -> [VarName] 17757 // [OtherCapture] -> [OtherCapture, VarName] 17758 FixBuffer.assign({Separator, Var->getName()}); 17759 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17760 << Var << /*value*/ 0 17761 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17762 } 17763 // As above but capture by reference. 17764 FixBuffer.assign({Separator, "&", Var->getName()}); 17765 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17766 << Var << /*reference*/ 1 17767 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17768 } 17769 17770 // Only try to offer default capture if there are no captures excluding this 17771 // and init captures. 17772 // [this]: OK. 17773 // [X = Y]: OK. 17774 // [&A, &B]: Don't offer. 17775 // [A, B]: Don't offer. 17776 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17777 return !C.isThisCapture() && !C.isInitCapture(); 17778 })) 17779 return; 17780 17781 // The default capture specifiers, '=' or '&', must appear first in the 17782 // capture body. 17783 SourceLocation DefaultInsertLoc = 17784 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17785 17786 if (ShouldOfferCopyFix) { 17787 bool CanDefaultCopyCapture = true; 17788 // [=, *this] OK since c++17 17789 // [=, this] OK since c++20 17790 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17791 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17792 ? LSI->getCXXThisCapture().isCopyCapture() 17793 : false; 17794 // We can't use default capture by copy if any captures already specified 17795 // capture by copy. 17796 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17797 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17798 })) { 17799 FixBuffer.assign({"=", Separator}); 17800 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17801 << /*value*/ 0 17802 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17803 } 17804 } 17805 17806 // We can't use default capture by reference if any captures already specified 17807 // capture by reference. 17808 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17809 return !C.isInitCapture() && C.isReferenceCapture() && 17810 !C.isThisCapture(); 17811 })) { 17812 FixBuffer.assign({"&", Separator}); 17813 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17814 << /*reference*/ 1 17815 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17816 } 17817 } 17818 17819 bool Sema::tryCaptureVariable( 17820 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17821 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17822 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17823 // An init-capture is notionally from the context surrounding its 17824 // declaration, but its parent DC is the lambda class. 17825 DeclContext *VarDC = Var->getDeclContext(); 17826 if (Var->isInitCapture()) 17827 VarDC = VarDC->getParent(); 17828 17829 DeclContext *DC = CurContext; 17830 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17831 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17832 // We need to sync up the Declaration Context with the 17833 // FunctionScopeIndexToStopAt 17834 if (FunctionScopeIndexToStopAt) { 17835 unsigned FSIndex = FunctionScopes.size() - 1; 17836 while (FSIndex != MaxFunctionScopesIndex) { 17837 DC = getLambdaAwareParentOfDeclContext(DC); 17838 --FSIndex; 17839 } 17840 } 17841 17842 17843 // If the variable is declared in the current context, there is no need to 17844 // capture it. 17845 if (VarDC == DC) return true; 17846 17847 // Capture global variables if it is required to use private copy of this 17848 // variable. 17849 bool IsGlobal = !Var->hasLocalStorage(); 17850 if (IsGlobal && 17851 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17852 MaxFunctionScopesIndex))) 17853 return true; 17854 Var = Var->getCanonicalDecl(); 17855 17856 // Walk up the stack to determine whether we can capture the variable, 17857 // performing the "simple" checks that don't depend on type. We stop when 17858 // we've either hit the declared scope of the variable or find an existing 17859 // capture of that variable. We start from the innermost capturing-entity 17860 // (the DC) and ensure that all intervening capturing-entities 17861 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17862 // declcontext can either capture the variable or have already captured 17863 // the variable. 17864 CaptureType = Var->getType(); 17865 DeclRefType = CaptureType.getNonReferenceType(); 17866 bool Nested = false; 17867 bool Explicit = (Kind != TryCapture_Implicit); 17868 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17869 do { 17870 // Only block literals, captured statements, and lambda expressions can 17871 // capture; other scopes don't work. 17872 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17873 ExprLoc, 17874 BuildAndDiagnose, 17875 *this); 17876 // We need to check for the parent *first* because, if we *have* 17877 // private-captured a global variable, we need to recursively capture it in 17878 // intermediate blocks, lambdas, etc. 17879 if (!ParentDC) { 17880 if (IsGlobal) { 17881 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17882 break; 17883 } 17884 return true; 17885 } 17886 17887 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17888 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17889 17890 17891 // Check whether we've already captured it. 17892 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17893 DeclRefType)) { 17894 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17895 break; 17896 } 17897 // If we are instantiating a generic lambda call operator body, 17898 // we do not want to capture new variables. What was captured 17899 // during either a lambdas transformation or initial parsing 17900 // should be used. 17901 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17902 if (BuildAndDiagnose) { 17903 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17904 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17905 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17906 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17907 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17908 buildLambdaCaptureFixit(*this, LSI, Var); 17909 } else 17910 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17911 } 17912 return true; 17913 } 17914 17915 // Try to capture variable-length arrays types. 17916 if (Var->getType()->isVariablyModifiedType()) { 17917 // We're going to walk down into the type and look for VLA 17918 // expressions. 17919 QualType QTy = Var->getType(); 17920 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17921 QTy = PVD->getOriginalType(); 17922 captureVariablyModifiedType(Context, QTy, CSI); 17923 } 17924 17925 if (getLangOpts().OpenMP) { 17926 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17927 // OpenMP private variables should not be captured in outer scope, so 17928 // just break here. Similarly, global variables that are captured in a 17929 // target region should not be captured outside the scope of the region. 17930 if (RSI->CapRegionKind == CR_OpenMP) { 17931 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17932 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17933 // If the variable is private (i.e. not captured) and has variably 17934 // modified type, we still need to capture the type for correct 17935 // codegen in all regions, associated with the construct. Currently, 17936 // it is captured in the innermost captured region only. 17937 if (IsOpenMPPrivateDecl != OMPC_unknown && 17938 Var->getType()->isVariablyModifiedType()) { 17939 QualType QTy = Var->getType(); 17940 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17941 QTy = PVD->getOriginalType(); 17942 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17943 I < E; ++I) { 17944 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17945 FunctionScopes[FunctionScopesIndex - I]); 17946 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17947 "Wrong number of captured regions associated with the " 17948 "OpenMP construct."); 17949 captureVariablyModifiedType(Context, QTy, OuterRSI); 17950 } 17951 } 17952 bool IsTargetCap = 17953 IsOpenMPPrivateDecl != OMPC_private && 17954 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17955 RSI->OpenMPCaptureLevel); 17956 // Do not capture global if it is not privatized in outer regions. 17957 bool IsGlobalCap = 17958 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17959 RSI->OpenMPCaptureLevel); 17960 17961 // When we detect target captures we are looking from inside the 17962 // target region, therefore we need to propagate the capture from the 17963 // enclosing region. Therefore, the capture is not initially nested. 17964 if (IsTargetCap) 17965 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17966 17967 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17968 (IsGlobal && !IsGlobalCap)) { 17969 Nested = !IsTargetCap; 17970 bool HasConst = DeclRefType.isConstQualified(); 17971 DeclRefType = DeclRefType.getUnqualifiedType(); 17972 // Don't lose diagnostics about assignments to const. 17973 if (HasConst) 17974 DeclRefType.addConst(); 17975 CaptureType = Context.getLValueReferenceType(DeclRefType); 17976 break; 17977 } 17978 } 17979 } 17980 } 17981 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17982 // No capture-default, and this is not an explicit capture 17983 // so cannot capture this variable. 17984 if (BuildAndDiagnose) { 17985 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17986 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17987 auto *LSI = cast<LambdaScopeInfo>(CSI); 17988 if (LSI->Lambda) { 17989 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17990 buildLambdaCaptureFixit(*this, LSI, Var); 17991 } 17992 // FIXME: If we error out because an outer lambda can not implicitly 17993 // capture a variable that an inner lambda explicitly captures, we 17994 // should have the inner lambda do the explicit capture - because 17995 // it makes for cleaner diagnostics later. This would purely be done 17996 // so that the diagnostic does not misleadingly claim that a variable 17997 // can not be captured by a lambda implicitly even though it is captured 17998 // explicitly. Suggestion: 17999 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18000 // at the function head 18001 // - cache the StartingDeclContext - this must be a lambda 18002 // - captureInLambda in the innermost lambda the variable. 18003 } 18004 return true; 18005 } 18006 18007 FunctionScopesIndex--; 18008 DC = ParentDC; 18009 Explicit = false; 18010 } while (!VarDC->Equals(DC)); 18011 18012 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18013 // computing the type of the capture at each step, checking type-specific 18014 // requirements, and adding captures if requested. 18015 // If the variable had already been captured previously, we start capturing 18016 // at the lambda nested within that one. 18017 bool Invalid = false; 18018 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18019 ++I) { 18020 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18021 18022 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18023 // certain types of variables (unnamed, variably modified types etc.) 18024 // so check for eligibility. 18025 if (!Invalid) 18026 Invalid = 18027 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18028 18029 // After encountering an error, if we're actually supposed to capture, keep 18030 // capturing in nested contexts to suppress any follow-on diagnostics. 18031 if (Invalid && !BuildAndDiagnose) 18032 return true; 18033 18034 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18035 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18036 DeclRefType, Nested, *this, Invalid); 18037 Nested = true; 18038 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18039 Invalid = !captureInCapturedRegion( 18040 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18041 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18042 Nested = true; 18043 } else { 18044 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18045 Invalid = 18046 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18047 DeclRefType, Nested, Kind, EllipsisLoc, 18048 /*IsTopScope*/ I == N - 1, *this, Invalid); 18049 Nested = true; 18050 } 18051 18052 if (Invalid && !BuildAndDiagnose) 18053 return true; 18054 } 18055 return Invalid; 18056 } 18057 18058 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18059 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18060 QualType CaptureType; 18061 QualType DeclRefType; 18062 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18063 /*BuildAndDiagnose=*/true, CaptureType, 18064 DeclRefType, nullptr); 18065 } 18066 18067 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18068 QualType CaptureType; 18069 QualType DeclRefType; 18070 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18071 /*BuildAndDiagnose=*/false, CaptureType, 18072 DeclRefType, nullptr); 18073 } 18074 18075 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18076 QualType CaptureType; 18077 QualType DeclRefType; 18078 18079 // Determine whether we can capture this variable. 18080 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18081 /*BuildAndDiagnose=*/false, CaptureType, 18082 DeclRefType, nullptr)) 18083 return QualType(); 18084 18085 return DeclRefType; 18086 } 18087 18088 namespace { 18089 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18090 // The produced TemplateArgumentListInfo* points to data stored within this 18091 // object, so should only be used in contexts where the pointer will not be 18092 // used after the CopiedTemplateArgs object is destroyed. 18093 class CopiedTemplateArgs { 18094 bool HasArgs; 18095 TemplateArgumentListInfo TemplateArgStorage; 18096 public: 18097 template<typename RefExpr> 18098 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18099 if (HasArgs) 18100 E->copyTemplateArgumentsInto(TemplateArgStorage); 18101 } 18102 operator TemplateArgumentListInfo*() 18103 #ifdef __has_cpp_attribute 18104 #if __has_cpp_attribute(clang::lifetimebound) 18105 [[clang::lifetimebound]] 18106 #endif 18107 #endif 18108 { 18109 return HasArgs ? &TemplateArgStorage : nullptr; 18110 } 18111 }; 18112 } 18113 18114 /// Walk the set of potential results of an expression and mark them all as 18115 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18116 /// 18117 /// \return A new expression if we found any potential results, ExprEmpty() if 18118 /// not, and ExprError() if we diagnosed an error. 18119 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18120 NonOdrUseReason NOUR) { 18121 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18122 // an object that satisfies the requirements for appearing in a 18123 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18124 // is immediately applied." This function handles the lvalue-to-rvalue 18125 // conversion part. 18126 // 18127 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18128 // transform it into the relevant kind of non-odr-use node and rebuild the 18129 // tree of nodes leading to it. 18130 // 18131 // This is a mini-TreeTransform that only transforms a restricted subset of 18132 // nodes (and only certain operands of them). 18133 18134 // Rebuild a subexpression. 18135 auto Rebuild = [&](Expr *Sub) { 18136 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18137 }; 18138 18139 // Check whether a potential result satisfies the requirements of NOUR. 18140 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18141 // Any entity other than a VarDecl is always odr-used whenever it's named 18142 // in a potentially-evaluated expression. 18143 auto *VD = dyn_cast<VarDecl>(D); 18144 if (!VD) 18145 return true; 18146 18147 // C++2a [basic.def.odr]p4: 18148 // A variable x whose name appears as a potentially-evalauted expression 18149 // e is odr-used by e unless 18150 // -- x is a reference that is usable in constant expressions, or 18151 // -- x is a variable of non-reference type that is usable in constant 18152 // expressions and has no mutable subobjects, and e is an element of 18153 // the set of potential results of an expression of 18154 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18155 // conversion is applied, or 18156 // -- x is a variable of non-reference type, and e is an element of the 18157 // set of potential results of a discarded-value expression to which 18158 // the lvalue-to-rvalue conversion is not applied 18159 // 18160 // We check the first bullet and the "potentially-evaluated" condition in 18161 // BuildDeclRefExpr. We check the type requirements in the second bullet 18162 // in CheckLValueToRValueConversionOperand below. 18163 switch (NOUR) { 18164 case NOUR_None: 18165 case NOUR_Unevaluated: 18166 llvm_unreachable("unexpected non-odr-use-reason"); 18167 18168 case NOUR_Constant: 18169 // Constant references were handled when they were built. 18170 if (VD->getType()->isReferenceType()) 18171 return true; 18172 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18173 if (RD->hasMutableFields()) 18174 return true; 18175 if (!VD->isUsableInConstantExpressions(S.Context)) 18176 return true; 18177 break; 18178 18179 case NOUR_Discarded: 18180 if (VD->getType()->isReferenceType()) 18181 return true; 18182 break; 18183 } 18184 return false; 18185 }; 18186 18187 // Mark that this expression does not constitute an odr-use. 18188 auto MarkNotOdrUsed = [&] { 18189 S.MaybeODRUseExprs.remove(E); 18190 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18191 LSI->markVariableExprAsNonODRUsed(E); 18192 }; 18193 18194 // C++2a [basic.def.odr]p2: 18195 // The set of potential results of an expression e is defined as follows: 18196 switch (E->getStmtClass()) { 18197 // -- If e is an id-expression, ... 18198 case Expr::DeclRefExprClass: { 18199 auto *DRE = cast<DeclRefExpr>(E); 18200 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18201 break; 18202 18203 // Rebuild as a non-odr-use DeclRefExpr. 18204 MarkNotOdrUsed(); 18205 return DeclRefExpr::Create( 18206 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18207 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18208 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18209 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18210 } 18211 18212 case Expr::FunctionParmPackExprClass: { 18213 auto *FPPE = cast<FunctionParmPackExpr>(E); 18214 // If any of the declarations in the pack is odr-used, then the expression 18215 // as a whole constitutes an odr-use. 18216 for (VarDecl *D : *FPPE) 18217 if (IsPotentialResultOdrUsed(D)) 18218 return ExprEmpty(); 18219 18220 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18221 // nothing cares about whether we marked this as an odr-use, but it might 18222 // be useful for non-compiler tools. 18223 MarkNotOdrUsed(); 18224 break; 18225 } 18226 18227 // -- If e is a subscripting operation with an array operand... 18228 case Expr::ArraySubscriptExprClass: { 18229 auto *ASE = cast<ArraySubscriptExpr>(E); 18230 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18231 if (!OldBase->getType()->isArrayType()) 18232 break; 18233 ExprResult Base = Rebuild(OldBase); 18234 if (!Base.isUsable()) 18235 return Base; 18236 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18237 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18238 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18239 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18240 ASE->getRBracketLoc()); 18241 } 18242 18243 case Expr::MemberExprClass: { 18244 auto *ME = cast<MemberExpr>(E); 18245 // -- If e is a class member access expression [...] naming a non-static 18246 // data member... 18247 if (isa<FieldDecl>(ME->getMemberDecl())) { 18248 ExprResult Base = Rebuild(ME->getBase()); 18249 if (!Base.isUsable()) 18250 return Base; 18251 return MemberExpr::Create( 18252 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18253 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18254 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18255 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18256 ME->getObjectKind(), ME->isNonOdrUse()); 18257 } 18258 18259 if (ME->getMemberDecl()->isCXXInstanceMember()) 18260 break; 18261 18262 // -- If e is a class member access expression naming a static data member, 18263 // ... 18264 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18265 break; 18266 18267 // Rebuild as a non-odr-use MemberExpr. 18268 MarkNotOdrUsed(); 18269 return MemberExpr::Create( 18270 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18271 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18272 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18273 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18274 return ExprEmpty(); 18275 } 18276 18277 case Expr::BinaryOperatorClass: { 18278 auto *BO = cast<BinaryOperator>(E); 18279 Expr *LHS = BO->getLHS(); 18280 Expr *RHS = BO->getRHS(); 18281 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18282 if (BO->getOpcode() == BO_PtrMemD) { 18283 ExprResult Sub = Rebuild(LHS); 18284 if (!Sub.isUsable()) 18285 return Sub; 18286 LHS = Sub.get(); 18287 // -- If e is a comma expression, ... 18288 } else if (BO->getOpcode() == BO_Comma) { 18289 ExprResult Sub = Rebuild(RHS); 18290 if (!Sub.isUsable()) 18291 return Sub; 18292 RHS = Sub.get(); 18293 } else { 18294 break; 18295 } 18296 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18297 LHS, RHS); 18298 } 18299 18300 // -- If e has the form (e1)... 18301 case Expr::ParenExprClass: { 18302 auto *PE = cast<ParenExpr>(E); 18303 ExprResult Sub = Rebuild(PE->getSubExpr()); 18304 if (!Sub.isUsable()) 18305 return Sub; 18306 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18307 } 18308 18309 // -- If e is a glvalue conditional expression, ... 18310 // We don't apply this to a binary conditional operator. FIXME: Should we? 18311 case Expr::ConditionalOperatorClass: { 18312 auto *CO = cast<ConditionalOperator>(E); 18313 ExprResult LHS = Rebuild(CO->getLHS()); 18314 if (LHS.isInvalid()) 18315 return ExprError(); 18316 ExprResult RHS = Rebuild(CO->getRHS()); 18317 if (RHS.isInvalid()) 18318 return ExprError(); 18319 if (!LHS.isUsable() && !RHS.isUsable()) 18320 return ExprEmpty(); 18321 if (!LHS.isUsable()) 18322 LHS = CO->getLHS(); 18323 if (!RHS.isUsable()) 18324 RHS = CO->getRHS(); 18325 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18326 CO->getCond(), LHS.get(), RHS.get()); 18327 } 18328 18329 // [Clang extension] 18330 // -- If e has the form __extension__ e1... 18331 case Expr::UnaryOperatorClass: { 18332 auto *UO = cast<UnaryOperator>(E); 18333 if (UO->getOpcode() != UO_Extension) 18334 break; 18335 ExprResult Sub = Rebuild(UO->getSubExpr()); 18336 if (!Sub.isUsable()) 18337 return Sub; 18338 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18339 Sub.get()); 18340 } 18341 18342 // [Clang extension] 18343 // -- If e has the form _Generic(...), the set of potential results is the 18344 // union of the sets of potential results of the associated expressions. 18345 case Expr::GenericSelectionExprClass: { 18346 auto *GSE = cast<GenericSelectionExpr>(E); 18347 18348 SmallVector<Expr *, 4> AssocExprs; 18349 bool AnyChanged = false; 18350 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18351 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18352 if (AssocExpr.isInvalid()) 18353 return ExprError(); 18354 if (AssocExpr.isUsable()) { 18355 AssocExprs.push_back(AssocExpr.get()); 18356 AnyChanged = true; 18357 } else { 18358 AssocExprs.push_back(OrigAssocExpr); 18359 } 18360 } 18361 18362 return AnyChanged ? S.CreateGenericSelectionExpr( 18363 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18364 GSE->getRParenLoc(), GSE->getControllingExpr(), 18365 GSE->getAssocTypeSourceInfos(), AssocExprs) 18366 : ExprEmpty(); 18367 } 18368 18369 // [Clang extension] 18370 // -- If e has the form __builtin_choose_expr(...), the set of potential 18371 // results is the union of the sets of potential results of the 18372 // second and third subexpressions. 18373 case Expr::ChooseExprClass: { 18374 auto *CE = cast<ChooseExpr>(E); 18375 18376 ExprResult LHS = Rebuild(CE->getLHS()); 18377 if (LHS.isInvalid()) 18378 return ExprError(); 18379 18380 ExprResult RHS = Rebuild(CE->getLHS()); 18381 if (RHS.isInvalid()) 18382 return ExprError(); 18383 18384 if (!LHS.get() && !RHS.get()) 18385 return ExprEmpty(); 18386 if (!LHS.isUsable()) 18387 LHS = CE->getLHS(); 18388 if (!RHS.isUsable()) 18389 RHS = CE->getRHS(); 18390 18391 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18392 RHS.get(), CE->getRParenLoc()); 18393 } 18394 18395 // Step through non-syntactic nodes. 18396 case Expr::ConstantExprClass: { 18397 auto *CE = cast<ConstantExpr>(E); 18398 ExprResult Sub = Rebuild(CE->getSubExpr()); 18399 if (!Sub.isUsable()) 18400 return Sub; 18401 return ConstantExpr::Create(S.Context, Sub.get()); 18402 } 18403 18404 // We could mostly rely on the recursive rebuilding to rebuild implicit 18405 // casts, but not at the top level, so rebuild them here. 18406 case Expr::ImplicitCastExprClass: { 18407 auto *ICE = cast<ImplicitCastExpr>(E); 18408 // Only step through the narrow set of cast kinds we expect to encounter. 18409 // Anything else suggests we've left the region in which potential results 18410 // can be found. 18411 switch (ICE->getCastKind()) { 18412 case CK_NoOp: 18413 case CK_DerivedToBase: 18414 case CK_UncheckedDerivedToBase: { 18415 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18416 if (!Sub.isUsable()) 18417 return Sub; 18418 CXXCastPath Path(ICE->path()); 18419 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18420 ICE->getValueKind(), &Path); 18421 } 18422 18423 default: 18424 break; 18425 } 18426 break; 18427 } 18428 18429 default: 18430 break; 18431 } 18432 18433 // Can't traverse through this node. Nothing to do. 18434 return ExprEmpty(); 18435 } 18436 18437 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18438 // Check whether the operand is or contains an object of non-trivial C union 18439 // type. 18440 if (E->getType().isVolatileQualified() && 18441 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18442 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18443 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18444 Sema::NTCUC_LValueToRValueVolatile, 18445 NTCUK_Destruct|NTCUK_Copy); 18446 18447 // C++2a [basic.def.odr]p4: 18448 // [...] an expression of non-volatile-qualified non-class type to which 18449 // the lvalue-to-rvalue conversion is applied [...] 18450 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18451 return E; 18452 18453 ExprResult Result = 18454 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18455 if (Result.isInvalid()) 18456 return ExprError(); 18457 return Result.get() ? Result : E; 18458 } 18459 18460 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18461 Res = CorrectDelayedTyposInExpr(Res); 18462 18463 if (!Res.isUsable()) 18464 return Res; 18465 18466 // If a constant-expression is a reference to a variable where we delay 18467 // deciding whether it is an odr-use, just assume we will apply the 18468 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18469 // (a non-type template argument), we have special handling anyway. 18470 return CheckLValueToRValueConversionOperand(Res.get()); 18471 } 18472 18473 void Sema::CleanupVarDeclMarking() { 18474 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18475 // call. 18476 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18477 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18478 18479 for (Expr *E : LocalMaybeODRUseExprs) { 18480 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18481 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18482 DRE->getLocation(), *this); 18483 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18484 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18485 *this); 18486 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18487 for (VarDecl *VD : *FP) 18488 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18489 } else { 18490 llvm_unreachable("Unexpected expression"); 18491 } 18492 } 18493 18494 assert(MaybeODRUseExprs.empty() && 18495 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18496 } 18497 18498 static void DoMarkVarDeclReferenced( 18499 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18500 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18501 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18502 isa<FunctionParmPackExpr>(E)) && 18503 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18504 Var->setReferenced(); 18505 18506 if (Var->isInvalidDecl()) 18507 return; 18508 18509 auto *MSI = Var->getMemberSpecializationInfo(); 18510 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18511 : Var->getTemplateSpecializationKind(); 18512 18513 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18514 bool UsableInConstantExpr = 18515 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18516 18517 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18518 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18519 } 18520 18521 // C++20 [expr.const]p12: 18522 // A variable [...] is needed for constant evaluation if it is [...] a 18523 // variable whose name appears as a potentially constant evaluated 18524 // expression that is either a contexpr variable or is of non-volatile 18525 // const-qualified integral type or of reference type 18526 bool NeededForConstantEvaluation = 18527 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18528 18529 bool NeedDefinition = 18530 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18531 18532 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18533 "Can't instantiate a partial template specialization."); 18534 18535 // If this might be a member specialization of a static data member, check 18536 // the specialization is visible. We already did the checks for variable 18537 // template specializations when we created them. 18538 if (NeedDefinition && TSK != TSK_Undeclared && 18539 !isa<VarTemplateSpecializationDecl>(Var)) 18540 SemaRef.checkSpecializationVisibility(Loc, Var); 18541 18542 // Perform implicit instantiation of static data members, static data member 18543 // templates of class templates, and variable template specializations. Delay 18544 // instantiations of variable templates, except for those that could be used 18545 // in a constant expression. 18546 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18547 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18548 // instantiation declaration if a variable is usable in a constant 18549 // expression (among other cases). 18550 bool TryInstantiating = 18551 TSK == TSK_ImplicitInstantiation || 18552 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18553 18554 if (TryInstantiating) { 18555 SourceLocation PointOfInstantiation = 18556 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18557 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18558 if (FirstInstantiation) { 18559 PointOfInstantiation = Loc; 18560 if (MSI) 18561 MSI->setPointOfInstantiation(PointOfInstantiation); 18562 // FIXME: Notify listener. 18563 else 18564 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18565 } 18566 18567 if (UsableInConstantExpr) { 18568 // Do not defer instantiations of variables that could be used in a 18569 // constant expression. 18570 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18571 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18572 }); 18573 18574 // Re-set the member to trigger a recomputation of the dependence bits 18575 // for the expression. 18576 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18577 DRE->setDecl(DRE->getDecl()); 18578 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18579 ME->setMemberDecl(ME->getMemberDecl()); 18580 } else if (FirstInstantiation || 18581 isa<VarTemplateSpecializationDecl>(Var)) { 18582 // FIXME: For a specialization of a variable template, we don't 18583 // distinguish between "declaration and type implicitly instantiated" 18584 // and "implicit instantiation of definition requested", so we have 18585 // no direct way to avoid enqueueing the pending instantiation 18586 // multiple times. 18587 SemaRef.PendingInstantiations 18588 .push_back(std::make_pair(Var, PointOfInstantiation)); 18589 } 18590 } 18591 } 18592 18593 // C++2a [basic.def.odr]p4: 18594 // A variable x whose name appears as a potentially-evaluated expression e 18595 // is odr-used by e unless 18596 // -- x is a reference that is usable in constant expressions 18597 // -- x is a variable of non-reference type that is usable in constant 18598 // expressions and has no mutable subobjects [FIXME], and e is an 18599 // element of the set of potential results of an expression of 18600 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18601 // conversion is applied 18602 // -- x is a variable of non-reference type, and e is an element of the set 18603 // of potential results of a discarded-value expression to which the 18604 // lvalue-to-rvalue conversion is not applied [FIXME] 18605 // 18606 // We check the first part of the second bullet here, and 18607 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18608 // FIXME: To get the third bullet right, we need to delay this even for 18609 // variables that are not usable in constant expressions. 18610 18611 // If we already know this isn't an odr-use, there's nothing more to do. 18612 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18613 if (DRE->isNonOdrUse()) 18614 return; 18615 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18616 if (ME->isNonOdrUse()) 18617 return; 18618 18619 switch (OdrUse) { 18620 case OdrUseContext::None: 18621 assert((!E || isa<FunctionParmPackExpr>(E)) && 18622 "missing non-odr-use marking for unevaluated decl ref"); 18623 break; 18624 18625 case OdrUseContext::FormallyOdrUsed: 18626 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18627 // behavior. 18628 break; 18629 18630 case OdrUseContext::Used: 18631 // If we might later find that this expression isn't actually an odr-use, 18632 // delay the marking. 18633 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18634 SemaRef.MaybeODRUseExprs.insert(E); 18635 else 18636 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18637 break; 18638 18639 case OdrUseContext::Dependent: 18640 // If this is a dependent context, we don't need to mark variables as 18641 // odr-used, but we may still need to track them for lambda capture. 18642 // FIXME: Do we also need to do this inside dependent typeid expressions 18643 // (which are modeled as unevaluated at this point)? 18644 const bool RefersToEnclosingScope = 18645 (SemaRef.CurContext != Var->getDeclContext() && 18646 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18647 if (RefersToEnclosingScope) { 18648 LambdaScopeInfo *const LSI = 18649 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18650 if (LSI && (!LSI->CallOperator || 18651 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18652 // If a variable could potentially be odr-used, defer marking it so 18653 // until we finish analyzing the full expression for any 18654 // lvalue-to-rvalue 18655 // or discarded value conversions that would obviate odr-use. 18656 // Add it to the list of potential captures that will be analyzed 18657 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18658 // unless the variable is a reference that was initialized by a constant 18659 // expression (this will never need to be captured or odr-used). 18660 // 18661 // FIXME: We can simplify this a lot after implementing P0588R1. 18662 assert(E && "Capture variable should be used in an expression."); 18663 if (!Var->getType()->isReferenceType() || 18664 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18665 LSI->addPotentialCapture(E->IgnoreParens()); 18666 } 18667 } 18668 break; 18669 } 18670 } 18671 18672 /// Mark a variable referenced, and check whether it is odr-used 18673 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18674 /// used directly for normal expressions referring to VarDecl. 18675 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18676 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18677 } 18678 18679 static void 18680 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18681 bool MightBeOdrUse, 18682 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18683 if (SemaRef.isInOpenMPDeclareTargetContext()) 18684 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18685 18686 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18687 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18688 return; 18689 } 18690 18691 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18692 18693 // If this is a call to a method via a cast, also mark the method in the 18694 // derived class used in case codegen can devirtualize the call. 18695 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18696 if (!ME) 18697 return; 18698 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18699 if (!MD) 18700 return; 18701 // Only attempt to devirtualize if this is truly a virtual call. 18702 bool IsVirtualCall = MD->isVirtual() && 18703 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18704 if (!IsVirtualCall) 18705 return; 18706 18707 // If it's possible to devirtualize the call, mark the called function 18708 // referenced. 18709 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18710 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18711 if (DM) 18712 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18713 } 18714 18715 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18716 /// 18717 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18718 /// handled with care if the DeclRefExpr is not newly-created. 18719 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18720 // TODO: update this with DR# once a defect report is filed. 18721 // C++11 defect. The address of a pure member should not be an ODR use, even 18722 // if it's a qualified reference. 18723 bool OdrUse = true; 18724 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18725 if (Method->isVirtual() && 18726 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18727 OdrUse = false; 18728 18729 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18730 if (!isConstantEvaluated() && FD->isConsteval() && 18731 !RebuildingImmediateInvocation) 18732 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18733 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18734 RefsMinusAssignments); 18735 } 18736 18737 /// Perform reference-marking and odr-use handling for a MemberExpr. 18738 void Sema::MarkMemberReferenced(MemberExpr *E) { 18739 // C++11 [basic.def.odr]p2: 18740 // A non-overloaded function whose name appears as a potentially-evaluated 18741 // expression or a member of a set of candidate functions, if selected by 18742 // overload resolution when referred to from a potentially-evaluated 18743 // expression, is odr-used, unless it is a pure virtual function and its 18744 // name is not explicitly qualified. 18745 bool MightBeOdrUse = true; 18746 if (E->performsVirtualDispatch(getLangOpts())) { 18747 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18748 if (Method->isPure()) 18749 MightBeOdrUse = false; 18750 } 18751 SourceLocation Loc = 18752 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18753 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18754 RefsMinusAssignments); 18755 } 18756 18757 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18758 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18759 for (VarDecl *VD : *E) 18760 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18761 RefsMinusAssignments); 18762 } 18763 18764 /// Perform marking for a reference to an arbitrary declaration. It 18765 /// marks the declaration referenced, and performs odr-use checking for 18766 /// functions and variables. This method should not be used when building a 18767 /// normal expression which refers to a variable. 18768 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18769 bool MightBeOdrUse) { 18770 if (MightBeOdrUse) { 18771 if (auto *VD = dyn_cast<VarDecl>(D)) { 18772 MarkVariableReferenced(Loc, VD); 18773 return; 18774 } 18775 } 18776 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18777 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18778 return; 18779 } 18780 D->setReferenced(); 18781 } 18782 18783 namespace { 18784 // Mark all of the declarations used by a type as referenced. 18785 // FIXME: Not fully implemented yet! We need to have a better understanding 18786 // of when we're entering a context we should not recurse into. 18787 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18788 // TreeTransforms rebuilding the type in a new context. Rather than 18789 // duplicating the TreeTransform logic, we should consider reusing it here. 18790 // Currently that causes problems when rebuilding LambdaExprs. 18791 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18792 Sema &S; 18793 SourceLocation Loc; 18794 18795 public: 18796 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18797 18798 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18799 18800 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18801 }; 18802 } 18803 18804 bool MarkReferencedDecls::TraverseTemplateArgument( 18805 const TemplateArgument &Arg) { 18806 { 18807 // A non-type template argument is a constant-evaluated context. 18808 EnterExpressionEvaluationContext Evaluated( 18809 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18810 if (Arg.getKind() == TemplateArgument::Declaration) { 18811 if (Decl *D = Arg.getAsDecl()) 18812 S.MarkAnyDeclReferenced(Loc, D, true); 18813 } else if (Arg.getKind() == TemplateArgument::Expression) { 18814 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18815 } 18816 } 18817 18818 return Inherited::TraverseTemplateArgument(Arg); 18819 } 18820 18821 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18822 MarkReferencedDecls Marker(*this, Loc); 18823 Marker.TraverseType(T); 18824 } 18825 18826 namespace { 18827 /// Helper class that marks all of the declarations referenced by 18828 /// potentially-evaluated subexpressions as "referenced". 18829 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18830 public: 18831 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18832 bool SkipLocalVariables; 18833 18834 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18835 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18836 18837 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18838 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18839 } 18840 18841 void VisitDeclRefExpr(DeclRefExpr *E) { 18842 // If we were asked not to visit local variables, don't. 18843 if (SkipLocalVariables) { 18844 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18845 if (VD->hasLocalStorage()) 18846 return; 18847 } 18848 18849 // FIXME: This can trigger the instantiation of the initializer of a 18850 // variable, which can cause the expression to become value-dependent 18851 // or error-dependent. Do we need to propagate the new dependence bits? 18852 S.MarkDeclRefReferenced(E); 18853 } 18854 18855 void VisitMemberExpr(MemberExpr *E) { 18856 S.MarkMemberReferenced(E); 18857 Visit(E->getBase()); 18858 } 18859 }; 18860 } // namespace 18861 18862 /// Mark any declarations that appear within this expression or any 18863 /// potentially-evaluated subexpressions as "referenced". 18864 /// 18865 /// \param SkipLocalVariables If true, don't mark local variables as 18866 /// 'referenced'. 18867 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18868 bool SkipLocalVariables) { 18869 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18870 } 18871 18872 /// Emit a diagnostic that describes an effect on the run-time behavior 18873 /// of the program being compiled. 18874 /// 18875 /// This routine emits the given diagnostic when the code currently being 18876 /// type-checked is "potentially evaluated", meaning that there is a 18877 /// possibility that the code will actually be executable. Code in sizeof() 18878 /// expressions, code used only during overload resolution, etc., are not 18879 /// potentially evaluated. This routine will suppress such diagnostics or, 18880 /// in the absolutely nutty case of potentially potentially evaluated 18881 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18882 /// later. 18883 /// 18884 /// This routine should be used for all diagnostics that describe the run-time 18885 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18886 /// Failure to do so will likely result in spurious diagnostics or failures 18887 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18888 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18889 const PartialDiagnostic &PD) { 18890 switch (ExprEvalContexts.back().Context) { 18891 case ExpressionEvaluationContext::Unevaluated: 18892 case ExpressionEvaluationContext::UnevaluatedList: 18893 case ExpressionEvaluationContext::UnevaluatedAbstract: 18894 case ExpressionEvaluationContext::DiscardedStatement: 18895 // The argument will never be evaluated, so don't complain. 18896 break; 18897 18898 case ExpressionEvaluationContext::ConstantEvaluated: 18899 // Relevant diagnostics should be produced by constant evaluation. 18900 break; 18901 18902 case ExpressionEvaluationContext::PotentiallyEvaluated: 18903 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18904 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18905 FunctionScopes.back()->PossiblyUnreachableDiags. 18906 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18907 return true; 18908 } 18909 18910 // The initializer of a constexpr variable or of the first declaration of a 18911 // static data member is not syntactically a constant evaluated constant, 18912 // but nonetheless is always required to be a constant expression, so we 18913 // can skip diagnosing. 18914 // FIXME: Using the mangling context here is a hack. 18915 if (auto *VD = dyn_cast_or_null<VarDecl>( 18916 ExprEvalContexts.back().ManglingContextDecl)) { 18917 if (VD->isConstexpr() || 18918 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18919 break; 18920 // FIXME: For any other kind of variable, we should build a CFG for its 18921 // initializer and check whether the context in question is reachable. 18922 } 18923 18924 Diag(Loc, PD); 18925 return true; 18926 } 18927 18928 return false; 18929 } 18930 18931 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18932 const PartialDiagnostic &PD) { 18933 return DiagRuntimeBehavior( 18934 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18935 } 18936 18937 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18938 CallExpr *CE, FunctionDecl *FD) { 18939 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18940 return false; 18941 18942 // If we're inside a decltype's expression, don't check for a valid return 18943 // type or construct temporaries until we know whether this is the last call. 18944 if (ExprEvalContexts.back().ExprContext == 18945 ExpressionEvaluationContextRecord::EK_Decltype) { 18946 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18947 return false; 18948 } 18949 18950 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18951 FunctionDecl *FD; 18952 CallExpr *CE; 18953 18954 public: 18955 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18956 : FD(FD), CE(CE) { } 18957 18958 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18959 if (!FD) { 18960 S.Diag(Loc, diag::err_call_incomplete_return) 18961 << T << CE->getSourceRange(); 18962 return; 18963 } 18964 18965 S.Diag(Loc, diag::err_call_function_incomplete_return) 18966 << CE->getSourceRange() << FD << T; 18967 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18968 << FD->getDeclName(); 18969 } 18970 } Diagnoser(FD, CE); 18971 18972 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18973 return true; 18974 18975 return false; 18976 } 18977 18978 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18979 // will prevent this condition from triggering, which is what we want. 18980 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18981 SourceLocation Loc; 18982 18983 unsigned diagnostic = diag::warn_condition_is_assignment; 18984 bool IsOrAssign = false; 18985 18986 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18987 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18988 return; 18989 18990 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18991 18992 // Greylist some idioms by putting them into a warning subcategory. 18993 if (ObjCMessageExpr *ME 18994 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18995 Selector Sel = ME->getSelector(); 18996 18997 // self = [<foo> init...] 18998 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18999 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19000 19001 // <foo> = [<bar> nextObject] 19002 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19003 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19004 } 19005 19006 Loc = Op->getOperatorLoc(); 19007 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19008 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19009 return; 19010 19011 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19012 Loc = Op->getOperatorLoc(); 19013 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19014 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19015 else { 19016 // Not an assignment. 19017 return; 19018 } 19019 19020 Diag(Loc, diagnostic) << E->getSourceRange(); 19021 19022 SourceLocation Open = E->getBeginLoc(); 19023 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19024 Diag(Loc, diag::note_condition_assign_silence) 19025 << FixItHint::CreateInsertion(Open, "(") 19026 << FixItHint::CreateInsertion(Close, ")"); 19027 19028 if (IsOrAssign) 19029 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19030 << FixItHint::CreateReplacement(Loc, "!="); 19031 else 19032 Diag(Loc, diag::note_condition_assign_to_comparison) 19033 << FixItHint::CreateReplacement(Loc, "=="); 19034 } 19035 19036 /// Redundant parentheses over an equality comparison can indicate 19037 /// that the user intended an assignment used as condition. 19038 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19039 // Don't warn if the parens came from a macro. 19040 SourceLocation parenLoc = ParenE->getBeginLoc(); 19041 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19042 return; 19043 // Don't warn for dependent expressions. 19044 if (ParenE->isTypeDependent()) 19045 return; 19046 19047 Expr *E = ParenE->IgnoreParens(); 19048 19049 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19050 if (opE->getOpcode() == BO_EQ && 19051 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19052 == Expr::MLV_Valid) { 19053 SourceLocation Loc = opE->getOperatorLoc(); 19054 19055 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19056 SourceRange ParenERange = ParenE->getSourceRange(); 19057 Diag(Loc, diag::note_equality_comparison_silence) 19058 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19059 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19060 Diag(Loc, diag::note_equality_comparison_to_assign) 19061 << FixItHint::CreateReplacement(Loc, "="); 19062 } 19063 } 19064 19065 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19066 bool IsConstexpr) { 19067 DiagnoseAssignmentAsCondition(E); 19068 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19069 DiagnoseEqualityWithExtraParens(parenE); 19070 19071 ExprResult result = CheckPlaceholderExpr(E); 19072 if (result.isInvalid()) return ExprError(); 19073 E = result.get(); 19074 19075 if (!E->isTypeDependent()) { 19076 if (getLangOpts().CPlusPlus) 19077 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19078 19079 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19080 if (ERes.isInvalid()) 19081 return ExprError(); 19082 E = ERes.get(); 19083 19084 QualType T = E->getType(); 19085 if (!T->isScalarType()) { // C99 6.8.4.1p1 19086 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19087 << T << E->getSourceRange(); 19088 return ExprError(); 19089 } 19090 CheckBoolLikeConversion(E, Loc); 19091 } 19092 19093 return E; 19094 } 19095 19096 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19097 Expr *SubExpr, ConditionKind CK) { 19098 // Empty conditions are valid in for-statements. 19099 if (!SubExpr) 19100 return ConditionResult(); 19101 19102 ExprResult Cond; 19103 switch (CK) { 19104 case ConditionKind::Boolean: 19105 Cond = CheckBooleanCondition(Loc, SubExpr); 19106 break; 19107 19108 case ConditionKind::ConstexprIf: 19109 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19110 break; 19111 19112 case ConditionKind::Switch: 19113 Cond = CheckSwitchCondition(Loc, SubExpr); 19114 break; 19115 } 19116 if (Cond.isInvalid()) { 19117 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19118 {SubExpr}); 19119 if (!Cond.get()) 19120 return ConditionError(); 19121 } 19122 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19123 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19124 if (!FullExpr.get()) 19125 return ConditionError(); 19126 19127 return ConditionResult(*this, nullptr, FullExpr, 19128 CK == ConditionKind::ConstexprIf); 19129 } 19130 19131 namespace { 19132 /// A visitor for rebuilding a call to an __unknown_any expression 19133 /// to have an appropriate type. 19134 struct RebuildUnknownAnyFunction 19135 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19136 19137 Sema &S; 19138 19139 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19140 19141 ExprResult VisitStmt(Stmt *S) { 19142 llvm_unreachable("unexpected statement!"); 19143 } 19144 19145 ExprResult VisitExpr(Expr *E) { 19146 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19147 << E->getSourceRange(); 19148 return ExprError(); 19149 } 19150 19151 /// Rebuild an expression which simply semantically wraps another 19152 /// expression which it shares the type and value kind of. 19153 template <class T> ExprResult rebuildSugarExpr(T *E) { 19154 ExprResult SubResult = Visit(E->getSubExpr()); 19155 if (SubResult.isInvalid()) return ExprError(); 19156 19157 Expr *SubExpr = SubResult.get(); 19158 E->setSubExpr(SubExpr); 19159 E->setType(SubExpr->getType()); 19160 E->setValueKind(SubExpr->getValueKind()); 19161 assert(E->getObjectKind() == OK_Ordinary); 19162 return E; 19163 } 19164 19165 ExprResult VisitParenExpr(ParenExpr *E) { 19166 return rebuildSugarExpr(E); 19167 } 19168 19169 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19170 return rebuildSugarExpr(E); 19171 } 19172 19173 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19174 ExprResult SubResult = Visit(E->getSubExpr()); 19175 if (SubResult.isInvalid()) return ExprError(); 19176 19177 Expr *SubExpr = SubResult.get(); 19178 E->setSubExpr(SubExpr); 19179 E->setType(S.Context.getPointerType(SubExpr->getType())); 19180 assert(E->getValueKind() == VK_PRValue); 19181 assert(E->getObjectKind() == OK_Ordinary); 19182 return E; 19183 } 19184 19185 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19186 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19187 19188 E->setType(VD->getType()); 19189 19190 assert(E->getValueKind() == VK_PRValue); 19191 if (S.getLangOpts().CPlusPlus && 19192 !(isa<CXXMethodDecl>(VD) && 19193 cast<CXXMethodDecl>(VD)->isInstance())) 19194 E->setValueKind(VK_LValue); 19195 19196 return E; 19197 } 19198 19199 ExprResult VisitMemberExpr(MemberExpr *E) { 19200 return resolveDecl(E, E->getMemberDecl()); 19201 } 19202 19203 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19204 return resolveDecl(E, E->getDecl()); 19205 } 19206 }; 19207 } 19208 19209 /// Given a function expression of unknown-any type, try to rebuild it 19210 /// to have a function type. 19211 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19212 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19213 if (Result.isInvalid()) return ExprError(); 19214 return S.DefaultFunctionArrayConversion(Result.get()); 19215 } 19216 19217 namespace { 19218 /// A visitor for rebuilding an expression of type __unknown_anytype 19219 /// into one which resolves the type directly on the referring 19220 /// expression. Strict preservation of the original source 19221 /// structure is not a goal. 19222 struct RebuildUnknownAnyExpr 19223 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19224 19225 Sema &S; 19226 19227 /// The current destination type. 19228 QualType DestType; 19229 19230 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19231 : S(S), DestType(CastType) {} 19232 19233 ExprResult VisitStmt(Stmt *S) { 19234 llvm_unreachable("unexpected statement!"); 19235 } 19236 19237 ExprResult VisitExpr(Expr *E) { 19238 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19239 << E->getSourceRange(); 19240 return ExprError(); 19241 } 19242 19243 ExprResult VisitCallExpr(CallExpr *E); 19244 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19245 19246 /// Rebuild an expression which simply semantically wraps another 19247 /// expression which it shares the type and value kind of. 19248 template <class T> ExprResult rebuildSugarExpr(T *E) { 19249 ExprResult SubResult = Visit(E->getSubExpr()); 19250 if (SubResult.isInvalid()) return ExprError(); 19251 Expr *SubExpr = SubResult.get(); 19252 E->setSubExpr(SubExpr); 19253 E->setType(SubExpr->getType()); 19254 E->setValueKind(SubExpr->getValueKind()); 19255 assert(E->getObjectKind() == OK_Ordinary); 19256 return E; 19257 } 19258 19259 ExprResult VisitParenExpr(ParenExpr *E) { 19260 return rebuildSugarExpr(E); 19261 } 19262 19263 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19264 return rebuildSugarExpr(E); 19265 } 19266 19267 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19268 const PointerType *Ptr = DestType->getAs<PointerType>(); 19269 if (!Ptr) { 19270 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19271 << E->getSourceRange(); 19272 return ExprError(); 19273 } 19274 19275 if (isa<CallExpr>(E->getSubExpr())) { 19276 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19277 << E->getSourceRange(); 19278 return ExprError(); 19279 } 19280 19281 assert(E->getValueKind() == VK_PRValue); 19282 assert(E->getObjectKind() == OK_Ordinary); 19283 E->setType(DestType); 19284 19285 // Build the sub-expression as if it were an object of the pointee type. 19286 DestType = Ptr->getPointeeType(); 19287 ExprResult SubResult = Visit(E->getSubExpr()); 19288 if (SubResult.isInvalid()) return ExprError(); 19289 E->setSubExpr(SubResult.get()); 19290 return E; 19291 } 19292 19293 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19294 19295 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19296 19297 ExprResult VisitMemberExpr(MemberExpr *E) { 19298 return resolveDecl(E, E->getMemberDecl()); 19299 } 19300 19301 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19302 return resolveDecl(E, E->getDecl()); 19303 } 19304 }; 19305 } 19306 19307 /// Rebuilds a call expression which yielded __unknown_anytype. 19308 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19309 Expr *CalleeExpr = E->getCallee(); 19310 19311 enum FnKind { 19312 FK_MemberFunction, 19313 FK_FunctionPointer, 19314 FK_BlockPointer 19315 }; 19316 19317 FnKind Kind; 19318 QualType CalleeType = CalleeExpr->getType(); 19319 if (CalleeType == S.Context.BoundMemberTy) { 19320 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19321 Kind = FK_MemberFunction; 19322 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19323 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19324 CalleeType = Ptr->getPointeeType(); 19325 Kind = FK_FunctionPointer; 19326 } else { 19327 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19328 Kind = FK_BlockPointer; 19329 } 19330 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19331 19332 // Verify that this is a legal result type of a function. 19333 if (DestType->isArrayType() || DestType->isFunctionType()) { 19334 unsigned diagID = diag::err_func_returning_array_function; 19335 if (Kind == FK_BlockPointer) 19336 diagID = diag::err_block_returning_array_function; 19337 19338 S.Diag(E->getExprLoc(), diagID) 19339 << DestType->isFunctionType() << DestType; 19340 return ExprError(); 19341 } 19342 19343 // Otherwise, go ahead and set DestType as the call's result. 19344 E->setType(DestType.getNonLValueExprType(S.Context)); 19345 E->setValueKind(Expr::getValueKindForType(DestType)); 19346 assert(E->getObjectKind() == OK_Ordinary); 19347 19348 // Rebuild the function type, replacing the result type with DestType. 19349 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19350 if (Proto) { 19351 // __unknown_anytype(...) is a special case used by the debugger when 19352 // it has no idea what a function's signature is. 19353 // 19354 // We want to build this call essentially under the K&R 19355 // unprototyped rules, but making a FunctionNoProtoType in C++ 19356 // would foul up all sorts of assumptions. However, we cannot 19357 // simply pass all arguments as variadic arguments, nor can we 19358 // portably just call the function under a non-variadic type; see 19359 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19360 // However, it turns out that in practice it is generally safe to 19361 // call a function declared as "A foo(B,C,D);" under the prototype 19362 // "A foo(B,C,D,...);". The only known exception is with the 19363 // Windows ABI, where any variadic function is implicitly cdecl 19364 // regardless of its normal CC. Therefore we change the parameter 19365 // types to match the types of the arguments. 19366 // 19367 // This is a hack, but it is far superior to moving the 19368 // corresponding target-specific code from IR-gen to Sema/AST. 19369 19370 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19371 SmallVector<QualType, 8> ArgTypes; 19372 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19373 ArgTypes.reserve(E->getNumArgs()); 19374 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19375 Expr *Arg = E->getArg(i); 19376 QualType ArgType = Arg->getType(); 19377 if (E->isLValue()) { 19378 ArgType = S.Context.getLValueReferenceType(ArgType); 19379 } else if (E->isXValue()) { 19380 ArgType = S.Context.getRValueReferenceType(ArgType); 19381 } 19382 ArgTypes.push_back(ArgType); 19383 } 19384 ParamTypes = ArgTypes; 19385 } 19386 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19387 Proto->getExtProtoInfo()); 19388 } else { 19389 DestType = S.Context.getFunctionNoProtoType(DestType, 19390 FnType->getExtInfo()); 19391 } 19392 19393 // Rebuild the appropriate pointer-to-function type. 19394 switch (Kind) { 19395 case FK_MemberFunction: 19396 // Nothing to do. 19397 break; 19398 19399 case FK_FunctionPointer: 19400 DestType = S.Context.getPointerType(DestType); 19401 break; 19402 19403 case FK_BlockPointer: 19404 DestType = S.Context.getBlockPointerType(DestType); 19405 break; 19406 } 19407 19408 // Finally, we can recurse. 19409 ExprResult CalleeResult = Visit(CalleeExpr); 19410 if (!CalleeResult.isUsable()) return ExprError(); 19411 E->setCallee(CalleeResult.get()); 19412 19413 // Bind a temporary if necessary. 19414 return S.MaybeBindToTemporary(E); 19415 } 19416 19417 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19418 // Verify that this is a legal result type of a call. 19419 if (DestType->isArrayType() || DestType->isFunctionType()) { 19420 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19421 << DestType->isFunctionType() << DestType; 19422 return ExprError(); 19423 } 19424 19425 // Rewrite the method result type if available. 19426 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19427 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19428 Method->setReturnType(DestType); 19429 } 19430 19431 // Change the type of the message. 19432 E->setType(DestType.getNonReferenceType()); 19433 E->setValueKind(Expr::getValueKindForType(DestType)); 19434 19435 return S.MaybeBindToTemporary(E); 19436 } 19437 19438 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19439 // The only case we should ever see here is a function-to-pointer decay. 19440 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19441 assert(E->getValueKind() == VK_PRValue); 19442 assert(E->getObjectKind() == OK_Ordinary); 19443 19444 E->setType(DestType); 19445 19446 // Rebuild the sub-expression as the pointee (function) type. 19447 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19448 19449 ExprResult Result = Visit(E->getSubExpr()); 19450 if (!Result.isUsable()) return ExprError(); 19451 19452 E->setSubExpr(Result.get()); 19453 return E; 19454 } else if (E->getCastKind() == CK_LValueToRValue) { 19455 assert(E->getValueKind() == VK_PRValue); 19456 assert(E->getObjectKind() == OK_Ordinary); 19457 19458 assert(isa<BlockPointerType>(E->getType())); 19459 19460 E->setType(DestType); 19461 19462 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19463 DestType = S.Context.getLValueReferenceType(DestType); 19464 19465 ExprResult Result = Visit(E->getSubExpr()); 19466 if (!Result.isUsable()) return ExprError(); 19467 19468 E->setSubExpr(Result.get()); 19469 return E; 19470 } else { 19471 llvm_unreachable("Unhandled cast type!"); 19472 } 19473 } 19474 19475 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19476 ExprValueKind ValueKind = VK_LValue; 19477 QualType Type = DestType; 19478 19479 // We know how to make this work for certain kinds of decls: 19480 19481 // - functions 19482 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19483 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19484 DestType = Ptr->getPointeeType(); 19485 ExprResult Result = resolveDecl(E, VD); 19486 if (Result.isInvalid()) return ExprError(); 19487 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19488 VK_PRValue); 19489 } 19490 19491 if (!Type->isFunctionType()) { 19492 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19493 << VD << E->getSourceRange(); 19494 return ExprError(); 19495 } 19496 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19497 // We must match the FunctionDecl's type to the hack introduced in 19498 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19499 // type. See the lengthy commentary in that routine. 19500 QualType FDT = FD->getType(); 19501 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19502 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19503 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19504 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19505 SourceLocation Loc = FD->getLocation(); 19506 FunctionDecl *NewFD = FunctionDecl::Create( 19507 S.Context, FD->getDeclContext(), Loc, Loc, 19508 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19509 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19510 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19511 19512 if (FD->getQualifier()) 19513 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19514 19515 SmallVector<ParmVarDecl*, 16> Params; 19516 for (const auto &AI : FT->param_types()) { 19517 ParmVarDecl *Param = 19518 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19519 Param->setScopeInfo(0, Params.size()); 19520 Params.push_back(Param); 19521 } 19522 NewFD->setParams(Params); 19523 DRE->setDecl(NewFD); 19524 VD = DRE->getDecl(); 19525 } 19526 } 19527 19528 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19529 if (MD->isInstance()) { 19530 ValueKind = VK_PRValue; 19531 Type = S.Context.BoundMemberTy; 19532 } 19533 19534 // Function references aren't l-values in C. 19535 if (!S.getLangOpts().CPlusPlus) 19536 ValueKind = VK_PRValue; 19537 19538 // - variables 19539 } else if (isa<VarDecl>(VD)) { 19540 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19541 Type = RefTy->getPointeeType(); 19542 } else if (Type->isFunctionType()) { 19543 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19544 << VD << E->getSourceRange(); 19545 return ExprError(); 19546 } 19547 19548 // - nothing else 19549 } else { 19550 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19551 << VD << E->getSourceRange(); 19552 return ExprError(); 19553 } 19554 19555 // Modifying the declaration like this is friendly to IR-gen but 19556 // also really dangerous. 19557 VD->setType(DestType); 19558 E->setType(Type); 19559 E->setValueKind(ValueKind); 19560 return E; 19561 } 19562 19563 /// Check a cast of an unknown-any type. We intentionally only 19564 /// trigger this for C-style casts. 19565 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19566 Expr *CastExpr, CastKind &CastKind, 19567 ExprValueKind &VK, CXXCastPath &Path) { 19568 // The type we're casting to must be either void or complete. 19569 if (!CastType->isVoidType() && 19570 RequireCompleteType(TypeRange.getBegin(), CastType, 19571 diag::err_typecheck_cast_to_incomplete)) 19572 return ExprError(); 19573 19574 // Rewrite the casted expression from scratch. 19575 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19576 if (!result.isUsable()) return ExprError(); 19577 19578 CastExpr = result.get(); 19579 VK = CastExpr->getValueKind(); 19580 CastKind = CK_NoOp; 19581 19582 return CastExpr; 19583 } 19584 19585 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19586 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19587 } 19588 19589 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19590 Expr *arg, QualType ¶mType) { 19591 // If the syntactic form of the argument is not an explicit cast of 19592 // any sort, just do default argument promotion. 19593 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19594 if (!castArg) { 19595 ExprResult result = DefaultArgumentPromotion(arg); 19596 if (result.isInvalid()) return ExprError(); 19597 paramType = result.get()->getType(); 19598 return result; 19599 } 19600 19601 // Otherwise, use the type that was written in the explicit cast. 19602 assert(!arg->hasPlaceholderType()); 19603 paramType = castArg->getTypeAsWritten(); 19604 19605 // Copy-initialize a parameter of that type. 19606 InitializedEntity entity = 19607 InitializedEntity::InitializeParameter(Context, paramType, 19608 /*consumed*/ false); 19609 return PerformCopyInitialization(entity, callLoc, arg); 19610 } 19611 19612 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19613 Expr *orig = E; 19614 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19615 while (true) { 19616 E = E->IgnoreParenImpCasts(); 19617 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19618 E = call->getCallee(); 19619 diagID = diag::err_uncasted_call_of_unknown_any; 19620 } else { 19621 break; 19622 } 19623 } 19624 19625 SourceLocation loc; 19626 NamedDecl *d; 19627 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19628 loc = ref->getLocation(); 19629 d = ref->getDecl(); 19630 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19631 loc = mem->getMemberLoc(); 19632 d = mem->getMemberDecl(); 19633 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19634 diagID = diag::err_uncasted_call_of_unknown_any; 19635 loc = msg->getSelectorStartLoc(); 19636 d = msg->getMethodDecl(); 19637 if (!d) { 19638 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19639 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19640 << orig->getSourceRange(); 19641 return ExprError(); 19642 } 19643 } else { 19644 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19645 << E->getSourceRange(); 19646 return ExprError(); 19647 } 19648 19649 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19650 19651 // Never recoverable. 19652 return ExprError(); 19653 } 19654 19655 /// Check for operands with placeholder types and complain if found. 19656 /// Returns ExprError() if there was an error and no recovery was possible. 19657 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19658 if (!Context.isDependenceAllowed()) { 19659 // C cannot handle TypoExpr nodes on either side of a binop because it 19660 // doesn't handle dependent types properly, so make sure any TypoExprs have 19661 // been dealt with before checking the operands. 19662 ExprResult Result = CorrectDelayedTyposInExpr(E); 19663 if (!Result.isUsable()) return ExprError(); 19664 E = Result.get(); 19665 } 19666 19667 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19668 if (!placeholderType) return E; 19669 19670 switch (placeholderType->getKind()) { 19671 19672 // Overloaded expressions. 19673 case BuiltinType::Overload: { 19674 // Try to resolve a single function template specialization. 19675 // This is obligatory. 19676 ExprResult Result = E; 19677 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19678 return Result; 19679 19680 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19681 // leaves Result unchanged on failure. 19682 Result = E; 19683 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19684 return Result; 19685 19686 // If that failed, try to recover with a call. 19687 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19688 /*complain*/ true); 19689 return Result; 19690 } 19691 19692 // Bound member functions. 19693 case BuiltinType::BoundMember: { 19694 ExprResult result = E; 19695 const Expr *BME = E->IgnoreParens(); 19696 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19697 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19698 if (isa<CXXPseudoDestructorExpr>(BME)) { 19699 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19700 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19701 if (ME->getMemberNameInfo().getName().getNameKind() == 19702 DeclarationName::CXXDestructorName) 19703 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19704 } 19705 tryToRecoverWithCall(result, PD, 19706 /*complain*/ true); 19707 return result; 19708 } 19709 19710 // ARC unbridged casts. 19711 case BuiltinType::ARCUnbridgedCast: { 19712 Expr *realCast = stripARCUnbridgedCast(E); 19713 diagnoseARCUnbridgedCast(realCast); 19714 return realCast; 19715 } 19716 19717 // Expressions of unknown type. 19718 case BuiltinType::UnknownAny: 19719 return diagnoseUnknownAnyExpr(*this, E); 19720 19721 // Pseudo-objects. 19722 case BuiltinType::PseudoObject: 19723 return checkPseudoObjectRValue(E); 19724 19725 case BuiltinType::BuiltinFn: { 19726 // Accept __noop without parens by implicitly converting it to a call expr. 19727 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19728 if (DRE) { 19729 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19730 if (FD->getBuiltinID() == Builtin::BI__noop) { 19731 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19732 CK_BuiltinFnToFnPtr) 19733 .get(); 19734 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19735 VK_PRValue, SourceLocation(), 19736 FPOptionsOverride()); 19737 } 19738 } 19739 19740 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19741 return ExprError(); 19742 } 19743 19744 case BuiltinType::IncompleteMatrixIdx: 19745 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19746 ->getRowIdx() 19747 ->getBeginLoc(), 19748 diag::err_matrix_incomplete_index); 19749 return ExprError(); 19750 19751 // Expressions of unknown type. 19752 case BuiltinType::OMPArraySection: 19753 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19754 return ExprError(); 19755 19756 // Expressions of unknown type. 19757 case BuiltinType::OMPArrayShaping: 19758 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19759 19760 case BuiltinType::OMPIterator: 19761 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19762 19763 // Everything else should be impossible. 19764 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19765 case BuiltinType::Id: 19766 #include "clang/Basic/OpenCLImageTypes.def" 19767 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19768 case BuiltinType::Id: 19769 #include "clang/Basic/OpenCLExtensionTypes.def" 19770 #define SVE_TYPE(Name, Id, SingletonId) \ 19771 case BuiltinType::Id: 19772 #include "clang/Basic/AArch64SVEACLETypes.def" 19773 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19774 case BuiltinType::Id: 19775 #include "clang/Basic/PPCTypes.def" 19776 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19777 #include "clang/Basic/RISCVVTypes.def" 19778 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19779 #define PLACEHOLDER_TYPE(Id, SingletonId) 19780 #include "clang/AST/BuiltinTypes.def" 19781 break; 19782 } 19783 19784 llvm_unreachable("invalid placeholder type!"); 19785 } 19786 19787 bool Sema::CheckCaseExpression(Expr *E) { 19788 if (E->isTypeDependent()) 19789 return true; 19790 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19791 return E->getType()->isIntegralOrEnumerationType(); 19792 return false; 19793 } 19794 19795 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19796 ExprResult 19797 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19798 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19799 "Unknown Objective-C Boolean value!"); 19800 QualType BoolT = Context.ObjCBuiltinBoolTy; 19801 if (!Context.getBOOLDecl()) { 19802 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19803 Sema::LookupOrdinaryName); 19804 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19805 NamedDecl *ND = Result.getFoundDecl(); 19806 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19807 Context.setBOOLDecl(TD); 19808 } 19809 } 19810 if (Context.getBOOLDecl()) 19811 BoolT = Context.getBOOLType(); 19812 return new (Context) 19813 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19814 } 19815 19816 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19817 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19818 SourceLocation RParen) { 19819 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19820 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19821 return Spec.getPlatform() == Platform; 19822 }); 19823 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19824 // for "maccatalyst" if "maccatalyst" is not specified. 19825 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19826 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19827 return Spec.getPlatform() == "ios"; 19828 }); 19829 } 19830 if (Spec == AvailSpecs.end()) 19831 return None; 19832 return Spec->getVersion(); 19833 }; 19834 19835 VersionTuple Version; 19836 if (auto MaybeVersion = 19837 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19838 Version = *MaybeVersion; 19839 19840 // The use of `@available` in the enclosing context should be analyzed to 19841 // warn when it's used inappropriately (i.e. not if(@available)). 19842 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19843 Context->HasPotentialAvailabilityViolations = true; 19844 19845 return new (Context) 19846 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19847 } 19848 19849 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19850 ArrayRef<Expr *> SubExprs, QualType T) { 19851 if (!Context.getLangOpts().RecoveryAST) 19852 return ExprError(); 19853 19854 if (isSFINAEContext()) 19855 return ExprError(); 19856 19857 if (T.isNull() || T->isUndeducedType() || 19858 !Context.getLangOpts().RecoveryASTType) 19859 // We don't know the concrete type, fallback to dependent type. 19860 T = Context.DependentTy; 19861 19862 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19863 } 19864