1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/OperationKinds.h" 28 #include "clang/AST/ParentMapContext.h" 29 #include "clang/AST/RecursiveASTVisitor.h" 30 #include "clang/AST/TypeLoc.h" 31 #include "clang/Basic/Builtins.h" 32 #include "clang/Basic/DiagnosticSema.h" 33 #include "clang/Basic/PartialDiagnostic.h" 34 #include "clang/Basic/SourceManager.h" 35 #include "clang/Basic/TargetInfo.h" 36 #include "clang/Lex/LiteralSupport.h" 37 #include "clang/Lex/Preprocessor.h" 38 #include "clang/Sema/AnalysisBasedWarnings.h" 39 #include "clang/Sema/DeclSpec.h" 40 #include "clang/Sema/DelayedDiagnostic.h" 41 #include "clang/Sema/Designator.h" 42 #include "clang/Sema/Initialization.h" 43 #include "clang/Sema/Lookup.h" 44 #include "clang/Sema/Overload.h" 45 #include "clang/Sema/ParsedTemplate.h" 46 #include "clang/Sema/Scope.h" 47 #include "clang/Sema/ScopeInfo.h" 48 #include "clang/Sema/SemaFixItUtils.h" 49 #include "clang/Sema/SemaInternal.h" 50 #include "clang/Sema/Template.h" 51 #include "llvm/ADT/STLExtras.h" 52 #include "llvm/ADT/StringExtras.h" 53 #include "llvm/Support/ConvertUTF.h" 54 #include "llvm/Support/SaveAndRestore.h" 55 56 using namespace clang; 57 using namespace sema; 58 using llvm::RoundingMode; 59 60 /// Determine whether the use of this declaration is valid, without 61 /// emitting diagnostics. 62 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 63 // See if this is an auto-typed variable whose initializer we are parsing. 64 if (ParsingInitForAutoVars.count(D)) 65 return false; 66 67 // See if this is a deleted function. 68 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 69 if (FD->isDeleted()) 70 return false; 71 72 // If the function has a deduced return type, and we can't deduce it, 73 // then we can't use it either. 74 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 75 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 76 return false; 77 78 // See if this is an aligned allocation/deallocation function that is 79 // unavailable. 80 if (TreatUnavailableAsInvalid && 81 isUnavailableAlignedAllocationFunction(*FD)) 82 return false; 83 } 84 85 // See if this function is unavailable. 86 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 87 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 88 return false; 89 90 if (isa<UnresolvedUsingIfExistsDecl>(D)) 91 return false; 92 93 return true; 94 } 95 96 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 97 // Warn if this is used but marked unused. 98 if (const auto *A = D->getAttr<UnusedAttr>()) { 99 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 100 // should diagnose them. 101 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 102 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 103 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 104 if (DC && !DC->hasAttr<UnusedAttr>()) 105 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 106 } 107 } 108 } 109 110 /// Emit a note explaining that this function is deleted. 111 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 112 assert(Decl && Decl->isDeleted()); 113 114 if (Decl->isDefaulted()) { 115 // If the method was explicitly defaulted, point at that declaration. 116 if (!Decl->isImplicit()) 117 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 118 119 // Try to diagnose why this special member function was implicitly 120 // deleted. This might fail, if that reason no longer applies. 121 DiagnoseDeletedDefaultedFunction(Decl); 122 return; 123 } 124 125 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 126 if (Ctor && Ctor->isInheritingConstructor()) 127 return NoteDeletedInheritingConstructor(Ctor); 128 129 Diag(Decl->getLocation(), diag::note_availability_specified_here) 130 << Decl << 1; 131 } 132 133 /// Determine whether a FunctionDecl was ever declared with an 134 /// explicit storage class. 135 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 136 for (auto I : D->redecls()) { 137 if (I->getStorageClass() != SC_None) 138 return true; 139 } 140 return false; 141 } 142 143 /// Check whether we're in an extern inline function and referring to a 144 /// variable or function with internal linkage (C11 6.7.4p3). 145 /// 146 /// This is only a warning because we used to silently accept this code, but 147 /// in many cases it will not behave correctly. This is not enabled in C++ mode 148 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 149 /// and so while there may still be user mistakes, most of the time we can't 150 /// prove that there are errors. 151 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 152 const NamedDecl *D, 153 SourceLocation Loc) { 154 // This is disabled under C++; there are too many ways for this to fire in 155 // contexts where the warning is a false positive, or where it is technically 156 // correct but benign. 157 if (S.getLangOpts().CPlusPlus) 158 return; 159 160 // Check if this is an inlined function or method. 161 FunctionDecl *Current = S.getCurFunctionDecl(); 162 if (!Current) 163 return; 164 if (!Current->isInlined()) 165 return; 166 if (!Current->isExternallyVisible()) 167 return; 168 169 // Check if the decl has internal linkage. 170 if (D->getFormalLinkage() != InternalLinkage) 171 return; 172 173 // Downgrade from ExtWarn to Extension if 174 // (1) the supposedly external inline function is in the main file, 175 // and probably won't be included anywhere else. 176 // (2) the thing we're referencing is a pure function. 177 // (3) the thing we're referencing is another inline function. 178 // This last can give us false negatives, but it's better than warning on 179 // wrappers for simple C library functions. 180 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 181 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 182 if (!DowngradeWarning && UsedFn) 183 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 184 185 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 186 : diag::ext_internal_in_extern_inline) 187 << /*IsVar=*/!UsedFn << D; 188 189 S.MaybeSuggestAddingStaticToDecl(Current); 190 191 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 192 << D; 193 } 194 195 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 196 const FunctionDecl *First = Cur->getFirstDecl(); 197 198 // Suggest "static" on the function, if possible. 199 if (!hasAnyExplicitStorageClass(First)) { 200 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 201 Diag(DeclBegin, diag::note_convert_inline_to_static) 202 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 203 } 204 } 205 206 /// Determine whether the use of this declaration is valid, and 207 /// emit any corresponding diagnostics. 208 /// 209 /// This routine diagnoses various problems with referencing 210 /// declarations that can occur when using a declaration. For example, 211 /// it might warn if a deprecated or unavailable declaration is being 212 /// used, or produce an error (and return true) if a C++0x deleted 213 /// function is being used. 214 /// 215 /// \returns true if there was an error (this declaration cannot be 216 /// referenced), false otherwise. 217 /// 218 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 219 const ObjCInterfaceDecl *UnknownObjCClass, 220 bool ObjCPropertyAccess, 221 bool AvoidPartialAvailabilityChecks, 222 ObjCInterfaceDecl *ClassReceiver) { 223 SourceLocation Loc = Locs.front(); 224 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 225 // If there were any diagnostics suppressed by template argument deduction, 226 // emit them now. 227 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 228 if (Pos != SuppressedDiagnostics.end()) { 229 for (const PartialDiagnosticAt &Suppressed : Pos->second) 230 Diag(Suppressed.first, Suppressed.second); 231 232 // Clear out the list of suppressed diagnostics, so that we don't emit 233 // them again for this specialization. However, we don't obsolete this 234 // entry from the table, because we want to avoid ever emitting these 235 // diagnostics again. 236 Pos->second.clear(); 237 } 238 239 // C++ [basic.start.main]p3: 240 // The function 'main' shall not be used within a program. 241 if (cast<FunctionDecl>(D)->isMain()) 242 Diag(Loc, diag::ext_main_used); 243 244 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 245 } 246 247 // See if this is an auto-typed variable whose initializer we are parsing. 248 if (ParsingInitForAutoVars.count(D)) { 249 if (isa<BindingDecl>(D)) { 250 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 251 << D->getDeclName(); 252 } else { 253 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 254 << D->getDeclName() << cast<VarDecl>(D)->getType(); 255 } 256 return true; 257 } 258 259 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 260 // See if this is a deleted function. 261 if (FD->isDeleted()) { 262 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 263 if (Ctor && Ctor->isInheritingConstructor()) 264 Diag(Loc, diag::err_deleted_inherited_ctor_use) 265 << Ctor->getParent() 266 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 267 else 268 Diag(Loc, diag::err_deleted_function_use); 269 NoteDeletedFunction(FD); 270 return true; 271 } 272 273 // [expr.prim.id]p4 274 // A program that refers explicitly or implicitly to a function with a 275 // trailing requires-clause whose constraint-expression is not satisfied, 276 // other than to declare it, is ill-formed. [...] 277 // 278 // See if this is a function with constraints that need to be satisfied. 279 // Check this before deducing the return type, as it might instantiate the 280 // definition. 281 if (FD->getTrailingRequiresClause()) { 282 ConstraintSatisfaction Satisfaction; 283 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 284 // A diagnostic will have already been generated (non-constant 285 // constraint expression, for example) 286 return true; 287 if (!Satisfaction.IsSatisfied) { 288 Diag(Loc, 289 diag::err_reference_to_function_with_unsatisfied_constraints) 290 << D; 291 DiagnoseUnsatisfiedConstraint(Satisfaction); 292 return true; 293 } 294 } 295 296 // If the function has a deduced return type, and we can't deduce it, 297 // then we can't use it either. 298 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 299 DeduceReturnType(FD, Loc)) 300 return true; 301 302 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 303 return true; 304 305 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 306 return true; 307 } 308 309 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 310 // Lambdas are only default-constructible or assignable in C++2a onwards. 311 if (MD->getParent()->isLambda() && 312 ((isa<CXXConstructorDecl>(MD) && 313 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 314 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 315 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 316 << !isa<CXXConstructorDecl>(MD); 317 } 318 } 319 320 auto getReferencedObjCProp = [](const NamedDecl *D) -> 321 const ObjCPropertyDecl * { 322 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 323 return MD->findPropertyDecl(); 324 return nullptr; 325 }; 326 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 327 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 328 return true; 329 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 330 return true; 331 } 332 333 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 334 // Only the variables omp_in and omp_out are allowed in the combiner. 335 // Only the variables omp_priv and omp_orig are allowed in the 336 // initializer-clause. 337 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 338 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 339 isa<VarDecl>(D)) { 340 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 341 << getCurFunction()->HasOMPDeclareReductionCombiner; 342 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 343 return true; 344 } 345 346 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 347 // List-items in map clauses on this construct may only refer to the declared 348 // variable var and entities that could be referenced by a procedure defined 349 // at the same location 350 if (LangOpts.OpenMP && isa<VarDecl>(D) && 351 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 352 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 353 << getOpenMPDeclareMapperVarName(); 354 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 355 return true; 356 } 357 358 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 359 Diag(Loc, diag::err_use_of_empty_using_if_exists); 360 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 361 return true; 362 } 363 364 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 365 AvoidPartialAvailabilityChecks, ClassReceiver); 366 367 DiagnoseUnusedOfDecl(*this, D, Loc); 368 369 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 370 371 if (auto *VD = dyn_cast<ValueDecl>(D)) 372 checkTypeSupport(VD->getType(), Loc, VD); 373 374 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 375 if (!Context.getTargetInfo().isTLSSupported()) 376 if (const auto *VD = dyn_cast<VarDecl>(D)) 377 if (VD->getTLSKind() != VarDecl::TLS_None) 378 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 379 } 380 381 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 382 !isUnevaluatedContext()) { 383 // C++ [expr.prim.req.nested] p3 384 // A local parameter shall only appear as an unevaluated operand 385 // (Clause 8) within the constraint-expression. 386 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 387 << D; 388 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 389 return true; 390 } 391 392 return false; 393 } 394 395 /// DiagnoseSentinelCalls - This routine checks whether a call or 396 /// message-send is to a declaration with the sentinel attribute, and 397 /// if so, it checks that the requirements of the sentinel are 398 /// satisfied. 399 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 400 ArrayRef<Expr *> Args) { 401 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 402 if (!attr) 403 return; 404 405 // The number of formal parameters of the declaration. 406 unsigned numFormalParams; 407 408 // The kind of declaration. This is also an index into a %select in 409 // the diagnostic. 410 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 411 412 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 413 numFormalParams = MD->param_size(); 414 calleeType = CT_Method; 415 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 416 numFormalParams = FD->param_size(); 417 calleeType = CT_Function; 418 } else if (isa<VarDecl>(D)) { 419 QualType type = cast<ValueDecl>(D)->getType(); 420 const FunctionType *fn = nullptr; 421 if (const PointerType *ptr = type->getAs<PointerType>()) { 422 fn = ptr->getPointeeType()->getAs<FunctionType>(); 423 if (!fn) return; 424 calleeType = CT_Function; 425 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 426 fn = ptr->getPointeeType()->castAs<FunctionType>(); 427 calleeType = CT_Block; 428 } else { 429 return; 430 } 431 432 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 433 numFormalParams = proto->getNumParams(); 434 } else { 435 numFormalParams = 0; 436 } 437 } else { 438 return; 439 } 440 441 // "nullPos" is the number of formal parameters at the end which 442 // effectively count as part of the variadic arguments. This is 443 // useful if you would prefer to not have *any* formal parameters, 444 // but the language forces you to have at least one. 445 unsigned nullPos = attr->getNullPos(); 446 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 447 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 448 449 // The number of arguments which should follow the sentinel. 450 unsigned numArgsAfterSentinel = attr->getSentinel(); 451 452 // If there aren't enough arguments for all the formal parameters, 453 // the sentinel, and the args after the sentinel, complain. 454 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 455 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 456 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 457 return; 458 } 459 460 // Otherwise, find the sentinel expression. 461 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 462 if (!sentinelExpr) return; 463 if (sentinelExpr->isValueDependent()) return; 464 if (Context.isSentinelNullExpr(sentinelExpr)) return; 465 466 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 467 // or 'NULL' if those are actually defined in the context. Only use 468 // 'nil' for ObjC methods, where it's much more likely that the 469 // variadic arguments form a list of object pointers. 470 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 471 std::string NullValue; 472 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 473 NullValue = "nil"; 474 else if (getLangOpts().CPlusPlus11) 475 NullValue = "nullptr"; 476 else if (PP.isMacroDefined("NULL")) 477 NullValue = "NULL"; 478 else 479 NullValue = "(void*) 0"; 480 481 if (MissingNilLoc.isInvalid()) 482 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 483 else 484 Diag(MissingNilLoc, diag::warn_missing_sentinel) 485 << int(calleeType) 486 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 487 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 488 } 489 490 SourceRange Sema::getExprRange(Expr *E) const { 491 return E ? E->getSourceRange() : SourceRange(); 492 } 493 494 //===----------------------------------------------------------------------===// 495 // Standard Promotions and Conversions 496 //===----------------------------------------------------------------------===// 497 498 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 499 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 500 // Handle any placeholder expressions which made it here. 501 if (E->getType()->isPlaceholderType()) { 502 ExprResult result = CheckPlaceholderExpr(E); 503 if (result.isInvalid()) return ExprError(); 504 E = result.get(); 505 } 506 507 QualType Ty = E->getType(); 508 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 509 510 if (Ty->isFunctionType()) { 511 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 512 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 513 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 514 return ExprError(); 515 516 E = ImpCastExprToType(E, Context.getPointerType(Ty), 517 CK_FunctionToPointerDecay).get(); 518 } else if (Ty->isArrayType()) { 519 // In C90 mode, arrays only promote to pointers if the array expression is 520 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 521 // type 'array of type' is converted to an expression that has type 'pointer 522 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 523 // that has type 'array of type' ...". The relevant change is "an lvalue" 524 // (C90) to "an expression" (C99). 525 // 526 // C++ 4.2p1: 527 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 528 // T" can be converted to an rvalue of type "pointer to T". 529 // 530 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 531 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 532 CK_ArrayToPointerDecay); 533 if (Res.isInvalid()) 534 return ExprError(); 535 E = Res.get(); 536 } 537 } 538 return E; 539 } 540 541 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 542 // Check to see if we are dereferencing a null pointer. If so, 543 // and if not volatile-qualified, this is undefined behavior that the 544 // optimizer will delete, so warn about it. People sometimes try to use this 545 // to get a deterministic trap and are surprised by clang's behavior. This 546 // only handles the pattern "*null", which is a very syntactic check. 547 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 548 if (UO && UO->getOpcode() == UO_Deref && 549 UO->getSubExpr()->getType()->isPointerType()) { 550 const LangAS AS = 551 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 552 if ((!isTargetAddressSpace(AS) || 553 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 554 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 555 S.Context, Expr::NPC_ValueDependentIsNotNull) && 556 !UO->getType().isVolatileQualified()) { 557 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 558 S.PDiag(diag::warn_indirection_through_null) 559 << UO->getSubExpr()->getSourceRange()); 560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 561 S.PDiag(diag::note_indirection_through_null)); 562 } 563 } 564 } 565 566 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 567 SourceLocation AssignLoc, 568 const Expr* RHS) { 569 const ObjCIvarDecl *IV = OIRE->getDecl(); 570 if (!IV) 571 return; 572 573 DeclarationName MemberName = IV->getDeclName(); 574 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 575 if (!Member || !Member->isStr("isa")) 576 return; 577 578 const Expr *Base = OIRE->getBase(); 579 QualType BaseType = Base->getType(); 580 if (OIRE->isArrow()) 581 BaseType = BaseType->getPointeeType(); 582 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 583 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 584 ObjCInterfaceDecl *ClassDeclared = nullptr; 585 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 586 if (!ClassDeclared->getSuperClass() 587 && (*ClassDeclared->ivar_begin()) == IV) { 588 if (RHS) { 589 NamedDecl *ObjectSetClass = 590 S.LookupSingleName(S.TUScope, 591 &S.Context.Idents.get("object_setClass"), 592 SourceLocation(), S.LookupOrdinaryName); 593 if (ObjectSetClass) { 594 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 595 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 596 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 597 "object_setClass(") 598 << FixItHint::CreateReplacement( 599 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 600 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 601 } 602 else 603 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 604 } else { 605 NamedDecl *ObjectGetClass = 606 S.LookupSingleName(S.TUScope, 607 &S.Context.Idents.get("object_getClass"), 608 SourceLocation(), S.LookupOrdinaryName); 609 if (ObjectGetClass) 610 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 611 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 612 "object_getClass(") 613 << FixItHint::CreateReplacement( 614 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 615 else 616 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 617 } 618 S.Diag(IV->getLocation(), diag::note_ivar_decl); 619 } 620 } 621 } 622 623 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 624 // Handle any placeholder expressions which made it here. 625 if (E->getType()->isPlaceholderType()) { 626 ExprResult result = CheckPlaceholderExpr(E); 627 if (result.isInvalid()) return ExprError(); 628 E = result.get(); 629 } 630 631 // C++ [conv.lval]p1: 632 // A glvalue of a non-function, non-array type T can be 633 // converted to a prvalue. 634 if (!E->isGLValue()) return E; 635 636 QualType T = E->getType(); 637 assert(!T.isNull() && "r-value conversion on typeless expression?"); 638 639 // lvalue-to-rvalue conversion cannot be applied to function or array types. 640 if (T->isFunctionType() || T->isArrayType()) 641 return E; 642 643 // We don't want to throw lvalue-to-rvalue casts on top of 644 // expressions of certain types in C++. 645 if (getLangOpts().CPlusPlus && 646 (E->getType() == Context.OverloadTy || 647 T->isDependentType() || 648 T->isRecordType())) 649 return E; 650 651 // The C standard is actually really unclear on this point, and 652 // DR106 tells us what the result should be but not why. It's 653 // generally best to say that void types just doesn't undergo 654 // lvalue-to-rvalue at all. Note that expressions of unqualified 655 // 'void' type are never l-values, but qualified void can be. 656 if (T->isVoidType()) 657 return E; 658 659 // OpenCL usually rejects direct accesses to values of 'half' type. 660 if (getLangOpts().OpenCL && 661 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 662 T->isHalfType()) { 663 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 664 << 0 << T; 665 return ExprError(); 666 } 667 668 CheckForNullPointerDereference(*this, E); 669 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 670 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 671 &Context.Idents.get("object_getClass"), 672 SourceLocation(), LookupOrdinaryName); 673 if (ObjectGetClass) 674 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 675 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 676 << FixItHint::CreateReplacement( 677 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 678 else 679 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 680 } 681 else if (const ObjCIvarRefExpr *OIRE = 682 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 683 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 684 685 // C++ [conv.lval]p1: 686 // [...] If T is a non-class type, the type of the prvalue is the 687 // cv-unqualified version of T. Otherwise, the type of the 688 // rvalue is T. 689 // 690 // C99 6.3.2.1p2: 691 // If the lvalue has qualified type, the value has the unqualified 692 // version of the type of the lvalue; otherwise, the value has the 693 // type of the lvalue. 694 if (T.hasQualifiers()) 695 T = T.getUnqualifiedType(); 696 697 // Under the MS ABI, lock down the inheritance model now. 698 if (T->isMemberPointerType() && 699 Context.getTargetInfo().getCXXABI().isMicrosoft()) 700 (void)isCompleteType(E->getExprLoc(), T); 701 702 ExprResult Res = CheckLValueToRValueConversionOperand(E); 703 if (Res.isInvalid()) 704 return Res; 705 E = Res.get(); 706 707 // Loading a __weak object implicitly retains the value, so we need a cleanup to 708 // balance that. 709 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 710 Cleanup.setExprNeedsCleanups(true); 711 712 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 713 Cleanup.setExprNeedsCleanups(true); 714 715 // C++ [conv.lval]p3: 716 // If T is cv std::nullptr_t, the result is a null pointer constant. 717 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 718 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 719 CurFPFeatureOverrides()); 720 721 // C11 6.3.2.1p2: 722 // ... if the lvalue has atomic type, the value has the non-atomic version 723 // of the type of the lvalue ... 724 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 725 T = Atomic->getValueType().getUnqualifiedType(); 726 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 727 nullptr, VK_PRValue, FPOptionsOverride()); 728 } 729 730 return Res; 731 } 732 733 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 734 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 735 if (Res.isInvalid()) 736 return ExprError(); 737 Res = DefaultLvalueConversion(Res.get()); 738 if (Res.isInvalid()) 739 return ExprError(); 740 return Res; 741 } 742 743 /// CallExprUnaryConversions - a special case of an unary conversion 744 /// performed on a function designator of a call expression. 745 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 746 QualType Ty = E->getType(); 747 ExprResult Res = E; 748 // Only do implicit cast for a function type, but not for a pointer 749 // to function type. 750 if (Ty->isFunctionType()) { 751 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 752 CK_FunctionToPointerDecay); 753 if (Res.isInvalid()) 754 return ExprError(); 755 } 756 Res = DefaultLvalueConversion(Res.get()); 757 if (Res.isInvalid()) 758 return ExprError(); 759 return Res.get(); 760 } 761 762 /// UsualUnaryConversions - Performs various conversions that are common to most 763 /// operators (C99 6.3). The conversions of array and function types are 764 /// sometimes suppressed. For example, the array->pointer conversion doesn't 765 /// apply if the array is an argument to the sizeof or address (&) operators. 766 /// In these instances, this routine should *not* be called. 767 ExprResult Sema::UsualUnaryConversions(Expr *E) { 768 // First, convert to an r-value. 769 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 770 if (Res.isInvalid()) 771 return ExprError(); 772 E = Res.get(); 773 774 QualType Ty = E->getType(); 775 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 776 777 // Half FP have to be promoted to float unless it is natively supported 778 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 779 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 780 781 // Try to perform integral promotions if the object has a theoretically 782 // promotable type. 783 if (Ty->isIntegralOrUnscopedEnumerationType()) { 784 // C99 6.3.1.1p2: 785 // 786 // The following may be used in an expression wherever an int or 787 // unsigned int may be used: 788 // - an object or expression with an integer type whose integer 789 // conversion rank is less than or equal to the rank of int 790 // and unsigned int. 791 // - A bit-field of type _Bool, int, signed int, or unsigned int. 792 // 793 // If an int can represent all values of the original type, the 794 // value is converted to an int; otherwise, it is converted to an 795 // unsigned int. These are called the integer promotions. All 796 // other types are unchanged by the integer promotions. 797 798 QualType PTy = Context.isPromotableBitField(E); 799 if (!PTy.isNull()) { 800 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 801 return E; 802 } 803 if (Ty->isPromotableIntegerType()) { 804 QualType PT = Context.getPromotedIntegerType(Ty); 805 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 806 return E; 807 } 808 } 809 return E; 810 } 811 812 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 813 /// do not have a prototype. Arguments that have type float or __fp16 814 /// are promoted to double. All other argument types are converted by 815 /// UsualUnaryConversions(). 816 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 817 QualType Ty = E->getType(); 818 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 819 820 ExprResult Res = UsualUnaryConversions(E); 821 if (Res.isInvalid()) 822 return ExprError(); 823 E = Res.get(); 824 825 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 826 // promote to double. 827 // Note that default argument promotion applies only to float (and 828 // half/fp16); it does not apply to _Float16. 829 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 830 if (BTy && (BTy->getKind() == BuiltinType::Half || 831 BTy->getKind() == BuiltinType::Float)) { 832 if (getLangOpts().OpenCL && 833 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 834 if (BTy->getKind() == BuiltinType::Half) { 835 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 836 } 837 } else { 838 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 839 } 840 } 841 if (BTy && 842 getLangOpts().getExtendIntArgs() == 843 LangOptions::ExtendArgsKind::ExtendTo64 && 844 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 845 Context.getTypeSizeInChars(BTy) < 846 Context.getTypeSizeInChars(Context.LongLongTy)) { 847 E = (Ty->isUnsignedIntegerType()) 848 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 849 .get() 850 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 851 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 852 "Unexpected typesize for LongLongTy"); 853 } 854 855 // C++ performs lvalue-to-rvalue conversion as a default argument 856 // promotion, even on class types, but note: 857 // C++11 [conv.lval]p2: 858 // When an lvalue-to-rvalue conversion occurs in an unevaluated 859 // operand or a subexpression thereof the value contained in the 860 // referenced object is not accessed. Otherwise, if the glvalue 861 // has a class type, the conversion copy-initializes a temporary 862 // of type T from the glvalue and the result of the conversion 863 // is a prvalue for the temporary. 864 // FIXME: add some way to gate this entire thing for correctness in 865 // potentially potentially evaluated contexts. 866 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 867 ExprResult Temp = PerformCopyInitialization( 868 InitializedEntity::InitializeTemporary(E->getType()), 869 E->getExprLoc(), E); 870 if (Temp.isInvalid()) 871 return ExprError(); 872 E = Temp.get(); 873 } 874 875 return E; 876 } 877 878 /// Determine the degree of POD-ness for an expression. 879 /// Incomplete types are considered POD, since this check can be performed 880 /// when we're in an unevaluated context. 881 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 882 if (Ty->isIncompleteType()) { 883 // C++11 [expr.call]p7: 884 // After these conversions, if the argument does not have arithmetic, 885 // enumeration, pointer, pointer to member, or class type, the program 886 // is ill-formed. 887 // 888 // Since we've already performed array-to-pointer and function-to-pointer 889 // decay, the only such type in C++ is cv void. This also handles 890 // initializer lists as variadic arguments. 891 if (Ty->isVoidType()) 892 return VAK_Invalid; 893 894 if (Ty->isObjCObjectType()) 895 return VAK_Invalid; 896 return VAK_Valid; 897 } 898 899 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 900 return VAK_Invalid; 901 902 if (Ty.isCXX98PODType(Context)) 903 return VAK_Valid; 904 905 // C++11 [expr.call]p7: 906 // Passing a potentially-evaluated argument of class type (Clause 9) 907 // having a non-trivial copy constructor, a non-trivial move constructor, 908 // or a non-trivial destructor, with no corresponding parameter, 909 // is conditionally-supported with implementation-defined semantics. 910 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 911 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 912 if (!Record->hasNonTrivialCopyConstructor() && 913 !Record->hasNonTrivialMoveConstructor() && 914 !Record->hasNonTrivialDestructor()) 915 return VAK_ValidInCXX11; 916 917 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 918 return VAK_Valid; 919 920 if (Ty->isObjCObjectType()) 921 return VAK_Invalid; 922 923 if (getLangOpts().MSVCCompat) 924 return VAK_MSVCUndefined; 925 926 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 927 // permitted to reject them. We should consider doing so. 928 return VAK_Undefined; 929 } 930 931 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 932 // Don't allow one to pass an Objective-C interface to a vararg. 933 const QualType &Ty = E->getType(); 934 VarArgKind VAK = isValidVarArgType(Ty); 935 936 // Complain about passing non-POD types through varargs. 937 switch (VAK) { 938 case VAK_ValidInCXX11: 939 DiagRuntimeBehavior( 940 E->getBeginLoc(), nullptr, 941 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 942 LLVM_FALLTHROUGH; 943 case VAK_Valid: 944 if (Ty->isRecordType()) { 945 // This is unlikely to be what the user intended. If the class has a 946 // 'c_str' member function, the user probably meant to call that. 947 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 948 PDiag(diag::warn_pass_class_arg_to_vararg) 949 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 950 } 951 break; 952 953 case VAK_Undefined: 954 case VAK_MSVCUndefined: 955 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 956 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 957 << getLangOpts().CPlusPlus11 << Ty << CT); 958 break; 959 960 case VAK_Invalid: 961 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 962 Diag(E->getBeginLoc(), 963 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 964 << Ty << CT; 965 else if (Ty->isObjCObjectType()) 966 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 967 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 968 << Ty << CT); 969 else 970 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 971 << isa<InitListExpr>(E) << Ty << CT; 972 break; 973 } 974 } 975 976 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 977 /// will create a trap if the resulting type is not a POD type. 978 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 979 FunctionDecl *FDecl) { 980 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 981 // Strip the unbridged-cast placeholder expression off, if applicable. 982 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 983 (CT == VariadicMethod || 984 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 985 E = stripARCUnbridgedCast(E); 986 987 // Otherwise, do normal placeholder checking. 988 } else { 989 ExprResult ExprRes = CheckPlaceholderExpr(E); 990 if (ExprRes.isInvalid()) 991 return ExprError(); 992 E = ExprRes.get(); 993 } 994 } 995 996 ExprResult ExprRes = DefaultArgumentPromotion(E); 997 if (ExprRes.isInvalid()) 998 return ExprError(); 999 1000 // Copy blocks to the heap. 1001 if (ExprRes.get()->getType()->isBlockPointerType()) 1002 maybeExtendBlockObject(ExprRes); 1003 1004 E = ExprRes.get(); 1005 1006 // Diagnostics regarding non-POD argument types are 1007 // emitted along with format string checking in Sema::CheckFunctionCall(). 1008 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1009 // Turn this into a trap. 1010 CXXScopeSpec SS; 1011 SourceLocation TemplateKWLoc; 1012 UnqualifiedId Name; 1013 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1014 E->getBeginLoc()); 1015 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1016 /*HasTrailingLParen=*/true, 1017 /*IsAddressOfOperand=*/false); 1018 if (TrapFn.isInvalid()) 1019 return ExprError(); 1020 1021 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1022 None, E->getEndLoc()); 1023 if (Call.isInvalid()) 1024 return ExprError(); 1025 1026 ExprResult Comma = 1027 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1028 if (Comma.isInvalid()) 1029 return ExprError(); 1030 return Comma.get(); 1031 } 1032 1033 if (!getLangOpts().CPlusPlus && 1034 RequireCompleteType(E->getExprLoc(), E->getType(), 1035 diag::err_call_incomplete_argument)) 1036 return ExprError(); 1037 1038 return E; 1039 } 1040 1041 /// Converts an integer to complex float type. Helper function of 1042 /// UsualArithmeticConversions() 1043 /// 1044 /// \return false if the integer expression is an integer type and is 1045 /// successfully converted to the complex type. 1046 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1047 ExprResult &ComplexExpr, 1048 QualType IntTy, 1049 QualType ComplexTy, 1050 bool SkipCast) { 1051 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1052 if (SkipCast) return false; 1053 if (IntTy->isIntegerType()) { 1054 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1055 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1056 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1057 CK_FloatingRealToComplex); 1058 } else { 1059 assert(IntTy->isComplexIntegerType()); 1060 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1061 CK_IntegralComplexToFloatingComplex); 1062 } 1063 return false; 1064 } 1065 1066 /// Handle arithmetic conversion with complex types. Helper function of 1067 /// UsualArithmeticConversions() 1068 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1069 ExprResult &RHS, QualType LHSType, 1070 QualType RHSType, 1071 bool IsCompAssign) { 1072 // if we have an integer operand, the result is the complex type. 1073 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1074 /*skipCast*/false)) 1075 return LHSType; 1076 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1077 /*skipCast*/IsCompAssign)) 1078 return RHSType; 1079 1080 // This handles complex/complex, complex/float, or float/complex. 1081 // When both operands are complex, the shorter operand is converted to the 1082 // type of the longer, and that is the type of the result. This corresponds 1083 // to what is done when combining two real floating-point operands. 1084 // The fun begins when size promotion occur across type domains. 1085 // From H&S 6.3.4: When one operand is complex and the other is a real 1086 // floating-point type, the less precise type is converted, within it's 1087 // real or complex domain, to the precision of the other type. For example, 1088 // when combining a "long double" with a "double _Complex", the 1089 // "double _Complex" is promoted to "long double _Complex". 1090 1091 // Compute the rank of the two types, regardless of whether they are complex. 1092 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1093 1094 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1095 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1096 QualType LHSElementType = 1097 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1098 QualType RHSElementType = 1099 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1100 1101 QualType ResultType = S.Context.getComplexType(LHSElementType); 1102 if (Order < 0) { 1103 // Promote the precision of the LHS if not an assignment. 1104 ResultType = S.Context.getComplexType(RHSElementType); 1105 if (!IsCompAssign) { 1106 if (LHSComplexType) 1107 LHS = 1108 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1109 else 1110 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1111 } 1112 } else if (Order > 0) { 1113 // Promote the precision of the RHS. 1114 if (RHSComplexType) 1115 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1116 else 1117 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1118 } 1119 return ResultType; 1120 } 1121 1122 /// Handle arithmetic conversion from integer to float. Helper function 1123 /// of UsualArithmeticConversions() 1124 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1125 ExprResult &IntExpr, 1126 QualType FloatTy, QualType IntTy, 1127 bool ConvertFloat, bool ConvertInt) { 1128 if (IntTy->isIntegerType()) { 1129 if (ConvertInt) 1130 // Convert intExpr to the lhs floating point type. 1131 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1132 CK_IntegralToFloating); 1133 return FloatTy; 1134 } 1135 1136 // Convert both sides to the appropriate complex float. 1137 assert(IntTy->isComplexIntegerType()); 1138 QualType result = S.Context.getComplexType(FloatTy); 1139 1140 // _Complex int -> _Complex float 1141 if (ConvertInt) 1142 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1143 CK_IntegralComplexToFloatingComplex); 1144 1145 // float -> _Complex float 1146 if (ConvertFloat) 1147 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1148 CK_FloatingRealToComplex); 1149 1150 return result; 1151 } 1152 1153 /// Handle arithmethic conversion with floating point types. Helper 1154 /// function of UsualArithmeticConversions() 1155 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1156 ExprResult &RHS, QualType LHSType, 1157 QualType RHSType, bool IsCompAssign) { 1158 bool LHSFloat = LHSType->isRealFloatingType(); 1159 bool RHSFloat = RHSType->isRealFloatingType(); 1160 1161 // N1169 4.1.4: If one of the operands has a floating type and the other 1162 // operand has a fixed-point type, the fixed-point operand 1163 // is converted to the floating type [...] 1164 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1165 if (LHSFloat) 1166 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1167 else if (!IsCompAssign) 1168 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1169 return LHSFloat ? LHSType : RHSType; 1170 } 1171 1172 // If we have two real floating types, convert the smaller operand 1173 // to the bigger result. 1174 if (LHSFloat && RHSFloat) { 1175 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1176 if (order > 0) { 1177 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1178 return LHSType; 1179 } 1180 1181 assert(order < 0 && "illegal float comparison"); 1182 if (!IsCompAssign) 1183 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1184 return RHSType; 1185 } 1186 1187 if (LHSFloat) { 1188 // Half FP has to be promoted to float unless it is natively supported 1189 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1190 LHSType = S.Context.FloatTy; 1191 1192 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1193 /*ConvertFloat=*/!IsCompAssign, 1194 /*ConvertInt=*/ true); 1195 } 1196 assert(RHSFloat); 1197 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1198 /*ConvertFloat=*/ true, 1199 /*ConvertInt=*/!IsCompAssign); 1200 } 1201 1202 /// Diagnose attempts to convert between __float128, __ibm128 and 1203 /// long double if there is no support for such conversion. 1204 /// Helper function of UsualArithmeticConversions(). 1205 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1206 QualType RHSType) { 1207 // No issue if either is not a floating point type. 1208 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1209 return false; 1210 1211 // No issue if both have the same 128-bit float semantics. 1212 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1213 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1214 1215 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1216 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1217 1218 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1219 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1220 1221 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1222 &RHSSem != &llvm::APFloat::IEEEquad()) && 1223 (&LHSSem != &llvm::APFloat::IEEEquad() || 1224 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1225 return false; 1226 1227 return true; 1228 } 1229 1230 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1231 1232 namespace { 1233 /// These helper callbacks are placed in an anonymous namespace to 1234 /// permit their use as function template parameters. 1235 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1236 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1237 } 1238 1239 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1240 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1241 CK_IntegralComplexCast); 1242 } 1243 } 1244 1245 /// Handle integer arithmetic conversions. Helper function of 1246 /// UsualArithmeticConversions() 1247 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1248 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1249 ExprResult &RHS, QualType LHSType, 1250 QualType RHSType, bool IsCompAssign) { 1251 // The rules for this case are in C99 6.3.1.8 1252 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1253 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1254 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1255 if (LHSSigned == RHSSigned) { 1256 // Same signedness; use the higher-ranked type 1257 if (order >= 0) { 1258 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1259 return LHSType; 1260 } else if (!IsCompAssign) 1261 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1262 return RHSType; 1263 } else if (order != (LHSSigned ? 1 : -1)) { 1264 // The unsigned type has greater than or equal rank to the 1265 // signed type, so use the unsigned type 1266 if (RHSSigned) { 1267 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1268 return LHSType; 1269 } else if (!IsCompAssign) 1270 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1271 return RHSType; 1272 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1273 // The two types are different widths; if we are here, that 1274 // means the signed type is larger than the unsigned type, so 1275 // use the signed type. 1276 if (LHSSigned) { 1277 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1278 return LHSType; 1279 } else if (!IsCompAssign) 1280 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1281 return RHSType; 1282 } else { 1283 // The signed type is higher-ranked than the unsigned type, 1284 // but isn't actually any bigger (like unsigned int and long 1285 // on most 32-bit systems). Use the unsigned type corresponding 1286 // to the signed type. 1287 QualType result = 1288 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1289 RHS = (*doRHSCast)(S, RHS.get(), result); 1290 if (!IsCompAssign) 1291 LHS = (*doLHSCast)(S, LHS.get(), result); 1292 return result; 1293 } 1294 } 1295 1296 /// Handle conversions with GCC complex int extension. Helper function 1297 /// of UsualArithmeticConversions() 1298 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1299 ExprResult &RHS, QualType LHSType, 1300 QualType RHSType, 1301 bool IsCompAssign) { 1302 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1303 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1304 1305 if (LHSComplexInt && RHSComplexInt) { 1306 QualType LHSEltType = LHSComplexInt->getElementType(); 1307 QualType RHSEltType = RHSComplexInt->getElementType(); 1308 QualType ScalarType = 1309 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1310 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1311 1312 return S.Context.getComplexType(ScalarType); 1313 } 1314 1315 if (LHSComplexInt) { 1316 QualType LHSEltType = LHSComplexInt->getElementType(); 1317 QualType ScalarType = 1318 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1319 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1320 QualType ComplexType = S.Context.getComplexType(ScalarType); 1321 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1322 CK_IntegralRealToComplex); 1323 1324 return ComplexType; 1325 } 1326 1327 assert(RHSComplexInt); 1328 1329 QualType RHSEltType = RHSComplexInt->getElementType(); 1330 QualType ScalarType = 1331 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1332 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1333 QualType ComplexType = S.Context.getComplexType(ScalarType); 1334 1335 if (!IsCompAssign) 1336 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1337 CK_IntegralRealToComplex); 1338 return ComplexType; 1339 } 1340 1341 /// Return the rank of a given fixed point or integer type. The value itself 1342 /// doesn't matter, but the values must be increasing with proper increasing 1343 /// rank as described in N1169 4.1.1. 1344 static unsigned GetFixedPointRank(QualType Ty) { 1345 const auto *BTy = Ty->getAs<BuiltinType>(); 1346 assert(BTy && "Expected a builtin type."); 1347 1348 switch (BTy->getKind()) { 1349 case BuiltinType::ShortFract: 1350 case BuiltinType::UShortFract: 1351 case BuiltinType::SatShortFract: 1352 case BuiltinType::SatUShortFract: 1353 return 1; 1354 case BuiltinType::Fract: 1355 case BuiltinType::UFract: 1356 case BuiltinType::SatFract: 1357 case BuiltinType::SatUFract: 1358 return 2; 1359 case BuiltinType::LongFract: 1360 case BuiltinType::ULongFract: 1361 case BuiltinType::SatLongFract: 1362 case BuiltinType::SatULongFract: 1363 return 3; 1364 case BuiltinType::ShortAccum: 1365 case BuiltinType::UShortAccum: 1366 case BuiltinType::SatShortAccum: 1367 case BuiltinType::SatUShortAccum: 1368 return 4; 1369 case BuiltinType::Accum: 1370 case BuiltinType::UAccum: 1371 case BuiltinType::SatAccum: 1372 case BuiltinType::SatUAccum: 1373 return 5; 1374 case BuiltinType::LongAccum: 1375 case BuiltinType::ULongAccum: 1376 case BuiltinType::SatLongAccum: 1377 case BuiltinType::SatULongAccum: 1378 return 6; 1379 default: 1380 if (BTy->isInteger()) 1381 return 0; 1382 llvm_unreachable("Unexpected fixed point or integer type"); 1383 } 1384 } 1385 1386 /// handleFixedPointConversion - Fixed point operations between fixed 1387 /// point types and integers or other fixed point types do not fall under 1388 /// usual arithmetic conversion since these conversions could result in loss 1389 /// of precsision (N1169 4.1.4). These operations should be calculated with 1390 /// the full precision of their result type (N1169 4.1.6.2.1). 1391 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1392 QualType RHSTy) { 1393 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1394 "Expected at least one of the operands to be a fixed point type"); 1395 assert((LHSTy->isFixedPointOrIntegerType() || 1396 RHSTy->isFixedPointOrIntegerType()) && 1397 "Special fixed point arithmetic operation conversions are only " 1398 "applied to ints or other fixed point types"); 1399 1400 // If one operand has signed fixed-point type and the other operand has 1401 // unsigned fixed-point type, then the unsigned fixed-point operand is 1402 // converted to its corresponding signed fixed-point type and the resulting 1403 // type is the type of the converted operand. 1404 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1405 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1406 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1407 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1408 1409 // The result type is the type with the highest rank, whereby a fixed-point 1410 // conversion rank is always greater than an integer conversion rank; if the 1411 // type of either of the operands is a saturating fixedpoint type, the result 1412 // type shall be the saturating fixed-point type corresponding to the type 1413 // with the highest rank; the resulting value is converted (taking into 1414 // account rounding and overflow) to the precision of the resulting type. 1415 // Same ranks between signed and unsigned types are resolved earlier, so both 1416 // types are either signed or both unsigned at this point. 1417 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1418 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1419 1420 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1421 1422 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1423 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1424 1425 return ResultTy; 1426 } 1427 1428 /// Check that the usual arithmetic conversions can be performed on this pair of 1429 /// expressions that might be of enumeration type. 1430 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1431 SourceLocation Loc, 1432 Sema::ArithConvKind ACK) { 1433 // C++2a [expr.arith.conv]p1: 1434 // If one operand is of enumeration type and the other operand is of a 1435 // different enumeration type or a floating-point type, this behavior is 1436 // deprecated ([depr.arith.conv.enum]). 1437 // 1438 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1439 // Eventually we will presumably reject these cases (in C++23 onwards?). 1440 QualType L = LHS->getType(), R = RHS->getType(); 1441 bool LEnum = L->isUnscopedEnumerationType(), 1442 REnum = R->isUnscopedEnumerationType(); 1443 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1444 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1445 (REnum && L->isFloatingType())) { 1446 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1447 ? diag::warn_arith_conv_enum_float_cxx20 1448 : diag::warn_arith_conv_enum_float) 1449 << LHS->getSourceRange() << RHS->getSourceRange() 1450 << (int)ACK << LEnum << L << R; 1451 } else if (!IsCompAssign && LEnum && REnum && 1452 !S.Context.hasSameUnqualifiedType(L, R)) { 1453 unsigned DiagID; 1454 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1455 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1456 // If either enumeration type is unnamed, it's less likely that the 1457 // user cares about this, but this situation is still deprecated in 1458 // C++2a. Use a different warning group. 1459 DiagID = S.getLangOpts().CPlusPlus20 1460 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1461 : diag::warn_arith_conv_mixed_anon_enum_types; 1462 } else if (ACK == Sema::ACK_Conditional) { 1463 // Conditional expressions are separated out because they have 1464 // historically had a different warning flag. 1465 DiagID = S.getLangOpts().CPlusPlus20 1466 ? diag::warn_conditional_mixed_enum_types_cxx20 1467 : diag::warn_conditional_mixed_enum_types; 1468 } else if (ACK == Sema::ACK_Comparison) { 1469 // Comparison expressions are separated out because they have 1470 // historically had a different warning flag. 1471 DiagID = S.getLangOpts().CPlusPlus20 1472 ? diag::warn_comparison_mixed_enum_types_cxx20 1473 : diag::warn_comparison_mixed_enum_types; 1474 } else { 1475 DiagID = S.getLangOpts().CPlusPlus20 1476 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1477 : diag::warn_arith_conv_mixed_enum_types; 1478 } 1479 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1480 << (int)ACK << L << R; 1481 } 1482 } 1483 1484 /// UsualArithmeticConversions - Performs various conversions that are common to 1485 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1486 /// routine returns the first non-arithmetic type found. The client is 1487 /// responsible for emitting appropriate error diagnostics. 1488 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1489 SourceLocation Loc, 1490 ArithConvKind ACK) { 1491 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1492 1493 if (ACK != ACK_CompAssign) { 1494 LHS = UsualUnaryConversions(LHS.get()); 1495 if (LHS.isInvalid()) 1496 return QualType(); 1497 } 1498 1499 RHS = UsualUnaryConversions(RHS.get()); 1500 if (RHS.isInvalid()) 1501 return QualType(); 1502 1503 // For conversion purposes, we ignore any qualifiers. 1504 // For example, "const float" and "float" are equivalent. 1505 QualType LHSType = 1506 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1507 QualType RHSType = 1508 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1509 1510 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1511 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1512 LHSType = AtomicLHS->getValueType(); 1513 1514 // If both types are identical, no conversion is needed. 1515 if (LHSType == RHSType) 1516 return LHSType; 1517 1518 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1519 // The caller can deal with this (e.g. pointer + int). 1520 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1521 return QualType(); 1522 1523 // Apply unary and bitfield promotions to the LHS's type. 1524 QualType LHSUnpromotedType = LHSType; 1525 if (LHSType->isPromotableIntegerType()) 1526 LHSType = Context.getPromotedIntegerType(LHSType); 1527 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1528 if (!LHSBitfieldPromoteTy.isNull()) 1529 LHSType = LHSBitfieldPromoteTy; 1530 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1531 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1532 1533 // If both types are identical, no conversion is needed. 1534 if (LHSType == RHSType) 1535 return LHSType; 1536 1537 // At this point, we have two different arithmetic types. 1538 1539 // Diagnose attempts to convert between __ibm128, __float128 and long double 1540 // where such conversions currently can't be handled. 1541 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1542 return QualType(); 1543 1544 // Handle complex types first (C99 6.3.1.8p1). 1545 if (LHSType->isComplexType() || RHSType->isComplexType()) 1546 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1547 ACK == ACK_CompAssign); 1548 1549 // Now handle "real" floating types (i.e. float, double, long double). 1550 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1551 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1552 ACK == ACK_CompAssign); 1553 1554 // Handle GCC complex int extension. 1555 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1556 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1557 ACK == ACK_CompAssign); 1558 1559 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1560 return handleFixedPointConversion(*this, LHSType, RHSType); 1561 1562 // Finally, we have two differing integer types. 1563 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1564 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1565 } 1566 1567 //===----------------------------------------------------------------------===// 1568 // Semantic Analysis for various Expression Types 1569 //===----------------------------------------------------------------------===// 1570 1571 1572 ExprResult 1573 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1574 SourceLocation DefaultLoc, 1575 SourceLocation RParenLoc, 1576 Expr *ControllingExpr, 1577 ArrayRef<ParsedType> ArgTypes, 1578 ArrayRef<Expr *> ArgExprs) { 1579 unsigned NumAssocs = ArgTypes.size(); 1580 assert(NumAssocs == ArgExprs.size()); 1581 1582 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1583 for (unsigned i = 0; i < NumAssocs; ++i) { 1584 if (ArgTypes[i]) 1585 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1586 else 1587 Types[i] = nullptr; 1588 } 1589 1590 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1591 ControllingExpr, 1592 llvm::makeArrayRef(Types, NumAssocs), 1593 ArgExprs); 1594 delete [] Types; 1595 return ER; 1596 } 1597 1598 ExprResult 1599 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1600 SourceLocation DefaultLoc, 1601 SourceLocation RParenLoc, 1602 Expr *ControllingExpr, 1603 ArrayRef<TypeSourceInfo *> Types, 1604 ArrayRef<Expr *> Exprs) { 1605 unsigned NumAssocs = Types.size(); 1606 assert(NumAssocs == Exprs.size()); 1607 1608 // Decay and strip qualifiers for the controlling expression type, and handle 1609 // placeholder type replacement. See committee discussion from WG14 DR423. 1610 { 1611 EnterExpressionEvaluationContext Unevaluated( 1612 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1613 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1614 if (R.isInvalid()) 1615 return ExprError(); 1616 ControllingExpr = R.get(); 1617 } 1618 1619 // The controlling expression is an unevaluated operand, so side effects are 1620 // likely unintended. 1621 if (!inTemplateInstantiation() && 1622 ControllingExpr->HasSideEffects(Context, false)) 1623 Diag(ControllingExpr->getExprLoc(), 1624 diag::warn_side_effects_unevaluated_context); 1625 1626 bool TypeErrorFound = false, 1627 IsResultDependent = ControllingExpr->isTypeDependent(), 1628 ContainsUnexpandedParameterPack 1629 = ControllingExpr->containsUnexpandedParameterPack(); 1630 1631 for (unsigned i = 0; i < NumAssocs; ++i) { 1632 if (Exprs[i]->containsUnexpandedParameterPack()) 1633 ContainsUnexpandedParameterPack = true; 1634 1635 if (Types[i]) { 1636 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1637 ContainsUnexpandedParameterPack = true; 1638 1639 if (Types[i]->getType()->isDependentType()) { 1640 IsResultDependent = true; 1641 } else { 1642 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1643 // complete object type other than a variably modified type." 1644 unsigned D = 0; 1645 if (Types[i]->getType()->isIncompleteType()) 1646 D = diag::err_assoc_type_incomplete; 1647 else if (!Types[i]->getType()->isObjectType()) 1648 D = diag::err_assoc_type_nonobject; 1649 else if (Types[i]->getType()->isVariablyModifiedType()) 1650 D = diag::err_assoc_type_variably_modified; 1651 1652 if (D != 0) { 1653 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1654 << Types[i]->getTypeLoc().getSourceRange() 1655 << Types[i]->getType(); 1656 TypeErrorFound = true; 1657 } 1658 1659 // C11 6.5.1.1p2 "No two generic associations in the same generic 1660 // selection shall specify compatible types." 1661 for (unsigned j = i+1; j < NumAssocs; ++j) 1662 if (Types[j] && !Types[j]->getType()->isDependentType() && 1663 Context.typesAreCompatible(Types[i]->getType(), 1664 Types[j]->getType())) { 1665 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1666 diag::err_assoc_compatible_types) 1667 << Types[j]->getTypeLoc().getSourceRange() 1668 << Types[j]->getType() 1669 << Types[i]->getType(); 1670 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1671 diag::note_compat_assoc) 1672 << Types[i]->getTypeLoc().getSourceRange() 1673 << Types[i]->getType(); 1674 TypeErrorFound = true; 1675 } 1676 } 1677 } 1678 } 1679 if (TypeErrorFound) 1680 return ExprError(); 1681 1682 // If we determined that the generic selection is result-dependent, don't 1683 // try to compute the result expression. 1684 if (IsResultDependent) 1685 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1686 Exprs, DefaultLoc, RParenLoc, 1687 ContainsUnexpandedParameterPack); 1688 1689 SmallVector<unsigned, 1> CompatIndices; 1690 unsigned DefaultIndex = -1U; 1691 for (unsigned i = 0; i < NumAssocs; ++i) { 1692 if (!Types[i]) 1693 DefaultIndex = i; 1694 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1695 Types[i]->getType())) 1696 CompatIndices.push_back(i); 1697 } 1698 1699 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1700 // type compatible with at most one of the types named in its generic 1701 // association list." 1702 if (CompatIndices.size() > 1) { 1703 // We strip parens here because the controlling expression is typically 1704 // parenthesized in macro definitions. 1705 ControllingExpr = ControllingExpr->IgnoreParens(); 1706 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1707 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1708 << (unsigned)CompatIndices.size(); 1709 for (unsigned I : CompatIndices) { 1710 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1711 diag::note_compat_assoc) 1712 << Types[I]->getTypeLoc().getSourceRange() 1713 << Types[I]->getType(); 1714 } 1715 return ExprError(); 1716 } 1717 1718 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1719 // its controlling expression shall have type compatible with exactly one of 1720 // the types named in its generic association list." 1721 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1722 // We strip parens here because the controlling expression is typically 1723 // parenthesized in macro definitions. 1724 ControllingExpr = ControllingExpr->IgnoreParens(); 1725 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1726 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1727 return ExprError(); 1728 } 1729 1730 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1731 // type name that is compatible with the type of the controlling expression, 1732 // then the result expression of the generic selection is the expression 1733 // in that generic association. Otherwise, the result expression of the 1734 // generic selection is the expression in the default generic association." 1735 unsigned ResultIndex = 1736 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1737 1738 return GenericSelectionExpr::Create( 1739 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1740 ContainsUnexpandedParameterPack, ResultIndex); 1741 } 1742 1743 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1744 /// location of the token and the offset of the ud-suffix within it. 1745 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1746 unsigned Offset) { 1747 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1748 S.getLangOpts()); 1749 } 1750 1751 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1752 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1753 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1754 IdentifierInfo *UDSuffix, 1755 SourceLocation UDSuffixLoc, 1756 ArrayRef<Expr*> Args, 1757 SourceLocation LitEndLoc) { 1758 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1759 1760 QualType ArgTy[2]; 1761 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1762 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1763 if (ArgTy[ArgIdx]->isArrayType()) 1764 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1765 } 1766 1767 DeclarationName OpName = 1768 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1769 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1770 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1771 1772 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1773 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1774 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1775 /*AllowStringTemplatePack*/ false, 1776 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1777 return ExprError(); 1778 1779 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1780 } 1781 1782 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1783 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1784 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1785 /// multiple tokens. However, the common case is that StringToks points to one 1786 /// string. 1787 /// 1788 ExprResult 1789 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1790 assert(!StringToks.empty() && "Must have at least one string!"); 1791 1792 StringLiteralParser Literal(StringToks, PP); 1793 if (Literal.hadError) 1794 return ExprError(); 1795 1796 SmallVector<SourceLocation, 4> StringTokLocs; 1797 for (const Token &Tok : StringToks) 1798 StringTokLocs.push_back(Tok.getLocation()); 1799 1800 QualType CharTy = Context.CharTy; 1801 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1802 if (Literal.isWide()) { 1803 CharTy = Context.getWideCharType(); 1804 Kind = StringLiteral::Wide; 1805 } else if (Literal.isUTF8()) { 1806 if (getLangOpts().Char8) 1807 CharTy = Context.Char8Ty; 1808 Kind = StringLiteral::UTF8; 1809 } else if (Literal.isUTF16()) { 1810 CharTy = Context.Char16Ty; 1811 Kind = StringLiteral::UTF16; 1812 } else if (Literal.isUTF32()) { 1813 CharTy = Context.Char32Ty; 1814 Kind = StringLiteral::UTF32; 1815 } else if (Literal.isPascal()) { 1816 CharTy = Context.UnsignedCharTy; 1817 } 1818 1819 // Warn on initializing an array of char from a u8 string literal; this 1820 // becomes ill-formed in C++2a. 1821 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1822 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1823 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1824 1825 // Create removals for all 'u8' prefixes in the string literal(s). This 1826 // ensures C++2a compatibility (but may change the program behavior when 1827 // built by non-Clang compilers for which the execution character set is 1828 // not always UTF-8). 1829 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1830 SourceLocation RemovalDiagLoc; 1831 for (const Token &Tok : StringToks) { 1832 if (Tok.getKind() == tok::utf8_string_literal) { 1833 if (RemovalDiagLoc.isInvalid()) 1834 RemovalDiagLoc = Tok.getLocation(); 1835 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1836 Tok.getLocation(), 1837 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1838 getSourceManager(), getLangOpts()))); 1839 } 1840 } 1841 Diag(RemovalDiagLoc, RemovalDiag); 1842 } 1843 1844 QualType StrTy = 1845 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1846 1847 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1848 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1849 Kind, Literal.Pascal, StrTy, 1850 &StringTokLocs[0], 1851 StringTokLocs.size()); 1852 if (Literal.getUDSuffix().empty()) 1853 return Lit; 1854 1855 // We're building a user-defined literal. 1856 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1857 SourceLocation UDSuffixLoc = 1858 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1859 Literal.getUDSuffixOffset()); 1860 1861 // Make sure we're allowed user-defined literals here. 1862 if (!UDLScope) 1863 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1864 1865 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1866 // operator "" X (str, len) 1867 QualType SizeType = Context.getSizeType(); 1868 1869 DeclarationName OpName = 1870 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1871 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1872 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1873 1874 QualType ArgTy[] = { 1875 Context.getArrayDecayedType(StrTy), SizeType 1876 }; 1877 1878 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1879 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1880 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1881 /*AllowStringTemplatePack*/ true, 1882 /*DiagnoseMissing*/ true, Lit)) { 1883 1884 case LOLR_Cooked: { 1885 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1886 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1887 StringTokLocs[0]); 1888 Expr *Args[] = { Lit, LenArg }; 1889 1890 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1891 } 1892 1893 case LOLR_Template: { 1894 TemplateArgumentListInfo ExplicitArgs; 1895 TemplateArgument Arg(Lit); 1896 TemplateArgumentLocInfo ArgInfo(Lit); 1897 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1898 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1899 &ExplicitArgs); 1900 } 1901 1902 case LOLR_StringTemplatePack: { 1903 TemplateArgumentListInfo ExplicitArgs; 1904 1905 unsigned CharBits = Context.getIntWidth(CharTy); 1906 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1907 llvm::APSInt Value(CharBits, CharIsUnsigned); 1908 1909 TemplateArgument TypeArg(CharTy); 1910 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1911 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1912 1913 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1914 Value = Lit->getCodeUnit(I); 1915 TemplateArgument Arg(Context, Value, CharTy); 1916 TemplateArgumentLocInfo ArgInfo; 1917 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1918 } 1919 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1920 &ExplicitArgs); 1921 } 1922 case LOLR_Raw: 1923 case LOLR_ErrorNoDiagnostic: 1924 llvm_unreachable("unexpected literal operator lookup result"); 1925 case LOLR_Error: 1926 return ExprError(); 1927 } 1928 llvm_unreachable("unexpected literal operator lookup result"); 1929 } 1930 1931 DeclRefExpr * 1932 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1933 SourceLocation Loc, 1934 const CXXScopeSpec *SS) { 1935 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1936 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1937 } 1938 1939 DeclRefExpr * 1940 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1941 const DeclarationNameInfo &NameInfo, 1942 const CXXScopeSpec *SS, NamedDecl *FoundD, 1943 SourceLocation TemplateKWLoc, 1944 const TemplateArgumentListInfo *TemplateArgs) { 1945 NestedNameSpecifierLoc NNS = 1946 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1947 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1948 TemplateArgs); 1949 } 1950 1951 // CUDA/HIP: Check whether a captured reference variable is referencing a 1952 // host variable in a device or host device lambda. 1953 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1954 VarDecl *VD) { 1955 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1956 return false; 1957 assert(VD->getType()->isReferenceType()); 1958 1959 // Check whether the reference variable is referencing a host variable. 1960 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1961 if (!DRE) 1962 return false; 1963 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1964 if (!Referee || !Referee->hasGlobalStorage() || 1965 Referee->hasAttr<CUDADeviceAttr>()) 1966 return false; 1967 1968 // Check whether the current function is a device or host device lambda. 1969 // Check whether the reference variable is a capture by getDeclContext() 1970 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1971 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1972 if (MD && MD->getParent()->isLambda() && 1973 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1974 VD->getDeclContext() != MD) 1975 return true; 1976 1977 return false; 1978 } 1979 1980 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1981 // A declaration named in an unevaluated operand never constitutes an odr-use. 1982 if (isUnevaluatedContext()) 1983 return NOUR_Unevaluated; 1984 1985 // C++2a [basic.def.odr]p4: 1986 // A variable x whose name appears as a potentially-evaluated expression e 1987 // is odr-used by e unless [...] x is a reference that is usable in 1988 // constant expressions. 1989 // CUDA/HIP: 1990 // If a reference variable referencing a host variable is captured in a 1991 // device or host device lambda, the value of the referee must be copied 1992 // to the capture and the reference variable must be treated as odr-use 1993 // since the value of the referee is not known at compile time and must 1994 // be loaded from the captured. 1995 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1996 if (VD->getType()->isReferenceType() && 1997 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1998 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 1999 VD->isUsableInConstantExpressions(Context)) 2000 return NOUR_Constant; 2001 } 2002 2003 // All remaining non-variable cases constitute an odr-use. For variables, we 2004 // need to wait and see how the expression is used. 2005 return NOUR_None; 2006 } 2007 2008 /// BuildDeclRefExpr - Build an expression that references a 2009 /// declaration that does not require a closure capture. 2010 DeclRefExpr * 2011 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2012 const DeclarationNameInfo &NameInfo, 2013 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2014 SourceLocation TemplateKWLoc, 2015 const TemplateArgumentListInfo *TemplateArgs) { 2016 bool RefersToCapturedVariable = 2017 isa<VarDecl>(D) && 2018 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2019 2020 DeclRefExpr *E = DeclRefExpr::Create( 2021 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2022 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2023 MarkDeclRefReferenced(E); 2024 2025 // C++ [except.spec]p17: 2026 // An exception-specification is considered to be needed when: 2027 // - in an expression, the function is the unique lookup result or 2028 // the selected member of a set of overloaded functions. 2029 // 2030 // We delay doing this until after we've built the function reference and 2031 // marked it as used so that: 2032 // a) if the function is defaulted, we get errors from defining it before / 2033 // instead of errors from computing its exception specification, and 2034 // b) if the function is a defaulted comparison, we can use the body we 2035 // build when defining it as input to the exception specification 2036 // computation rather than computing a new body. 2037 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2038 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2039 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2040 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2041 } 2042 } 2043 2044 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2045 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2046 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2047 getCurFunction()->recordUseOfWeak(E); 2048 2049 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2050 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2051 FD = IFD->getAnonField(); 2052 if (FD) { 2053 UnusedPrivateFields.remove(FD); 2054 // Just in case we're building an illegal pointer-to-member. 2055 if (FD->isBitField()) 2056 E->setObjectKind(OK_BitField); 2057 } 2058 2059 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2060 // designates a bit-field. 2061 if (auto *BD = dyn_cast<BindingDecl>(D)) 2062 if (auto *BE = BD->getBinding()) 2063 E->setObjectKind(BE->getObjectKind()); 2064 2065 return E; 2066 } 2067 2068 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2069 /// possibly a list of template arguments. 2070 /// 2071 /// If this produces template arguments, it is permitted to call 2072 /// DecomposeTemplateName. 2073 /// 2074 /// This actually loses a lot of source location information for 2075 /// non-standard name kinds; we should consider preserving that in 2076 /// some way. 2077 void 2078 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2079 TemplateArgumentListInfo &Buffer, 2080 DeclarationNameInfo &NameInfo, 2081 const TemplateArgumentListInfo *&TemplateArgs) { 2082 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2083 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2084 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2085 2086 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2087 Id.TemplateId->NumArgs); 2088 translateTemplateArguments(TemplateArgsPtr, Buffer); 2089 2090 TemplateName TName = Id.TemplateId->Template.get(); 2091 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2092 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2093 TemplateArgs = &Buffer; 2094 } else { 2095 NameInfo = GetNameFromUnqualifiedId(Id); 2096 TemplateArgs = nullptr; 2097 } 2098 } 2099 2100 static void emitEmptyLookupTypoDiagnostic( 2101 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2102 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2103 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2104 DeclContext *Ctx = 2105 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2106 if (!TC) { 2107 // Emit a special diagnostic for failed member lookups. 2108 // FIXME: computing the declaration context might fail here (?) 2109 if (Ctx) 2110 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2111 << SS.getRange(); 2112 else 2113 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2114 return; 2115 } 2116 2117 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2118 bool DroppedSpecifier = 2119 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2120 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2121 ? diag::note_implicit_param_decl 2122 : diag::note_previous_decl; 2123 if (!Ctx) 2124 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2125 SemaRef.PDiag(NoteID)); 2126 else 2127 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2128 << Typo << Ctx << DroppedSpecifier 2129 << SS.getRange(), 2130 SemaRef.PDiag(NoteID)); 2131 } 2132 2133 /// Diagnose a lookup that found results in an enclosing class during error 2134 /// recovery. This usually indicates that the results were found in a dependent 2135 /// base class that could not be searched as part of a template definition. 2136 /// Always issues a diagnostic (though this may be only a warning in MS 2137 /// compatibility mode). 2138 /// 2139 /// Return \c true if the error is unrecoverable, or \c false if the caller 2140 /// should attempt to recover using these lookup results. 2141 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2142 // During a default argument instantiation the CurContext points 2143 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2144 // function parameter list, hence add an explicit check. 2145 bool isDefaultArgument = 2146 !CodeSynthesisContexts.empty() && 2147 CodeSynthesisContexts.back().Kind == 2148 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2149 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2150 bool isInstance = CurMethod && CurMethod->isInstance() && 2151 R.getNamingClass() == CurMethod->getParent() && 2152 !isDefaultArgument; 2153 2154 // There are two ways we can find a class-scope declaration during template 2155 // instantiation that we did not find in the template definition: if it is a 2156 // member of a dependent base class, or if it is declared after the point of 2157 // use in the same class. Distinguish these by comparing the class in which 2158 // the member was found to the naming class of the lookup. 2159 unsigned DiagID = diag::err_found_in_dependent_base; 2160 unsigned NoteID = diag::note_member_declared_at; 2161 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2162 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2163 : diag::err_found_later_in_class; 2164 } else if (getLangOpts().MSVCCompat) { 2165 DiagID = diag::ext_found_in_dependent_base; 2166 NoteID = diag::note_dependent_member_use; 2167 } 2168 2169 if (isInstance) { 2170 // Give a code modification hint to insert 'this->'. 2171 Diag(R.getNameLoc(), DiagID) 2172 << R.getLookupName() 2173 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2174 CheckCXXThisCapture(R.getNameLoc()); 2175 } else { 2176 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2177 // they're not shadowed). 2178 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2179 } 2180 2181 for (NamedDecl *D : R) 2182 Diag(D->getLocation(), NoteID); 2183 2184 // Return true if we are inside a default argument instantiation 2185 // and the found name refers to an instance member function, otherwise 2186 // the caller will try to create an implicit member call and this is wrong 2187 // for default arguments. 2188 // 2189 // FIXME: Is this special case necessary? We could allow the caller to 2190 // diagnose this. 2191 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2192 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2193 return true; 2194 } 2195 2196 // Tell the callee to try to recover. 2197 return false; 2198 } 2199 2200 /// Diagnose an empty lookup. 2201 /// 2202 /// \return false if new lookup candidates were found 2203 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2204 CorrectionCandidateCallback &CCC, 2205 TemplateArgumentListInfo *ExplicitTemplateArgs, 2206 ArrayRef<Expr *> Args, TypoExpr **Out) { 2207 DeclarationName Name = R.getLookupName(); 2208 2209 unsigned diagnostic = diag::err_undeclared_var_use; 2210 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2211 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2212 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2213 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2214 diagnostic = diag::err_undeclared_use; 2215 diagnostic_suggest = diag::err_undeclared_use_suggest; 2216 } 2217 2218 // If the original lookup was an unqualified lookup, fake an 2219 // unqualified lookup. This is useful when (for example) the 2220 // original lookup would not have found something because it was a 2221 // dependent name. 2222 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2223 while (DC) { 2224 if (isa<CXXRecordDecl>(DC)) { 2225 LookupQualifiedName(R, DC); 2226 2227 if (!R.empty()) { 2228 // Don't give errors about ambiguities in this lookup. 2229 R.suppressDiagnostics(); 2230 2231 // If there's a best viable function among the results, only mention 2232 // that one in the notes. 2233 OverloadCandidateSet Candidates(R.getNameLoc(), 2234 OverloadCandidateSet::CSK_Normal); 2235 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2236 OverloadCandidateSet::iterator Best; 2237 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2238 OR_Success) { 2239 R.clear(); 2240 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2241 R.resolveKind(); 2242 } 2243 2244 return DiagnoseDependentMemberLookup(R); 2245 } 2246 2247 R.clear(); 2248 } 2249 2250 DC = DC->getLookupParent(); 2251 } 2252 2253 // We didn't find anything, so try to correct for a typo. 2254 TypoCorrection Corrected; 2255 if (S && Out) { 2256 SourceLocation TypoLoc = R.getNameLoc(); 2257 assert(!ExplicitTemplateArgs && 2258 "Diagnosing an empty lookup with explicit template args!"); 2259 *Out = CorrectTypoDelayed( 2260 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2261 [=](const TypoCorrection &TC) { 2262 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2263 diagnostic, diagnostic_suggest); 2264 }, 2265 nullptr, CTK_ErrorRecovery); 2266 if (*Out) 2267 return true; 2268 } else if (S && 2269 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2270 S, &SS, CCC, CTK_ErrorRecovery))) { 2271 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2272 bool DroppedSpecifier = 2273 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2274 R.setLookupName(Corrected.getCorrection()); 2275 2276 bool AcceptableWithRecovery = false; 2277 bool AcceptableWithoutRecovery = false; 2278 NamedDecl *ND = Corrected.getFoundDecl(); 2279 if (ND) { 2280 if (Corrected.isOverloaded()) { 2281 OverloadCandidateSet OCS(R.getNameLoc(), 2282 OverloadCandidateSet::CSK_Normal); 2283 OverloadCandidateSet::iterator Best; 2284 for (NamedDecl *CD : Corrected) { 2285 if (FunctionTemplateDecl *FTD = 2286 dyn_cast<FunctionTemplateDecl>(CD)) 2287 AddTemplateOverloadCandidate( 2288 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2289 Args, OCS); 2290 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2291 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2292 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2293 Args, OCS); 2294 } 2295 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2296 case OR_Success: 2297 ND = Best->FoundDecl; 2298 Corrected.setCorrectionDecl(ND); 2299 break; 2300 default: 2301 // FIXME: Arbitrarily pick the first declaration for the note. 2302 Corrected.setCorrectionDecl(ND); 2303 break; 2304 } 2305 } 2306 R.addDecl(ND); 2307 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2308 CXXRecordDecl *Record = nullptr; 2309 if (Corrected.getCorrectionSpecifier()) { 2310 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2311 Record = Ty->getAsCXXRecordDecl(); 2312 } 2313 if (!Record) 2314 Record = cast<CXXRecordDecl>( 2315 ND->getDeclContext()->getRedeclContext()); 2316 R.setNamingClass(Record); 2317 } 2318 2319 auto *UnderlyingND = ND->getUnderlyingDecl(); 2320 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2321 isa<FunctionTemplateDecl>(UnderlyingND); 2322 // FIXME: If we ended up with a typo for a type name or 2323 // Objective-C class name, we're in trouble because the parser 2324 // is in the wrong place to recover. Suggest the typo 2325 // correction, but don't make it a fix-it since we're not going 2326 // to recover well anyway. 2327 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2328 getAsTypeTemplateDecl(UnderlyingND) || 2329 isa<ObjCInterfaceDecl>(UnderlyingND); 2330 } else { 2331 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2332 // because we aren't able to recover. 2333 AcceptableWithoutRecovery = true; 2334 } 2335 2336 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2337 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2338 ? diag::note_implicit_param_decl 2339 : diag::note_previous_decl; 2340 if (SS.isEmpty()) 2341 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2342 PDiag(NoteID), AcceptableWithRecovery); 2343 else 2344 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2345 << Name << computeDeclContext(SS, false) 2346 << DroppedSpecifier << SS.getRange(), 2347 PDiag(NoteID), AcceptableWithRecovery); 2348 2349 // Tell the callee whether to try to recover. 2350 return !AcceptableWithRecovery; 2351 } 2352 } 2353 R.clear(); 2354 2355 // Emit a special diagnostic for failed member lookups. 2356 // FIXME: computing the declaration context might fail here (?) 2357 if (!SS.isEmpty()) { 2358 Diag(R.getNameLoc(), diag::err_no_member) 2359 << Name << computeDeclContext(SS, false) 2360 << SS.getRange(); 2361 return true; 2362 } 2363 2364 // Give up, we can't recover. 2365 Diag(R.getNameLoc(), diagnostic) << Name; 2366 return true; 2367 } 2368 2369 /// In Microsoft mode, if we are inside a template class whose parent class has 2370 /// dependent base classes, and we can't resolve an unqualified identifier, then 2371 /// assume the identifier is a member of a dependent base class. We can only 2372 /// recover successfully in static methods, instance methods, and other contexts 2373 /// where 'this' is available. This doesn't precisely match MSVC's 2374 /// instantiation model, but it's close enough. 2375 static Expr * 2376 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2377 DeclarationNameInfo &NameInfo, 2378 SourceLocation TemplateKWLoc, 2379 const TemplateArgumentListInfo *TemplateArgs) { 2380 // Only try to recover from lookup into dependent bases in static methods or 2381 // contexts where 'this' is available. 2382 QualType ThisType = S.getCurrentThisType(); 2383 const CXXRecordDecl *RD = nullptr; 2384 if (!ThisType.isNull()) 2385 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2386 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2387 RD = MD->getParent(); 2388 if (!RD || !RD->hasAnyDependentBases()) 2389 return nullptr; 2390 2391 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2392 // is available, suggest inserting 'this->' as a fixit. 2393 SourceLocation Loc = NameInfo.getLoc(); 2394 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2395 DB << NameInfo.getName() << RD; 2396 2397 if (!ThisType.isNull()) { 2398 DB << FixItHint::CreateInsertion(Loc, "this->"); 2399 return CXXDependentScopeMemberExpr::Create( 2400 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2401 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2402 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2403 } 2404 2405 // Synthesize a fake NNS that points to the derived class. This will 2406 // perform name lookup during template instantiation. 2407 CXXScopeSpec SS; 2408 auto *NNS = 2409 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2410 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2411 return DependentScopeDeclRefExpr::Create( 2412 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2413 TemplateArgs); 2414 } 2415 2416 ExprResult 2417 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2418 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2419 bool HasTrailingLParen, bool IsAddressOfOperand, 2420 CorrectionCandidateCallback *CCC, 2421 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2422 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2423 "cannot be direct & operand and have a trailing lparen"); 2424 if (SS.isInvalid()) 2425 return ExprError(); 2426 2427 TemplateArgumentListInfo TemplateArgsBuffer; 2428 2429 // Decompose the UnqualifiedId into the following data. 2430 DeclarationNameInfo NameInfo; 2431 const TemplateArgumentListInfo *TemplateArgs; 2432 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2433 2434 DeclarationName Name = NameInfo.getName(); 2435 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2436 SourceLocation NameLoc = NameInfo.getLoc(); 2437 2438 if (II && II->isEditorPlaceholder()) { 2439 // FIXME: When typed placeholders are supported we can create a typed 2440 // placeholder expression node. 2441 return ExprError(); 2442 } 2443 2444 // C++ [temp.dep.expr]p3: 2445 // An id-expression is type-dependent if it contains: 2446 // -- an identifier that was declared with a dependent type, 2447 // (note: handled after lookup) 2448 // -- a template-id that is dependent, 2449 // (note: handled in BuildTemplateIdExpr) 2450 // -- a conversion-function-id that specifies a dependent type, 2451 // -- a nested-name-specifier that contains a class-name that 2452 // names a dependent type. 2453 // Determine whether this is a member of an unknown specialization; 2454 // we need to handle these differently. 2455 bool DependentID = false; 2456 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2457 Name.getCXXNameType()->isDependentType()) { 2458 DependentID = true; 2459 } else if (SS.isSet()) { 2460 if (DeclContext *DC = computeDeclContext(SS, false)) { 2461 if (RequireCompleteDeclContext(SS, DC)) 2462 return ExprError(); 2463 } else { 2464 DependentID = true; 2465 } 2466 } 2467 2468 if (DependentID) 2469 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2470 IsAddressOfOperand, TemplateArgs); 2471 2472 // Perform the required lookup. 2473 LookupResult R(*this, NameInfo, 2474 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2475 ? LookupObjCImplicitSelfParam 2476 : LookupOrdinaryName); 2477 if (TemplateKWLoc.isValid() || TemplateArgs) { 2478 // Lookup the template name again to correctly establish the context in 2479 // which it was found. This is really unfortunate as we already did the 2480 // lookup to determine that it was a template name in the first place. If 2481 // this becomes a performance hit, we can work harder to preserve those 2482 // results until we get here but it's likely not worth it. 2483 bool MemberOfUnknownSpecialization; 2484 AssumedTemplateKind AssumedTemplate; 2485 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2486 MemberOfUnknownSpecialization, TemplateKWLoc, 2487 &AssumedTemplate)) 2488 return ExprError(); 2489 2490 if (MemberOfUnknownSpecialization || 2491 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2492 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2493 IsAddressOfOperand, TemplateArgs); 2494 } else { 2495 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2496 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2497 2498 // If the result might be in a dependent base class, this is a dependent 2499 // id-expression. 2500 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2501 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2502 IsAddressOfOperand, TemplateArgs); 2503 2504 // If this reference is in an Objective-C method, then we need to do 2505 // some special Objective-C lookup, too. 2506 if (IvarLookupFollowUp) { 2507 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2508 if (E.isInvalid()) 2509 return ExprError(); 2510 2511 if (Expr *Ex = E.getAs<Expr>()) 2512 return Ex; 2513 } 2514 } 2515 2516 if (R.isAmbiguous()) 2517 return ExprError(); 2518 2519 // This could be an implicitly declared function reference (legal in C90, 2520 // extension in C99, forbidden in C++). 2521 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2522 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2523 if (D) R.addDecl(D); 2524 } 2525 2526 // Determine whether this name might be a candidate for 2527 // argument-dependent lookup. 2528 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2529 2530 if (R.empty() && !ADL) { 2531 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2532 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2533 TemplateKWLoc, TemplateArgs)) 2534 return E; 2535 } 2536 2537 // Don't diagnose an empty lookup for inline assembly. 2538 if (IsInlineAsmIdentifier) 2539 return ExprError(); 2540 2541 // If this name wasn't predeclared and if this is not a function 2542 // call, diagnose the problem. 2543 TypoExpr *TE = nullptr; 2544 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2545 : nullptr); 2546 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2547 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2548 "Typo correction callback misconfigured"); 2549 if (CCC) { 2550 // Make sure the callback knows what the typo being diagnosed is. 2551 CCC->setTypoName(II); 2552 if (SS.isValid()) 2553 CCC->setTypoNNS(SS.getScopeRep()); 2554 } 2555 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2556 // a template name, but we happen to have always already looked up the name 2557 // before we get here if it must be a template name. 2558 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2559 None, &TE)) { 2560 if (TE && KeywordReplacement) { 2561 auto &State = getTypoExprState(TE); 2562 auto BestTC = State.Consumer->getNextCorrection(); 2563 if (BestTC.isKeyword()) { 2564 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2565 if (State.DiagHandler) 2566 State.DiagHandler(BestTC); 2567 KeywordReplacement->startToken(); 2568 KeywordReplacement->setKind(II->getTokenID()); 2569 KeywordReplacement->setIdentifierInfo(II); 2570 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2571 // Clean up the state associated with the TypoExpr, since it has 2572 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2573 clearDelayedTypo(TE); 2574 // Signal that a correction to a keyword was performed by returning a 2575 // valid-but-null ExprResult. 2576 return (Expr*)nullptr; 2577 } 2578 State.Consumer->resetCorrectionStream(); 2579 } 2580 return TE ? TE : ExprError(); 2581 } 2582 2583 assert(!R.empty() && 2584 "DiagnoseEmptyLookup returned false but added no results"); 2585 2586 // If we found an Objective-C instance variable, let 2587 // LookupInObjCMethod build the appropriate expression to 2588 // reference the ivar. 2589 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2590 R.clear(); 2591 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2592 // In a hopelessly buggy code, Objective-C instance variable 2593 // lookup fails and no expression will be built to reference it. 2594 if (!E.isInvalid() && !E.get()) 2595 return ExprError(); 2596 return E; 2597 } 2598 } 2599 2600 // This is guaranteed from this point on. 2601 assert(!R.empty() || ADL); 2602 2603 // Check whether this might be a C++ implicit instance member access. 2604 // C++ [class.mfct.non-static]p3: 2605 // When an id-expression that is not part of a class member access 2606 // syntax and not used to form a pointer to member is used in the 2607 // body of a non-static member function of class X, if name lookup 2608 // resolves the name in the id-expression to a non-static non-type 2609 // member of some class C, the id-expression is transformed into a 2610 // class member access expression using (*this) as the 2611 // postfix-expression to the left of the . operator. 2612 // 2613 // But we don't actually need to do this for '&' operands if R 2614 // resolved to a function or overloaded function set, because the 2615 // expression is ill-formed if it actually works out to be a 2616 // non-static member function: 2617 // 2618 // C++ [expr.ref]p4: 2619 // Otherwise, if E1.E2 refers to a non-static member function. . . 2620 // [t]he expression can be used only as the left-hand operand of a 2621 // member function call. 2622 // 2623 // There are other safeguards against such uses, but it's important 2624 // to get this right here so that we don't end up making a 2625 // spuriously dependent expression if we're inside a dependent 2626 // instance method. 2627 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2628 bool MightBeImplicitMember; 2629 if (!IsAddressOfOperand) 2630 MightBeImplicitMember = true; 2631 else if (!SS.isEmpty()) 2632 MightBeImplicitMember = false; 2633 else if (R.isOverloadedResult()) 2634 MightBeImplicitMember = false; 2635 else if (R.isUnresolvableResult()) 2636 MightBeImplicitMember = true; 2637 else 2638 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2639 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2640 isa<MSPropertyDecl>(R.getFoundDecl()); 2641 2642 if (MightBeImplicitMember) 2643 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2644 R, TemplateArgs, S); 2645 } 2646 2647 if (TemplateArgs || TemplateKWLoc.isValid()) { 2648 2649 // In C++1y, if this is a variable template id, then check it 2650 // in BuildTemplateIdExpr(). 2651 // The single lookup result must be a variable template declaration. 2652 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2653 Id.TemplateId->Kind == TNK_Var_template) { 2654 assert(R.getAsSingle<VarTemplateDecl>() && 2655 "There should only be one declaration found."); 2656 } 2657 2658 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2659 } 2660 2661 return BuildDeclarationNameExpr(SS, R, ADL); 2662 } 2663 2664 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2665 /// declaration name, generally during template instantiation. 2666 /// There's a large number of things which don't need to be done along 2667 /// this path. 2668 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2669 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2670 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2671 DeclContext *DC = computeDeclContext(SS, false); 2672 if (!DC) 2673 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2674 NameInfo, /*TemplateArgs=*/nullptr); 2675 2676 if (RequireCompleteDeclContext(SS, DC)) 2677 return ExprError(); 2678 2679 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2680 LookupQualifiedName(R, DC); 2681 2682 if (R.isAmbiguous()) 2683 return ExprError(); 2684 2685 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2686 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2687 NameInfo, /*TemplateArgs=*/nullptr); 2688 2689 if (R.empty()) { 2690 // Don't diagnose problems with invalid record decl, the secondary no_member 2691 // diagnostic during template instantiation is likely bogus, e.g. if a class 2692 // is invalid because it's derived from an invalid base class, then missing 2693 // members were likely supposed to be inherited. 2694 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2695 if (CD->isInvalidDecl()) 2696 return ExprError(); 2697 Diag(NameInfo.getLoc(), diag::err_no_member) 2698 << NameInfo.getName() << DC << SS.getRange(); 2699 return ExprError(); 2700 } 2701 2702 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2703 // Diagnose a missing typename if this resolved unambiguously to a type in 2704 // a dependent context. If we can recover with a type, downgrade this to 2705 // a warning in Microsoft compatibility mode. 2706 unsigned DiagID = diag::err_typename_missing; 2707 if (RecoveryTSI && getLangOpts().MSVCCompat) 2708 DiagID = diag::ext_typename_missing; 2709 SourceLocation Loc = SS.getBeginLoc(); 2710 auto D = Diag(Loc, DiagID); 2711 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2712 << SourceRange(Loc, NameInfo.getEndLoc()); 2713 2714 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2715 // context. 2716 if (!RecoveryTSI) 2717 return ExprError(); 2718 2719 // Only issue the fixit if we're prepared to recover. 2720 D << FixItHint::CreateInsertion(Loc, "typename "); 2721 2722 // Recover by pretending this was an elaborated type. 2723 QualType Ty = Context.getTypeDeclType(TD); 2724 TypeLocBuilder TLB; 2725 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2726 2727 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2728 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2729 QTL.setElaboratedKeywordLoc(SourceLocation()); 2730 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2731 2732 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2733 2734 return ExprEmpty(); 2735 } 2736 2737 // Defend against this resolving to an implicit member access. We usually 2738 // won't get here if this might be a legitimate a class member (we end up in 2739 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2740 // a pointer-to-member or in an unevaluated context in C++11. 2741 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2742 return BuildPossibleImplicitMemberExpr(SS, 2743 /*TemplateKWLoc=*/SourceLocation(), 2744 R, /*TemplateArgs=*/nullptr, S); 2745 2746 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2747 } 2748 2749 /// The parser has read a name in, and Sema has detected that we're currently 2750 /// inside an ObjC method. Perform some additional checks and determine if we 2751 /// should form a reference to an ivar. 2752 /// 2753 /// Ideally, most of this would be done by lookup, but there's 2754 /// actually quite a lot of extra work involved. 2755 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2756 IdentifierInfo *II) { 2757 SourceLocation Loc = Lookup.getNameLoc(); 2758 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2759 2760 // Check for error condition which is already reported. 2761 if (!CurMethod) 2762 return DeclResult(true); 2763 2764 // There are two cases to handle here. 1) scoped lookup could have failed, 2765 // in which case we should look for an ivar. 2) scoped lookup could have 2766 // found a decl, but that decl is outside the current instance method (i.e. 2767 // a global variable). In these two cases, we do a lookup for an ivar with 2768 // this name, if the lookup sucedes, we replace it our current decl. 2769 2770 // If we're in a class method, we don't normally want to look for 2771 // ivars. But if we don't find anything else, and there's an 2772 // ivar, that's an error. 2773 bool IsClassMethod = CurMethod->isClassMethod(); 2774 2775 bool LookForIvars; 2776 if (Lookup.empty()) 2777 LookForIvars = true; 2778 else if (IsClassMethod) 2779 LookForIvars = false; 2780 else 2781 LookForIvars = (Lookup.isSingleResult() && 2782 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2783 ObjCInterfaceDecl *IFace = nullptr; 2784 if (LookForIvars) { 2785 IFace = CurMethod->getClassInterface(); 2786 ObjCInterfaceDecl *ClassDeclared; 2787 ObjCIvarDecl *IV = nullptr; 2788 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2789 // Diagnose using an ivar in a class method. 2790 if (IsClassMethod) { 2791 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2792 return DeclResult(true); 2793 } 2794 2795 // Diagnose the use of an ivar outside of the declaring class. 2796 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2797 !declaresSameEntity(ClassDeclared, IFace) && 2798 !getLangOpts().DebuggerSupport) 2799 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2800 2801 // Success. 2802 return IV; 2803 } 2804 } else if (CurMethod->isInstanceMethod()) { 2805 // We should warn if a local variable hides an ivar. 2806 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2807 ObjCInterfaceDecl *ClassDeclared; 2808 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2809 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2810 declaresSameEntity(IFace, ClassDeclared)) 2811 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2812 } 2813 } 2814 } else if (Lookup.isSingleResult() && 2815 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2816 // If accessing a stand-alone ivar in a class method, this is an error. 2817 if (const ObjCIvarDecl *IV = 2818 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2819 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2820 return DeclResult(true); 2821 } 2822 } 2823 2824 // Didn't encounter an error, didn't find an ivar. 2825 return DeclResult(false); 2826 } 2827 2828 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2829 ObjCIvarDecl *IV) { 2830 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2831 assert(CurMethod && CurMethod->isInstanceMethod() && 2832 "should not reference ivar from this context"); 2833 2834 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2835 assert(IFace && "should not reference ivar from this context"); 2836 2837 // If we're referencing an invalid decl, just return this as a silent 2838 // error node. The error diagnostic was already emitted on the decl. 2839 if (IV->isInvalidDecl()) 2840 return ExprError(); 2841 2842 // Check if referencing a field with __attribute__((deprecated)). 2843 if (DiagnoseUseOfDecl(IV, Loc)) 2844 return ExprError(); 2845 2846 // FIXME: This should use a new expr for a direct reference, don't 2847 // turn this into Self->ivar, just return a BareIVarExpr or something. 2848 IdentifierInfo &II = Context.Idents.get("self"); 2849 UnqualifiedId SelfName; 2850 SelfName.setImplicitSelfParam(&II); 2851 CXXScopeSpec SelfScopeSpec; 2852 SourceLocation TemplateKWLoc; 2853 ExprResult SelfExpr = 2854 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2855 /*HasTrailingLParen=*/false, 2856 /*IsAddressOfOperand=*/false); 2857 if (SelfExpr.isInvalid()) 2858 return ExprError(); 2859 2860 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2861 if (SelfExpr.isInvalid()) 2862 return ExprError(); 2863 2864 MarkAnyDeclReferenced(Loc, IV, true); 2865 2866 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2867 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2868 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2869 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2870 2871 ObjCIvarRefExpr *Result = new (Context) 2872 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2873 IV->getLocation(), SelfExpr.get(), true, true); 2874 2875 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2876 if (!isUnevaluatedContext() && 2877 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2878 getCurFunction()->recordUseOfWeak(Result); 2879 } 2880 if (getLangOpts().ObjCAutoRefCount) 2881 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2882 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2883 2884 return Result; 2885 } 2886 2887 /// The parser has read a name in, and Sema has detected that we're currently 2888 /// inside an ObjC method. Perform some additional checks and determine if we 2889 /// should form a reference to an ivar. If so, build an expression referencing 2890 /// that ivar. 2891 ExprResult 2892 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2893 IdentifierInfo *II, bool AllowBuiltinCreation) { 2894 // FIXME: Integrate this lookup step into LookupParsedName. 2895 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2896 if (Ivar.isInvalid()) 2897 return ExprError(); 2898 if (Ivar.isUsable()) 2899 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2900 cast<ObjCIvarDecl>(Ivar.get())); 2901 2902 if (Lookup.empty() && II && AllowBuiltinCreation) 2903 LookupBuiltin(Lookup); 2904 2905 // Sentinel value saying that we didn't do anything special. 2906 return ExprResult(false); 2907 } 2908 2909 /// Cast a base object to a member's actual type. 2910 /// 2911 /// There are two relevant checks: 2912 /// 2913 /// C++ [class.access.base]p7: 2914 /// 2915 /// If a class member access operator [...] is used to access a non-static 2916 /// data member or non-static member function, the reference is ill-formed if 2917 /// the left operand [...] cannot be implicitly converted to a pointer to the 2918 /// naming class of the right operand. 2919 /// 2920 /// C++ [expr.ref]p7: 2921 /// 2922 /// If E2 is a non-static data member or a non-static member function, the 2923 /// program is ill-formed if the class of which E2 is directly a member is an 2924 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2925 /// 2926 /// Note that the latter check does not consider access; the access of the 2927 /// "real" base class is checked as appropriate when checking the access of the 2928 /// member name. 2929 ExprResult 2930 Sema::PerformObjectMemberConversion(Expr *From, 2931 NestedNameSpecifier *Qualifier, 2932 NamedDecl *FoundDecl, 2933 NamedDecl *Member) { 2934 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2935 if (!RD) 2936 return From; 2937 2938 QualType DestRecordType; 2939 QualType DestType; 2940 QualType FromRecordType; 2941 QualType FromType = From->getType(); 2942 bool PointerConversions = false; 2943 if (isa<FieldDecl>(Member)) { 2944 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2945 auto FromPtrType = FromType->getAs<PointerType>(); 2946 DestRecordType = Context.getAddrSpaceQualType( 2947 DestRecordType, FromPtrType 2948 ? FromType->getPointeeType().getAddressSpace() 2949 : FromType.getAddressSpace()); 2950 2951 if (FromPtrType) { 2952 DestType = Context.getPointerType(DestRecordType); 2953 FromRecordType = FromPtrType->getPointeeType(); 2954 PointerConversions = true; 2955 } else { 2956 DestType = DestRecordType; 2957 FromRecordType = FromType; 2958 } 2959 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2960 if (Method->isStatic()) 2961 return From; 2962 2963 DestType = Method->getThisType(); 2964 DestRecordType = DestType->getPointeeType(); 2965 2966 if (FromType->getAs<PointerType>()) { 2967 FromRecordType = FromType->getPointeeType(); 2968 PointerConversions = true; 2969 } else { 2970 FromRecordType = FromType; 2971 DestType = DestRecordType; 2972 } 2973 2974 LangAS FromAS = FromRecordType.getAddressSpace(); 2975 LangAS DestAS = DestRecordType.getAddressSpace(); 2976 if (FromAS != DestAS) { 2977 QualType FromRecordTypeWithoutAS = 2978 Context.removeAddrSpaceQualType(FromRecordType); 2979 QualType FromTypeWithDestAS = 2980 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2981 if (PointerConversions) 2982 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2983 From = ImpCastExprToType(From, FromTypeWithDestAS, 2984 CK_AddressSpaceConversion, From->getValueKind()) 2985 .get(); 2986 } 2987 } else { 2988 // No conversion necessary. 2989 return From; 2990 } 2991 2992 if (DestType->isDependentType() || FromType->isDependentType()) 2993 return From; 2994 2995 // If the unqualified types are the same, no conversion is necessary. 2996 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2997 return From; 2998 2999 SourceRange FromRange = From->getSourceRange(); 3000 SourceLocation FromLoc = FromRange.getBegin(); 3001 3002 ExprValueKind VK = From->getValueKind(); 3003 3004 // C++ [class.member.lookup]p8: 3005 // [...] Ambiguities can often be resolved by qualifying a name with its 3006 // class name. 3007 // 3008 // If the member was a qualified name and the qualified referred to a 3009 // specific base subobject type, we'll cast to that intermediate type 3010 // first and then to the object in which the member is declared. That allows 3011 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3012 // 3013 // class Base { public: int x; }; 3014 // class Derived1 : public Base { }; 3015 // class Derived2 : public Base { }; 3016 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3017 // 3018 // void VeryDerived::f() { 3019 // x = 17; // error: ambiguous base subobjects 3020 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3021 // } 3022 if (Qualifier && Qualifier->getAsType()) { 3023 QualType QType = QualType(Qualifier->getAsType(), 0); 3024 assert(QType->isRecordType() && "lookup done with non-record type"); 3025 3026 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3027 3028 // In C++98, the qualifier type doesn't actually have to be a base 3029 // type of the object type, in which case we just ignore it. 3030 // Otherwise build the appropriate casts. 3031 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3032 CXXCastPath BasePath; 3033 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3034 FromLoc, FromRange, &BasePath)) 3035 return ExprError(); 3036 3037 if (PointerConversions) 3038 QType = Context.getPointerType(QType); 3039 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3040 VK, &BasePath).get(); 3041 3042 FromType = QType; 3043 FromRecordType = QRecordType; 3044 3045 // If the qualifier type was the same as the destination type, 3046 // we're done. 3047 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3048 return From; 3049 } 3050 } 3051 3052 CXXCastPath BasePath; 3053 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3054 FromLoc, FromRange, &BasePath, 3055 /*IgnoreAccess=*/true)) 3056 return ExprError(); 3057 3058 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3059 VK, &BasePath); 3060 } 3061 3062 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3063 const LookupResult &R, 3064 bool HasTrailingLParen) { 3065 // Only when used directly as the postfix-expression of a call. 3066 if (!HasTrailingLParen) 3067 return false; 3068 3069 // Never if a scope specifier was provided. 3070 if (SS.isSet()) 3071 return false; 3072 3073 // Only in C++ or ObjC++. 3074 if (!getLangOpts().CPlusPlus) 3075 return false; 3076 3077 // Turn off ADL when we find certain kinds of declarations during 3078 // normal lookup: 3079 for (NamedDecl *D : R) { 3080 // C++0x [basic.lookup.argdep]p3: 3081 // -- a declaration of a class member 3082 // Since using decls preserve this property, we check this on the 3083 // original decl. 3084 if (D->isCXXClassMember()) 3085 return false; 3086 3087 // C++0x [basic.lookup.argdep]p3: 3088 // -- a block-scope function declaration that is not a 3089 // using-declaration 3090 // NOTE: we also trigger this for function templates (in fact, we 3091 // don't check the decl type at all, since all other decl types 3092 // turn off ADL anyway). 3093 if (isa<UsingShadowDecl>(D)) 3094 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3095 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3096 return false; 3097 3098 // C++0x [basic.lookup.argdep]p3: 3099 // -- a declaration that is neither a function or a function 3100 // template 3101 // And also for builtin functions. 3102 if (isa<FunctionDecl>(D)) { 3103 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3104 3105 // But also builtin functions. 3106 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3107 return false; 3108 } else if (!isa<FunctionTemplateDecl>(D)) 3109 return false; 3110 } 3111 3112 return true; 3113 } 3114 3115 3116 /// Diagnoses obvious problems with the use of the given declaration 3117 /// as an expression. This is only actually called for lookups that 3118 /// were not overloaded, and it doesn't promise that the declaration 3119 /// will in fact be used. 3120 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3121 if (D->isInvalidDecl()) 3122 return true; 3123 3124 if (isa<TypedefNameDecl>(D)) { 3125 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3126 return true; 3127 } 3128 3129 if (isa<ObjCInterfaceDecl>(D)) { 3130 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3131 return true; 3132 } 3133 3134 if (isa<NamespaceDecl>(D)) { 3135 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3136 return true; 3137 } 3138 3139 return false; 3140 } 3141 3142 // Certain multiversion types should be treated as overloaded even when there is 3143 // only one result. 3144 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3145 assert(R.isSingleResult() && "Expected only a single result"); 3146 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3147 return FD && 3148 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3149 } 3150 3151 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3152 LookupResult &R, bool NeedsADL, 3153 bool AcceptInvalidDecl) { 3154 // If this is a single, fully-resolved result and we don't need ADL, 3155 // just build an ordinary singleton decl ref. 3156 if (!NeedsADL && R.isSingleResult() && 3157 !R.getAsSingle<FunctionTemplateDecl>() && 3158 !ShouldLookupResultBeMultiVersionOverload(R)) 3159 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3160 R.getRepresentativeDecl(), nullptr, 3161 AcceptInvalidDecl); 3162 3163 // We only need to check the declaration if there's exactly one 3164 // result, because in the overloaded case the results can only be 3165 // functions and function templates. 3166 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3167 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3168 return ExprError(); 3169 3170 // Otherwise, just build an unresolved lookup expression. Suppress 3171 // any lookup-related diagnostics; we'll hash these out later, when 3172 // we've picked a target. 3173 R.suppressDiagnostics(); 3174 3175 UnresolvedLookupExpr *ULE 3176 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3177 SS.getWithLocInContext(Context), 3178 R.getLookupNameInfo(), 3179 NeedsADL, R.isOverloadedResult(), 3180 R.begin(), R.end()); 3181 3182 return ULE; 3183 } 3184 3185 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3186 ValueDecl *var); 3187 3188 /// Complete semantic analysis for a reference to the given declaration. 3189 ExprResult Sema::BuildDeclarationNameExpr( 3190 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3191 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3192 bool AcceptInvalidDecl) { 3193 assert(D && "Cannot refer to a NULL declaration"); 3194 assert(!isa<FunctionTemplateDecl>(D) && 3195 "Cannot refer unambiguously to a function template"); 3196 3197 SourceLocation Loc = NameInfo.getLoc(); 3198 if (CheckDeclInExpr(*this, Loc, D)) 3199 return ExprError(); 3200 3201 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3202 // Specifically diagnose references to class templates that are missing 3203 // a template argument list. 3204 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3205 return ExprError(); 3206 } 3207 3208 // Make sure that we're referring to a value. 3209 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3210 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3211 Diag(D->getLocation(), diag::note_declared_at); 3212 return ExprError(); 3213 } 3214 3215 // Check whether this declaration can be used. Note that we suppress 3216 // this check when we're going to perform argument-dependent lookup 3217 // on this function name, because this might not be the function 3218 // that overload resolution actually selects. 3219 if (DiagnoseUseOfDecl(D, Loc)) 3220 return ExprError(); 3221 3222 auto *VD = cast<ValueDecl>(D); 3223 3224 // Only create DeclRefExpr's for valid Decl's. 3225 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3226 return ExprError(); 3227 3228 // Handle members of anonymous structs and unions. If we got here, 3229 // and the reference is to a class member indirect field, then this 3230 // must be the subject of a pointer-to-member expression. 3231 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3232 if (!indirectField->isCXXClassMember()) 3233 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3234 indirectField); 3235 3236 QualType type = VD->getType(); 3237 if (type.isNull()) 3238 return ExprError(); 3239 ExprValueKind valueKind = VK_PRValue; 3240 3241 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3242 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3243 // is expanded by some outer '...' in the context of the use. 3244 type = type.getNonPackExpansionType(); 3245 3246 switch (D->getKind()) { 3247 // Ignore all the non-ValueDecl kinds. 3248 #define ABSTRACT_DECL(kind) 3249 #define VALUE(type, base) 3250 #define DECL(type, base) case Decl::type: 3251 #include "clang/AST/DeclNodes.inc" 3252 llvm_unreachable("invalid value decl kind"); 3253 3254 // These shouldn't make it here. 3255 case Decl::ObjCAtDefsField: 3256 llvm_unreachable("forming non-member reference to ivar?"); 3257 3258 // Enum constants are always r-values and never references. 3259 // Unresolved using declarations are dependent. 3260 case Decl::EnumConstant: 3261 case Decl::UnresolvedUsingValue: 3262 case Decl::OMPDeclareReduction: 3263 case Decl::OMPDeclareMapper: 3264 valueKind = VK_PRValue; 3265 break; 3266 3267 // Fields and indirect fields that got here must be for 3268 // pointer-to-member expressions; we just call them l-values for 3269 // internal consistency, because this subexpression doesn't really 3270 // exist in the high-level semantics. 3271 case Decl::Field: 3272 case Decl::IndirectField: 3273 case Decl::ObjCIvar: 3274 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3275 3276 // These can't have reference type in well-formed programs, but 3277 // for internal consistency we do this anyway. 3278 type = type.getNonReferenceType(); 3279 valueKind = VK_LValue; 3280 break; 3281 3282 // Non-type template parameters are either l-values or r-values 3283 // depending on the type. 3284 case Decl::NonTypeTemplateParm: { 3285 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3286 type = reftype->getPointeeType(); 3287 valueKind = VK_LValue; // even if the parameter is an r-value reference 3288 break; 3289 } 3290 3291 // [expr.prim.id.unqual]p2: 3292 // If the entity is a template parameter object for a template 3293 // parameter of type T, the type of the expression is const T. 3294 // [...] The expression is an lvalue if the entity is a [...] template 3295 // parameter object. 3296 if (type->isRecordType()) { 3297 type = type.getUnqualifiedType().withConst(); 3298 valueKind = VK_LValue; 3299 break; 3300 } 3301 3302 // For non-references, we need to strip qualifiers just in case 3303 // the template parameter was declared as 'const int' or whatever. 3304 valueKind = VK_PRValue; 3305 type = type.getUnqualifiedType(); 3306 break; 3307 } 3308 3309 case Decl::Var: 3310 case Decl::VarTemplateSpecialization: 3311 case Decl::VarTemplatePartialSpecialization: 3312 case Decl::Decomposition: 3313 case Decl::OMPCapturedExpr: 3314 // In C, "extern void blah;" is valid and is an r-value. 3315 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3316 type->isVoidType()) { 3317 valueKind = VK_PRValue; 3318 break; 3319 } 3320 LLVM_FALLTHROUGH; 3321 3322 case Decl::ImplicitParam: 3323 case Decl::ParmVar: { 3324 // These are always l-values. 3325 valueKind = VK_LValue; 3326 type = type.getNonReferenceType(); 3327 3328 // FIXME: Does the addition of const really only apply in 3329 // potentially-evaluated contexts? Since the variable isn't actually 3330 // captured in an unevaluated context, it seems that the answer is no. 3331 if (!isUnevaluatedContext()) { 3332 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3333 if (!CapturedType.isNull()) 3334 type = CapturedType; 3335 } 3336 3337 break; 3338 } 3339 3340 case Decl::Binding: { 3341 // These are always lvalues. 3342 valueKind = VK_LValue; 3343 type = type.getNonReferenceType(); 3344 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3345 // decides how that's supposed to work. 3346 auto *BD = cast<BindingDecl>(VD); 3347 if (BD->getDeclContext() != CurContext) { 3348 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3349 if (DD && DD->hasLocalStorage()) 3350 diagnoseUncapturableValueReference(*this, Loc, BD); 3351 } 3352 break; 3353 } 3354 3355 case Decl::Function: { 3356 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3357 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3358 type = Context.BuiltinFnTy; 3359 valueKind = VK_PRValue; 3360 break; 3361 } 3362 } 3363 3364 const FunctionType *fty = type->castAs<FunctionType>(); 3365 3366 // If we're referring to a function with an __unknown_anytype 3367 // result type, make the entire expression __unknown_anytype. 3368 if (fty->getReturnType() == Context.UnknownAnyTy) { 3369 type = Context.UnknownAnyTy; 3370 valueKind = VK_PRValue; 3371 break; 3372 } 3373 3374 // Functions are l-values in C++. 3375 if (getLangOpts().CPlusPlus) { 3376 valueKind = VK_LValue; 3377 break; 3378 } 3379 3380 // C99 DR 316 says that, if a function type comes from a 3381 // function definition (without a prototype), that type is only 3382 // used for checking compatibility. Therefore, when referencing 3383 // the function, we pretend that we don't have the full function 3384 // type. 3385 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3386 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3387 fty->getExtInfo()); 3388 3389 // Functions are r-values in C. 3390 valueKind = VK_PRValue; 3391 break; 3392 } 3393 3394 case Decl::CXXDeductionGuide: 3395 llvm_unreachable("building reference to deduction guide"); 3396 3397 case Decl::MSProperty: 3398 case Decl::MSGuid: 3399 case Decl::TemplateParamObject: 3400 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3401 // capture in OpenMP, or duplicated between host and device? 3402 valueKind = VK_LValue; 3403 break; 3404 3405 case Decl::CXXMethod: 3406 // If we're referring to a method with an __unknown_anytype 3407 // result type, make the entire expression __unknown_anytype. 3408 // This should only be possible with a type written directly. 3409 if (const FunctionProtoType *proto = 3410 dyn_cast<FunctionProtoType>(VD->getType())) 3411 if (proto->getReturnType() == Context.UnknownAnyTy) { 3412 type = Context.UnknownAnyTy; 3413 valueKind = VK_PRValue; 3414 break; 3415 } 3416 3417 // C++ methods are l-values if static, r-values if non-static. 3418 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3419 valueKind = VK_LValue; 3420 break; 3421 } 3422 LLVM_FALLTHROUGH; 3423 3424 case Decl::CXXConversion: 3425 case Decl::CXXDestructor: 3426 case Decl::CXXConstructor: 3427 valueKind = VK_PRValue; 3428 break; 3429 } 3430 3431 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3432 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3433 TemplateArgs); 3434 } 3435 3436 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3437 SmallString<32> &Target) { 3438 Target.resize(CharByteWidth * (Source.size() + 1)); 3439 char *ResultPtr = &Target[0]; 3440 const llvm::UTF8 *ErrorPtr; 3441 bool success = 3442 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3443 (void)success; 3444 assert(success); 3445 Target.resize(ResultPtr - &Target[0]); 3446 } 3447 3448 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3449 PredefinedExpr::IdentKind IK) { 3450 // Pick the current block, lambda, captured statement or function. 3451 Decl *currentDecl = nullptr; 3452 if (const BlockScopeInfo *BSI = getCurBlock()) 3453 currentDecl = BSI->TheDecl; 3454 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3455 currentDecl = LSI->CallOperator; 3456 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3457 currentDecl = CSI->TheCapturedDecl; 3458 else 3459 currentDecl = getCurFunctionOrMethodDecl(); 3460 3461 if (!currentDecl) { 3462 Diag(Loc, diag::ext_predef_outside_function); 3463 currentDecl = Context.getTranslationUnitDecl(); 3464 } 3465 3466 QualType ResTy; 3467 StringLiteral *SL = nullptr; 3468 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3469 ResTy = Context.DependentTy; 3470 else { 3471 // Pre-defined identifiers are of type char[x], where x is the length of 3472 // the string. 3473 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3474 unsigned Length = Str.length(); 3475 3476 llvm::APInt LengthI(32, Length + 1); 3477 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3478 ResTy = 3479 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3480 SmallString<32> RawChars; 3481 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3482 Str, RawChars); 3483 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3484 ArrayType::Normal, 3485 /*IndexTypeQuals*/ 0); 3486 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3487 /*Pascal*/ false, ResTy, Loc); 3488 } else { 3489 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3490 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3491 ArrayType::Normal, 3492 /*IndexTypeQuals*/ 0); 3493 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3494 /*Pascal*/ false, ResTy, Loc); 3495 } 3496 } 3497 3498 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3499 } 3500 3501 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3502 SourceLocation LParen, 3503 SourceLocation RParen, 3504 TypeSourceInfo *TSI) { 3505 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3506 } 3507 3508 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3509 SourceLocation LParen, 3510 SourceLocation RParen, 3511 ParsedType ParsedTy) { 3512 TypeSourceInfo *TSI = nullptr; 3513 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3514 3515 if (Ty.isNull()) 3516 return ExprError(); 3517 if (!TSI) 3518 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3519 3520 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3521 } 3522 3523 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3524 PredefinedExpr::IdentKind IK; 3525 3526 switch (Kind) { 3527 default: llvm_unreachable("Unknown simple primary expr!"); 3528 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3529 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3530 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3531 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3532 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3533 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3534 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3535 } 3536 3537 return BuildPredefinedExpr(Loc, IK); 3538 } 3539 3540 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3541 SmallString<16> CharBuffer; 3542 bool Invalid = false; 3543 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3544 if (Invalid) 3545 return ExprError(); 3546 3547 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3548 PP, Tok.getKind()); 3549 if (Literal.hadError()) 3550 return ExprError(); 3551 3552 QualType Ty; 3553 if (Literal.isWide()) 3554 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3555 else if (Literal.isUTF8() && getLangOpts().Char8) 3556 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3557 else if (Literal.isUTF16()) 3558 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3559 else if (Literal.isUTF32()) 3560 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3561 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3562 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3563 else 3564 Ty = Context.CharTy; // 'x' -> char in C++ 3565 3566 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3567 if (Literal.isWide()) 3568 Kind = CharacterLiteral::Wide; 3569 else if (Literal.isUTF16()) 3570 Kind = CharacterLiteral::UTF16; 3571 else if (Literal.isUTF32()) 3572 Kind = CharacterLiteral::UTF32; 3573 else if (Literal.isUTF8()) 3574 Kind = CharacterLiteral::UTF8; 3575 3576 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3577 Tok.getLocation()); 3578 3579 if (Literal.getUDSuffix().empty()) 3580 return Lit; 3581 3582 // We're building a user-defined literal. 3583 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3584 SourceLocation UDSuffixLoc = 3585 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3586 3587 // Make sure we're allowed user-defined literals here. 3588 if (!UDLScope) 3589 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3590 3591 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3592 // operator "" X (ch) 3593 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3594 Lit, Tok.getLocation()); 3595 } 3596 3597 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3598 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3599 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3600 Context.IntTy, Loc); 3601 } 3602 3603 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3604 QualType Ty, SourceLocation Loc) { 3605 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3606 3607 using llvm::APFloat; 3608 APFloat Val(Format); 3609 3610 APFloat::opStatus result = Literal.GetFloatValue(Val); 3611 3612 // Overflow is always an error, but underflow is only an error if 3613 // we underflowed to zero (APFloat reports denormals as underflow). 3614 if ((result & APFloat::opOverflow) || 3615 ((result & APFloat::opUnderflow) && Val.isZero())) { 3616 unsigned diagnostic; 3617 SmallString<20> buffer; 3618 if (result & APFloat::opOverflow) { 3619 diagnostic = diag::warn_float_overflow; 3620 APFloat::getLargest(Format).toString(buffer); 3621 } else { 3622 diagnostic = diag::warn_float_underflow; 3623 APFloat::getSmallest(Format).toString(buffer); 3624 } 3625 3626 S.Diag(Loc, diagnostic) 3627 << Ty 3628 << StringRef(buffer.data(), buffer.size()); 3629 } 3630 3631 bool isExact = (result == APFloat::opOK); 3632 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3633 } 3634 3635 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3636 assert(E && "Invalid expression"); 3637 3638 if (E->isValueDependent()) 3639 return false; 3640 3641 QualType QT = E->getType(); 3642 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3643 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3644 return true; 3645 } 3646 3647 llvm::APSInt ValueAPS; 3648 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3649 3650 if (R.isInvalid()) 3651 return true; 3652 3653 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3654 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3655 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3656 << toString(ValueAPS, 10) << ValueIsPositive; 3657 return true; 3658 } 3659 3660 return false; 3661 } 3662 3663 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3664 // Fast path for a single digit (which is quite common). A single digit 3665 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3666 if (Tok.getLength() == 1) { 3667 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3668 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3669 } 3670 3671 SmallString<128> SpellingBuffer; 3672 // NumericLiteralParser wants to overread by one character. Add padding to 3673 // the buffer in case the token is copied to the buffer. If getSpelling() 3674 // returns a StringRef to the memory buffer, it should have a null char at 3675 // the EOF, so it is also safe. 3676 SpellingBuffer.resize(Tok.getLength() + 1); 3677 3678 // Get the spelling of the token, which eliminates trigraphs, etc. 3679 bool Invalid = false; 3680 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3681 if (Invalid) 3682 return ExprError(); 3683 3684 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3685 PP.getSourceManager(), PP.getLangOpts(), 3686 PP.getTargetInfo(), PP.getDiagnostics()); 3687 if (Literal.hadError) 3688 return ExprError(); 3689 3690 if (Literal.hasUDSuffix()) { 3691 // We're building a user-defined literal. 3692 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3693 SourceLocation UDSuffixLoc = 3694 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3695 3696 // Make sure we're allowed user-defined literals here. 3697 if (!UDLScope) 3698 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3699 3700 QualType CookedTy; 3701 if (Literal.isFloatingLiteral()) { 3702 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3703 // long double, the literal is treated as a call of the form 3704 // operator "" X (f L) 3705 CookedTy = Context.LongDoubleTy; 3706 } else { 3707 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3708 // unsigned long long, the literal is treated as a call of the form 3709 // operator "" X (n ULL) 3710 CookedTy = Context.UnsignedLongLongTy; 3711 } 3712 3713 DeclarationName OpName = 3714 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3715 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3716 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3717 3718 SourceLocation TokLoc = Tok.getLocation(); 3719 3720 // Perform literal operator lookup to determine if we're building a raw 3721 // literal or a cooked one. 3722 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3723 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3724 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3725 /*AllowStringTemplatePack*/ false, 3726 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3727 case LOLR_ErrorNoDiagnostic: 3728 // Lookup failure for imaginary constants isn't fatal, there's still the 3729 // GNU extension producing _Complex types. 3730 break; 3731 case LOLR_Error: 3732 return ExprError(); 3733 case LOLR_Cooked: { 3734 Expr *Lit; 3735 if (Literal.isFloatingLiteral()) { 3736 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3737 } else { 3738 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3739 if (Literal.GetIntegerValue(ResultVal)) 3740 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3741 << /* Unsigned */ 1; 3742 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3743 Tok.getLocation()); 3744 } 3745 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3746 } 3747 3748 case LOLR_Raw: { 3749 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3750 // literal is treated as a call of the form 3751 // operator "" X ("n") 3752 unsigned Length = Literal.getUDSuffixOffset(); 3753 QualType StrTy = Context.getConstantArrayType( 3754 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3755 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3756 Expr *Lit = StringLiteral::Create( 3757 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3758 /*Pascal*/false, StrTy, &TokLoc, 1); 3759 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3760 } 3761 3762 case LOLR_Template: { 3763 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3764 // template), L is treated as a call fo the form 3765 // operator "" X <'c1', 'c2', ... 'ck'>() 3766 // where n is the source character sequence c1 c2 ... ck. 3767 TemplateArgumentListInfo ExplicitArgs; 3768 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3769 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3770 llvm::APSInt Value(CharBits, CharIsUnsigned); 3771 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3772 Value = TokSpelling[I]; 3773 TemplateArgument Arg(Context, Value, Context.CharTy); 3774 TemplateArgumentLocInfo ArgInfo; 3775 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3776 } 3777 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3778 &ExplicitArgs); 3779 } 3780 case LOLR_StringTemplatePack: 3781 llvm_unreachable("unexpected literal operator lookup result"); 3782 } 3783 } 3784 3785 Expr *Res; 3786 3787 if (Literal.isFixedPointLiteral()) { 3788 QualType Ty; 3789 3790 if (Literal.isAccum) { 3791 if (Literal.isHalf) { 3792 Ty = Context.ShortAccumTy; 3793 } else if (Literal.isLong) { 3794 Ty = Context.LongAccumTy; 3795 } else { 3796 Ty = Context.AccumTy; 3797 } 3798 } else if (Literal.isFract) { 3799 if (Literal.isHalf) { 3800 Ty = Context.ShortFractTy; 3801 } else if (Literal.isLong) { 3802 Ty = Context.LongFractTy; 3803 } else { 3804 Ty = Context.FractTy; 3805 } 3806 } 3807 3808 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3809 3810 bool isSigned = !Literal.isUnsigned; 3811 unsigned scale = Context.getFixedPointScale(Ty); 3812 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3813 3814 llvm::APInt Val(bit_width, 0, isSigned); 3815 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3816 bool ValIsZero = Val.isZero() && !Overflowed; 3817 3818 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3819 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3820 // Clause 6.4.4 - The value of a constant shall be in the range of 3821 // representable values for its type, with exception for constants of a 3822 // fract type with a value of exactly 1; such a constant shall denote 3823 // the maximal value for the type. 3824 --Val; 3825 else if (Val.ugt(MaxVal) || Overflowed) 3826 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3827 3828 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3829 Tok.getLocation(), scale); 3830 } else if (Literal.isFloatingLiteral()) { 3831 QualType Ty; 3832 if (Literal.isHalf){ 3833 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3834 Ty = Context.HalfTy; 3835 else { 3836 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3837 return ExprError(); 3838 } 3839 } else if (Literal.isFloat) 3840 Ty = Context.FloatTy; 3841 else if (Literal.isLong) 3842 Ty = Context.LongDoubleTy; 3843 else if (Literal.isFloat16) 3844 Ty = Context.Float16Ty; 3845 else if (Literal.isFloat128) 3846 Ty = Context.Float128Ty; 3847 else 3848 Ty = Context.DoubleTy; 3849 3850 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3851 3852 if (Ty == Context.DoubleTy) { 3853 if (getLangOpts().SinglePrecisionConstants) { 3854 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3855 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3856 } 3857 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3858 "cl_khr_fp64", getLangOpts())) { 3859 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3860 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3861 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3862 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3863 } 3864 } 3865 } else if (!Literal.isIntegerLiteral()) { 3866 return ExprError(); 3867 } else { 3868 QualType Ty; 3869 3870 // 'long long' is a C99 or C++11 feature. 3871 if (!getLangOpts().C99 && Literal.isLongLong) { 3872 if (getLangOpts().CPlusPlus) 3873 Diag(Tok.getLocation(), 3874 getLangOpts().CPlusPlus11 ? 3875 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3876 else 3877 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3878 } 3879 3880 // 'z/uz' literals are a C++2b feature. 3881 if (Literal.isSizeT) 3882 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3883 ? getLangOpts().CPlusPlus2b 3884 ? diag::warn_cxx20_compat_size_t_suffix 3885 : diag::ext_cxx2b_size_t_suffix 3886 : diag::err_cxx2b_size_t_suffix); 3887 3888 // Get the value in the widest-possible width. 3889 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3890 llvm::APInt ResultVal(MaxWidth, 0); 3891 3892 if (Literal.GetIntegerValue(ResultVal)) { 3893 // If this value didn't fit into uintmax_t, error and force to ull. 3894 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3895 << /* Unsigned */ 1; 3896 Ty = Context.UnsignedLongLongTy; 3897 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3898 "long long is not intmax_t?"); 3899 } else { 3900 // If this value fits into a ULL, try to figure out what else it fits into 3901 // according to the rules of C99 6.4.4.1p5. 3902 3903 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3904 // be an unsigned int. 3905 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3906 3907 // Check from smallest to largest, picking the smallest type we can. 3908 unsigned Width = 0; 3909 3910 // Microsoft specific integer suffixes are explicitly sized. 3911 if (Literal.MicrosoftInteger) { 3912 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3913 Width = 8; 3914 Ty = Context.CharTy; 3915 } else { 3916 Width = Literal.MicrosoftInteger; 3917 Ty = Context.getIntTypeForBitwidth(Width, 3918 /*Signed=*/!Literal.isUnsigned); 3919 } 3920 } 3921 3922 // Check C++2b size_t literals. 3923 if (Literal.isSizeT) { 3924 assert(!Literal.MicrosoftInteger && 3925 "size_t literals can't be Microsoft literals"); 3926 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3927 Context.getTargetInfo().getSizeType()); 3928 3929 // Does it fit in size_t? 3930 if (ResultVal.isIntN(SizeTSize)) { 3931 // Does it fit in ssize_t? 3932 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3933 Ty = Context.getSignedSizeType(); 3934 else if (AllowUnsigned) 3935 Ty = Context.getSizeType(); 3936 Width = SizeTSize; 3937 } 3938 } 3939 3940 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3941 !Literal.isSizeT) { 3942 // Are int/unsigned possibilities? 3943 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3944 3945 // Does it fit in a unsigned int? 3946 if (ResultVal.isIntN(IntSize)) { 3947 // Does it fit in a signed int? 3948 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3949 Ty = Context.IntTy; 3950 else if (AllowUnsigned) 3951 Ty = Context.UnsignedIntTy; 3952 Width = IntSize; 3953 } 3954 } 3955 3956 // Are long/unsigned long possibilities? 3957 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3958 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3959 3960 // Does it fit in a unsigned long? 3961 if (ResultVal.isIntN(LongSize)) { 3962 // Does it fit in a signed long? 3963 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3964 Ty = Context.LongTy; 3965 else if (AllowUnsigned) 3966 Ty = Context.UnsignedLongTy; 3967 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3968 // is compatible. 3969 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3970 const unsigned LongLongSize = 3971 Context.getTargetInfo().getLongLongWidth(); 3972 Diag(Tok.getLocation(), 3973 getLangOpts().CPlusPlus 3974 ? Literal.isLong 3975 ? diag::warn_old_implicitly_unsigned_long_cxx 3976 : /*C++98 UB*/ diag:: 3977 ext_old_implicitly_unsigned_long_cxx 3978 : diag::warn_old_implicitly_unsigned_long) 3979 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3980 : /*will be ill-formed*/ 1); 3981 Ty = Context.UnsignedLongTy; 3982 } 3983 Width = LongSize; 3984 } 3985 } 3986 3987 // Check long long if needed. 3988 if (Ty.isNull() && !Literal.isSizeT) { 3989 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3990 3991 // Does it fit in a unsigned long long? 3992 if (ResultVal.isIntN(LongLongSize)) { 3993 // Does it fit in a signed long long? 3994 // To be compatible with MSVC, hex integer literals ending with the 3995 // LL or i64 suffix are always signed in Microsoft mode. 3996 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3997 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3998 Ty = Context.LongLongTy; 3999 else if (AllowUnsigned) 4000 Ty = Context.UnsignedLongLongTy; 4001 Width = LongLongSize; 4002 } 4003 } 4004 4005 // If we still couldn't decide a type, we either have 'size_t' literal 4006 // that is out of range, or a decimal literal that does not fit in a 4007 // signed long long and has no U suffix. 4008 if (Ty.isNull()) { 4009 if (Literal.isSizeT) 4010 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4011 << Literal.isUnsigned; 4012 else 4013 Diag(Tok.getLocation(), 4014 diag::ext_integer_literal_too_large_for_signed); 4015 Ty = Context.UnsignedLongLongTy; 4016 Width = Context.getTargetInfo().getLongLongWidth(); 4017 } 4018 4019 if (ResultVal.getBitWidth() != Width) 4020 ResultVal = ResultVal.trunc(Width); 4021 } 4022 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4023 } 4024 4025 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4026 if (Literal.isImaginary) { 4027 Res = new (Context) ImaginaryLiteral(Res, 4028 Context.getComplexType(Res->getType())); 4029 4030 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4031 } 4032 return Res; 4033 } 4034 4035 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4036 assert(E && "ActOnParenExpr() missing expr"); 4037 QualType ExprTy = E->getType(); 4038 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4039 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4040 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4041 return new (Context) ParenExpr(L, R, E); 4042 } 4043 4044 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4045 SourceLocation Loc, 4046 SourceRange ArgRange) { 4047 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4048 // scalar or vector data type argument..." 4049 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4050 // type (C99 6.2.5p18) or void. 4051 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4052 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4053 << T << ArgRange; 4054 return true; 4055 } 4056 4057 assert((T->isVoidType() || !T->isIncompleteType()) && 4058 "Scalar types should always be complete"); 4059 return false; 4060 } 4061 4062 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4063 SourceLocation Loc, 4064 SourceRange ArgRange, 4065 UnaryExprOrTypeTrait TraitKind) { 4066 // Invalid types must be hard errors for SFINAE in C++. 4067 if (S.LangOpts.CPlusPlus) 4068 return true; 4069 4070 // C99 6.5.3.4p1: 4071 if (T->isFunctionType() && 4072 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4073 TraitKind == UETT_PreferredAlignOf)) { 4074 // sizeof(function)/alignof(function) is allowed as an extension. 4075 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4076 << getTraitSpelling(TraitKind) << ArgRange; 4077 return false; 4078 } 4079 4080 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4081 // this is an error (OpenCL v1.1 s6.3.k) 4082 if (T->isVoidType()) { 4083 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4084 : diag::ext_sizeof_alignof_void_type; 4085 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4086 return false; 4087 } 4088 4089 return true; 4090 } 4091 4092 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4093 SourceLocation Loc, 4094 SourceRange ArgRange, 4095 UnaryExprOrTypeTrait TraitKind) { 4096 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4097 // runtime doesn't allow it. 4098 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4099 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4100 << T << (TraitKind == UETT_SizeOf) 4101 << ArgRange; 4102 return true; 4103 } 4104 4105 return false; 4106 } 4107 4108 /// Check whether E is a pointer from a decayed array type (the decayed 4109 /// pointer type is equal to T) and emit a warning if it is. 4110 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4111 Expr *E) { 4112 // Don't warn if the operation changed the type. 4113 if (T != E->getType()) 4114 return; 4115 4116 // Now look for array decays. 4117 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4118 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4119 return; 4120 4121 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4122 << ICE->getType() 4123 << ICE->getSubExpr()->getType(); 4124 } 4125 4126 /// Check the constraints on expression operands to unary type expression 4127 /// and type traits. 4128 /// 4129 /// Completes any types necessary and validates the constraints on the operand 4130 /// expression. The logic mostly mirrors the type-based overload, but may modify 4131 /// the expression as it completes the type for that expression through template 4132 /// instantiation, etc. 4133 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4134 UnaryExprOrTypeTrait ExprKind) { 4135 QualType ExprTy = E->getType(); 4136 assert(!ExprTy->isReferenceType()); 4137 4138 bool IsUnevaluatedOperand = 4139 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4140 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4141 if (IsUnevaluatedOperand) { 4142 ExprResult Result = CheckUnevaluatedOperand(E); 4143 if (Result.isInvalid()) 4144 return true; 4145 E = Result.get(); 4146 } 4147 4148 // The operand for sizeof and alignof is in an unevaluated expression context, 4149 // so side effects could result in unintended consequences. 4150 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4151 // used to build SFINAE gadgets. 4152 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4153 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4154 !E->isInstantiationDependent() && 4155 E->HasSideEffects(Context, false)) 4156 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4157 4158 if (ExprKind == UETT_VecStep) 4159 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4160 E->getSourceRange()); 4161 4162 // Explicitly list some types as extensions. 4163 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4164 E->getSourceRange(), ExprKind)) 4165 return false; 4166 4167 // 'alignof' applied to an expression only requires the base element type of 4168 // the expression to be complete. 'sizeof' requires the expression's type to 4169 // be complete (and will attempt to complete it if it's an array of unknown 4170 // bound). 4171 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4172 if (RequireCompleteSizedType( 4173 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4174 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4175 getTraitSpelling(ExprKind), E->getSourceRange())) 4176 return true; 4177 } else { 4178 if (RequireCompleteSizedExprType( 4179 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4180 getTraitSpelling(ExprKind), E->getSourceRange())) 4181 return true; 4182 } 4183 4184 // Completing the expression's type may have changed it. 4185 ExprTy = E->getType(); 4186 assert(!ExprTy->isReferenceType()); 4187 4188 if (ExprTy->isFunctionType()) { 4189 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4190 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4191 return true; 4192 } 4193 4194 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4195 E->getSourceRange(), ExprKind)) 4196 return true; 4197 4198 if (ExprKind == UETT_SizeOf) { 4199 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4200 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4201 QualType OType = PVD->getOriginalType(); 4202 QualType Type = PVD->getType(); 4203 if (Type->isPointerType() && OType->isArrayType()) { 4204 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4205 << Type << OType; 4206 Diag(PVD->getLocation(), diag::note_declared_at); 4207 } 4208 } 4209 } 4210 4211 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4212 // decays into a pointer and returns an unintended result. This is most 4213 // likely a typo for "sizeof(array) op x". 4214 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4215 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4216 BO->getLHS()); 4217 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4218 BO->getRHS()); 4219 } 4220 } 4221 4222 return false; 4223 } 4224 4225 /// Check the constraints on operands to unary expression and type 4226 /// traits. 4227 /// 4228 /// This will complete any types necessary, and validate the various constraints 4229 /// on those operands. 4230 /// 4231 /// The UsualUnaryConversions() function is *not* called by this routine. 4232 /// C99 6.3.2.1p[2-4] all state: 4233 /// Except when it is the operand of the sizeof operator ... 4234 /// 4235 /// C++ [expr.sizeof]p4 4236 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4237 /// standard conversions are not applied to the operand of sizeof. 4238 /// 4239 /// This policy is followed for all of the unary trait expressions. 4240 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4241 SourceLocation OpLoc, 4242 SourceRange ExprRange, 4243 UnaryExprOrTypeTrait ExprKind) { 4244 if (ExprType->isDependentType()) 4245 return false; 4246 4247 // C++ [expr.sizeof]p2: 4248 // When applied to a reference or a reference type, the result 4249 // is the size of the referenced type. 4250 // C++11 [expr.alignof]p3: 4251 // When alignof is applied to a reference type, the result 4252 // shall be the alignment of the referenced type. 4253 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4254 ExprType = Ref->getPointeeType(); 4255 4256 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4257 // When alignof or _Alignof is applied to an array type, the result 4258 // is the alignment of the element type. 4259 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4260 ExprKind == UETT_OpenMPRequiredSimdAlign) 4261 ExprType = Context.getBaseElementType(ExprType); 4262 4263 if (ExprKind == UETT_VecStep) 4264 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4265 4266 // Explicitly list some types as extensions. 4267 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4268 ExprKind)) 4269 return false; 4270 4271 if (RequireCompleteSizedType( 4272 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4273 getTraitSpelling(ExprKind), ExprRange)) 4274 return true; 4275 4276 if (ExprType->isFunctionType()) { 4277 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4278 << getTraitSpelling(ExprKind) << ExprRange; 4279 return true; 4280 } 4281 4282 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4283 ExprKind)) 4284 return true; 4285 4286 return false; 4287 } 4288 4289 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4290 // Cannot know anything else if the expression is dependent. 4291 if (E->isTypeDependent()) 4292 return false; 4293 4294 if (E->getObjectKind() == OK_BitField) { 4295 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4296 << 1 << E->getSourceRange(); 4297 return true; 4298 } 4299 4300 ValueDecl *D = nullptr; 4301 Expr *Inner = E->IgnoreParens(); 4302 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4303 D = DRE->getDecl(); 4304 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4305 D = ME->getMemberDecl(); 4306 } 4307 4308 // If it's a field, require the containing struct to have a 4309 // complete definition so that we can compute the layout. 4310 // 4311 // This can happen in C++11 onwards, either by naming the member 4312 // in a way that is not transformed into a member access expression 4313 // (in an unevaluated operand, for instance), or by naming the member 4314 // in a trailing-return-type. 4315 // 4316 // For the record, since __alignof__ on expressions is a GCC 4317 // extension, GCC seems to permit this but always gives the 4318 // nonsensical answer 0. 4319 // 4320 // We don't really need the layout here --- we could instead just 4321 // directly check for all the appropriate alignment-lowing 4322 // attributes --- but that would require duplicating a lot of 4323 // logic that just isn't worth duplicating for such a marginal 4324 // use-case. 4325 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4326 // Fast path this check, since we at least know the record has a 4327 // definition if we can find a member of it. 4328 if (!FD->getParent()->isCompleteDefinition()) { 4329 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4330 << E->getSourceRange(); 4331 return true; 4332 } 4333 4334 // Otherwise, if it's a field, and the field doesn't have 4335 // reference type, then it must have a complete type (or be a 4336 // flexible array member, which we explicitly want to 4337 // white-list anyway), which makes the following checks trivial. 4338 if (!FD->getType()->isReferenceType()) 4339 return false; 4340 } 4341 4342 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4343 } 4344 4345 bool Sema::CheckVecStepExpr(Expr *E) { 4346 E = E->IgnoreParens(); 4347 4348 // Cannot know anything else if the expression is dependent. 4349 if (E->isTypeDependent()) 4350 return false; 4351 4352 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4353 } 4354 4355 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4356 CapturingScopeInfo *CSI) { 4357 assert(T->isVariablyModifiedType()); 4358 assert(CSI != nullptr); 4359 4360 // We're going to walk down into the type and look for VLA expressions. 4361 do { 4362 const Type *Ty = T.getTypePtr(); 4363 switch (Ty->getTypeClass()) { 4364 #define TYPE(Class, Base) 4365 #define ABSTRACT_TYPE(Class, Base) 4366 #define NON_CANONICAL_TYPE(Class, Base) 4367 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4368 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4369 #include "clang/AST/TypeNodes.inc" 4370 T = QualType(); 4371 break; 4372 // These types are never variably-modified. 4373 case Type::Builtin: 4374 case Type::Complex: 4375 case Type::Vector: 4376 case Type::ExtVector: 4377 case Type::ConstantMatrix: 4378 case Type::Record: 4379 case Type::Enum: 4380 case Type::Elaborated: 4381 case Type::TemplateSpecialization: 4382 case Type::ObjCObject: 4383 case Type::ObjCInterface: 4384 case Type::ObjCObjectPointer: 4385 case Type::ObjCTypeParam: 4386 case Type::Pipe: 4387 case Type::BitInt: 4388 llvm_unreachable("type class is never variably-modified!"); 4389 case Type::Adjusted: 4390 T = cast<AdjustedType>(Ty)->getOriginalType(); 4391 break; 4392 case Type::Decayed: 4393 T = cast<DecayedType>(Ty)->getPointeeType(); 4394 break; 4395 case Type::Pointer: 4396 T = cast<PointerType>(Ty)->getPointeeType(); 4397 break; 4398 case Type::BlockPointer: 4399 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4400 break; 4401 case Type::LValueReference: 4402 case Type::RValueReference: 4403 T = cast<ReferenceType>(Ty)->getPointeeType(); 4404 break; 4405 case Type::MemberPointer: 4406 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4407 break; 4408 case Type::ConstantArray: 4409 case Type::IncompleteArray: 4410 // Losing element qualification here is fine. 4411 T = cast<ArrayType>(Ty)->getElementType(); 4412 break; 4413 case Type::VariableArray: { 4414 // Losing element qualification here is fine. 4415 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4416 4417 // Unknown size indication requires no size computation. 4418 // Otherwise, evaluate and record it. 4419 auto Size = VAT->getSizeExpr(); 4420 if (Size && !CSI->isVLATypeCaptured(VAT) && 4421 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4422 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4423 4424 T = VAT->getElementType(); 4425 break; 4426 } 4427 case Type::FunctionProto: 4428 case Type::FunctionNoProto: 4429 T = cast<FunctionType>(Ty)->getReturnType(); 4430 break; 4431 case Type::Paren: 4432 case Type::TypeOf: 4433 case Type::UnaryTransform: 4434 case Type::Attributed: 4435 case Type::SubstTemplateTypeParm: 4436 case Type::MacroQualified: 4437 // Keep walking after single level desugaring. 4438 T = T.getSingleStepDesugaredType(Context); 4439 break; 4440 case Type::Typedef: 4441 T = cast<TypedefType>(Ty)->desugar(); 4442 break; 4443 case Type::Decltype: 4444 T = cast<DecltypeType>(Ty)->desugar(); 4445 break; 4446 case Type::Using: 4447 T = cast<UsingType>(Ty)->desugar(); 4448 break; 4449 case Type::Auto: 4450 case Type::DeducedTemplateSpecialization: 4451 T = cast<DeducedType>(Ty)->getDeducedType(); 4452 break; 4453 case Type::TypeOfExpr: 4454 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4455 break; 4456 case Type::Atomic: 4457 T = cast<AtomicType>(Ty)->getValueType(); 4458 break; 4459 } 4460 } while (!T.isNull() && T->isVariablyModifiedType()); 4461 } 4462 4463 /// Build a sizeof or alignof expression given a type operand. 4464 ExprResult 4465 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4466 SourceLocation OpLoc, 4467 UnaryExprOrTypeTrait ExprKind, 4468 SourceRange R) { 4469 if (!TInfo) 4470 return ExprError(); 4471 4472 QualType T = TInfo->getType(); 4473 4474 if (!T->isDependentType() && 4475 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4476 return ExprError(); 4477 4478 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4479 if (auto *TT = T->getAs<TypedefType>()) { 4480 for (auto I = FunctionScopes.rbegin(), 4481 E = std::prev(FunctionScopes.rend()); 4482 I != E; ++I) { 4483 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4484 if (CSI == nullptr) 4485 break; 4486 DeclContext *DC = nullptr; 4487 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4488 DC = LSI->CallOperator; 4489 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4490 DC = CRSI->TheCapturedDecl; 4491 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4492 DC = BSI->TheDecl; 4493 if (DC) { 4494 if (DC->containsDecl(TT->getDecl())) 4495 break; 4496 captureVariablyModifiedType(Context, T, CSI); 4497 } 4498 } 4499 } 4500 } 4501 4502 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4503 return new (Context) UnaryExprOrTypeTraitExpr( 4504 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4505 } 4506 4507 /// Build a sizeof or alignof expression given an expression 4508 /// operand. 4509 ExprResult 4510 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4511 UnaryExprOrTypeTrait ExprKind) { 4512 ExprResult PE = CheckPlaceholderExpr(E); 4513 if (PE.isInvalid()) 4514 return ExprError(); 4515 4516 E = PE.get(); 4517 4518 // Verify that the operand is valid. 4519 bool isInvalid = false; 4520 if (E->isTypeDependent()) { 4521 // Delay type-checking for type-dependent expressions. 4522 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4523 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4524 } else if (ExprKind == UETT_VecStep) { 4525 isInvalid = CheckVecStepExpr(E); 4526 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4527 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4528 isInvalid = true; 4529 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4530 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4531 isInvalid = true; 4532 } else { 4533 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4534 } 4535 4536 if (isInvalid) 4537 return ExprError(); 4538 4539 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4540 PE = TransformToPotentiallyEvaluated(E); 4541 if (PE.isInvalid()) return ExprError(); 4542 E = PE.get(); 4543 } 4544 4545 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4546 return new (Context) UnaryExprOrTypeTraitExpr( 4547 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4548 } 4549 4550 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4551 /// expr and the same for @c alignof and @c __alignof 4552 /// Note that the ArgRange is invalid if isType is false. 4553 ExprResult 4554 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4555 UnaryExprOrTypeTrait ExprKind, bool IsType, 4556 void *TyOrEx, SourceRange ArgRange) { 4557 // If error parsing type, ignore. 4558 if (!TyOrEx) return ExprError(); 4559 4560 if (IsType) { 4561 TypeSourceInfo *TInfo; 4562 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4563 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4564 } 4565 4566 Expr *ArgEx = (Expr *)TyOrEx; 4567 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4568 return Result; 4569 } 4570 4571 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4572 bool IsReal) { 4573 if (V.get()->isTypeDependent()) 4574 return S.Context.DependentTy; 4575 4576 // _Real and _Imag are only l-values for normal l-values. 4577 if (V.get()->getObjectKind() != OK_Ordinary) { 4578 V = S.DefaultLvalueConversion(V.get()); 4579 if (V.isInvalid()) 4580 return QualType(); 4581 } 4582 4583 // These operators return the element type of a complex type. 4584 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4585 return CT->getElementType(); 4586 4587 // Otherwise they pass through real integer and floating point types here. 4588 if (V.get()->getType()->isArithmeticType()) 4589 return V.get()->getType(); 4590 4591 // Test for placeholders. 4592 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4593 if (PR.isInvalid()) return QualType(); 4594 if (PR.get() != V.get()) { 4595 V = PR; 4596 return CheckRealImagOperand(S, V, Loc, IsReal); 4597 } 4598 4599 // Reject anything else. 4600 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4601 << (IsReal ? "__real" : "__imag"); 4602 return QualType(); 4603 } 4604 4605 4606 4607 ExprResult 4608 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4609 tok::TokenKind Kind, Expr *Input) { 4610 UnaryOperatorKind Opc; 4611 switch (Kind) { 4612 default: llvm_unreachable("Unknown unary op!"); 4613 case tok::plusplus: Opc = UO_PostInc; break; 4614 case tok::minusminus: Opc = UO_PostDec; break; 4615 } 4616 4617 // Since this might is a postfix expression, get rid of ParenListExprs. 4618 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4619 if (Result.isInvalid()) return ExprError(); 4620 Input = Result.get(); 4621 4622 return BuildUnaryOp(S, OpLoc, Opc, Input); 4623 } 4624 4625 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4626 /// 4627 /// \return true on error 4628 static bool checkArithmeticOnObjCPointer(Sema &S, 4629 SourceLocation opLoc, 4630 Expr *op) { 4631 assert(op->getType()->isObjCObjectPointerType()); 4632 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4633 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4634 return false; 4635 4636 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4637 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4638 << op->getSourceRange(); 4639 return true; 4640 } 4641 4642 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4643 auto *BaseNoParens = Base->IgnoreParens(); 4644 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4645 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4646 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4647 } 4648 4649 ExprResult 4650 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4651 Expr *idx, SourceLocation rbLoc) { 4652 if (base && !base->getType().isNull() && 4653 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4654 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4655 SourceLocation(), /*Length*/ nullptr, 4656 /*Stride=*/nullptr, rbLoc); 4657 4658 // Since this might be a postfix expression, get rid of ParenListExprs. 4659 if (isa<ParenListExpr>(base)) { 4660 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4661 if (result.isInvalid()) return ExprError(); 4662 base = result.get(); 4663 } 4664 4665 // Check if base and idx form a MatrixSubscriptExpr. 4666 // 4667 // Helper to check for comma expressions, which are not allowed as indices for 4668 // matrix subscript expressions. 4669 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4670 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4671 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4672 << SourceRange(base->getBeginLoc(), rbLoc); 4673 return true; 4674 } 4675 return false; 4676 }; 4677 // The matrix subscript operator ([][])is considered a single operator. 4678 // Separating the index expressions by parenthesis is not allowed. 4679 if (base->getType()->isSpecificPlaceholderType( 4680 BuiltinType::IncompleteMatrixIdx) && 4681 !isa<MatrixSubscriptExpr>(base)) { 4682 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4683 << SourceRange(base->getBeginLoc(), rbLoc); 4684 return ExprError(); 4685 } 4686 // If the base is a MatrixSubscriptExpr, try to create a new 4687 // MatrixSubscriptExpr. 4688 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4689 if (matSubscriptE) { 4690 if (CheckAndReportCommaError(idx)) 4691 return ExprError(); 4692 4693 assert(matSubscriptE->isIncomplete() && 4694 "base has to be an incomplete matrix subscript"); 4695 return CreateBuiltinMatrixSubscriptExpr( 4696 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4697 } 4698 4699 // Handle any non-overload placeholder types in the base and index 4700 // expressions. We can't handle overloads here because the other 4701 // operand might be an overloadable type, in which case the overload 4702 // resolution for the operator overload should get the first crack 4703 // at the overload. 4704 bool IsMSPropertySubscript = false; 4705 if (base->getType()->isNonOverloadPlaceholderType()) { 4706 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4707 if (!IsMSPropertySubscript) { 4708 ExprResult result = CheckPlaceholderExpr(base); 4709 if (result.isInvalid()) 4710 return ExprError(); 4711 base = result.get(); 4712 } 4713 } 4714 4715 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4716 if (base->getType()->isMatrixType()) { 4717 if (CheckAndReportCommaError(idx)) 4718 return ExprError(); 4719 4720 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4721 } 4722 4723 // A comma-expression as the index is deprecated in C++2a onwards. 4724 if (getLangOpts().CPlusPlus20 && 4725 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4726 (isa<CXXOperatorCallExpr>(idx) && 4727 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4728 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4729 << SourceRange(base->getBeginLoc(), rbLoc); 4730 } 4731 4732 if (idx->getType()->isNonOverloadPlaceholderType()) { 4733 ExprResult result = CheckPlaceholderExpr(idx); 4734 if (result.isInvalid()) return ExprError(); 4735 idx = result.get(); 4736 } 4737 4738 // Build an unanalyzed expression if either operand is type-dependent. 4739 if (getLangOpts().CPlusPlus && 4740 (base->isTypeDependent() || idx->isTypeDependent())) { 4741 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4742 VK_LValue, OK_Ordinary, rbLoc); 4743 } 4744 4745 // MSDN, property (C++) 4746 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4747 // This attribute can also be used in the declaration of an empty array in a 4748 // class or structure definition. For example: 4749 // __declspec(property(get=GetX, put=PutX)) int x[]; 4750 // The above statement indicates that x[] can be used with one or more array 4751 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4752 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4753 if (IsMSPropertySubscript) { 4754 // Build MS property subscript expression if base is MS property reference 4755 // or MS property subscript. 4756 return new (Context) MSPropertySubscriptExpr( 4757 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4758 } 4759 4760 // Use C++ overloaded-operator rules if either operand has record 4761 // type. The spec says to do this if either type is *overloadable*, 4762 // but enum types can't declare subscript operators or conversion 4763 // operators, so there's nothing interesting for overload resolution 4764 // to do if there aren't any record types involved. 4765 // 4766 // ObjC pointers have their own subscripting logic that is not tied 4767 // to overload resolution and so should not take this path. 4768 if (getLangOpts().CPlusPlus && 4769 (base->getType()->isRecordType() || 4770 (!base->getType()->isObjCObjectPointerType() && 4771 idx->getType()->isRecordType()))) { 4772 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4773 } 4774 4775 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4776 4777 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4778 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4779 4780 return Res; 4781 } 4782 4783 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4784 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4785 InitializationKind Kind = 4786 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4787 InitializationSequence InitSeq(*this, Entity, Kind, E); 4788 return InitSeq.Perform(*this, Entity, Kind, E); 4789 } 4790 4791 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4792 Expr *ColumnIdx, 4793 SourceLocation RBLoc) { 4794 ExprResult BaseR = CheckPlaceholderExpr(Base); 4795 if (BaseR.isInvalid()) 4796 return BaseR; 4797 Base = BaseR.get(); 4798 4799 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4800 if (RowR.isInvalid()) 4801 return RowR; 4802 RowIdx = RowR.get(); 4803 4804 if (!ColumnIdx) 4805 return new (Context) MatrixSubscriptExpr( 4806 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4807 4808 // Build an unanalyzed expression if any of the operands is type-dependent. 4809 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4810 ColumnIdx->isTypeDependent()) 4811 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4812 Context.DependentTy, RBLoc); 4813 4814 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4815 if (ColumnR.isInvalid()) 4816 return ColumnR; 4817 ColumnIdx = ColumnR.get(); 4818 4819 // Check that IndexExpr is an integer expression. If it is a constant 4820 // expression, check that it is less than Dim (= the number of elements in the 4821 // corresponding dimension). 4822 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4823 bool IsColumnIdx) -> Expr * { 4824 if (!IndexExpr->getType()->isIntegerType() && 4825 !IndexExpr->isTypeDependent()) { 4826 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4827 << IsColumnIdx; 4828 return nullptr; 4829 } 4830 4831 if (Optional<llvm::APSInt> Idx = 4832 IndexExpr->getIntegerConstantExpr(Context)) { 4833 if ((*Idx < 0 || *Idx >= Dim)) { 4834 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4835 << IsColumnIdx << Dim; 4836 return nullptr; 4837 } 4838 } 4839 4840 ExprResult ConvExpr = 4841 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4842 assert(!ConvExpr.isInvalid() && 4843 "should be able to convert any integer type to size type"); 4844 return ConvExpr.get(); 4845 }; 4846 4847 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4848 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4849 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4850 if (!RowIdx || !ColumnIdx) 4851 return ExprError(); 4852 4853 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4854 MTy->getElementType(), RBLoc); 4855 } 4856 4857 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4858 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4859 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4860 4861 // For expressions like `&(*s).b`, the base is recorded and what should be 4862 // checked. 4863 const MemberExpr *Member = nullptr; 4864 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4865 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4866 4867 LastRecord.PossibleDerefs.erase(StrippedExpr); 4868 } 4869 4870 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4871 if (isUnevaluatedContext()) 4872 return; 4873 4874 QualType ResultTy = E->getType(); 4875 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4876 4877 // Bail if the element is an array since it is not memory access. 4878 if (isa<ArrayType>(ResultTy)) 4879 return; 4880 4881 if (ResultTy->hasAttr(attr::NoDeref)) { 4882 LastRecord.PossibleDerefs.insert(E); 4883 return; 4884 } 4885 4886 // Check if the base type is a pointer to a member access of a struct 4887 // marked with noderef. 4888 const Expr *Base = E->getBase(); 4889 QualType BaseTy = Base->getType(); 4890 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4891 // Not a pointer access 4892 return; 4893 4894 const MemberExpr *Member = nullptr; 4895 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4896 Member->isArrow()) 4897 Base = Member->getBase(); 4898 4899 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4900 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4901 LastRecord.PossibleDerefs.insert(E); 4902 } 4903 } 4904 4905 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4906 Expr *LowerBound, 4907 SourceLocation ColonLocFirst, 4908 SourceLocation ColonLocSecond, 4909 Expr *Length, Expr *Stride, 4910 SourceLocation RBLoc) { 4911 if (Base->getType()->isPlaceholderType() && 4912 !Base->getType()->isSpecificPlaceholderType( 4913 BuiltinType::OMPArraySection)) { 4914 ExprResult Result = CheckPlaceholderExpr(Base); 4915 if (Result.isInvalid()) 4916 return ExprError(); 4917 Base = Result.get(); 4918 } 4919 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4920 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4921 if (Result.isInvalid()) 4922 return ExprError(); 4923 Result = DefaultLvalueConversion(Result.get()); 4924 if (Result.isInvalid()) 4925 return ExprError(); 4926 LowerBound = Result.get(); 4927 } 4928 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4929 ExprResult Result = CheckPlaceholderExpr(Length); 4930 if (Result.isInvalid()) 4931 return ExprError(); 4932 Result = DefaultLvalueConversion(Result.get()); 4933 if (Result.isInvalid()) 4934 return ExprError(); 4935 Length = Result.get(); 4936 } 4937 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4938 ExprResult Result = CheckPlaceholderExpr(Stride); 4939 if (Result.isInvalid()) 4940 return ExprError(); 4941 Result = DefaultLvalueConversion(Result.get()); 4942 if (Result.isInvalid()) 4943 return ExprError(); 4944 Stride = Result.get(); 4945 } 4946 4947 // Build an unanalyzed expression if either operand is type-dependent. 4948 if (Base->isTypeDependent() || 4949 (LowerBound && 4950 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4951 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4952 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4953 return new (Context) OMPArraySectionExpr( 4954 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4955 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4956 } 4957 4958 // Perform default conversions. 4959 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4960 QualType ResultTy; 4961 if (OriginalTy->isAnyPointerType()) { 4962 ResultTy = OriginalTy->getPointeeType(); 4963 } else if (OriginalTy->isArrayType()) { 4964 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4965 } else { 4966 return ExprError( 4967 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4968 << Base->getSourceRange()); 4969 } 4970 // C99 6.5.2.1p1 4971 if (LowerBound) { 4972 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4973 LowerBound); 4974 if (Res.isInvalid()) 4975 return ExprError(Diag(LowerBound->getExprLoc(), 4976 diag::err_omp_typecheck_section_not_integer) 4977 << 0 << LowerBound->getSourceRange()); 4978 LowerBound = Res.get(); 4979 4980 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4981 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4982 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4983 << 0 << LowerBound->getSourceRange(); 4984 } 4985 if (Length) { 4986 auto Res = 4987 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4988 if (Res.isInvalid()) 4989 return ExprError(Diag(Length->getExprLoc(), 4990 diag::err_omp_typecheck_section_not_integer) 4991 << 1 << Length->getSourceRange()); 4992 Length = Res.get(); 4993 4994 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4995 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4996 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4997 << 1 << Length->getSourceRange(); 4998 } 4999 if (Stride) { 5000 ExprResult Res = 5001 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5002 if (Res.isInvalid()) 5003 return ExprError(Diag(Stride->getExprLoc(), 5004 diag::err_omp_typecheck_section_not_integer) 5005 << 1 << Stride->getSourceRange()); 5006 Stride = Res.get(); 5007 5008 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5009 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5010 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5011 << 1 << Stride->getSourceRange(); 5012 } 5013 5014 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5015 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5016 // type. Note that functions are not objects, and that (in C99 parlance) 5017 // incomplete types are not object types. 5018 if (ResultTy->isFunctionType()) { 5019 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5020 << ResultTy << Base->getSourceRange(); 5021 return ExprError(); 5022 } 5023 5024 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5025 diag::err_omp_section_incomplete_type, Base)) 5026 return ExprError(); 5027 5028 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5029 Expr::EvalResult Result; 5030 if (LowerBound->EvaluateAsInt(Result, Context)) { 5031 // OpenMP 5.0, [2.1.5 Array Sections] 5032 // The array section must be a subset of the original array. 5033 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5034 if (LowerBoundValue.isNegative()) { 5035 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5036 << LowerBound->getSourceRange(); 5037 return ExprError(); 5038 } 5039 } 5040 } 5041 5042 if (Length) { 5043 Expr::EvalResult Result; 5044 if (Length->EvaluateAsInt(Result, Context)) { 5045 // OpenMP 5.0, [2.1.5 Array Sections] 5046 // The length must evaluate to non-negative integers. 5047 llvm::APSInt LengthValue = Result.Val.getInt(); 5048 if (LengthValue.isNegative()) { 5049 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5050 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5051 << Length->getSourceRange(); 5052 return ExprError(); 5053 } 5054 } 5055 } else if (ColonLocFirst.isValid() && 5056 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5057 !OriginalTy->isVariableArrayType()))) { 5058 // OpenMP 5.0, [2.1.5 Array Sections] 5059 // When the size of the array dimension is not known, the length must be 5060 // specified explicitly. 5061 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5062 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5063 return ExprError(); 5064 } 5065 5066 if (Stride) { 5067 Expr::EvalResult Result; 5068 if (Stride->EvaluateAsInt(Result, Context)) { 5069 // OpenMP 5.0, [2.1.5 Array Sections] 5070 // The stride must evaluate to a positive integer. 5071 llvm::APSInt StrideValue = Result.Val.getInt(); 5072 if (!StrideValue.isStrictlyPositive()) { 5073 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5074 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5075 << Stride->getSourceRange(); 5076 return ExprError(); 5077 } 5078 } 5079 } 5080 5081 if (!Base->getType()->isSpecificPlaceholderType( 5082 BuiltinType::OMPArraySection)) { 5083 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5084 if (Result.isInvalid()) 5085 return ExprError(); 5086 Base = Result.get(); 5087 } 5088 return new (Context) OMPArraySectionExpr( 5089 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5090 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5091 } 5092 5093 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5094 SourceLocation RParenLoc, 5095 ArrayRef<Expr *> Dims, 5096 ArrayRef<SourceRange> Brackets) { 5097 if (Base->getType()->isPlaceholderType()) { 5098 ExprResult Result = CheckPlaceholderExpr(Base); 5099 if (Result.isInvalid()) 5100 return ExprError(); 5101 Result = DefaultLvalueConversion(Result.get()); 5102 if (Result.isInvalid()) 5103 return ExprError(); 5104 Base = Result.get(); 5105 } 5106 QualType BaseTy = Base->getType(); 5107 // Delay analysis of the types/expressions if instantiation/specialization is 5108 // required. 5109 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5110 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5111 LParenLoc, RParenLoc, Dims, Brackets); 5112 if (!BaseTy->isPointerType() || 5113 (!Base->isTypeDependent() && 5114 BaseTy->getPointeeType()->isIncompleteType())) 5115 return ExprError(Diag(Base->getExprLoc(), 5116 diag::err_omp_non_pointer_type_array_shaping_base) 5117 << Base->getSourceRange()); 5118 5119 SmallVector<Expr *, 4> NewDims; 5120 bool ErrorFound = false; 5121 for (Expr *Dim : Dims) { 5122 if (Dim->getType()->isPlaceholderType()) { 5123 ExprResult Result = CheckPlaceholderExpr(Dim); 5124 if (Result.isInvalid()) { 5125 ErrorFound = true; 5126 continue; 5127 } 5128 Result = DefaultLvalueConversion(Result.get()); 5129 if (Result.isInvalid()) { 5130 ErrorFound = true; 5131 continue; 5132 } 5133 Dim = Result.get(); 5134 } 5135 if (!Dim->isTypeDependent()) { 5136 ExprResult Result = 5137 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5138 if (Result.isInvalid()) { 5139 ErrorFound = true; 5140 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5141 << Dim->getSourceRange(); 5142 continue; 5143 } 5144 Dim = Result.get(); 5145 Expr::EvalResult EvResult; 5146 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5147 // OpenMP 5.0, [2.1.4 Array Shaping] 5148 // Each si is an integral type expression that must evaluate to a 5149 // positive integer. 5150 llvm::APSInt Value = EvResult.Val.getInt(); 5151 if (!Value.isStrictlyPositive()) { 5152 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5153 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5154 << Dim->getSourceRange(); 5155 ErrorFound = true; 5156 continue; 5157 } 5158 } 5159 } 5160 NewDims.push_back(Dim); 5161 } 5162 if (ErrorFound) 5163 return ExprError(); 5164 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5165 LParenLoc, RParenLoc, NewDims, Brackets); 5166 } 5167 5168 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5169 SourceLocation LLoc, SourceLocation RLoc, 5170 ArrayRef<OMPIteratorData> Data) { 5171 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5172 bool IsCorrect = true; 5173 for (const OMPIteratorData &D : Data) { 5174 TypeSourceInfo *TInfo = nullptr; 5175 SourceLocation StartLoc; 5176 QualType DeclTy; 5177 if (!D.Type.getAsOpaquePtr()) { 5178 // OpenMP 5.0, 2.1.6 Iterators 5179 // In an iterator-specifier, if the iterator-type is not specified then 5180 // the type of that iterator is of int type. 5181 DeclTy = Context.IntTy; 5182 StartLoc = D.DeclIdentLoc; 5183 } else { 5184 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5185 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5186 } 5187 5188 bool IsDeclTyDependent = DeclTy->isDependentType() || 5189 DeclTy->containsUnexpandedParameterPack() || 5190 DeclTy->isInstantiationDependentType(); 5191 if (!IsDeclTyDependent) { 5192 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5193 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5194 // The iterator-type must be an integral or pointer type. 5195 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5196 << DeclTy; 5197 IsCorrect = false; 5198 continue; 5199 } 5200 if (DeclTy.isConstant(Context)) { 5201 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5202 // The iterator-type must not be const qualified. 5203 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5204 << DeclTy; 5205 IsCorrect = false; 5206 continue; 5207 } 5208 } 5209 5210 // Iterator declaration. 5211 assert(D.DeclIdent && "Identifier expected."); 5212 // Always try to create iterator declarator to avoid extra error messages 5213 // about unknown declarations use. 5214 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5215 D.DeclIdent, DeclTy, TInfo, SC_None); 5216 VD->setImplicit(); 5217 if (S) { 5218 // Check for conflicting previous declaration. 5219 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5220 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5221 ForVisibleRedeclaration); 5222 Previous.suppressDiagnostics(); 5223 LookupName(Previous, S); 5224 5225 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5226 /*AllowInlineNamespace=*/false); 5227 if (!Previous.empty()) { 5228 NamedDecl *Old = Previous.getRepresentativeDecl(); 5229 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5230 Diag(Old->getLocation(), diag::note_previous_definition); 5231 } else { 5232 PushOnScopeChains(VD, S); 5233 } 5234 } else { 5235 CurContext->addDecl(VD); 5236 } 5237 Expr *Begin = D.Range.Begin; 5238 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5239 ExprResult BeginRes = 5240 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5241 Begin = BeginRes.get(); 5242 } 5243 Expr *End = D.Range.End; 5244 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5245 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5246 End = EndRes.get(); 5247 } 5248 Expr *Step = D.Range.Step; 5249 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5250 if (!Step->getType()->isIntegralType(Context)) { 5251 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5252 << Step << Step->getSourceRange(); 5253 IsCorrect = false; 5254 continue; 5255 } 5256 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5257 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5258 // If the step expression of a range-specification equals zero, the 5259 // behavior is unspecified. 5260 if (Result && Result->isZero()) { 5261 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5262 << Step << Step->getSourceRange(); 5263 IsCorrect = false; 5264 continue; 5265 } 5266 } 5267 if (!Begin || !End || !IsCorrect) { 5268 IsCorrect = false; 5269 continue; 5270 } 5271 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5272 IDElem.IteratorDecl = VD; 5273 IDElem.AssignmentLoc = D.AssignLoc; 5274 IDElem.Range.Begin = Begin; 5275 IDElem.Range.End = End; 5276 IDElem.Range.Step = Step; 5277 IDElem.ColonLoc = D.ColonLoc; 5278 IDElem.SecondColonLoc = D.SecColonLoc; 5279 } 5280 if (!IsCorrect) { 5281 // Invalidate all created iterator declarations if error is found. 5282 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5283 if (Decl *ID = D.IteratorDecl) 5284 ID->setInvalidDecl(); 5285 } 5286 return ExprError(); 5287 } 5288 SmallVector<OMPIteratorHelperData, 4> Helpers; 5289 if (!CurContext->isDependentContext()) { 5290 // Build number of ityeration for each iteration range. 5291 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5292 // ((Begini-Stepi-1-Endi) / -Stepi); 5293 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5294 // (Endi - Begini) 5295 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5296 D.Range.Begin); 5297 if(!Res.isUsable()) { 5298 IsCorrect = false; 5299 continue; 5300 } 5301 ExprResult St, St1; 5302 if (D.Range.Step) { 5303 St = D.Range.Step; 5304 // (Endi - Begini) + Stepi 5305 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5306 if (!Res.isUsable()) { 5307 IsCorrect = false; 5308 continue; 5309 } 5310 // (Endi - Begini) + Stepi - 1 5311 Res = 5312 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5313 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5314 if (!Res.isUsable()) { 5315 IsCorrect = false; 5316 continue; 5317 } 5318 // ((Endi - Begini) + Stepi - 1) / Stepi 5319 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5320 if (!Res.isUsable()) { 5321 IsCorrect = false; 5322 continue; 5323 } 5324 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5325 // (Begini - Endi) 5326 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5327 D.Range.Begin, D.Range.End); 5328 if (!Res1.isUsable()) { 5329 IsCorrect = false; 5330 continue; 5331 } 5332 // (Begini - Endi) - Stepi 5333 Res1 = 5334 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5335 if (!Res1.isUsable()) { 5336 IsCorrect = false; 5337 continue; 5338 } 5339 // (Begini - Endi) - Stepi - 1 5340 Res1 = 5341 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5342 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5343 if (!Res1.isUsable()) { 5344 IsCorrect = false; 5345 continue; 5346 } 5347 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5348 Res1 = 5349 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5350 if (!Res1.isUsable()) { 5351 IsCorrect = false; 5352 continue; 5353 } 5354 // Stepi > 0. 5355 ExprResult CmpRes = 5356 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5357 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5358 if (!CmpRes.isUsable()) { 5359 IsCorrect = false; 5360 continue; 5361 } 5362 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5363 Res.get(), Res1.get()); 5364 if (!Res.isUsable()) { 5365 IsCorrect = false; 5366 continue; 5367 } 5368 } 5369 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5370 if (!Res.isUsable()) { 5371 IsCorrect = false; 5372 continue; 5373 } 5374 5375 // Build counter update. 5376 // Build counter. 5377 auto *CounterVD = 5378 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5379 D.IteratorDecl->getBeginLoc(), nullptr, 5380 Res.get()->getType(), nullptr, SC_None); 5381 CounterVD->setImplicit(); 5382 ExprResult RefRes = 5383 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5384 D.IteratorDecl->getBeginLoc()); 5385 // Build counter update. 5386 // I = Begini + counter * Stepi; 5387 ExprResult UpdateRes; 5388 if (D.Range.Step) { 5389 UpdateRes = CreateBuiltinBinOp( 5390 D.AssignmentLoc, BO_Mul, 5391 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5392 } else { 5393 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5394 } 5395 if (!UpdateRes.isUsable()) { 5396 IsCorrect = false; 5397 continue; 5398 } 5399 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5400 UpdateRes.get()); 5401 if (!UpdateRes.isUsable()) { 5402 IsCorrect = false; 5403 continue; 5404 } 5405 ExprResult VDRes = 5406 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5407 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5408 D.IteratorDecl->getBeginLoc()); 5409 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5410 UpdateRes.get()); 5411 if (!UpdateRes.isUsable()) { 5412 IsCorrect = false; 5413 continue; 5414 } 5415 UpdateRes = 5416 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5417 if (!UpdateRes.isUsable()) { 5418 IsCorrect = false; 5419 continue; 5420 } 5421 ExprResult CounterUpdateRes = 5422 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5423 if (!CounterUpdateRes.isUsable()) { 5424 IsCorrect = false; 5425 continue; 5426 } 5427 CounterUpdateRes = 5428 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5429 if (!CounterUpdateRes.isUsable()) { 5430 IsCorrect = false; 5431 continue; 5432 } 5433 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5434 HD.CounterVD = CounterVD; 5435 HD.Upper = Res.get(); 5436 HD.Update = UpdateRes.get(); 5437 HD.CounterUpdate = CounterUpdateRes.get(); 5438 } 5439 } else { 5440 Helpers.assign(ID.size(), {}); 5441 } 5442 if (!IsCorrect) { 5443 // Invalidate all created iterator declarations if error is found. 5444 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5445 if (Decl *ID = D.IteratorDecl) 5446 ID->setInvalidDecl(); 5447 } 5448 return ExprError(); 5449 } 5450 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5451 LLoc, RLoc, ID, Helpers); 5452 } 5453 5454 ExprResult 5455 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5456 Expr *Idx, SourceLocation RLoc) { 5457 Expr *LHSExp = Base; 5458 Expr *RHSExp = Idx; 5459 5460 ExprValueKind VK = VK_LValue; 5461 ExprObjectKind OK = OK_Ordinary; 5462 5463 // Per C++ core issue 1213, the result is an xvalue if either operand is 5464 // a non-lvalue array, and an lvalue otherwise. 5465 if (getLangOpts().CPlusPlus11) { 5466 for (auto *Op : {LHSExp, RHSExp}) { 5467 Op = Op->IgnoreImplicit(); 5468 if (Op->getType()->isArrayType() && !Op->isLValue()) 5469 VK = VK_XValue; 5470 } 5471 } 5472 5473 // Perform default conversions. 5474 if (!LHSExp->getType()->getAs<VectorType>()) { 5475 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5476 if (Result.isInvalid()) 5477 return ExprError(); 5478 LHSExp = Result.get(); 5479 } 5480 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5481 if (Result.isInvalid()) 5482 return ExprError(); 5483 RHSExp = Result.get(); 5484 5485 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5486 5487 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5488 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5489 // in the subscript position. As a result, we need to derive the array base 5490 // and index from the expression types. 5491 Expr *BaseExpr, *IndexExpr; 5492 QualType ResultType; 5493 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5494 BaseExpr = LHSExp; 5495 IndexExpr = RHSExp; 5496 ResultType = Context.DependentTy; 5497 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5498 BaseExpr = LHSExp; 5499 IndexExpr = RHSExp; 5500 ResultType = PTy->getPointeeType(); 5501 } else if (const ObjCObjectPointerType *PTy = 5502 LHSTy->getAs<ObjCObjectPointerType>()) { 5503 BaseExpr = LHSExp; 5504 IndexExpr = RHSExp; 5505 5506 // Use custom logic if this should be the pseudo-object subscript 5507 // expression. 5508 if (!LangOpts.isSubscriptPointerArithmetic()) 5509 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5510 nullptr); 5511 5512 ResultType = PTy->getPointeeType(); 5513 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5514 // Handle the uncommon case of "123[Ptr]". 5515 BaseExpr = RHSExp; 5516 IndexExpr = LHSExp; 5517 ResultType = PTy->getPointeeType(); 5518 } else if (const ObjCObjectPointerType *PTy = 5519 RHSTy->getAs<ObjCObjectPointerType>()) { 5520 // Handle the uncommon case of "123[Ptr]". 5521 BaseExpr = RHSExp; 5522 IndexExpr = LHSExp; 5523 ResultType = PTy->getPointeeType(); 5524 if (!LangOpts.isSubscriptPointerArithmetic()) { 5525 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5526 << ResultType << BaseExpr->getSourceRange(); 5527 return ExprError(); 5528 } 5529 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5530 BaseExpr = LHSExp; // vectors: V[123] 5531 IndexExpr = RHSExp; 5532 // We apply C++ DR1213 to vector subscripting too. 5533 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5534 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5535 if (Materialized.isInvalid()) 5536 return ExprError(); 5537 LHSExp = Materialized.get(); 5538 } 5539 VK = LHSExp->getValueKind(); 5540 if (VK != VK_PRValue) 5541 OK = OK_VectorComponent; 5542 5543 ResultType = VTy->getElementType(); 5544 QualType BaseType = BaseExpr->getType(); 5545 Qualifiers BaseQuals = BaseType.getQualifiers(); 5546 Qualifiers MemberQuals = ResultType.getQualifiers(); 5547 Qualifiers Combined = BaseQuals + MemberQuals; 5548 if (Combined != MemberQuals) 5549 ResultType = Context.getQualifiedType(ResultType, Combined); 5550 } else if (LHSTy->isArrayType()) { 5551 // If we see an array that wasn't promoted by 5552 // DefaultFunctionArrayLvalueConversion, it must be an array that 5553 // wasn't promoted because of the C90 rule that doesn't 5554 // allow promoting non-lvalue arrays. Warn, then 5555 // force the promotion here. 5556 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5557 << LHSExp->getSourceRange(); 5558 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5559 CK_ArrayToPointerDecay).get(); 5560 LHSTy = LHSExp->getType(); 5561 5562 BaseExpr = LHSExp; 5563 IndexExpr = RHSExp; 5564 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5565 } else if (RHSTy->isArrayType()) { 5566 // Same as previous, except for 123[f().a] case 5567 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5568 << RHSExp->getSourceRange(); 5569 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5570 CK_ArrayToPointerDecay).get(); 5571 RHSTy = RHSExp->getType(); 5572 5573 BaseExpr = RHSExp; 5574 IndexExpr = LHSExp; 5575 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5576 } else { 5577 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5578 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5579 } 5580 // C99 6.5.2.1p1 5581 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5582 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5583 << IndexExpr->getSourceRange()); 5584 5585 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5586 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5587 && !IndexExpr->isTypeDependent()) 5588 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5589 5590 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5591 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5592 // type. Note that Functions are not objects, and that (in C99 parlance) 5593 // incomplete types are not object types. 5594 if (ResultType->isFunctionType()) { 5595 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5596 << ResultType << BaseExpr->getSourceRange(); 5597 return ExprError(); 5598 } 5599 5600 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5601 // GNU extension: subscripting on pointer to void 5602 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5603 << BaseExpr->getSourceRange(); 5604 5605 // C forbids expressions of unqualified void type from being l-values. 5606 // See IsCForbiddenLValueType. 5607 if (!ResultType.hasQualifiers()) 5608 VK = VK_PRValue; 5609 } else if (!ResultType->isDependentType() && 5610 RequireCompleteSizedType( 5611 LLoc, ResultType, 5612 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5613 return ExprError(); 5614 5615 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5616 !ResultType.isCForbiddenLValueType()); 5617 5618 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5619 FunctionScopes.size() > 1) { 5620 if (auto *TT = 5621 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5622 for (auto I = FunctionScopes.rbegin(), 5623 E = std::prev(FunctionScopes.rend()); 5624 I != E; ++I) { 5625 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5626 if (CSI == nullptr) 5627 break; 5628 DeclContext *DC = nullptr; 5629 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5630 DC = LSI->CallOperator; 5631 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5632 DC = CRSI->TheCapturedDecl; 5633 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5634 DC = BSI->TheDecl; 5635 if (DC) { 5636 if (DC->containsDecl(TT->getDecl())) 5637 break; 5638 captureVariablyModifiedType( 5639 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5640 } 5641 } 5642 } 5643 } 5644 5645 return new (Context) 5646 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5647 } 5648 5649 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5650 ParmVarDecl *Param) { 5651 if (Param->hasUnparsedDefaultArg()) { 5652 // If we've already cleared out the location for the default argument, 5653 // that means we're parsing it right now. 5654 if (!UnparsedDefaultArgLocs.count(Param)) { 5655 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5656 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5657 Param->setInvalidDecl(); 5658 return true; 5659 } 5660 5661 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5662 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5663 Diag(UnparsedDefaultArgLocs[Param], 5664 diag::note_default_argument_declared_here); 5665 return true; 5666 } 5667 5668 if (Param->hasUninstantiatedDefaultArg() && 5669 InstantiateDefaultArgument(CallLoc, FD, Param)) 5670 return true; 5671 5672 assert(Param->hasInit() && "default argument but no initializer?"); 5673 5674 // If the default expression creates temporaries, we need to 5675 // push them to the current stack of expression temporaries so they'll 5676 // be properly destroyed. 5677 // FIXME: We should really be rebuilding the default argument with new 5678 // bound temporaries; see the comment in PR5810. 5679 // We don't need to do that with block decls, though, because 5680 // blocks in default argument expression can never capture anything. 5681 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5682 // Set the "needs cleanups" bit regardless of whether there are 5683 // any explicit objects. 5684 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5685 5686 // Append all the objects to the cleanup list. Right now, this 5687 // should always be a no-op, because blocks in default argument 5688 // expressions should never be able to capture anything. 5689 assert(!Init->getNumObjects() && 5690 "default argument expression has capturing blocks?"); 5691 } 5692 5693 // We already type-checked the argument, so we know it works. 5694 // Just mark all of the declarations in this potentially-evaluated expression 5695 // as being "referenced". 5696 EnterExpressionEvaluationContext EvalContext( 5697 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5698 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5699 /*SkipLocalVariables=*/true); 5700 return false; 5701 } 5702 5703 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5704 FunctionDecl *FD, ParmVarDecl *Param) { 5705 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5706 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5707 return ExprError(); 5708 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5709 } 5710 5711 Sema::VariadicCallType 5712 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5713 Expr *Fn) { 5714 if (Proto && Proto->isVariadic()) { 5715 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 5716 return VariadicConstructor; 5717 else if (Fn && Fn->getType()->isBlockPointerType()) 5718 return VariadicBlock; 5719 else if (FDecl) { 5720 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5721 if (Method->isInstance()) 5722 return VariadicMethod; 5723 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5724 return VariadicMethod; 5725 return VariadicFunction; 5726 } 5727 return VariadicDoesNotApply; 5728 } 5729 5730 namespace { 5731 class FunctionCallCCC final : public FunctionCallFilterCCC { 5732 public: 5733 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5734 unsigned NumArgs, MemberExpr *ME) 5735 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5736 FunctionName(FuncName) {} 5737 5738 bool ValidateCandidate(const TypoCorrection &candidate) override { 5739 if (!candidate.getCorrectionSpecifier() || 5740 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5741 return false; 5742 } 5743 5744 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5745 } 5746 5747 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5748 return std::make_unique<FunctionCallCCC>(*this); 5749 } 5750 5751 private: 5752 const IdentifierInfo *const FunctionName; 5753 }; 5754 } 5755 5756 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5757 FunctionDecl *FDecl, 5758 ArrayRef<Expr *> Args) { 5759 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5760 DeclarationName FuncName = FDecl->getDeclName(); 5761 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5762 5763 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5764 if (TypoCorrection Corrected = S.CorrectTypo( 5765 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5766 S.getScopeForContext(S.CurContext), nullptr, CCC, 5767 Sema::CTK_ErrorRecovery)) { 5768 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5769 if (Corrected.isOverloaded()) { 5770 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5771 OverloadCandidateSet::iterator Best; 5772 for (NamedDecl *CD : Corrected) { 5773 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5774 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5775 OCS); 5776 } 5777 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5778 case OR_Success: 5779 ND = Best->FoundDecl; 5780 Corrected.setCorrectionDecl(ND); 5781 break; 5782 default: 5783 break; 5784 } 5785 } 5786 ND = ND->getUnderlyingDecl(); 5787 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5788 return Corrected; 5789 } 5790 } 5791 return TypoCorrection(); 5792 } 5793 5794 /// ConvertArgumentsForCall - Converts the arguments specified in 5795 /// Args/NumArgs to the parameter types of the function FDecl with 5796 /// function prototype Proto. Call is the call expression itself, and 5797 /// Fn is the function expression. For a C++ member function, this 5798 /// routine does not attempt to convert the object argument. Returns 5799 /// true if the call is ill-formed. 5800 bool 5801 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5802 FunctionDecl *FDecl, 5803 const FunctionProtoType *Proto, 5804 ArrayRef<Expr *> Args, 5805 SourceLocation RParenLoc, 5806 bool IsExecConfig) { 5807 // Bail out early if calling a builtin with custom typechecking. 5808 if (FDecl) 5809 if (unsigned ID = FDecl->getBuiltinID()) 5810 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5811 return false; 5812 5813 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5814 // assignment, to the types of the corresponding parameter, ... 5815 unsigned NumParams = Proto->getNumParams(); 5816 bool Invalid = false; 5817 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5818 unsigned FnKind = Fn->getType()->isBlockPointerType() 5819 ? 1 /* block */ 5820 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5821 : 0 /* function */); 5822 5823 // If too few arguments are available (and we don't have default 5824 // arguments for the remaining parameters), don't make the call. 5825 if (Args.size() < NumParams) { 5826 if (Args.size() < MinArgs) { 5827 TypoCorrection TC; 5828 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5829 unsigned diag_id = 5830 MinArgs == NumParams && !Proto->isVariadic() 5831 ? diag::err_typecheck_call_too_few_args_suggest 5832 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5833 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5834 << static_cast<unsigned>(Args.size()) 5835 << TC.getCorrectionRange()); 5836 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5837 Diag(RParenLoc, 5838 MinArgs == NumParams && !Proto->isVariadic() 5839 ? diag::err_typecheck_call_too_few_args_one 5840 : diag::err_typecheck_call_too_few_args_at_least_one) 5841 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5842 else 5843 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5844 ? diag::err_typecheck_call_too_few_args 5845 : diag::err_typecheck_call_too_few_args_at_least) 5846 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5847 << Fn->getSourceRange(); 5848 5849 // Emit the location of the prototype. 5850 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5851 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5852 5853 return true; 5854 } 5855 // We reserve space for the default arguments when we create 5856 // the call expression, before calling ConvertArgumentsForCall. 5857 assert((Call->getNumArgs() == NumParams) && 5858 "We should have reserved space for the default arguments before!"); 5859 } 5860 5861 // If too many are passed and not variadic, error on the extras and drop 5862 // them. 5863 if (Args.size() > NumParams) { 5864 if (!Proto->isVariadic()) { 5865 TypoCorrection TC; 5866 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5867 unsigned diag_id = 5868 MinArgs == NumParams && !Proto->isVariadic() 5869 ? diag::err_typecheck_call_too_many_args_suggest 5870 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5871 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5872 << static_cast<unsigned>(Args.size()) 5873 << TC.getCorrectionRange()); 5874 } else if (NumParams == 1 && FDecl && 5875 FDecl->getParamDecl(0)->getDeclName()) 5876 Diag(Args[NumParams]->getBeginLoc(), 5877 MinArgs == NumParams 5878 ? diag::err_typecheck_call_too_many_args_one 5879 : diag::err_typecheck_call_too_many_args_at_most_one) 5880 << FnKind << FDecl->getParamDecl(0) 5881 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5882 << SourceRange(Args[NumParams]->getBeginLoc(), 5883 Args.back()->getEndLoc()); 5884 else 5885 Diag(Args[NumParams]->getBeginLoc(), 5886 MinArgs == NumParams 5887 ? diag::err_typecheck_call_too_many_args 5888 : diag::err_typecheck_call_too_many_args_at_most) 5889 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5890 << Fn->getSourceRange() 5891 << SourceRange(Args[NumParams]->getBeginLoc(), 5892 Args.back()->getEndLoc()); 5893 5894 // Emit the location of the prototype. 5895 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5896 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5897 5898 // This deletes the extra arguments. 5899 Call->shrinkNumArgs(NumParams); 5900 return true; 5901 } 5902 } 5903 SmallVector<Expr *, 8> AllArgs; 5904 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5905 5906 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5907 AllArgs, CallType); 5908 if (Invalid) 5909 return true; 5910 unsigned TotalNumArgs = AllArgs.size(); 5911 for (unsigned i = 0; i < TotalNumArgs; ++i) 5912 Call->setArg(i, AllArgs[i]); 5913 5914 Call->computeDependence(); 5915 return false; 5916 } 5917 5918 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5919 const FunctionProtoType *Proto, 5920 unsigned FirstParam, ArrayRef<Expr *> Args, 5921 SmallVectorImpl<Expr *> &AllArgs, 5922 VariadicCallType CallType, bool AllowExplicit, 5923 bool IsListInitialization) { 5924 unsigned NumParams = Proto->getNumParams(); 5925 bool Invalid = false; 5926 size_t ArgIx = 0; 5927 // Continue to check argument types (even if we have too few/many args). 5928 for (unsigned i = FirstParam; i < NumParams; i++) { 5929 QualType ProtoArgType = Proto->getParamType(i); 5930 5931 Expr *Arg; 5932 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5933 if (ArgIx < Args.size()) { 5934 Arg = Args[ArgIx++]; 5935 5936 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5937 diag::err_call_incomplete_argument, Arg)) 5938 return true; 5939 5940 // Strip the unbridged-cast placeholder expression off, if applicable. 5941 bool CFAudited = false; 5942 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5943 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5944 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5945 Arg = stripARCUnbridgedCast(Arg); 5946 else if (getLangOpts().ObjCAutoRefCount && 5947 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5948 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5949 CFAudited = true; 5950 5951 if (Proto->getExtParameterInfo(i).isNoEscape() && 5952 ProtoArgType->isBlockPointerType()) 5953 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5954 BE->getBlockDecl()->setDoesNotEscape(); 5955 5956 InitializedEntity Entity = 5957 Param ? InitializedEntity::InitializeParameter(Context, Param, 5958 ProtoArgType) 5959 : InitializedEntity::InitializeParameter( 5960 Context, ProtoArgType, Proto->isParamConsumed(i)); 5961 5962 // Remember that parameter belongs to a CF audited API. 5963 if (CFAudited) 5964 Entity.setParameterCFAudited(); 5965 5966 ExprResult ArgE = PerformCopyInitialization( 5967 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5968 if (ArgE.isInvalid()) 5969 return true; 5970 5971 Arg = ArgE.getAs<Expr>(); 5972 } else { 5973 assert(Param && "can't use default arguments without a known callee"); 5974 5975 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5976 if (ArgExpr.isInvalid()) 5977 return true; 5978 5979 Arg = ArgExpr.getAs<Expr>(); 5980 } 5981 5982 // Check for array bounds violations for each argument to the call. This 5983 // check only triggers warnings when the argument isn't a more complex Expr 5984 // with its own checking, such as a BinaryOperator. 5985 CheckArrayAccess(Arg); 5986 5987 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5988 CheckStaticArrayArgument(CallLoc, Param, Arg); 5989 5990 AllArgs.push_back(Arg); 5991 } 5992 5993 // If this is a variadic call, handle args passed through "...". 5994 if (CallType != VariadicDoesNotApply) { 5995 // Assume that extern "C" functions with variadic arguments that 5996 // return __unknown_anytype aren't *really* variadic. 5997 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5998 FDecl->isExternC()) { 5999 for (Expr *A : Args.slice(ArgIx)) { 6000 QualType paramType; // ignored 6001 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6002 Invalid |= arg.isInvalid(); 6003 AllArgs.push_back(arg.get()); 6004 } 6005 6006 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6007 } else { 6008 for (Expr *A : Args.slice(ArgIx)) { 6009 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6010 Invalid |= Arg.isInvalid(); 6011 AllArgs.push_back(Arg.get()); 6012 } 6013 } 6014 6015 // Check for array bounds violations. 6016 for (Expr *A : Args.slice(ArgIx)) 6017 CheckArrayAccess(A); 6018 } 6019 return Invalid; 6020 } 6021 6022 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6023 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6024 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6025 TL = DTL.getOriginalLoc(); 6026 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6027 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6028 << ATL.getLocalSourceRange(); 6029 } 6030 6031 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6032 /// array parameter, check that it is non-null, and that if it is formed by 6033 /// array-to-pointer decay, the underlying array is sufficiently large. 6034 /// 6035 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6036 /// array type derivation, then for each call to the function, the value of the 6037 /// corresponding actual argument shall provide access to the first element of 6038 /// an array with at least as many elements as specified by the size expression. 6039 void 6040 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6041 ParmVarDecl *Param, 6042 const Expr *ArgExpr) { 6043 // Static array parameters are not supported in C++. 6044 if (!Param || getLangOpts().CPlusPlus) 6045 return; 6046 6047 QualType OrigTy = Param->getOriginalType(); 6048 6049 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6050 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6051 return; 6052 6053 if (ArgExpr->isNullPointerConstant(Context, 6054 Expr::NPC_NeverValueDependent)) { 6055 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6056 DiagnoseCalleeStaticArrayParam(*this, Param); 6057 return; 6058 } 6059 6060 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6061 if (!CAT) 6062 return; 6063 6064 const ConstantArrayType *ArgCAT = 6065 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6066 if (!ArgCAT) 6067 return; 6068 6069 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6070 ArgCAT->getElementType())) { 6071 if (ArgCAT->getSize().ult(CAT->getSize())) { 6072 Diag(CallLoc, diag::warn_static_array_too_small) 6073 << ArgExpr->getSourceRange() 6074 << (unsigned)ArgCAT->getSize().getZExtValue() 6075 << (unsigned)CAT->getSize().getZExtValue() << 0; 6076 DiagnoseCalleeStaticArrayParam(*this, Param); 6077 } 6078 return; 6079 } 6080 6081 Optional<CharUnits> ArgSize = 6082 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6083 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6084 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6085 Diag(CallLoc, diag::warn_static_array_too_small) 6086 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6087 << (unsigned)ParmSize->getQuantity() << 1; 6088 DiagnoseCalleeStaticArrayParam(*this, Param); 6089 } 6090 } 6091 6092 /// Given a function expression of unknown-any type, try to rebuild it 6093 /// to have a function type. 6094 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6095 6096 /// Is the given type a placeholder that we need to lower out 6097 /// immediately during argument processing? 6098 static bool isPlaceholderToRemoveAsArg(QualType type) { 6099 // Placeholders are never sugared. 6100 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6101 if (!placeholder) return false; 6102 6103 switch (placeholder->getKind()) { 6104 // Ignore all the non-placeholder types. 6105 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6106 case BuiltinType::Id: 6107 #include "clang/Basic/OpenCLImageTypes.def" 6108 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6109 case BuiltinType::Id: 6110 #include "clang/Basic/OpenCLExtensionTypes.def" 6111 // In practice we'll never use this, since all SVE types are sugared 6112 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6113 #define SVE_TYPE(Name, Id, SingletonId) \ 6114 case BuiltinType::Id: 6115 #include "clang/Basic/AArch64SVEACLETypes.def" 6116 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6117 case BuiltinType::Id: 6118 #include "clang/Basic/PPCTypes.def" 6119 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6120 #include "clang/Basic/RISCVVTypes.def" 6121 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6122 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6123 #include "clang/AST/BuiltinTypes.def" 6124 return false; 6125 6126 // We cannot lower out overload sets; they might validly be resolved 6127 // by the call machinery. 6128 case BuiltinType::Overload: 6129 return false; 6130 6131 // Unbridged casts in ARC can be handled in some call positions and 6132 // should be left in place. 6133 case BuiltinType::ARCUnbridgedCast: 6134 return false; 6135 6136 // Pseudo-objects should be converted as soon as possible. 6137 case BuiltinType::PseudoObject: 6138 return true; 6139 6140 // The debugger mode could theoretically but currently does not try 6141 // to resolve unknown-typed arguments based on known parameter types. 6142 case BuiltinType::UnknownAny: 6143 return true; 6144 6145 // These are always invalid as call arguments and should be reported. 6146 case BuiltinType::BoundMember: 6147 case BuiltinType::BuiltinFn: 6148 case BuiltinType::IncompleteMatrixIdx: 6149 case BuiltinType::OMPArraySection: 6150 case BuiltinType::OMPArrayShaping: 6151 case BuiltinType::OMPIterator: 6152 return true; 6153 6154 } 6155 llvm_unreachable("bad builtin type kind"); 6156 } 6157 6158 /// Check an argument list for placeholders that we won't try to 6159 /// handle later. 6160 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6161 // Apply this processing to all the arguments at once instead of 6162 // dying at the first failure. 6163 bool hasInvalid = false; 6164 for (size_t i = 0, e = args.size(); i != e; i++) { 6165 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6166 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6167 if (result.isInvalid()) hasInvalid = true; 6168 else args[i] = result.get(); 6169 } 6170 } 6171 return hasInvalid; 6172 } 6173 6174 /// If a builtin function has a pointer argument with no explicit address 6175 /// space, then it should be able to accept a pointer to any address 6176 /// space as input. In order to do this, we need to replace the 6177 /// standard builtin declaration with one that uses the same address space 6178 /// as the call. 6179 /// 6180 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6181 /// it does not contain any pointer arguments without 6182 /// an address space qualifer. Otherwise the rewritten 6183 /// FunctionDecl is returned. 6184 /// TODO: Handle pointer return types. 6185 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6186 FunctionDecl *FDecl, 6187 MultiExprArg ArgExprs) { 6188 6189 QualType DeclType = FDecl->getType(); 6190 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6191 6192 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6193 ArgExprs.size() < FT->getNumParams()) 6194 return nullptr; 6195 6196 bool NeedsNewDecl = false; 6197 unsigned i = 0; 6198 SmallVector<QualType, 8> OverloadParams; 6199 6200 for (QualType ParamType : FT->param_types()) { 6201 6202 // Convert array arguments to pointer to simplify type lookup. 6203 ExprResult ArgRes = 6204 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6205 if (ArgRes.isInvalid()) 6206 return nullptr; 6207 Expr *Arg = ArgRes.get(); 6208 QualType ArgType = Arg->getType(); 6209 if (!ParamType->isPointerType() || 6210 ParamType.hasAddressSpace() || 6211 !ArgType->isPointerType() || 6212 !ArgType->getPointeeType().hasAddressSpace()) { 6213 OverloadParams.push_back(ParamType); 6214 continue; 6215 } 6216 6217 QualType PointeeType = ParamType->getPointeeType(); 6218 if (PointeeType.hasAddressSpace()) 6219 continue; 6220 6221 NeedsNewDecl = true; 6222 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6223 6224 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6225 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6226 } 6227 6228 if (!NeedsNewDecl) 6229 return nullptr; 6230 6231 FunctionProtoType::ExtProtoInfo EPI; 6232 EPI.Variadic = FT->isVariadic(); 6233 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6234 OverloadParams, EPI); 6235 DeclContext *Parent = FDecl->getParent(); 6236 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6237 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6238 FDecl->getIdentifier(), OverloadTy, 6239 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6240 false, 6241 /*hasPrototype=*/true); 6242 SmallVector<ParmVarDecl*, 16> Params; 6243 FT = cast<FunctionProtoType>(OverloadTy); 6244 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6245 QualType ParamType = FT->getParamType(i); 6246 ParmVarDecl *Parm = 6247 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6248 SourceLocation(), nullptr, ParamType, 6249 /*TInfo=*/nullptr, SC_None, nullptr); 6250 Parm->setScopeInfo(0, i); 6251 Params.push_back(Parm); 6252 } 6253 OverloadDecl->setParams(Params); 6254 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6255 return OverloadDecl; 6256 } 6257 6258 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6259 FunctionDecl *Callee, 6260 MultiExprArg ArgExprs) { 6261 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6262 // similar attributes) really don't like it when functions are called with an 6263 // invalid number of args. 6264 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6265 /*PartialOverloading=*/false) && 6266 !Callee->isVariadic()) 6267 return; 6268 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6269 return; 6270 6271 if (const EnableIfAttr *Attr = 6272 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6273 S.Diag(Fn->getBeginLoc(), 6274 isa<CXXMethodDecl>(Callee) 6275 ? diag::err_ovl_no_viable_member_function_in_call 6276 : diag::err_ovl_no_viable_function_in_call) 6277 << Callee << Callee->getSourceRange(); 6278 S.Diag(Callee->getLocation(), 6279 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6280 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6281 return; 6282 } 6283 } 6284 6285 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6286 const UnresolvedMemberExpr *const UME, Sema &S) { 6287 6288 const auto GetFunctionLevelDCIfCXXClass = 6289 [](Sema &S) -> const CXXRecordDecl * { 6290 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6291 if (!DC || !DC->getParent()) 6292 return nullptr; 6293 6294 // If the call to some member function was made from within a member 6295 // function body 'M' return return 'M's parent. 6296 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6297 return MD->getParent()->getCanonicalDecl(); 6298 // else the call was made from within a default member initializer of a 6299 // class, so return the class. 6300 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6301 return RD->getCanonicalDecl(); 6302 return nullptr; 6303 }; 6304 // If our DeclContext is neither a member function nor a class (in the 6305 // case of a lambda in a default member initializer), we can't have an 6306 // enclosing 'this'. 6307 6308 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6309 if (!CurParentClass) 6310 return false; 6311 6312 // The naming class for implicit member functions call is the class in which 6313 // name lookup starts. 6314 const CXXRecordDecl *const NamingClass = 6315 UME->getNamingClass()->getCanonicalDecl(); 6316 assert(NamingClass && "Must have naming class even for implicit access"); 6317 6318 // If the unresolved member functions were found in a 'naming class' that is 6319 // related (either the same or derived from) to the class that contains the 6320 // member function that itself contained the implicit member access. 6321 6322 return CurParentClass == NamingClass || 6323 CurParentClass->isDerivedFrom(NamingClass); 6324 } 6325 6326 static void 6327 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6328 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6329 6330 if (!UME) 6331 return; 6332 6333 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6334 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6335 // already been captured, or if this is an implicit member function call (if 6336 // it isn't, an attempt to capture 'this' should already have been made). 6337 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6338 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6339 return; 6340 6341 // Check if the naming class in which the unresolved members were found is 6342 // related (same as or is a base of) to the enclosing class. 6343 6344 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6345 return; 6346 6347 6348 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6349 // If the enclosing function is not dependent, then this lambda is 6350 // capture ready, so if we can capture this, do so. 6351 if (!EnclosingFunctionCtx->isDependentContext()) { 6352 // If the current lambda and all enclosing lambdas can capture 'this' - 6353 // then go ahead and capture 'this' (since our unresolved overload set 6354 // contains at least one non-static member function). 6355 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6356 S.CheckCXXThisCapture(CallLoc); 6357 } else if (S.CurContext->isDependentContext()) { 6358 // ... since this is an implicit member reference, that might potentially 6359 // involve a 'this' capture, mark 'this' for potential capture in 6360 // enclosing lambdas. 6361 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6362 CurLSI->addPotentialThisCapture(CallLoc); 6363 } 6364 } 6365 6366 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6367 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6368 Expr *ExecConfig) { 6369 ExprResult Call = 6370 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6371 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6372 if (Call.isInvalid()) 6373 return Call; 6374 6375 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6376 // language modes. 6377 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6378 if (ULE->hasExplicitTemplateArgs() && 6379 ULE->decls_begin() == ULE->decls_end()) { 6380 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6381 ? diag::warn_cxx17_compat_adl_only_template_id 6382 : diag::ext_adl_only_template_id) 6383 << ULE->getName(); 6384 } 6385 } 6386 6387 if (LangOpts.OpenMP) 6388 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6389 ExecConfig); 6390 6391 return Call; 6392 } 6393 6394 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6395 /// This provides the location of the left/right parens and a list of comma 6396 /// locations. 6397 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6398 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6399 Expr *ExecConfig, bool IsExecConfig, 6400 bool AllowRecovery) { 6401 // Since this might be a postfix expression, get rid of ParenListExprs. 6402 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6403 if (Result.isInvalid()) return ExprError(); 6404 Fn = Result.get(); 6405 6406 if (checkArgsForPlaceholders(*this, ArgExprs)) 6407 return ExprError(); 6408 6409 if (getLangOpts().CPlusPlus) { 6410 // If this is a pseudo-destructor expression, build the call immediately. 6411 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6412 if (!ArgExprs.empty()) { 6413 // Pseudo-destructor calls should not have any arguments. 6414 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6415 << FixItHint::CreateRemoval( 6416 SourceRange(ArgExprs.front()->getBeginLoc(), 6417 ArgExprs.back()->getEndLoc())); 6418 } 6419 6420 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6421 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6422 } 6423 if (Fn->getType() == Context.PseudoObjectTy) { 6424 ExprResult result = CheckPlaceholderExpr(Fn); 6425 if (result.isInvalid()) return ExprError(); 6426 Fn = result.get(); 6427 } 6428 6429 // Determine whether this is a dependent call inside a C++ template, 6430 // in which case we won't do any semantic analysis now. 6431 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6432 if (ExecConfig) { 6433 return CUDAKernelCallExpr::Create(Context, Fn, 6434 cast<CallExpr>(ExecConfig), ArgExprs, 6435 Context.DependentTy, VK_PRValue, 6436 RParenLoc, CurFPFeatureOverrides()); 6437 } else { 6438 6439 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6440 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6441 Fn->getBeginLoc()); 6442 6443 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6444 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6445 } 6446 } 6447 6448 // Determine whether this is a call to an object (C++ [over.call.object]). 6449 if (Fn->getType()->isRecordType()) 6450 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6451 RParenLoc); 6452 6453 if (Fn->getType() == Context.UnknownAnyTy) { 6454 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6455 if (result.isInvalid()) return ExprError(); 6456 Fn = result.get(); 6457 } 6458 6459 if (Fn->getType() == Context.BoundMemberTy) { 6460 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6461 RParenLoc, ExecConfig, IsExecConfig, 6462 AllowRecovery); 6463 } 6464 } 6465 6466 // Check for overloaded calls. This can happen even in C due to extensions. 6467 if (Fn->getType() == Context.OverloadTy) { 6468 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6469 6470 // We aren't supposed to apply this logic if there's an '&' involved. 6471 if (!find.HasFormOfMemberPointer) { 6472 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6473 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6474 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6475 OverloadExpr *ovl = find.Expression; 6476 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6477 return BuildOverloadedCallExpr( 6478 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6479 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6480 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6481 RParenLoc, ExecConfig, IsExecConfig, 6482 AllowRecovery); 6483 } 6484 } 6485 6486 // If we're directly calling a function, get the appropriate declaration. 6487 if (Fn->getType() == Context.UnknownAnyTy) { 6488 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6489 if (result.isInvalid()) return ExprError(); 6490 Fn = result.get(); 6491 } 6492 6493 Expr *NakedFn = Fn->IgnoreParens(); 6494 6495 bool CallingNDeclIndirectly = false; 6496 NamedDecl *NDecl = nullptr; 6497 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6498 if (UnOp->getOpcode() == UO_AddrOf) { 6499 CallingNDeclIndirectly = true; 6500 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6501 } 6502 } 6503 6504 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6505 NDecl = DRE->getDecl(); 6506 6507 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6508 if (FDecl && FDecl->getBuiltinID()) { 6509 // Rewrite the function decl for this builtin by replacing parameters 6510 // with no explicit address space with the address space of the arguments 6511 // in ArgExprs. 6512 if ((FDecl = 6513 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6514 NDecl = FDecl; 6515 Fn = DeclRefExpr::Create( 6516 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6517 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6518 nullptr, DRE->isNonOdrUse()); 6519 } 6520 } 6521 } else if (isa<MemberExpr>(NakedFn)) 6522 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6523 6524 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6525 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6526 FD, /*Complain=*/true, Fn->getBeginLoc())) 6527 return ExprError(); 6528 6529 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6530 6531 // If this expression is a call to a builtin function in HIP device 6532 // compilation, allow a pointer-type argument to default address space to be 6533 // passed as a pointer-type parameter to a non-default address space. 6534 // If Arg is declared in the default address space and Param is declared 6535 // in a non-default address space, perform an implicit address space cast to 6536 // the parameter type. 6537 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6538 FD->getBuiltinID()) { 6539 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6540 ParmVarDecl *Param = FD->getParamDecl(Idx); 6541 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6542 !ArgExprs[Idx]->getType()->isPointerType()) 6543 continue; 6544 6545 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6546 auto ArgTy = ArgExprs[Idx]->getType(); 6547 auto ArgPtTy = ArgTy->getPointeeType(); 6548 auto ArgAS = ArgPtTy.getAddressSpace(); 6549 6550 // Add address space cast if target address spaces are different 6551 bool NeedImplicitASC = 6552 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6553 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6554 // or from specific AS which has target AS matching that of Param. 6555 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6556 if (!NeedImplicitASC) 6557 continue; 6558 6559 // First, ensure that the Arg is an RValue. 6560 if (ArgExprs[Idx]->isGLValue()) { 6561 ArgExprs[Idx] = ImplicitCastExpr::Create( 6562 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6563 nullptr, VK_PRValue, FPOptionsOverride()); 6564 } 6565 6566 // Construct a new arg type with address space of Param 6567 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6568 ArgPtQuals.setAddressSpace(ParamAS); 6569 auto NewArgPtTy = 6570 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6571 auto NewArgTy = 6572 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6573 ArgTy.getQualifiers()); 6574 6575 // Finally perform an implicit address space cast 6576 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6577 CK_AddressSpaceConversion) 6578 .get(); 6579 } 6580 } 6581 } 6582 6583 if (Context.isDependenceAllowed() && 6584 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6585 assert(!getLangOpts().CPlusPlus); 6586 assert((Fn->containsErrors() || 6587 llvm::any_of(ArgExprs, 6588 [](clang::Expr *E) { return E->containsErrors(); })) && 6589 "should only occur in error-recovery path."); 6590 QualType ReturnType = 6591 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6592 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6593 : Context.DependentTy; 6594 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6595 Expr::getValueKindForType(ReturnType), RParenLoc, 6596 CurFPFeatureOverrides()); 6597 } 6598 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6599 ExecConfig, IsExecConfig); 6600 } 6601 6602 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6603 // with the specified CallArgs 6604 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6605 MultiExprArg CallArgs) { 6606 StringRef Name = Context.BuiltinInfo.getName(Id); 6607 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6608 Sema::LookupOrdinaryName); 6609 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6610 6611 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6612 assert(BuiltInDecl && "failed to find builtin declaration"); 6613 6614 ExprResult DeclRef = 6615 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6616 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6617 6618 ExprResult Call = 6619 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6620 6621 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6622 return Call.get(); 6623 } 6624 6625 /// Parse a __builtin_astype expression. 6626 /// 6627 /// __builtin_astype( value, dst type ) 6628 /// 6629 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6630 SourceLocation BuiltinLoc, 6631 SourceLocation RParenLoc) { 6632 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6633 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6634 } 6635 6636 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6637 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6638 SourceLocation BuiltinLoc, 6639 SourceLocation RParenLoc) { 6640 ExprValueKind VK = VK_PRValue; 6641 ExprObjectKind OK = OK_Ordinary; 6642 QualType SrcTy = E->getType(); 6643 if (!SrcTy->isDependentType() && 6644 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6645 return ExprError( 6646 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6647 << DestTy << SrcTy << E->getSourceRange()); 6648 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6649 } 6650 6651 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6652 /// provided arguments. 6653 /// 6654 /// __builtin_convertvector( value, dst type ) 6655 /// 6656 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6657 SourceLocation BuiltinLoc, 6658 SourceLocation RParenLoc) { 6659 TypeSourceInfo *TInfo; 6660 GetTypeFromParser(ParsedDestTy, &TInfo); 6661 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6662 } 6663 6664 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6665 /// i.e. an expression not of \p OverloadTy. The expression should 6666 /// unary-convert to an expression of function-pointer or 6667 /// block-pointer type. 6668 /// 6669 /// \param NDecl the declaration being called, if available 6670 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6671 SourceLocation LParenLoc, 6672 ArrayRef<Expr *> Args, 6673 SourceLocation RParenLoc, Expr *Config, 6674 bool IsExecConfig, ADLCallKind UsesADL) { 6675 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6676 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6677 6678 // Functions with 'interrupt' attribute cannot be called directly. 6679 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6680 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6681 return ExprError(); 6682 } 6683 6684 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6685 // so there's some risk when calling out to non-interrupt handler functions 6686 // that the callee might not preserve them. This is easy to diagnose here, 6687 // but can be very challenging to debug. 6688 // Likewise, X86 interrupt handlers may only call routines with attribute 6689 // no_caller_saved_registers since there is no efficient way to 6690 // save and restore the non-GPR state. 6691 if (auto *Caller = getCurFunctionDecl()) { 6692 if (Caller->hasAttr<ARMInterruptAttr>()) { 6693 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6694 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6695 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6696 if (FDecl) 6697 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6698 } 6699 } 6700 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6701 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6702 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6703 if (FDecl) 6704 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6705 } 6706 } 6707 6708 // Promote the function operand. 6709 // We special-case function promotion here because we only allow promoting 6710 // builtin functions to function pointers in the callee of a call. 6711 ExprResult Result; 6712 QualType ResultTy; 6713 if (BuiltinID && 6714 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6715 // Extract the return type from the (builtin) function pointer type. 6716 // FIXME Several builtins still have setType in 6717 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6718 // Builtins.def to ensure they are correct before removing setType calls. 6719 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6720 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6721 ResultTy = FDecl->getCallResultType(); 6722 } else { 6723 Result = CallExprUnaryConversions(Fn); 6724 ResultTy = Context.BoolTy; 6725 } 6726 if (Result.isInvalid()) 6727 return ExprError(); 6728 Fn = Result.get(); 6729 6730 // Check for a valid function type, but only if it is not a builtin which 6731 // requires custom type checking. These will be handled by 6732 // CheckBuiltinFunctionCall below just after creation of the call expression. 6733 const FunctionType *FuncT = nullptr; 6734 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6735 retry: 6736 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6737 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6738 // have type pointer to function". 6739 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6740 if (!FuncT) 6741 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6742 << Fn->getType() << Fn->getSourceRange()); 6743 } else if (const BlockPointerType *BPT = 6744 Fn->getType()->getAs<BlockPointerType>()) { 6745 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6746 } else { 6747 // Handle calls to expressions of unknown-any type. 6748 if (Fn->getType() == Context.UnknownAnyTy) { 6749 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6750 if (rewrite.isInvalid()) 6751 return ExprError(); 6752 Fn = rewrite.get(); 6753 goto retry; 6754 } 6755 6756 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6757 << Fn->getType() << Fn->getSourceRange()); 6758 } 6759 } 6760 6761 // Get the number of parameters in the function prototype, if any. 6762 // We will allocate space for max(Args.size(), NumParams) arguments 6763 // in the call expression. 6764 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6765 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6766 6767 CallExpr *TheCall; 6768 if (Config) { 6769 assert(UsesADL == ADLCallKind::NotADL && 6770 "CUDAKernelCallExpr should not use ADL"); 6771 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6772 Args, ResultTy, VK_PRValue, RParenLoc, 6773 CurFPFeatureOverrides(), NumParams); 6774 } else { 6775 TheCall = 6776 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6777 CurFPFeatureOverrides(), NumParams, UsesADL); 6778 } 6779 6780 if (!Context.isDependenceAllowed()) { 6781 // Forget about the nulled arguments since typo correction 6782 // do not handle them well. 6783 TheCall->shrinkNumArgs(Args.size()); 6784 // C cannot always handle TypoExpr nodes in builtin calls and direct 6785 // function calls as their argument checking don't necessarily handle 6786 // dependent types properly, so make sure any TypoExprs have been 6787 // dealt with. 6788 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6789 if (!Result.isUsable()) return ExprError(); 6790 CallExpr *TheOldCall = TheCall; 6791 TheCall = dyn_cast<CallExpr>(Result.get()); 6792 bool CorrectedTypos = TheCall != TheOldCall; 6793 if (!TheCall) return Result; 6794 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6795 6796 // A new call expression node was created if some typos were corrected. 6797 // However it may not have been constructed with enough storage. In this 6798 // case, rebuild the node with enough storage. The waste of space is 6799 // immaterial since this only happens when some typos were corrected. 6800 if (CorrectedTypos && Args.size() < NumParams) { 6801 if (Config) 6802 TheCall = CUDAKernelCallExpr::Create( 6803 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6804 RParenLoc, CurFPFeatureOverrides(), NumParams); 6805 else 6806 TheCall = 6807 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6808 CurFPFeatureOverrides(), NumParams, UsesADL); 6809 } 6810 // We can now handle the nulled arguments for the default arguments. 6811 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6812 } 6813 6814 // Bail out early if calling a builtin with custom type checking. 6815 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6816 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6817 6818 if (getLangOpts().CUDA) { 6819 if (Config) { 6820 // CUDA: Kernel calls must be to global functions 6821 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6822 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6823 << FDecl << Fn->getSourceRange()); 6824 6825 // CUDA: Kernel function must have 'void' return type 6826 if (!FuncT->getReturnType()->isVoidType() && 6827 !FuncT->getReturnType()->getAs<AutoType>() && 6828 !FuncT->getReturnType()->isInstantiationDependentType()) 6829 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6830 << Fn->getType() << Fn->getSourceRange()); 6831 } else { 6832 // CUDA: Calls to global functions must be configured 6833 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6834 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6835 << FDecl << Fn->getSourceRange()); 6836 } 6837 } 6838 6839 // Check for a valid return type 6840 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6841 FDecl)) 6842 return ExprError(); 6843 6844 // We know the result type of the call, set it. 6845 TheCall->setType(FuncT->getCallResultType(Context)); 6846 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6847 6848 if (Proto) { 6849 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6850 IsExecConfig)) 6851 return ExprError(); 6852 } else { 6853 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6854 6855 if (FDecl) { 6856 // Check if we have too few/too many template arguments, based 6857 // on our knowledge of the function definition. 6858 const FunctionDecl *Def = nullptr; 6859 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6860 Proto = Def->getType()->getAs<FunctionProtoType>(); 6861 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6862 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6863 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6864 } 6865 6866 // If the function we're calling isn't a function prototype, but we have 6867 // a function prototype from a prior declaratiom, use that prototype. 6868 if (!FDecl->hasPrototype()) 6869 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6870 } 6871 6872 // Promote the arguments (C99 6.5.2.2p6). 6873 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6874 Expr *Arg = Args[i]; 6875 6876 if (Proto && i < Proto->getNumParams()) { 6877 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6878 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6879 ExprResult ArgE = 6880 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6881 if (ArgE.isInvalid()) 6882 return true; 6883 6884 Arg = ArgE.getAs<Expr>(); 6885 6886 } else { 6887 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6888 6889 if (ArgE.isInvalid()) 6890 return true; 6891 6892 Arg = ArgE.getAs<Expr>(); 6893 } 6894 6895 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6896 diag::err_call_incomplete_argument, Arg)) 6897 return ExprError(); 6898 6899 TheCall->setArg(i, Arg); 6900 } 6901 TheCall->computeDependence(); 6902 } 6903 6904 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6905 if (!Method->isStatic()) 6906 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6907 << Fn->getSourceRange()); 6908 6909 // Check for sentinels 6910 if (NDecl) 6911 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6912 6913 // Warn for unions passing across security boundary (CMSE). 6914 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6915 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6916 if (const auto *RT = 6917 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6918 if (RT->getDecl()->isOrContainsUnion()) 6919 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6920 << 0 << i; 6921 } 6922 } 6923 } 6924 6925 // Do special checking on direct calls to functions. 6926 if (FDecl) { 6927 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6928 return ExprError(); 6929 6930 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6931 6932 if (BuiltinID) 6933 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6934 } else if (NDecl) { 6935 if (CheckPointerCall(NDecl, TheCall, Proto)) 6936 return ExprError(); 6937 } else { 6938 if (CheckOtherCall(TheCall, Proto)) 6939 return ExprError(); 6940 } 6941 6942 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6943 } 6944 6945 ExprResult 6946 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6947 SourceLocation RParenLoc, Expr *InitExpr) { 6948 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6949 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6950 6951 TypeSourceInfo *TInfo; 6952 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6953 if (!TInfo) 6954 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6955 6956 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6957 } 6958 6959 ExprResult 6960 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6961 SourceLocation RParenLoc, Expr *LiteralExpr) { 6962 QualType literalType = TInfo->getType(); 6963 6964 if (literalType->isArrayType()) { 6965 if (RequireCompleteSizedType( 6966 LParenLoc, Context.getBaseElementType(literalType), 6967 diag::err_array_incomplete_or_sizeless_type, 6968 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6969 return ExprError(); 6970 if (literalType->isVariableArrayType()) { 6971 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6972 diag::err_variable_object_no_init)) { 6973 return ExprError(); 6974 } 6975 } 6976 } else if (!literalType->isDependentType() && 6977 RequireCompleteType(LParenLoc, literalType, 6978 diag::err_typecheck_decl_incomplete_type, 6979 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6980 return ExprError(); 6981 6982 InitializedEntity Entity 6983 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6984 InitializationKind Kind 6985 = InitializationKind::CreateCStyleCast(LParenLoc, 6986 SourceRange(LParenLoc, RParenLoc), 6987 /*InitList=*/true); 6988 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6989 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6990 &literalType); 6991 if (Result.isInvalid()) 6992 return ExprError(); 6993 LiteralExpr = Result.get(); 6994 6995 bool isFileScope = !CurContext->isFunctionOrMethod(); 6996 6997 // In C, compound literals are l-values for some reason. 6998 // For GCC compatibility, in C++, file-scope array compound literals with 6999 // constant initializers are also l-values, and compound literals are 7000 // otherwise prvalues. 7001 // 7002 // (GCC also treats C++ list-initialized file-scope array prvalues with 7003 // constant initializers as l-values, but that's non-conforming, so we don't 7004 // follow it there.) 7005 // 7006 // FIXME: It would be better to handle the lvalue cases as materializing and 7007 // lifetime-extending a temporary object, but our materialized temporaries 7008 // representation only supports lifetime extension from a variable, not "out 7009 // of thin air". 7010 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7011 // is bound to the result of applying array-to-pointer decay to the compound 7012 // literal. 7013 // FIXME: GCC supports compound literals of reference type, which should 7014 // obviously have a value kind derived from the kind of reference involved. 7015 ExprValueKind VK = 7016 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7017 ? VK_PRValue 7018 : VK_LValue; 7019 7020 if (isFileScope) 7021 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7022 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7023 Expr *Init = ILE->getInit(i); 7024 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7025 } 7026 7027 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7028 VK, LiteralExpr, isFileScope); 7029 if (isFileScope) { 7030 if (!LiteralExpr->isTypeDependent() && 7031 !LiteralExpr->isValueDependent() && 7032 !literalType->isDependentType()) // C99 6.5.2.5p3 7033 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7034 return ExprError(); 7035 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7036 literalType.getAddressSpace() != LangAS::Default) { 7037 // Embedded-C extensions to C99 6.5.2.5: 7038 // "If the compound literal occurs inside the body of a function, the 7039 // type name shall not be qualified by an address-space qualifier." 7040 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7041 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7042 return ExprError(); 7043 } 7044 7045 if (!isFileScope && !getLangOpts().CPlusPlus) { 7046 // Compound literals that have automatic storage duration are destroyed at 7047 // the end of the scope in C; in C++, they're just temporaries. 7048 7049 // Emit diagnostics if it is or contains a C union type that is non-trivial 7050 // to destruct. 7051 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7052 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7053 NTCUC_CompoundLiteral, NTCUK_Destruct); 7054 7055 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7056 if (literalType.isDestructedType()) { 7057 Cleanup.setExprNeedsCleanups(true); 7058 ExprCleanupObjects.push_back(E); 7059 getCurFunction()->setHasBranchProtectedScope(); 7060 } 7061 } 7062 7063 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7064 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7065 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7066 E->getInitializer()->getExprLoc()); 7067 7068 return MaybeBindToTemporary(E); 7069 } 7070 7071 ExprResult 7072 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7073 SourceLocation RBraceLoc) { 7074 // Only produce each kind of designated initialization diagnostic once. 7075 SourceLocation FirstDesignator; 7076 bool DiagnosedArrayDesignator = false; 7077 bool DiagnosedNestedDesignator = false; 7078 bool DiagnosedMixedDesignator = false; 7079 7080 // Check that any designated initializers are syntactically valid in the 7081 // current language mode. 7082 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7083 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7084 if (FirstDesignator.isInvalid()) 7085 FirstDesignator = DIE->getBeginLoc(); 7086 7087 if (!getLangOpts().CPlusPlus) 7088 break; 7089 7090 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7091 DiagnosedNestedDesignator = true; 7092 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7093 << DIE->getDesignatorsSourceRange(); 7094 } 7095 7096 for (auto &Desig : DIE->designators()) { 7097 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7098 DiagnosedArrayDesignator = true; 7099 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7100 << Desig.getSourceRange(); 7101 } 7102 } 7103 7104 if (!DiagnosedMixedDesignator && 7105 !isa<DesignatedInitExpr>(InitArgList[0])) { 7106 DiagnosedMixedDesignator = true; 7107 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7108 << DIE->getSourceRange(); 7109 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7110 << InitArgList[0]->getSourceRange(); 7111 } 7112 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7113 isa<DesignatedInitExpr>(InitArgList[0])) { 7114 DiagnosedMixedDesignator = true; 7115 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7116 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7117 << DIE->getSourceRange(); 7118 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7119 << InitArgList[I]->getSourceRange(); 7120 } 7121 } 7122 7123 if (FirstDesignator.isValid()) { 7124 // Only diagnose designated initiaization as a C++20 extension if we didn't 7125 // already diagnose use of (non-C++20) C99 designator syntax. 7126 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7127 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7128 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7129 ? diag::warn_cxx17_compat_designated_init 7130 : diag::ext_cxx_designated_init); 7131 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7132 Diag(FirstDesignator, diag::ext_designated_init); 7133 } 7134 } 7135 7136 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7137 } 7138 7139 ExprResult 7140 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7141 SourceLocation RBraceLoc) { 7142 // Semantic analysis for initializers is done by ActOnDeclarator() and 7143 // CheckInitializer() - it requires knowledge of the object being initialized. 7144 7145 // Immediately handle non-overload placeholders. Overloads can be 7146 // resolved contextually, but everything else here can't. 7147 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7148 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7149 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7150 7151 // Ignore failures; dropping the entire initializer list because 7152 // of one failure would be terrible for indexing/etc. 7153 if (result.isInvalid()) continue; 7154 7155 InitArgList[I] = result.get(); 7156 } 7157 } 7158 7159 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7160 RBraceLoc); 7161 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7162 return E; 7163 } 7164 7165 /// Do an explicit extend of the given block pointer if we're in ARC. 7166 void Sema::maybeExtendBlockObject(ExprResult &E) { 7167 assert(E.get()->getType()->isBlockPointerType()); 7168 assert(E.get()->isPRValue()); 7169 7170 // Only do this in an r-value context. 7171 if (!getLangOpts().ObjCAutoRefCount) return; 7172 7173 E = ImplicitCastExpr::Create( 7174 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7175 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7176 Cleanup.setExprNeedsCleanups(true); 7177 } 7178 7179 /// Prepare a conversion of the given expression to an ObjC object 7180 /// pointer type. 7181 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7182 QualType type = E.get()->getType(); 7183 if (type->isObjCObjectPointerType()) { 7184 return CK_BitCast; 7185 } else if (type->isBlockPointerType()) { 7186 maybeExtendBlockObject(E); 7187 return CK_BlockPointerToObjCPointerCast; 7188 } else { 7189 assert(type->isPointerType()); 7190 return CK_CPointerToObjCPointerCast; 7191 } 7192 } 7193 7194 /// Prepares for a scalar cast, performing all the necessary stages 7195 /// except the final cast and returning the kind required. 7196 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7197 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7198 // Also, callers should have filtered out the invalid cases with 7199 // pointers. Everything else should be possible. 7200 7201 QualType SrcTy = Src.get()->getType(); 7202 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7203 return CK_NoOp; 7204 7205 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7206 case Type::STK_MemberPointer: 7207 llvm_unreachable("member pointer type in C"); 7208 7209 case Type::STK_CPointer: 7210 case Type::STK_BlockPointer: 7211 case Type::STK_ObjCObjectPointer: 7212 switch (DestTy->getScalarTypeKind()) { 7213 case Type::STK_CPointer: { 7214 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7215 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7216 if (SrcAS != DestAS) 7217 return CK_AddressSpaceConversion; 7218 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7219 return CK_NoOp; 7220 return CK_BitCast; 7221 } 7222 case Type::STK_BlockPointer: 7223 return (SrcKind == Type::STK_BlockPointer 7224 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7225 case Type::STK_ObjCObjectPointer: 7226 if (SrcKind == Type::STK_ObjCObjectPointer) 7227 return CK_BitCast; 7228 if (SrcKind == Type::STK_CPointer) 7229 return CK_CPointerToObjCPointerCast; 7230 maybeExtendBlockObject(Src); 7231 return CK_BlockPointerToObjCPointerCast; 7232 case Type::STK_Bool: 7233 return CK_PointerToBoolean; 7234 case Type::STK_Integral: 7235 return CK_PointerToIntegral; 7236 case Type::STK_Floating: 7237 case Type::STK_FloatingComplex: 7238 case Type::STK_IntegralComplex: 7239 case Type::STK_MemberPointer: 7240 case Type::STK_FixedPoint: 7241 llvm_unreachable("illegal cast from pointer"); 7242 } 7243 llvm_unreachable("Should have returned before this"); 7244 7245 case Type::STK_FixedPoint: 7246 switch (DestTy->getScalarTypeKind()) { 7247 case Type::STK_FixedPoint: 7248 return CK_FixedPointCast; 7249 case Type::STK_Bool: 7250 return CK_FixedPointToBoolean; 7251 case Type::STK_Integral: 7252 return CK_FixedPointToIntegral; 7253 case Type::STK_Floating: 7254 return CK_FixedPointToFloating; 7255 case Type::STK_IntegralComplex: 7256 case Type::STK_FloatingComplex: 7257 Diag(Src.get()->getExprLoc(), 7258 diag::err_unimplemented_conversion_with_fixed_point_type) 7259 << DestTy; 7260 return CK_IntegralCast; 7261 case Type::STK_CPointer: 7262 case Type::STK_ObjCObjectPointer: 7263 case Type::STK_BlockPointer: 7264 case Type::STK_MemberPointer: 7265 llvm_unreachable("illegal cast to pointer type"); 7266 } 7267 llvm_unreachable("Should have returned before this"); 7268 7269 case Type::STK_Bool: // casting from bool is like casting from an integer 7270 case Type::STK_Integral: 7271 switch (DestTy->getScalarTypeKind()) { 7272 case Type::STK_CPointer: 7273 case Type::STK_ObjCObjectPointer: 7274 case Type::STK_BlockPointer: 7275 if (Src.get()->isNullPointerConstant(Context, 7276 Expr::NPC_ValueDependentIsNull)) 7277 return CK_NullToPointer; 7278 return CK_IntegralToPointer; 7279 case Type::STK_Bool: 7280 return CK_IntegralToBoolean; 7281 case Type::STK_Integral: 7282 return CK_IntegralCast; 7283 case Type::STK_Floating: 7284 return CK_IntegralToFloating; 7285 case Type::STK_IntegralComplex: 7286 Src = ImpCastExprToType(Src.get(), 7287 DestTy->castAs<ComplexType>()->getElementType(), 7288 CK_IntegralCast); 7289 return CK_IntegralRealToComplex; 7290 case Type::STK_FloatingComplex: 7291 Src = ImpCastExprToType(Src.get(), 7292 DestTy->castAs<ComplexType>()->getElementType(), 7293 CK_IntegralToFloating); 7294 return CK_FloatingRealToComplex; 7295 case Type::STK_MemberPointer: 7296 llvm_unreachable("member pointer type in C"); 7297 case Type::STK_FixedPoint: 7298 return CK_IntegralToFixedPoint; 7299 } 7300 llvm_unreachable("Should have returned before this"); 7301 7302 case Type::STK_Floating: 7303 switch (DestTy->getScalarTypeKind()) { 7304 case Type::STK_Floating: 7305 return CK_FloatingCast; 7306 case Type::STK_Bool: 7307 return CK_FloatingToBoolean; 7308 case Type::STK_Integral: 7309 return CK_FloatingToIntegral; 7310 case Type::STK_FloatingComplex: 7311 Src = ImpCastExprToType(Src.get(), 7312 DestTy->castAs<ComplexType>()->getElementType(), 7313 CK_FloatingCast); 7314 return CK_FloatingRealToComplex; 7315 case Type::STK_IntegralComplex: 7316 Src = ImpCastExprToType(Src.get(), 7317 DestTy->castAs<ComplexType>()->getElementType(), 7318 CK_FloatingToIntegral); 7319 return CK_IntegralRealToComplex; 7320 case Type::STK_CPointer: 7321 case Type::STK_ObjCObjectPointer: 7322 case Type::STK_BlockPointer: 7323 llvm_unreachable("valid float->pointer cast?"); 7324 case Type::STK_MemberPointer: 7325 llvm_unreachable("member pointer type in C"); 7326 case Type::STK_FixedPoint: 7327 return CK_FloatingToFixedPoint; 7328 } 7329 llvm_unreachable("Should have returned before this"); 7330 7331 case Type::STK_FloatingComplex: 7332 switch (DestTy->getScalarTypeKind()) { 7333 case Type::STK_FloatingComplex: 7334 return CK_FloatingComplexCast; 7335 case Type::STK_IntegralComplex: 7336 return CK_FloatingComplexToIntegralComplex; 7337 case Type::STK_Floating: { 7338 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7339 if (Context.hasSameType(ET, DestTy)) 7340 return CK_FloatingComplexToReal; 7341 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7342 return CK_FloatingCast; 7343 } 7344 case Type::STK_Bool: 7345 return CK_FloatingComplexToBoolean; 7346 case Type::STK_Integral: 7347 Src = ImpCastExprToType(Src.get(), 7348 SrcTy->castAs<ComplexType>()->getElementType(), 7349 CK_FloatingComplexToReal); 7350 return CK_FloatingToIntegral; 7351 case Type::STK_CPointer: 7352 case Type::STK_ObjCObjectPointer: 7353 case Type::STK_BlockPointer: 7354 llvm_unreachable("valid complex float->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 case Type::STK_IntegralComplex: 7366 switch (DestTy->getScalarTypeKind()) { 7367 case Type::STK_FloatingComplex: 7368 return CK_IntegralComplexToFloatingComplex; 7369 case Type::STK_IntegralComplex: 7370 return CK_IntegralComplexCast; 7371 case Type::STK_Integral: { 7372 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7373 if (Context.hasSameType(ET, DestTy)) 7374 return CK_IntegralComplexToReal; 7375 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7376 return CK_IntegralCast; 7377 } 7378 case Type::STK_Bool: 7379 return CK_IntegralComplexToBoolean; 7380 case Type::STK_Floating: 7381 Src = ImpCastExprToType(Src.get(), 7382 SrcTy->castAs<ComplexType>()->getElementType(), 7383 CK_IntegralComplexToReal); 7384 return CK_IntegralToFloating; 7385 case Type::STK_CPointer: 7386 case Type::STK_ObjCObjectPointer: 7387 case Type::STK_BlockPointer: 7388 llvm_unreachable("valid complex int->pointer cast?"); 7389 case Type::STK_MemberPointer: 7390 llvm_unreachable("member pointer type in C"); 7391 case Type::STK_FixedPoint: 7392 Diag(Src.get()->getExprLoc(), 7393 diag::err_unimplemented_conversion_with_fixed_point_type) 7394 << SrcTy; 7395 return CK_IntegralCast; 7396 } 7397 llvm_unreachable("Should have returned before this"); 7398 } 7399 7400 llvm_unreachable("Unhandled scalar cast"); 7401 } 7402 7403 static bool breakDownVectorType(QualType type, uint64_t &len, 7404 QualType &eltType) { 7405 // Vectors are simple. 7406 if (const VectorType *vecType = type->getAs<VectorType>()) { 7407 len = vecType->getNumElements(); 7408 eltType = vecType->getElementType(); 7409 assert(eltType->isScalarType()); 7410 return true; 7411 } 7412 7413 // We allow lax conversion to and from non-vector types, but only if 7414 // they're real types (i.e. non-complex, non-pointer scalar types). 7415 if (!type->isRealType()) return false; 7416 7417 len = 1; 7418 eltType = type; 7419 return true; 7420 } 7421 7422 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7423 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7424 /// allowed? 7425 /// 7426 /// This will also return false if the two given types do not make sense from 7427 /// the perspective of SVE bitcasts. 7428 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7429 assert(srcTy->isVectorType() || destTy->isVectorType()); 7430 7431 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7432 if (!FirstType->isSizelessBuiltinType()) 7433 return false; 7434 7435 const auto *VecTy = SecondType->getAs<VectorType>(); 7436 return VecTy && 7437 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7438 }; 7439 7440 return ValidScalableConversion(srcTy, destTy) || 7441 ValidScalableConversion(destTy, srcTy); 7442 } 7443 7444 /// Are the two types matrix types and do they have the same dimensions i.e. 7445 /// do they have the same number of rows and the same number of columns? 7446 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7447 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7448 return false; 7449 7450 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7451 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7452 7453 return matSrcType->getNumRows() == matDestType->getNumRows() && 7454 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7455 } 7456 7457 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7458 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7459 7460 uint64_t SrcLen, DestLen; 7461 QualType SrcEltTy, DestEltTy; 7462 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7463 return false; 7464 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7465 return false; 7466 7467 // ASTContext::getTypeSize will return the size rounded up to a 7468 // power of 2, so instead of using that, we need to use the raw 7469 // element size multiplied by the element count. 7470 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7471 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7472 7473 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7474 } 7475 7476 /// Are the two types lax-compatible vector types? That is, given 7477 /// that one of them is a vector, do they have equal storage sizes, 7478 /// where the storage size is the number of elements times the element 7479 /// size? 7480 /// 7481 /// This will also return false if either of the types is neither a 7482 /// vector nor a real type. 7483 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7484 assert(destTy->isVectorType() || srcTy->isVectorType()); 7485 7486 // Disallow lax conversions between scalars and ExtVectors (these 7487 // conversions are allowed for other vector types because common headers 7488 // depend on them). Most scalar OP ExtVector cases are handled by the 7489 // splat path anyway, which does what we want (convert, not bitcast). 7490 // What this rules out for ExtVectors is crazy things like char4*float. 7491 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7492 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7493 7494 return areVectorTypesSameSize(srcTy, destTy); 7495 } 7496 7497 /// Is this a legal conversion between two types, one of which is 7498 /// known to be a vector type? 7499 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7500 assert(destTy->isVectorType() || srcTy->isVectorType()); 7501 7502 switch (Context.getLangOpts().getLaxVectorConversions()) { 7503 case LangOptions::LaxVectorConversionKind::None: 7504 return false; 7505 7506 case LangOptions::LaxVectorConversionKind::Integer: 7507 if (!srcTy->isIntegralOrEnumerationType()) { 7508 auto *Vec = srcTy->getAs<VectorType>(); 7509 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7510 return false; 7511 } 7512 if (!destTy->isIntegralOrEnumerationType()) { 7513 auto *Vec = destTy->getAs<VectorType>(); 7514 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7515 return false; 7516 } 7517 // OK, integer (vector) -> integer (vector) bitcast. 7518 break; 7519 7520 case LangOptions::LaxVectorConversionKind::All: 7521 break; 7522 } 7523 7524 return areLaxCompatibleVectorTypes(srcTy, destTy); 7525 } 7526 7527 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7528 CastKind &Kind) { 7529 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7530 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7531 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7532 << DestTy << SrcTy << R; 7533 } 7534 } else if (SrcTy->isMatrixType()) { 7535 return Diag(R.getBegin(), 7536 diag::err_invalid_conversion_between_matrix_and_type) 7537 << SrcTy << DestTy << R; 7538 } else if (DestTy->isMatrixType()) { 7539 return Diag(R.getBegin(), 7540 diag::err_invalid_conversion_between_matrix_and_type) 7541 << DestTy << SrcTy << R; 7542 } 7543 7544 Kind = CK_MatrixCast; 7545 return false; 7546 } 7547 7548 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7549 CastKind &Kind) { 7550 assert(VectorTy->isVectorType() && "Not a vector type!"); 7551 7552 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7553 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7554 return Diag(R.getBegin(), 7555 Ty->isVectorType() ? 7556 diag::err_invalid_conversion_between_vectors : 7557 diag::err_invalid_conversion_between_vector_and_integer) 7558 << VectorTy << Ty << R; 7559 } else 7560 return Diag(R.getBegin(), 7561 diag::err_invalid_conversion_between_vector_and_scalar) 7562 << VectorTy << Ty << R; 7563 7564 Kind = CK_BitCast; 7565 return false; 7566 } 7567 7568 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7569 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7570 7571 if (DestElemTy == SplattedExpr->getType()) 7572 return SplattedExpr; 7573 7574 assert(DestElemTy->isFloatingType() || 7575 DestElemTy->isIntegralOrEnumerationType()); 7576 7577 CastKind CK; 7578 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7579 // OpenCL requires that we convert `true` boolean expressions to -1, but 7580 // only when splatting vectors. 7581 if (DestElemTy->isFloatingType()) { 7582 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7583 // in two steps: boolean to signed integral, then to floating. 7584 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7585 CK_BooleanToSignedIntegral); 7586 SplattedExpr = CastExprRes.get(); 7587 CK = CK_IntegralToFloating; 7588 } else { 7589 CK = CK_BooleanToSignedIntegral; 7590 } 7591 } else { 7592 ExprResult CastExprRes = SplattedExpr; 7593 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7594 if (CastExprRes.isInvalid()) 7595 return ExprError(); 7596 SplattedExpr = CastExprRes.get(); 7597 } 7598 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7599 } 7600 7601 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7602 Expr *CastExpr, CastKind &Kind) { 7603 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7604 7605 QualType SrcTy = CastExpr->getType(); 7606 7607 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7608 // an ExtVectorType. 7609 // In OpenCL, casts between vectors of different types are not allowed. 7610 // (See OpenCL 6.2). 7611 if (SrcTy->isVectorType()) { 7612 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7613 (getLangOpts().OpenCL && 7614 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7615 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7616 << DestTy << SrcTy << R; 7617 return ExprError(); 7618 } 7619 Kind = CK_BitCast; 7620 return CastExpr; 7621 } 7622 7623 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7624 // conversion will take place first from scalar to elt type, and then 7625 // splat from elt type to vector. 7626 if (SrcTy->isPointerType()) 7627 return Diag(R.getBegin(), 7628 diag::err_invalid_conversion_between_vector_and_scalar) 7629 << DestTy << SrcTy << R; 7630 7631 Kind = CK_VectorSplat; 7632 return prepareVectorSplat(DestTy, CastExpr); 7633 } 7634 7635 ExprResult 7636 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7637 Declarator &D, ParsedType &Ty, 7638 SourceLocation RParenLoc, Expr *CastExpr) { 7639 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7640 "ActOnCastExpr(): missing type or expr"); 7641 7642 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7643 if (D.isInvalidType()) 7644 return ExprError(); 7645 7646 if (getLangOpts().CPlusPlus) { 7647 // Check that there are no default arguments (C++ only). 7648 CheckExtraCXXDefaultArguments(D); 7649 } else { 7650 // Make sure any TypoExprs have been dealt with. 7651 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7652 if (!Res.isUsable()) 7653 return ExprError(); 7654 CastExpr = Res.get(); 7655 } 7656 7657 checkUnusedDeclAttributes(D); 7658 7659 QualType castType = castTInfo->getType(); 7660 Ty = CreateParsedType(castType, castTInfo); 7661 7662 bool isVectorLiteral = false; 7663 7664 // Check for an altivec or OpenCL literal, 7665 // i.e. all the elements are integer constants. 7666 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7667 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7668 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7669 && castType->isVectorType() && (PE || PLE)) { 7670 if (PLE && PLE->getNumExprs() == 0) { 7671 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7672 return ExprError(); 7673 } 7674 if (PE || PLE->getNumExprs() == 1) { 7675 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7676 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7677 isVectorLiteral = true; 7678 } 7679 else 7680 isVectorLiteral = true; 7681 } 7682 7683 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7684 // then handle it as such. 7685 if (isVectorLiteral) 7686 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7687 7688 // If the Expr being casted is a ParenListExpr, handle it specially. 7689 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7690 // sequence of BinOp comma operators. 7691 if (isa<ParenListExpr>(CastExpr)) { 7692 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7693 if (Result.isInvalid()) return ExprError(); 7694 CastExpr = Result.get(); 7695 } 7696 7697 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7698 !getSourceManager().isInSystemMacro(LParenLoc)) 7699 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7700 7701 CheckTollFreeBridgeCast(castType, CastExpr); 7702 7703 CheckObjCBridgeRelatedCast(castType, CastExpr); 7704 7705 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7706 7707 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7708 } 7709 7710 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7711 SourceLocation RParenLoc, Expr *E, 7712 TypeSourceInfo *TInfo) { 7713 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7714 "Expected paren or paren list expression"); 7715 7716 Expr **exprs; 7717 unsigned numExprs; 7718 Expr *subExpr; 7719 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7720 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7721 LiteralLParenLoc = PE->getLParenLoc(); 7722 LiteralRParenLoc = PE->getRParenLoc(); 7723 exprs = PE->getExprs(); 7724 numExprs = PE->getNumExprs(); 7725 } else { // isa<ParenExpr> by assertion at function entrance 7726 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7727 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7728 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7729 exprs = &subExpr; 7730 numExprs = 1; 7731 } 7732 7733 QualType Ty = TInfo->getType(); 7734 assert(Ty->isVectorType() && "Expected vector type"); 7735 7736 SmallVector<Expr *, 8> initExprs; 7737 const VectorType *VTy = Ty->castAs<VectorType>(); 7738 unsigned numElems = VTy->getNumElements(); 7739 7740 // '(...)' form of vector initialization in AltiVec: the number of 7741 // initializers must be one or must match the size of the vector. 7742 // If a single value is specified in the initializer then it will be 7743 // replicated to all the components of the vector 7744 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7745 VTy->getElementType())) 7746 return ExprError(); 7747 if (ShouldSplatAltivecScalarInCast(VTy)) { 7748 // The number of initializers must be one or must match the size of the 7749 // vector. If a single value is specified in the initializer then it will 7750 // be replicated to all the components of the vector 7751 if (numExprs == 1) { 7752 QualType ElemTy = VTy->getElementType(); 7753 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7754 if (Literal.isInvalid()) 7755 return ExprError(); 7756 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7757 PrepareScalarCast(Literal, ElemTy)); 7758 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7759 } 7760 else if (numExprs < numElems) { 7761 Diag(E->getExprLoc(), 7762 diag::err_incorrect_number_of_vector_initializers); 7763 return ExprError(); 7764 } 7765 else 7766 initExprs.append(exprs, exprs + numExprs); 7767 } 7768 else { 7769 // For OpenCL, when the number of initializers is a single value, 7770 // it will be replicated to all components of the vector. 7771 if (getLangOpts().OpenCL && 7772 VTy->getVectorKind() == VectorType::GenericVector && 7773 numExprs == 1) { 7774 QualType ElemTy = VTy->getElementType(); 7775 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7776 if (Literal.isInvalid()) 7777 return ExprError(); 7778 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7779 PrepareScalarCast(Literal, ElemTy)); 7780 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7781 } 7782 7783 initExprs.append(exprs, exprs + numExprs); 7784 } 7785 // FIXME: This means that pretty-printing the final AST will produce curly 7786 // braces instead of the original commas. 7787 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7788 initExprs, LiteralRParenLoc); 7789 initE->setType(Ty); 7790 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7791 } 7792 7793 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7794 /// the ParenListExpr into a sequence of comma binary operators. 7795 ExprResult 7796 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7797 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7798 if (!E) 7799 return OrigExpr; 7800 7801 ExprResult Result(E->getExpr(0)); 7802 7803 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7804 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7805 E->getExpr(i)); 7806 7807 if (Result.isInvalid()) return ExprError(); 7808 7809 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7810 } 7811 7812 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7813 SourceLocation R, 7814 MultiExprArg Val) { 7815 return ParenListExpr::Create(Context, L, Val, R); 7816 } 7817 7818 /// Emit a specialized diagnostic when one expression is a null pointer 7819 /// constant and the other is not a pointer. Returns true if a diagnostic is 7820 /// emitted. 7821 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7822 SourceLocation QuestionLoc) { 7823 Expr *NullExpr = LHSExpr; 7824 Expr *NonPointerExpr = RHSExpr; 7825 Expr::NullPointerConstantKind NullKind = 7826 NullExpr->isNullPointerConstant(Context, 7827 Expr::NPC_ValueDependentIsNotNull); 7828 7829 if (NullKind == Expr::NPCK_NotNull) { 7830 NullExpr = RHSExpr; 7831 NonPointerExpr = LHSExpr; 7832 NullKind = 7833 NullExpr->isNullPointerConstant(Context, 7834 Expr::NPC_ValueDependentIsNotNull); 7835 } 7836 7837 if (NullKind == Expr::NPCK_NotNull) 7838 return false; 7839 7840 if (NullKind == Expr::NPCK_ZeroExpression) 7841 return false; 7842 7843 if (NullKind == Expr::NPCK_ZeroLiteral) { 7844 // In this case, check to make sure that we got here from a "NULL" 7845 // string in the source code. 7846 NullExpr = NullExpr->IgnoreParenImpCasts(); 7847 SourceLocation loc = NullExpr->getExprLoc(); 7848 if (!findMacroSpelling(loc, "NULL")) 7849 return false; 7850 } 7851 7852 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7853 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7854 << NonPointerExpr->getType() << DiagType 7855 << NonPointerExpr->getSourceRange(); 7856 return true; 7857 } 7858 7859 /// Return false if the condition expression is valid, true otherwise. 7860 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7861 QualType CondTy = Cond->getType(); 7862 7863 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7864 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7865 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7866 << CondTy << Cond->getSourceRange(); 7867 return true; 7868 } 7869 7870 // C99 6.5.15p2 7871 if (CondTy->isScalarType()) return false; 7872 7873 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7874 << CondTy << Cond->getSourceRange(); 7875 return true; 7876 } 7877 7878 /// Handle when one or both operands are void type. 7879 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7880 ExprResult &RHS) { 7881 Expr *LHSExpr = LHS.get(); 7882 Expr *RHSExpr = RHS.get(); 7883 7884 if (!LHSExpr->getType()->isVoidType()) 7885 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7886 << RHSExpr->getSourceRange(); 7887 if (!RHSExpr->getType()->isVoidType()) 7888 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7889 << LHSExpr->getSourceRange(); 7890 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7891 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7892 return S.Context.VoidTy; 7893 } 7894 7895 /// Return false if the NullExpr can be promoted to PointerTy, 7896 /// true otherwise. 7897 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7898 QualType PointerTy) { 7899 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7900 !NullExpr.get()->isNullPointerConstant(S.Context, 7901 Expr::NPC_ValueDependentIsNull)) 7902 return true; 7903 7904 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7905 return false; 7906 } 7907 7908 /// Checks compatibility between two pointers and return the resulting 7909 /// type. 7910 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7911 ExprResult &RHS, 7912 SourceLocation Loc) { 7913 QualType LHSTy = LHS.get()->getType(); 7914 QualType RHSTy = RHS.get()->getType(); 7915 7916 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7917 // Two identical pointers types are always compatible. 7918 return LHSTy; 7919 } 7920 7921 QualType lhptee, rhptee; 7922 7923 // Get the pointee types. 7924 bool IsBlockPointer = false; 7925 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7926 lhptee = LHSBTy->getPointeeType(); 7927 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7928 IsBlockPointer = true; 7929 } else { 7930 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7931 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7932 } 7933 7934 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7935 // differently qualified versions of compatible types, the result type is 7936 // a pointer to an appropriately qualified version of the composite 7937 // type. 7938 7939 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7940 // clause doesn't make sense for our extensions. E.g. address space 2 should 7941 // be incompatible with address space 3: they may live on different devices or 7942 // anything. 7943 Qualifiers lhQual = lhptee.getQualifiers(); 7944 Qualifiers rhQual = rhptee.getQualifiers(); 7945 7946 LangAS ResultAddrSpace = LangAS::Default; 7947 LangAS LAddrSpace = lhQual.getAddressSpace(); 7948 LangAS RAddrSpace = rhQual.getAddressSpace(); 7949 7950 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7951 // spaces is disallowed. 7952 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7953 ResultAddrSpace = LAddrSpace; 7954 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7955 ResultAddrSpace = RAddrSpace; 7956 else { 7957 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7958 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7959 << RHS.get()->getSourceRange(); 7960 return QualType(); 7961 } 7962 7963 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7964 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7965 lhQual.removeCVRQualifiers(); 7966 rhQual.removeCVRQualifiers(); 7967 7968 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7969 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7970 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7971 // qual types are compatible iff 7972 // * corresponded types are compatible 7973 // * CVR qualifiers are equal 7974 // * address spaces are equal 7975 // Thus for conditional operator we merge CVR and address space unqualified 7976 // pointees and if there is a composite type we return a pointer to it with 7977 // merged qualifiers. 7978 LHSCastKind = 7979 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7980 RHSCastKind = 7981 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7982 lhQual.removeAddressSpace(); 7983 rhQual.removeAddressSpace(); 7984 7985 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7986 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7987 7988 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7989 7990 if (CompositeTy.isNull()) { 7991 // In this situation, we assume void* type. No especially good 7992 // reason, but this is what gcc does, and we do have to pick 7993 // to get a consistent AST. 7994 QualType incompatTy; 7995 incompatTy = S.Context.getPointerType( 7996 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7997 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7998 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7999 8000 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 8001 // for casts between types with incompatible address space qualifiers. 8002 // For the following code the compiler produces casts between global and 8003 // local address spaces of the corresponded innermost pointees: 8004 // local int *global *a; 8005 // global int *global *b; 8006 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8007 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8008 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8009 << RHS.get()->getSourceRange(); 8010 8011 return incompatTy; 8012 } 8013 8014 // The pointer types are compatible. 8015 // In case of OpenCL ResultTy should have the address space qualifier 8016 // which is a superset of address spaces of both the 2nd and the 3rd 8017 // operands of the conditional operator. 8018 QualType ResultTy = [&, ResultAddrSpace]() { 8019 if (S.getLangOpts().OpenCL) { 8020 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8021 CompositeQuals.setAddressSpace(ResultAddrSpace); 8022 return S.Context 8023 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8024 .withCVRQualifiers(MergedCVRQual); 8025 } 8026 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8027 }(); 8028 if (IsBlockPointer) 8029 ResultTy = S.Context.getBlockPointerType(ResultTy); 8030 else 8031 ResultTy = S.Context.getPointerType(ResultTy); 8032 8033 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8034 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8035 return ResultTy; 8036 } 8037 8038 /// Return the resulting type when the operands are both block pointers. 8039 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8040 ExprResult &LHS, 8041 ExprResult &RHS, 8042 SourceLocation Loc) { 8043 QualType LHSTy = LHS.get()->getType(); 8044 QualType RHSTy = RHS.get()->getType(); 8045 8046 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8047 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8048 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8049 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8050 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8051 return destType; 8052 } 8053 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8054 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8055 << RHS.get()->getSourceRange(); 8056 return QualType(); 8057 } 8058 8059 // We have 2 block pointer types. 8060 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8061 } 8062 8063 /// Return the resulting type when the operands are both pointers. 8064 static QualType 8065 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8066 ExprResult &RHS, 8067 SourceLocation Loc) { 8068 // get the pointer types 8069 QualType LHSTy = LHS.get()->getType(); 8070 QualType RHSTy = RHS.get()->getType(); 8071 8072 // get the "pointed to" types 8073 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8074 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8075 8076 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8077 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8078 // Figure out necessary qualifiers (C99 6.5.15p6) 8079 QualType destPointee 8080 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8081 QualType destType = S.Context.getPointerType(destPointee); 8082 // Add qualifiers if necessary. 8083 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8084 // Promote to void*. 8085 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8086 return destType; 8087 } 8088 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8089 QualType destPointee 8090 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8091 QualType destType = S.Context.getPointerType(destPointee); 8092 // Add qualifiers if necessary. 8093 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8094 // Promote to void*. 8095 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8096 return destType; 8097 } 8098 8099 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8100 } 8101 8102 /// Return false if the first expression is not an integer and the second 8103 /// expression is not a pointer, true otherwise. 8104 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8105 Expr* PointerExpr, SourceLocation Loc, 8106 bool IsIntFirstExpr) { 8107 if (!PointerExpr->getType()->isPointerType() || 8108 !Int.get()->getType()->isIntegerType()) 8109 return false; 8110 8111 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8112 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8113 8114 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8115 << Expr1->getType() << Expr2->getType() 8116 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8117 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8118 CK_IntegralToPointer); 8119 return true; 8120 } 8121 8122 /// Simple conversion between integer and floating point types. 8123 /// 8124 /// Used when handling the OpenCL conditional operator where the 8125 /// condition is a vector while the other operands are scalar. 8126 /// 8127 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8128 /// types are either integer or floating type. Between the two 8129 /// operands, the type with the higher rank is defined as the "result 8130 /// type". The other operand needs to be promoted to the same type. No 8131 /// other type promotion is allowed. We cannot use 8132 /// UsualArithmeticConversions() for this purpose, since it always 8133 /// promotes promotable types. 8134 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8135 ExprResult &RHS, 8136 SourceLocation QuestionLoc) { 8137 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8138 if (LHS.isInvalid()) 8139 return QualType(); 8140 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8141 if (RHS.isInvalid()) 8142 return QualType(); 8143 8144 // For conversion purposes, we ignore any qualifiers. 8145 // For example, "const float" and "float" are equivalent. 8146 QualType LHSType = 8147 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8148 QualType RHSType = 8149 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8150 8151 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8152 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8153 << LHSType << LHS.get()->getSourceRange(); 8154 return QualType(); 8155 } 8156 8157 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8158 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8159 << RHSType << RHS.get()->getSourceRange(); 8160 return QualType(); 8161 } 8162 8163 // If both types are identical, no conversion is needed. 8164 if (LHSType == RHSType) 8165 return LHSType; 8166 8167 // Now handle "real" floating types (i.e. float, double, long double). 8168 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8169 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8170 /*IsCompAssign = */ false); 8171 8172 // Finally, we have two differing integer types. 8173 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8174 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8175 } 8176 8177 /// Convert scalar operands to a vector that matches the 8178 /// condition in length. 8179 /// 8180 /// Used when handling the OpenCL conditional operator where the 8181 /// condition is a vector while the other operands are scalar. 8182 /// 8183 /// We first compute the "result type" for the scalar operands 8184 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8185 /// into a vector of that type where the length matches the condition 8186 /// vector type. s6.11.6 requires that the element types of the result 8187 /// and the condition must have the same number of bits. 8188 static QualType 8189 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8190 QualType CondTy, SourceLocation QuestionLoc) { 8191 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8192 if (ResTy.isNull()) return QualType(); 8193 8194 const VectorType *CV = CondTy->getAs<VectorType>(); 8195 assert(CV); 8196 8197 // Determine the vector result type 8198 unsigned NumElements = CV->getNumElements(); 8199 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8200 8201 // Ensure that all types have the same number of bits 8202 if (S.Context.getTypeSize(CV->getElementType()) 8203 != S.Context.getTypeSize(ResTy)) { 8204 // Since VectorTy is created internally, it does not pretty print 8205 // with an OpenCL name. Instead, we just print a description. 8206 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8207 SmallString<64> Str; 8208 llvm::raw_svector_ostream OS(Str); 8209 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8210 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8211 << CondTy << OS.str(); 8212 return QualType(); 8213 } 8214 8215 // Convert operands to the vector result type 8216 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8217 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8218 8219 return VectorTy; 8220 } 8221 8222 /// Return false if this is a valid OpenCL condition vector 8223 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8224 SourceLocation QuestionLoc) { 8225 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8226 // integral type. 8227 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8228 assert(CondTy); 8229 QualType EleTy = CondTy->getElementType(); 8230 if (EleTy->isIntegerType()) return false; 8231 8232 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8233 << Cond->getType() << Cond->getSourceRange(); 8234 return true; 8235 } 8236 8237 /// Return false if the vector condition type and the vector 8238 /// result type are compatible. 8239 /// 8240 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8241 /// number of elements, and their element types have the same number 8242 /// of bits. 8243 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8244 SourceLocation QuestionLoc) { 8245 const VectorType *CV = CondTy->getAs<VectorType>(); 8246 const VectorType *RV = VecResTy->getAs<VectorType>(); 8247 assert(CV && RV); 8248 8249 if (CV->getNumElements() != RV->getNumElements()) { 8250 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8251 << CondTy << VecResTy; 8252 return true; 8253 } 8254 8255 QualType CVE = CV->getElementType(); 8256 QualType RVE = RV->getElementType(); 8257 8258 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8259 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8260 << CondTy << VecResTy; 8261 return true; 8262 } 8263 8264 return false; 8265 } 8266 8267 /// Return the resulting type for the conditional operator in 8268 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8269 /// s6.3.i) when the condition is a vector type. 8270 static QualType 8271 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8272 ExprResult &LHS, ExprResult &RHS, 8273 SourceLocation QuestionLoc) { 8274 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8275 if (Cond.isInvalid()) 8276 return QualType(); 8277 QualType CondTy = Cond.get()->getType(); 8278 8279 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8280 return QualType(); 8281 8282 // If either operand is a vector then find the vector type of the 8283 // result as specified in OpenCL v1.1 s6.3.i. 8284 if (LHS.get()->getType()->isVectorType() || 8285 RHS.get()->getType()->isVectorType()) { 8286 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8287 /*isCompAssign*/false, 8288 /*AllowBothBool*/true, 8289 /*AllowBoolConversions*/false); 8290 if (VecResTy.isNull()) return QualType(); 8291 // The result type must match the condition type as specified in 8292 // OpenCL v1.1 s6.11.6. 8293 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8294 return QualType(); 8295 return VecResTy; 8296 } 8297 8298 // Both operands are scalar. 8299 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8300 } 8301 8302 /// Return true if the Expr is block type 8303 static bool checkBlockType(Sema &S, const Expr *E) { 8304 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8305 QualType Ty = CE->getCallee()->getType(); 8306 if (Ty->isBlockPointerType()) { 8307 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8308 return true; 8309 } 8310 } 8311 return false; 8312 } 8313 8314 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8315 /// In that case, LHS = cond. 8316 /// C99 6.5.15 8317 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8318 ExprResult &RHS, ExprValueKind &VK, 8319 ExprObjectKind &OK, 8320 SourceLocation QuestionLoc) { 8321 8322 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8323 if (!LHSResult.isUsable()) return QualType(); 8324 LHS = LHSResult; 8325 8326 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8327 if (!RHSResult.isUsable()) return QualType(); 8328 RHS = RHSResult; 8329 8330 // C++ is sufficiently different to merit its own checker. 8331 if (getLangOpts().CPlusPlus) 8332 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8333 8334 VK = VK_PRValue; 8335 OK = OK_Ordinary; 8336 8337 if (Context.isDependenceAllowed() && 8338 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8339 RHS.get()->isTypeDependent())) { 8340 assert(!getLangOpts().CPlusPlus); 8341 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8342 RHS.get()->containsErrors()) && 8343 "should only occur in error-recovery path."); 8344 return Context.DependentTy; 8345 } 8346 8347 // The OpenCL operator with a vector condition is sufficiently 8348 // different to merit its own checker. 8349 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8350 Cond.get()->getType()->isExtVectorType()) 8351 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8352 8353 // First, check the condition. 8354 Cond = UsualUnaryConversions(Cond.get()); 8355 if (Cond.isInvalid()) 8356 return QualType(); 8357 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8358 return QualType(); 8359 8360 // Now check the two expressions. 8361 if (LHS.get()->getType()->isVectorType() || 8362 RHS.get()->getType()->isVectorType()) 8363 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8364 /*AllowBothBool*/true, 8365 /*AllowBoolConversions*/false); 8366 8367 QualType ResTy = 8368 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8369 if (LHS.isInvalid() || RHS.isInvalid()) 8370 return QualType(); 8371 8372 QualType LHSTy = LHS.get()->getType(); 8373 QualType RHSTy = RHS.get()->getType(); 8374 8375 // Diagnose attempts to convert between __ibm128, __float128 and long double 8376 // where such conversions currently can't be handled. 8377 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8378 Diag(QuestionLoc, 8379 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8380 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8381 return QualType(); 8382 } 8383 8384 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8385 // selection operator (?:). 8386 if (getLangOpts().OpenCL && 8387 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8388 return QualType(); 8389 } 8390 8391 // If both operands have arithmetic type, do the usual arithmetic conversions 8392 // to find a common type: C99 6.5.15p3,5. 8393 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8394 // Disallow invalid arithmetic conversions, such as those between bit- 8395 // precise integers types of different sizes, or between a bit-precise 8396 // integer and another type. 8397 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { 8398 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8399 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8400 << RHS.get()->getSourceRange(); 8401 return QualType(); 8402 } 8403 8404 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8405 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8406 8407 return ResTy; 8408 } 8409 8410 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8411 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8412 return LHSTy; 8413 } 8414 8415 // If both operands are the same structure or union type, the result is that 8416 // type. 8417 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8418 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8419 if (LHSRT->getDecl() == RHSRT->getDecl()) 8420 // "If both the operands have structure or union type, the result has 8421 // that type." This implies that CV qualifiers are dropped. 8422 return LHSTy.getUnqualifiedType(); 8423 // FIXME: Type of conditional expression must be complete in C mode. 8424 } 8425 8426 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8427 // The following || allows only one side to be void (a GCC-ism). 8428 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8429 return checkConditionalVoidType(*this, LHS, RHS); 8430 } 8431 8432 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8433 // the type of the other operand." 8434 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8435 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8436 8437 // All objective-c pointer type analysis is done here. 8438 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8439 QuestionLoc); 8440 if (LHS.isInvalid() || RHS.isInvalid()) 8441 return QualType(); 8442 if (!compositeType.isNull()) 8443 return compositeType; 8444 8445 8446 // Handle block pointer types. 8447 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8448 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8449 QuestionLoc); 8450 8451 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8452 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8453 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8454 QuestionLoc); 8455 8456 // GCC compatibility: soften pointer/integer mismatch. Note that 8457 // null pointers have been filtered out by this point. 8458 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8459 /*IsIntFirstExpr=*/true)) 8460 return RHSTy; 8461 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8462 /*IsIntFirstExpr=*/false)) 8463 return LHSTy; 8464 8465 // Allow ?: operations in which both operands have the same 8466 // built-in sizeless type. 8467 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8468 return LHSTy; 8469 8470 // Emit a better diagnostic if one of the expressions is a null pointer 8471 // constant and the other is not a pointer type. In this case, the user most 8472 // likely forgot to take the address of the other expression. 8473 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8474 return QualType(); 8475 8476 // Otherwise, the operands are not compatible. 8477 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8478 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8479 << RHS.get()->getSourceRange(); 8480 return QualType(); 8481 } 8482 8483 /// FindCompositeObjCPointerType - Helper method to find composite type of 8484 /// two objective-c pointer types of the two input expressions. 8485 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8486 SourceLocation QuestionLoc) { 8487 QualType LHSTy = LHS.get()->getType(); 8488 QualType RHSTy = RHS.get()->getType(); 8489 8490 // Handle things like Class and struct objc_class*. Here we case the result 8491 // to the pseudo-builtin, because that will be implicitly cast back to the 8492 // redefinition type if an attempt is made to access its fields. 8493 if (LHSTy->isObjCClassType() && 8494 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8495 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8496 return LHSTy; 8497 } 8498 if (RHSTy->isObjCClassType() && 8499 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8500 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8501 return RHSTy; 8502 } 8503 // And the same for struct objc_object* / id 8504 if (LHSTy->isObjCIdType() && 8505 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8506 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8507 return LHSTy; 8508 } 8509 if (RHSTy->isObjCIdType() && 8510 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8511 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8512 return RHSTy; 8513 } 8514 // And the same for struct objc_selector* / SEL 8515 if (Context.isObjCSelType(LHSTy) && 8516 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8517 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8518 return LHSTy; 8519 } 8520 if (Context.isObjCSelType(RHSTy) && 8521 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8522 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8523 return RHSTy; 8524 } 8525 // Check constraints for Objective-C object pointers types. 8526 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8527 8528 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8529 // Two identical object pointer types are always compatible. 8530 return LHSTy; 8531 } 8532 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8533 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8534 QualType compositeType = LHSTy; 8535 8536 // If both operands are interfaces and either operand can be 8537 // assigned to the other, use that type as the composite 8538 // type. This allows 8539 // xxx ? (A*) a : (B*) b 8540 // where B is a subclass of A. 8541 // 8542 // Additionally, as for assignment, if either type is 'id' 8543 // allow silent coercion. Finally, if the types are 8544 // incompatible then make sure to use 'id' as the composite 8545 // type so the result is acceptable for sending messages to. 8546 8547 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8548 // It could return the composite type. 8549 if (!(compositeType = 8550 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8551 // Nothing more to do. 8552 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8553 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8554 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8555 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8556 } else if ((LHSOPT->isObjCQualifiedIdType() || 8557 RHSOPT->isObjCQualifiedIdType()) && 8558 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8559 true)) { 8560 // Need to handle "id<xx>" explicitly. 8561 // GCC allows qualified id and any Objective-C type to devolve to 8562 // id. Currently localizing to here until clear this should be 8563 // part of ObjCQualifiedIdTypesAreCompatible. 8564 compositeType = Context.getObjCIdType(); 8565 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8566 compositeType = Context.getObjCIdType(); 8567 } else { 8568 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8569 << LHSTy << RHSTy 8570 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8571 QualType incompatTy = Context.getObjCIdType(); 8572 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8573 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8574 return incompatTy; 8575 } 8576 // The object pointer types are compatible. 8577 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8578 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8579 return compositeType; 8580 } 8581 // Check Objective-C object pointer types and 'void *' 8582 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8583 if (getLangOpts().ObjCAutoRefCount) { 8584 // ARC forbids the implicit conversion of object pointers to 'void *', 8585 // so these types are not compatible. 8586 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8587 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8588 LHS = RHS = true; 8589 return QualType(); 8590 } 8591 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8592 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8593 QualType destPointee 8594 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8595 QualType destType = Context.getPointerType(destPointee); 8596 // Add qualifiers if necessary. 8597 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8598 // Promote to void*. 8599 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8600 return destType; 8601 } 8602 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8603 if (getLangOpts().ObjCAutoRefCount) { 8604 // ARC forbids the implicit conversion of object pointers to 'void *', 8605 // so these types are not compatible. 8606 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8607 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8608 LHS = RHS = true; 8609 return QualType(); 8610 } 8611 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8612 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8613 QualType destPointee 8614 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8615 QualType destType = Context.getPointerType(destPointee); 8616 // Add qualifiers if necessary. 8617 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8618 // Promote to void*. 8619 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8620 return destType; 8621 } 8622 return QualType(); 8623 } 8624 8625 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8626 /// ParenRange in parentheses. 8627 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8628 const PartialDiagnostic &Note, 8629 SourceRange ParenRange) { 8630 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8631 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8632 EndLoc.isValid()) { 8633 Self.Diag(Loc, Note) 8634 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8635 << FixItHint::CreateInsertion(EndLoc, ")"); 8636 } else { 8637 // We can't display the parentheses, so just show the bare note. 8638 Self.Diag(Loc, Note) << ParenRange; 8639 } 8640 } 8641 8642 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8643 return BinaryOperator::isAdditiveOp(Opc) || 8644 BinaryOperator::isMultiplicativeOp(Opc) || 8645 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8646 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8647 // not any of the logical operators. Bitwise-xor is commonly used as a 8648 // logical-xor because there is no logical-xor operator. The logical 8649 // operators, including uses of xor, have a high false positive rate for 8650 // precedence warnings. 8651 } 8652 8653 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8654 /// expression, either using a built-in or overloaded operator, 8655 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8656 /// expression. 8657 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8658 Expr **RHSExprs) { 8659 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8660 E = E->IgnoreImpCasts(); 8661 E = E->IgnoreConversionOperatorSingleStep(); 8662 E = E->IgnoreImpCasts(); 8663 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8664 E = MTE->getSubExpr(); 8665 E = E->IgnoreImpCasts(); 8666 } 8667 8668 // Built-in binary operator. 8669 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8670 if (IsArithmeticOp(OP->getOpcode())) { 8671 *Opcode = OP->getOpcode(); 8672 *RHSExprs = OP->getRHS(); 8673 return true; 8674 } 8675 } 8676 8677 // Overloaded operator. 8678 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8679 if (Call->getNumArgs() != 2) 8680 return false; 8681 8682 // Make sure this is really a binary operator that is safe to pass into 8683 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8684 OverloadedOperatorKind OO = Call->getOperator(); 8685 if (OO < OO_Plus || OO > OO_Arrow || 8686 OO == OO_PlusPlus || OO == OO_MinusMinus) 8687 return false; 8688 8689 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8690 if (IsArithmeticOp(OpKind)) { 8691 *Opcode = OpKind; 8692 *RHSExprs = Call->getArg(1); 8693 return true; 8694 } 8695 } 8696 8697 return false; 8698 } 8699 8700 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8701 /// or is a logical expression such as (x==y) which has int type, but is 8702 /// commonly interpreted as boolean. 8703 static bool ExprLooksBoolean(Expr *E) { 8704 E = E->IgnoreParenImpCasts(); 8705 8706 if (E->getType()->isBooleanType()) 8707 return true; 8708 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8709 return OP->isComparisonOp() || OP->isLogicalOp(); 8710 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8711 return OP->getOpcode() == UO_LNot; 8712 if (E->getType()->isPointerType()) 8713 return true; 8714 // FIXME: What about overloaded operator calls returning "unspecified boolean 8715 // type"s (commonly pointer-to-members)? 8716 8717 return false; 8718 } 8719 8720 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8721 /// and binary operator are mixed in a way that suggests the programmer assumed 8722 /// the conditional operator has higher precedence, for example: 8723 /// "int x = a + someBinaryCondition ? 1 : 2". 8724 static void DiagnoseConditionalPrecedence(Sema &Self, 8725 SourceLocation OpLoc, 8726 Expr *Condition, 8727 Expr *LHSExpr, 8728 Expr *RHSExpr) { 8729 BinaryOperatorKind CondOpcode; 8730 Expr *CondRHS; 8731 8732 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8733 return; 8734 if (!ExprLooksBoolean(CondRHS)) 8735 return; 8736 8737 // The condition is an arithmetic binary expression, with a right- 8738 // hand side that looks boolean, so warn. 8739 8740 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8741 ? diag::warn_precedence_bitwise_conditional 8742 : diag::warn_precedence_conditional; 8743 8744 Self.Diag(OpLoc, DiagID) 8745 << Condition->getSourceRange() 8746 << BinaryOperator::getOpcodeStr(CondOpcode); 8747 8748 SuggestParentheses( 8749 Self, OpLoc, 8750 Self.PDiag(diag::note_precedence_silence) 8751 << BinaryOperator::getOpcodeStr(CondOpcode), 8752 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8753 8754 SuggestParentheses(Self, OpLoc, 8755 Self.PDiag(diag::note_precedence_conditional_first), 8756 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8757 } 8758 8759 /// Compute the nullability of a conditional expression. 8760 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8761 QualType LHSTy, QualType RHSTy, 8762 ASTContext &Ctx) { 8763 if (!ResTy->isAnyPointerType()) 8764 return ResTy; 8765 8766 auto GetNullability = [&Ctx](QualType Ty) { 8767 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8768 if (Kind) { 8769 // For our purposes, treat _Nullable_result as _Nullable. 8770 if (*Kind == NullabilityKind::NullableResult) 8771 return NullabilityKind::Nullable; 8772 return *Kind; 8773 } 8774 return NullabilityKind::Unspecified; 8775 }; 8776 8777 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8778 NullabilityKind MergedKind; 8779 8780 // Compute nullability of a binary conditional expression. 8781 if (IsBin) { 8782 if (LHSKind == NullabilityKind::NonNull) 8783 MergedKind = NullabilityKind::NonNull; 8784 else 8785 MergedKind = RHSKind; 8786 // Compute nullability of a normal conditional expression. 8787 } else { 8788 if (LHSKind == NullabilityKind::Nullable || 8789 RHSKind == NullabilityKind::Nullable) 8790 MergedKind = NullabilityKind::Nullable; 8791 else if (LHSKind == NullabilityKind::NonNull) 8792 MergedKind = RHSKind; 8793 else if (RHSKind == NullabilityKind::NonNull) 8794 MergedKind = LHSKind; 8795 else 8796 MergedKind = NullabilityKind::Unspecified; 8797 } 8798 8799 // Return if ResTy already has the correct nullability. 8800 if (GetNullability(ResTy) == MergedKind) 8801 return ResTy; 8802 8803 // Strip all nullability from ResTy. 8804 while (ResTy->getNullability(Ctx)) 8805 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8806 8807 // Create a new AttributedType with the new nullability kind. 8808 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8809 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8810 } 8811 8812 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8813 /// in the case of a the GNU conditional expr extension. 8814 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8815 SourceLocation ColonLoc, 8816 Expr *CondExpr, Expr *LHSExpr, 8817 Expr *RHSExpr) { 8818 if (!Context.isDependenceAllowed()) { 8819 // C cannot handle TypoExpr nodes in the condition because it 8820 // doesn't handle dependent types properly, so make sure any TypoExprs have 8821 // been dealt with before checking the operands. 8822 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8823 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8824 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8825 8826 if (!CondResult.isUsable()) 8827 return ExprError(); 8828 8829 if (LHSExpr) { 8830 if (!LHSResult.isUsable()) 8831 return ExprError(); 8832 } 8833 8834 if (!RHSResult.isUsable()) 8835 return ExprError(); 8836 8837 CondExpr = CondResult.get(); 8838 LHSExpr = LHSResult.get(); 8839 RHSExpr = RHSResult.get(); 8840 } 8841 8842 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8843 // was the condition. 8844 OpaqueValueExpr *opaqueValue = nullptr; 8845 Expr *commonExpr = nullptr; 8846 if (!LHSExpr) { 8847 commonExpr = CondExpr; 8848 // Lower out placeholder types first. This is important so that we don't 8849 // try to capture a placeholder. This happens in few cases in C++; such 8850 // as Objective-C++'s dictionary subscripting syntax. 8851 if (commonExpr->hasPlaceholderType()) { 8852 ExprResult result = CheckPlaceholderExpr(commonExpr); 8853 if (!result.isUsable()) return ExprError(); 8854 commonExpr = result.get(); 8855 } 8856 // We usually want to apply unary conversions *before* saving, except 8857 // in the special case of a C++ l-value conditional. 8858 if (!(getLangOpts().CPlusPlus 8859 && !commonExpr->isTypeDependent() 8860 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8861 && commonExpr->isGLValue() 8862 && commonExpr->isOrdinaryOrBitFieldObject() 8863 && RHSExpr->isOrdinaryOrBitFieldObject() 8864 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8865 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8866 if (commonRes.isInvalid()) 8867 return ExprError(); 8868 commonExpr = commonRes.get(); 8869 } 8870 8871 // If the common expression is a class or array prvalue, materialize it 8872 // so that we can safely refer to it multiple times. 8873 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8874 commonExpr->getType()->isArrayType())) { 8875 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8876 if (MatExpr.isInvalid()) 8877 return ExprError(); 8878 commonExpr = MatExpr.get(); 8879 } 8880 8881 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8882 commonExpr->getType(), 8883 commonExpr->getValueKind(), 8884 commonExpr->getObjectKind(), 8885 commonExpr); 8886 LHSExpr = CondExpr = opaqueValue; 8887 } 8888 8889 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8890 ExprValueKind VK = VK_PRValue; 8891 ExprObjectKind OK = OK_Ordinary; 8892 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8893 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8894 VK, OK, QuestionLoc); 8895 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8896 RHS.isInvalid()) 8897 return ExprError(); 8898 8899 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8900 RHS.get()); 8901 8902 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8903 8904 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8905 Context); 8906 8907 if (!commonExpr) 8908 return new (Context) 8909 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8910 RHS.get(), result, VK, OK); 8911 8912 return new (Context) BinaryConditionalOperator( 8913 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8914 ColonLoc, result, VK, OK); 8915 } 8916 8917 // Check if we have a conversion between incompatible cmse function pointer 8918 // types, that is, a conversion between a function pointer with the 8919 // cmse_nonsecure_call attribute and one without. 8920 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8921 QualType ToType) { 8922 if (const auto *ToFn = 8923 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8924 if (const auto *FromFn = 8925 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8926 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8927 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8928 8929 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8930 } 8931 } 8932 return false; 8933 } 8934 8935 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8936 // being closely modeled after the C99 spec:-). The odd characteristic of this 8937 // routine is it effectively iqnores the qualifiers on the top level pointee. 8938 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8939 // FIXME: add a couple examples in this comment. 8940 static Sema::AssignConvertType 8941 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8942 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8943 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8944 8945 // get the "pointed to" type (ignoring qualifiers at the top level) 8946 const Type *lhptee, *rhptee; 8947 Qualifiers lhq, rhq; 8948 std::tie(lhptee, lhq) = 8949 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8950 std::tie(rhptee, rhq) = 8951 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8952 8953 Sema::AssignConvertType ConvTy = Sema::Compatible; 8954 8955 // C99 6.5.16.1p1: This following citation is common to constraints 8956 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8957 // qualifiers of the type *pointed to* by the right; 8958 8959 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8960 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8961 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8962 // Ignore lifetime for further calculation. 8963 lhq.removeObjCLifetime(); 8964 rhq.removeObjCLifetime(); 8965 } 8966 8967 if (!lhq.compatiblyIncludes(rhq)) { 8968 // Treat address-space mismatches as fatal. 8969 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8970 return Sema::IncompatiblePointerDiscardsQualifiers; 8971 8972 // It's okay to add or remove GC or lifetime qualifiers when converting to 8973 // and from void*. 8974 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8975 .compatiblyIncludes( 8976 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8977 && (lhptee->isVoidType() || rhptee->isVoidType())) 8978 ; // keep old 8979 8980 // Treat lifetime mismatches as fatal. 8981 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8982 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8983 8984 // For GCC/MS compatibility, other qualifier mismatches are treated 8985 // as still compatible in C. 8986 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8987 } 8988 8989 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8990 // incomplete type and the other is a pointer to a qualified or unqualified 8991 // version of void... 8992 if (lhptee->isVoidType()) { 8993 if (rhptee->isIncompleteOrObjectType()) 8994 return ConvTy; 8995 8996 // As an extension, we allow cast to/from void* to function pointer. 8997 assert(rhptee->isFunctionType()); 8998 return Sema::FunctionVoidPointer; 8999 } 9000 9001 if (rhptee->isVoidType()) { 9002 if (lhptee->isIncompleteOrObjectType()) 9003 return ConvTy; 9004 9005 // As an extension, we allow cast to/from void* to function pointer. 9006 assert(lhptee->isFunctionType()); 9007 return Sema::FunctionVoidPointer; 9008 } 9009 9010 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9011 // unqualified versions of compatible types, ... 9012 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9013 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9014 // Check if the pointee types are compatible ignoring the sign. 9015 // We explicitly check for char so that we catch "char" vs 9016 // "unsigned char" on systems where "char" is unsigned. 9017 if (lhptee->isCharType()) 9018 ltrans = S.Context.UnsignedCharTy; 9019 else if (lhptee->hasSignedIntegerRepresentation()) 9020 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9021 9022 if (rhptee->isCharType()) 9023 rtrans = S.Context.UnsignedCharTy; 9024 else if (rhptee->hasSignedIntegerRepresentation()) 9025 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9026 9027 if (ltrans == rtrans) { 9028 // Types are compatible ignoring the sign. Qualifier incompatibility 9029 // takes priority over sign incompatibility because the sign 9030 // warning can be disabled. 9031 if (ConvTy != Sema::Compatible) 9032 return ConvTy; 9033 9034 return Sema::IncompatiblePointerSign; 9035 } 9036 9037 // If we are a multi-level pointer, it's possible that our issue is simply 9038 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9039 // the eventual target type is the same and the pointers have the same 9040 // level of indirection, this must be the issue. 9041 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9042 do { 9043 std::tie(lhptee, lhq) = 9044 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9045 std::tie(rhptee, rhq) = 9046 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9047 9048 // Inconsistent address spaces at this point is invalid, even if the 9049 // address spaces would be compatible. 9050 // FIXME: This doesn't catch address space mismatches for pointers of 9051 // different nesting levels, like: 9052 // __local int *** a; 9053 // int ** b = a; 9054 // It's not clear how to actually determine when such pointers are 9055 // invalidly incompatible. 9056 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9057 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9058 9059 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9060 9061 if (lhptee == rhptee) 9062 return Sema::IncompatibleNestedPointerQualifiers; 9063 } 9064 9065 // General pointer incompatibility takes priority over qualifiers. 9066 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9067 return Sema::IncompatibleFunctionPointer; 9068 return Sema::IncompatiblePointer; 9069 } 9070 if (!S.getLangOpts().CPlusPlus && 9071 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9072 return Sema::IncompatibleFunctionPointer; 9073 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9074 return Sema::IncompatibleFunctionPointer; 9075 return ConvTy; 9076 } 9077 9078 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9079 /// block pointer types are compatible or whether a block and normal pointer 9080 /// are compatible. It is more restrict than comparing two function pointer 9081 // types. 9082 static Sema::AssignConvertType 9083 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9084 QualType RHSType) { 9085 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9086 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9087 9088 QualType lhptee, rhptee; 9089 9090 // get the "pointed to" type (ignoring qualifiers at the top level) 9091 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9092 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9093 9094 // In C++, the types have to match exactly. 9095 if (S.getLangOpts().CPlusPlus) 9096 return Sema::IncompatibleBlockPointer; 9097 9098 Sema::AssignConvertType ConvTy = Sema::Compatible; 9099 9100 // For blocks we enforce that qualifiers are identical. 9101 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9102 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9103 if (S.getLangOpts().OpenCL) { 9104 LQuals.removeAddressSpace(); 9105 RQuals.removeAddressSpace(); 9106 } 9107 if (LQuals != RQuals) 9108 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9109 9110 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9111 // assignment. 9112 // The current behavior is similar to C++ lambdas. A block might be 9113 // assigned to a variable iff its return type and parameters are compatible 9114 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9115 // an assignment. Presumably it should behave in way that a function pointer 9116 // assignment does in C, so for each parameter and return type: 9117 // * CVR and address space of LHS should be a superset of CVR and address 9118 // space of RHS. 9119 // * unqualified types should be compatible. 9120 if (S.getLangOpts().OpenCL) { 9121 if (!S.Context.typesAreBlockPointerCompatible( 9122 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9123 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9124 return Sema::IncompatibleBlockPointer; 9125 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9126 return Sema::IncompatibleBlockPointer; 9127 9128 return ConvTy; 9129 } 9130 9131 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9132 /// for assignment compatibility. 9133 static Sema::AssignConvertType 9134 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9135 QualType RHSType) { 9136 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9137 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9138 9139 if (LHSType->isObjCBuiltinType()) { 9140 // Class is not compatible with ObjC object pointers. 9141 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9142 !RHSType->isObjCQualifiedClassType()) 9143 return Sema::IncompatiblePointer; 9144 return Sema::Compatible; 9145 } 9146 if (RHSType->isObjCBuiltinType()) { 9147 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9148 !LHSType->isObjCQualifiedClassType()) 9149 return Sema::IncompatiblePointer; 9150 return Sema::Compatible; 9151 } 9152 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9153 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9154 9155 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9156 // make an exception for id<P> 9157 !LHSType->isObjCQualifiedIdType()) 9158 return Sema::CompatiblePointerDiscardsQualifiers; 9159 9160 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9161 return Sema::Compatible; 9162 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9163 return Sema::IncompatibleObjCQualifiedId; 9164 return Sema::IncompatiblePointer; 9165 } 9166 9167 Sema::AssignConvertType 9168 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9169 QualType LHSType, QualType RHSType) { 9170 // Fake up an opaque expression. We don't actually care about what 9171 // cast operations are required, so if CheckAssignmentConstraints 9172 // adds casts to this they'll be wasted, but fortunately that doesn't 9173 // usually happen on valid code. 9174 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9175 ExprResult RHSPtr = &RHSExpr; 9176 CastKind K; 9177 9178 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9179 } 9180 9181 /// This helper function returns true if QT is a vector type that has element 9182 /// type ElementType. 9183 static bool isVector(QualType QT, QualType ElementType) { 9184 if (const VectorType *VT = QT->getAs<VectorType>()) 9185 return VT->getElementType().getCanonicalType() == ElementType; 9186 return false; 9187 } 9188 9189 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9190 /// has code to accommodate several GCC extensions when type checking 9191 /// pointers. Here are some objectionable examples that GCC considers warnings: 9192 /// 9193 /// int a, *pint; 9194 /// short *pshort; 9195 /// struct foo *pfoo; 9196 /// 9197 /// pint = pshort; // warning: assignment from incompatible pointer type 9198 /// a = pint; // warning: assignment makes integer from pointer without a cast 9199 /// pint = a; // warning: assignment makes pointer from integer without a cast 9200 /// pint = pfoo; // warning: assignment from incompatible pointer type 9201 /// 9202 /// As a result, the code for dealing with pointers is more complex than the 9203 /// C99 spec dictates. 9204 /// 9205 /// Sets 'Kind' for any result kind except Incompatible. 9206 Sema::AssignConvertType 9207 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9208 CastKind &Kind, bool ConvertRHS) { 9209 QualType RHSType = RHS.get()->getType(); 9210 QualType OrigLHSType = LHSType; 9211 9212 // Get canonical types. We're not formatting these types, just comparing 9213 // them. 9214 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9215 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9216 9217 // Common case: no conversion required. 9218 if (LHSType == RHSType) { 9219 Kind = CK_NoOp; 9220 return Compatible; 9221 } 9222 9223 // If we have an atomic type, try a non-atomic assignment, then just add an 9224 // atomic qualification step. 9225 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9226 Sema::AssignConvertType result = 9227 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9228 if (result != Compatible) 9229 return result; 9230 if (Kind != CK_NoOp && ConvertRHS) 9231 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9232 Kind = CK_NonAtomicToAtomic; 9233 return Compatible; 9234 } 9235 9236 // If the left-hand side is a reference type, then we are in a 9237 // (rare!) case where we've allowed the use of references in C, 9238 // e.g., as a parameter type in a built-in function. In this case, 9239 // just make sure that the type referenced is compatible with the 9240 // right-hand side type. The caller is responsible for adjusting 9241 // LHSType so that the resulting expression does not have reference 9242 // type. 9243 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9244 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9245 Kind = CK_LValueBitCast; 9246 return Compatible; 9247 } 9248 return Incompatible; 9249 } 9250 9251 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9252 // to the same ExtVector type. 9253 if (LHSType->isExtVectorType()) { 9254 if (RHSType->isExtVectorType()) 9255 return Incompatible; 9256 if (RHSType->isArithmeticType()) { 9257 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9258 if (ConvertRHS) 9259 RHS = prepareVectorSplat(LHSType, RHS.get()); 9260 Kind = CK_VectorSplat; 9261 return Compatible; 9262 } 9263 } 9264 9265 // Conversions to or from vector type. 9266 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9267 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9268 // Allow assignments of an AltiVec vector type to an equivalent GCC 9269 // vector type and vice versa 9270 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9271 Kind = CK_BitCast; 9272 return Compatible; 9273 } 9274 9275 // If we are allowing lax vector conversions, and LHS and RHS are both 9276 // vectors, the total size only needs to be the same. This is a bitcast; 9277 // no bits are changed but the result type is different. 9278 if (isLaxVectorConversion(RHSType, LHSType)) { 9279 Kind = CK_BitCast; 9280 return IncompatibleVectors; 9281 } 9282 } 9283 9284 // When the RHS comes from another lax conversion (e.g. binops between 9285 // scalars and vectors) the result is canonicalized as a vector. When the 9286 // LHS is also a vector, the lax is allowed by the condition above. Handle 9287 // the case where LHS is a scalar. 9288 if (LHSType->isScalarType()) { 9289 const VectorType *VecType = RHSType->getAs<VectorType>(); 9290 if (VecType && VecType->getNumElements() == 1 && 9291 isLaxVectorConversion(RHSType, LHSType)) { 9292 ExprResult *VecExpr = &RHS; 9293 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9294 Kind = CK_BitCast; 9295 return Compatible; 9296 } 9297 } 9298 9299 // Allow assignments between fixed-length and sizeless SVE vectors. 9300 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9301 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9302 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9303 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9304 Kind = CK_BitCast; 9305 return Compatible; 9306 } 9307 9308 return Incompatible; 9309 } 9310 9311 // Diagnose attempts to convert between __ibm128, __float128 and long double 9312 // where such conversions currently can't be handled. 9313 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9314 return Incompatible; 9315 9316 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9317 // discards the imaginary part. 9318 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9319 !LHSType->getAs<ComplexType>()) 9320 return Incompatible; 9321 9322 // Arithmetic conversions. 9323 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9324 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9325 if (ConvertRHS) 9326 Kind = PrepareScalarCast(RHS, LHSType); 9327 return Compatible; 9328 } 9329 9330 // Conversions to normal pointers. 9331 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9332 // U* -> T* 9333 if (isa<PointerType>(RHSType)) { 9334 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9335 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9336 if (AddrSpaceL != AddrSpaceR) 9337 Kind = CK_AddressSpaceConversion; 9338 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9339 Kind = CK_NoOp; 9340 else 9341 Kind = CK_BitCast; 9342 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9343 } 9344 9345 // int -> T* 9346 if (RHSType->isIntegerType()) { 9347 Kind = CK_IntegralToPointer; // FIXME: null? 9348 return IntToPointer; 9349 } 9350 9351 // C pointers are not compatible with ObjC object pointers, 9352 // with two exceptions: 9353 if (isa<ObjCObjectPointerType>(RHSType)) { 9354 // - conversions to void* 9355 if (LHSPointer->getPointeeType()->isVoidType()) { 9356 Kind = CK_BitCast; 9357 return Compatible; 9358 } 9359 9360 // - conversions from 'Class' to the redefinition type 9361 if (RHSType->isObjCClassType() && 9362 Context.hasSameType(LHSType, 9363 Context.getObjCClassRedefinitionType())) { 9364 Kind = CK_BitCast; 9365 return Compatible; 9366 } 9367 9368 Kind = CK_BitCast; 9369 return IncompatiblePointer; 9370 } 9371 9372 // U^ -> void* 9373 if (RHSType->getAs<BlockPointerType>()) { 9374 if (LHSPointer->getPointeeType()->isVoidType()) { 9375 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9376 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9377 ->getPointeeType() 9378 .getAddressSpace(); 9379 Kind = 9380 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9381 return Compatible; 9382 } 9383 } 9384 9385 return Incompatible; 9386 } 9387 9388 // Conversions to block pointers. 9389 if (isa<BlockPointerType>(LHSType)) { 9390 // U^ -> T^ 9391 if (RHSType->isBlockPointerType()) { 9392 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9393 ->getPointeeType() 9394 .getAddressSpace(); 9395 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9396 ->getPointeeType() 9397 .getAddressSpace(); 9398 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9399 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9400 } 9401 9402 // int or null -> T^ 9403 if (RHSType->isIntegerType()) { 9404 Kind = CK_IntegralToPointer; // FIXME: null 9405 return IntToBlockPointer; 9406 } 9407 9408 // id -> T^ 9409 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9410 Kind = CK_AnyPointerToBlockPointerCast; 9411 return Compatible; 9412 } 9413 9414 // void* -> T^ 9415 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9416 if (RHSPT->getPointeeType()->isVoidType()) { 9417 Kind = CK_AnyPointerToBlockPointerCast; 9418 return Compatible; 9419 } 9420 9421 return Incompatible; 9422 } 9423 9424 // Conversions to Objective-C pointers. 9425 if (isa<ObjCObjectPointerType>(LHSType)) { 9426 // A* -> B* 9427 if (RHSType->isObjCObjectPointerType()) { 9428 Kind = CK_BitCast; 9429 Sema::AssignConvertType result = 9430 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9431 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9432 result == Compatible && 9433 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9434 result = IncompatibleObjCWeakRef; 9435 return result; 9436 } 9437 9438 // int or null -> A* 9439 if (RHSType->isIntegerType()) { 9440 Kind = CK_IntegralToPointer; // FIXME: null 9441 return IntToPointer; 9442 } 9443 9444 // In general, C pointers are not compatible with ObjC object pointers, 9445 // with two exceptions: 9446 if (isa<PointerType>(RHSType)) { 9447 Kind = CK_CPointerToObjCPointerCast; 9448 9449 // - conversions from 'void*' 9450 if (RHSType->isVoidPointerType()) { 9451 return Compatible; 9452 } 9453 9454 // - conversions to 'Class' from its redefinition type 9455 if (LHSType->isObjCClassType() && 9456 Context.hasSameType(RHSType, 9457 Context.getObjCClassRedefinitionType())) { 9458 return Compatible; 9459 } 9460 9461 return IncompatiblePointer; 9462 } 9463 9464 // Only under strict condition T^ is compatible with an Objective-C pointer. 9465 if (RHSType->isBlockPointerType() && 9466 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9467 if (ConvertRHS) 9468 maybeExtendBlockObject(RHS); 9469 Kind = CK_BlockPointerToObjCPointerCast; 9470 return Compatible; 9471 } 9472 9473 return Incompatible; 9474 } 9475 9476 // Conversions from pointers that are not covered by the above. 9477 if (isa<PointerType>(RHSType)) { 9478 // T* -> _Bool 9479 if (LHSType == Context.BoolTy) { 9480 Kind = CK_PointerToBoolean; 9481 return Compatible; 9482 } 9483 9484 // T* -> int 9485 if (LHSType->isIntegerType()) { 9486 Kind = CK_PointerToIntegral; 9487 return PointerToInt; 9488 } 9489 9490 return Incompatible; 9491 } 9492 9493 // Conversions from Objective-C pointers that are not covered by the above. 9494 if (isa<ObjCObjectPointerType>(RHSType)) { 9495 // T* -> _Bool 9496 if (LHSType == Context.BoolTy) { 9497 Kind = CK_PointerToBoolean; 9498 return Compatible; 9499 } 9500 9501 // T* -> int 9502 if (LHSType->isIntegerType()) { 9503 Kind = CK_PointerToIntegral; 9504 return PointerToInt; 9505 } 9506 9507 return Incompatible; 9508 } 9509 9510 // struct A -> struct B 9511 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9512 if (Context.typesAreCompatible(LHSType, RHSType)) { 9513 Kind = CK_NoOp; 9514 return Compatible; 9515 } 9516 } 9517 9518 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9519 Kind = CK_IntToOCLSampler; 9520 return Compatible; 9521 } 9522 9523 return Incompatible; 9524 } 9525 9526 /// Constructs a transparent union from an expression that is 9527 /// used to initialize the transparent union. 9528 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9529 ExprResult &EResult, QualType UnionType, 9530 FieldDecl *Field) { 9531 // Build an initializer list that designates the appropriate member 9532 // of the transparent union. 9533 Expr *E = EResult.get(); 9534 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9535 E, SourceLocation()); 9536 Initializer->setType(UnionType); 9537 Initializer->setInitializedFieldInUnion(Field); 9538 9539 // Build a compound literal constructing a value of the transparent 9540 // union type from this initializer list. 9541 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9542 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9543 VK_PRValue, Initializer, false); 9544 } 9545 9546 Sema::AssignConvertType 9547 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9548 ExprResult &RHS) { 9549 QualType RHSType = RHS.get()->getType(); 9550 9551 // If the ArgType is a Union type, we want to handle a potential 9552 // transparent_union GCC extension. 9553 const RecordType *UT = ArgType->getAsUnionType(); 9554 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9555 return Incompatible; 9556 9557 // The field to initialize within the transparent union. 9558 RecordDecl *UD = UT->getDecl(); 9559 FieldDecl *InitField = nullptr; 9560 // It's compatible if the expression matches any of the fields. 9561 for (auto *it : UD->fields()) { 9562 if (it->getType()->isPointerType()) { 9563 // If the transparent union contains a pointer type, we allow: 9564 // 1) void pointer 9565 // 2) null pointer constant 9566 if (RHSType->isPointerType()) 9567 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9568 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9569 InitField = it; 9570 break; 9571 } 9572 9573 if (RHS.get()->isNullPointerConstant(Context, 9574 Expr::NPC_ValueDependentIsNull)) { 9575 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9576 CK_NullToPointer); 9577 InitField = it; 9578 break; 9579 } 9580 } 9581 9582 CastKind Kind; 9583 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9584 == Compatible) { 9585 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9586 InitField = it; 9587 break; 9588 } 9589 } 9590 9591 if (!InitField) 9592 return Incompatible; 9593 9594 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9595 return Compatible; 9596 } 9597 9598 Sema::AssignConvertType 9599 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9600 bool Diagnose, 9601 bool DiagnoseCFAudited, 9602 bool ConvertRHS) { 9603 // We need to be able to tell the caller whether we diagnosed a problem, if 9604 // they ask us to issue diagnostics. 9605 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9606 9607 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9608 // we can't avoid *all* modifications at the moment, so we need some somewhere 9609 // to put the updated value. 9610 ExprResult LocalRHS = CallerRHS; 9611 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9612 9613 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9614 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9615 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9616 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9617 Diag(RHS.get()->getExprLoc(), 9618 diag::warn_noderef_to_dereferenceable_pointer) 9619 << RHS.get()->getSourceRange(); 9620 } 9621 } 9622 } 9623 9624 if (getLangOpts().CPlusPlus) { 9625 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9626 // C++ 5.17p3: If the left operand is not of class type, the 9627 // expression is implicitly converted (C++ 4) to the 9628 // cv-unqualified type of the left operand. 9629 QualType RHSType = RHS.get()->getType(); 9630 if (Diagnose) { 9631 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9632 AA_Assigning); 9633 } else { 9634 ImplicitConversionSequence ICS = 9635 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9636 /*SuppressUserConversions=*/false, 9637 AllowedExplicit::None, 9638 /*InOverloadResolution=*/false, 9639 /*CStyle=*/false, 9640 /*AllowObjCWritebackConversion=*/false); 9641 if (ICS.isFailure()) 9642 return Incompatible; 9643 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9644 ICS, AA_Assigning); 9645 } 9646 if (RHS.isInvalid()) 9647 return Incompatible; 9648 Sema::AssignConvertType result = Compatible; 9649 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9650 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9651 result = IncompatibleObjCWeakRef; 9652 return result; 9653 } 9654 9655 // FIXME: Currently, we fall through and treat C++ classes like C 9656 // structures. 9657 // FIXME: We also fall through for atomics; not sure what should 9658 // happen there, though. 9659 } else if (RHS.get()->getType() == Context.OverloadTy) { 9660 // As a set of extensions to C, we support overloading on functions. These 9661 // functions need to be resolved here. 9662 DeclAccessPair DAP; 9663 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9664 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9665 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9666 else 9667 return Incompatible; 9668 } 9669 9670 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9671 // a null pointer constant. 9672 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9673 LHSType->isBlockPointerType()) && 9674 RHS.get()->isNullPointerConstant(Context, 9675 Expr::NPC_ValueDependentIsNull)) { 9676 if (Diagnose || ConvertRHS) { 9677 CastKind Kind; 9678 CXXCastPath Path; 9679 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9680 /*IgnoreBaseAccess=*/false, Diagnose); 9681 if (ConvertRHS) 9682 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9683 } 9684 return Compatible; 9685 } 9686 9687 // OpenCL queue_t type assignment. 9688 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9689 Context, Expr::NPC_ValueDependentIsNull)) { 9690 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9691 return Compatible; 9692 } 9693 9694 // This check seems unnatural, however it is necessary to ensure the proper 9695 // conversion of functions/arrays. If the conversion were done for all 9696 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9697 // expressions that suppress this implicit conversion (&, sizeof). 9698 // 9699 // Suppress this for references: C++ 8.5.3p5. 9700 if (!LHSType->isReferenceType()) { 9701 // FIXME: We potentially allocate here even if ConvertRHS is false. 9702 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9703 if (RHS.isInvalid()) 9704 return Incompatible; 9705 } 9706 CastKind Kind; 9707 Sema::AssignConvertType result = 9708 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9709 9710 // C99 6.5.16.1p2: The value of the right operand is converted to the 9711 // type of the assignment expression. 9712 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9713 // so that we can use references in built-in functions even in C. 9714 // The getNonReferenceType() call makes sure that the resulting expression 9715 // does not have reference type. 9716 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9717 QualType Ty = LHSType.getNonLValueExprType(Context); 9718 Expr *E = RHS.get(); 9719 9720 // Check for various Objective-C errors. If we are not reporting 9721 // diagnostics and just checking for errors, e.g., during overload 9722 // resolution, return Incompatible to indicate the failure. 9723 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9724 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9725 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9726 if (!Diagnose) 9727 return Incompatible; 9728 } 9729 if (getLangOpts().ObjC && 9730 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9731 E->getType(), E, Diagnose) || 9732 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9733 if (!Diagnose) 9734 return Incompatible; 9735 // Replace the expression with a corrected version and continue so we 9736 // can find further errors. 9737 RHS = E; 9738 return Compatible; 9739 } 9740 9741 if (ConvertRHS) 9742 RHS = ImpCastExprToType(E, Ty, Kind); 9743 } 9744 9745 return result; 9746 } 9747 9748 namespace { 9749 /// The original operand to an operator, prior to the application of the usual 9750 /// arithmetic conversions and converting the arguments of a builtin operator 9751 /// candidate. 9752 struct OriginalOperand { 9753 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9754 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9755 Op = MTE->getSubExpr(); 9756 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9757 Op = BTE->getSubExpr(); 9758 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9759 Orig = ICE->getSubExprAsWritten(); 9760 Conversion = ICE->getConversionFunction(); 9761 } 9762 } 9763 9764 QualType getType() const { return Orig->getType(); } 9765 9766 Expr *Orig; 9767 NamedDecl *Conversion; 9768 }; 9769 } 9770 9771 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9772 ExprResult &RHS) { 9773 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9774 9775 Diag(Loc, diag::err_typecheck_invalid_operands) 9776 << OrigLHS.getType() << OrigRHS.getType() 9777 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9778 9779 // If a user-defined conversion was applied to either of the operands prior 9780 // to applying the built-in operator rules, tell the user about it. 9781 if (OrigLHS.Conversion) { 9782 Diag(OrigLHS.Conversion->getLocation(), 9783 diag::note_typecheck_invalid_operands_converted) 9784 << 0 << LHS.get()->getType(); 9785 } 9786 if (OrigRHS.Conversion) { 9787 Diag(OrigRHS.Conversion->getLocation(), 9788 diag::note_typecheck_invalid_operands_converted) 9789 << 1 << RHS.get()->getType(); 9790 } 9791 9792 return QualType(); 9793 } 9794 9795 // Diagnose cases where a scalar was implicitly converted to a vector and 9796 // diagnose the underlying types. Otherwise, diagnose the error 9797 // as invalid vector logical operands for non-C++ cases. 9798 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9799 ExprResult &RHS) { 9800 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9801 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9802 9803 bool LHSNatVec = LHSType->isVectorType(); 9804 bool RHSNatVec = RHSType->isVectorType(); 9805 9806 if (!(LHSNatVec && RHSNatVec)) { 9807 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9808 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9809 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9810 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9811 << Vector->getSourceRange(); 9812 return QualType(); 9813 } 9814 9815 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9816 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9817 << RHS.get()->getSourceRange(); 9818 9819 return QualType(); 9820 } 9821 9822 /// Try to convert a value of non-vector type to a vector type by converting 9823 /// the type to the element type of the vector and then performing a splat. 9824 /// If the language is OpenCL, we only use conversions that promote scalar 9825 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9826 /// for float->int. 9827 /// 9828 /// OpenCL V2.0 6.2.6.p2: 9829 /// An error shall occur if any scalar operand type has greater rank 9830 /// than the type of the vector element. 9831 /// 9832 /// \param scalar - if non-null, actually perform the conversions 9833 /// \return true if the operation fails (but without diagnosing the failure) 9834 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9835 QualType scalarTy, 9836 QualType vectorEltTy, 9837 QualType vectorTy, 9838 unsigned &DiagID) { 9839 // The conversion to apply to the scalar before splatting it, 9840 // if necessary. 9841 CastKind scalarCast = CK_NoOp; 9842 9843 if (vectorEltTy->isIntegralType(S.Context)) { 9844 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9845 (scalarTy->isIntegerType() && 9846 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9847 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9848 return true; 9849 } 9850 if (!scalarTy->isIntegralType(S.Context)) 9851 return true; 9852 scalarCast = CK_IntegralCast; 9853 } else if (vectorEltTy->isRealFloatingType()) { 9854 if (scalarTy->isRealFloatingType()) { 9855 if (S.getLangOpts().OpenCL && 9856 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9857 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9858 return true; 9859 } 9860 scalarCast = CK_FloatingCast; 9861 } 9862 else if (scalarTy->isIntegralType(S.Context)) 9863 scalarCast = CK_IntegralToFloating; 9864 else 9865 return true; 9866 } else { 9867 return true; 9868 } 9869 9870 // Adjust scalar if desired. 9871 if (scalar) { 9872 if (scalarCast != CK_NoOp) 9873 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9874 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9875 } 9876 return false; 9877 } 9878 9879 /// Convert vector E to a vector with the same number of elements but different 9880 /// element type. 9881 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9882 const auto *VecTy = E->getType()->getAs<VectorType>(); 9883 assert(VecTy && "Expression E must be a vector"); 9884 QualType NewVecTy = S.Context.getVectorType(ElementType, 9885 VecTy->getNumElements(), 9886 VecTy->getVectorKind()); 9887 9888 // Look through the implicit cast. Return the subexpression if its type is 9889 // NewVecTy. 9890 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9891 if (ICE->getSubExpr()->getType() == NewVecTy) 9892 return ICE->getSubExpr(); 9893 9894 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9895 return S.ImpCastExprToType(E, NewVecTy, Cast); 9896 } 9897 9898 /// Test if a (constant) integer Int can be casted to another integer type 9899 /// IntTy without losing precision. 9900 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9901 QualType OtherIntTy) { 9902 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9903 9904 // Reject cases where the value of the Int is unknown as that would 9905 // possibly cause truncation, but accept cases where the scalar can be 9906 // demoted without loss of precision. 9907 Expr::EvalResult EVResult; 9908 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9909 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9910 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9911 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9912 9913 if (CstInt) { 9914 // If the scalar is constant and is of a higher order and has more active 9915 // bits that the vector element type, reject it. 9916 llvm::APSInt Result = EVResult.Val.getInt(); 9917 unsigned NumBits = IntSigned 9918 ? (Result.isNegative() ? Result.getMinSignedBits() 9919 : Result.getActiveBits()) 9920 : Result.getActiveBits(); 9921 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9922 return true; 9923 9924 // If the signedness of the scalar type and the vector element type 9925 // differs and the number of bits is greater than that of the vector 9926 // element reject it. 9927 return (IntSigned != OtherIntSigned && 9928 NumBits > S.Context.getIntWidth(OtherIntTy)); 9929 } 9930 9931 // Reject cases where the value of the scalar is not constant and it's 9932 // order is greater than that of the vector element type. 9933 return (Order < 0); 9934 } 9935 9936 /// Test if a (constant) integer Int can be casted to floating point type 9937 /// FloatTy without losing precision. 9938 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9939 QualType FloatTy) { 9940 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9941 9942 // Determine if the integer constant can be expressed as a floating point 9943 // number of the appropriate type. 9944 Expr::EvalResult EVResult; 9945 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9946 9947 uint64_t Bits = 0; 9948 if (CstInt) { 9949 // Reject constants that would be truncated if they were converted to 9950 // the floating point type. Test by simple to/from conversion. 9951 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9952 // could be avoided if there was a convertFromAPInt method 9953 // which could signal back if implicit truncation occurred. 9954 llvm::APSInt Result = EVResult.Val.getInt(); 9955 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9956 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9957 llvm::APFloat::rmTowardZero); 9958 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9959 !IntTy->hasSignedIntegerRepresentation()); 9960 bool Ignored = false; 9961 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9962 &Ignored); 9963 if (Result != ConvertBack) 9964 return true; 9965 } else { 9966 // Reject types that cannot be fully encoded into the mantissa of 9967 // the float. 9968 Bits = S.Context.getTypeSize(IntTy); 9969 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9970 S.Context.getFloatTypeSemantics(FloatTy)); 9971 if (Bits > FloatPrec) 9972 return true; 9973 } 9974 9975 return false; 9976 } 9977 9978 /// Attempt to convert and splat Scalar into a vector whose types matches 9979 /// Vector following GCC conversion rules. The rule is that implicit 9980 /// conversion can occur when Scalar can be casted to match Vector's element 9981 /// type without causing truncation of Scalar. 9982 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9983 ExprResult *Vector) { 9984 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9985 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9986 const VectorType *VT = VectorTy->getAs<VectorType>(); 9987 9988 assert(!isa<ExtVectorType>(VT) && 9989 "ExtVectorTypes should not be handled here!"); 9990 9991 QualType VectorEltTy = VT->getElementType(); 9992 9993 // Reject cases where the vector element type or the scalar element type are 9994 // not integral or floating point types. 9995 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9996 return true; 9997 9998 // The conversion to apply to the scalar before splatting it, 9999 // if necessary. 10000 CastKind ScalarCast = CK_NoOp; 10001 10002 // Accept cases where the vector elements are integers and the scalar is 10003 // an integer. 10004 // FIXME: Notionally if the scalar was a floating point value with a precise 10005 // integral representation, we could cast it to an appropriate integer 10006 // type and then perform the rest of the checks here. GCC will perform 10007 // this conversion in some cases as determined by the input language. 10008 // We should accept it on a language independent basis. 10009 if (VectorEltTy->isIntegralType(S.Context) && 10010 ScalarTy->isIntegralType(S.Context) && 10011 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10012 10013 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10014 return true; 10015 10016 ScalarCast = CK_IntegralCast; 10017 } else if (VectorEltTy->isIntegralType(S.Context) && 10018 ScalarTy->isRealFloatingType()) { 10019 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10020 ScalarCast = CK_FloatingToIntegral; 10021 else 10022 return true; 10023 } else if (VectorEltTy->isRealFloatingType()) { 10024 if (ScalarTy->isRealFloatingType()) { 10025 10026 // Reject cases where the scalar type is not a constant and has a higher 10027 // Order than the vector element type. 10028 llvm::APFloat Result(0.0); 10029 10030 // Determine whether this is a constant scalar. In the event that the 10031 // value is dependent (and thus cannot be evaluated by the constant 10032 // evaluator), skip the evaluation. This will then diagnose once the 10033 // expression is instantiated. 10034 bool CstScalar = Scalar->get()->isValueDependent() || 10035 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10036 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10037 if (!CstScalar && Order < 0) 10038 return true; 10039 10040 // If the scalar cannot be safely casted to the vector element type, 10041 // reject it. 10042 if (CstScalar) { 10043 bool Truncated = false; 10044 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10045 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10046 if (Truncated) 10047 return true; 10048 } 10049 10050 ScalarCast = CK_FloatingCast; 10051 } else if (ScalarTy->isIntegralType(S.Context)) { 10052 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10053 return true; 10054 10055 ScalarCast = CK_IntegralToFloating; 10056 } else 10057 return true; 10058 } else if (ScalarTy->isEnumeralType()) 10059 return true; 10060 10061 // Adjust scalar if desired. 10062 if (Scalar) { 10063 if (ScalarCast != CK_NoOp) 10064 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10065 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10066 } 10067 return false; 10068 } 10069 10070 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10071 SourceLocation Loc, bool IsCompAssign, 10072 bool AllowBothBool, 10073 bool AllowBoolConversions) { 10074 if (!IsCompAssign) { 10075 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10076 if (LHS.isInvalid()) 10077 return QualType(); 10078 } 10079 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10080 if (RHS.isInvalid()) 10081 return QualType(); 10082 10083 // For conversion purposes, we ignore any qualifiers. 10084 // For example, "const float" and "float" are equivalent. 10085 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10086 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10087 10088 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10089 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10090 assert(LHSVecType || RHSVecType); 10091 10092 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10093 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10094 return InvalidOperands(Loc, LHS, RHS); 10095 10096 // AltiVec-style "vector bool op vector bool" combinations are allowed 10097 // for some operators but not others. 10098 if (!AllowBothBool && 10099 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10100 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10101 return InvalidOperands(Loc, LHS, RHS); 10102 10103 // If the vector types are identical, return. 10104 if (Context.hasSameType(LHSType, RHSType)) 10105 return LHSType; 10106 10107 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10108 if (LHSVecType && RHSVecType && 10109 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10110 if (isa<ExtVectorType>(LHSVecType)) { 10111 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10112 return LHSType; 10113 } 10114 10115 if (!IsCompAssign) 10116 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10117 return RHSType; 10118 } 10119 10120 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10121 // can be mixed, with the result being the non-bool type. The non-bool 10122 // operand must have integer element type. 10123 if (AllowBoolConversions && LHSVecType && RHSVecType && 10124 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10125 (Context.getTypeSize(LHSVecType->getElementType()) == 10126 Context.getTypeSize(RHSVecType->getElementType()))) { 10127 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10128 LHSVecType->getElementType()->isIntegerType() && 10129 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10130 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10131 return LHSType; 10132 } 10133 if (!IsCompAssign && 10134 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10135 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10136 RHSVecType->getElementType()->isIntegerType()) { 10137 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10138 return RHSType; 10139 } 10140 } 10141 10142 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10143 // since the ambiguity can affect the ABI. 10144 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10145 const VectorType *VecType = SecondType->getAs<VectorType>(); 10146 return FirstType->isSizelessBuiltinType() && VecType && 10147 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10148 VecType->getVectorKind() == 10149 VectorType::SveFixedLengthPredicateVector); 10150 }; 10151 10152 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10153 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10154 return QualType(); 10155 } 10156 10157 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10158 // since the ambiguity can affect the ABI. 10159 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10160 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10161 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10162 10163 if (FirstVecType && SecondVecType) 10164 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10165 (SecondVecType->getVectorKind() == 10166 VectorType::SveFixedLengthDataVector || 10167 SecondVecType->getVectorKind() == 10168 VectorType::SveFixedLengthPredicateVector); 10169 10170 return FirstType->isSizelessBuiltinType() && SecondVecType && 10171 SecondVecType->getVectorKind() == VectorType::GenericVector; 10172 }; 10173 10174 if (IsSveGnuConversion(LHSType, RHSType) || 10175 IsSveGnuConversion(RHSType, LHSType)) { 10176 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10177 return QualType(); 10178 } 10179 10180 // If there's a vector type and a scalar, try to convert the scalar to 10181 // the vector element type and splat. 10182 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10183 if (!RHSVecType) { 10184 if (isa<ExtVectorType>(LHSVecType)) { 10185 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10186 LHSVecType->getElementType(), LHSType, 10187 DiagID)) 10188 return LHSType; 10189 } else { 10190 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10191 return LHSType; 10192 } 10193 } 10194 if (!LHSVecType) { 10195 if (isa<ExtVectorType>(RHSVecType)) { 10196 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10197 LHSType, RHSVecType->getElementType(), 10198 RHSType, DiagID)) 10199 return RHSType; 10200 } else { 10201 if (LHS.get()->isLValue() || 10202 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10203 return RHSType; 10204 } 10205 } 10206 10207 // FIXME: The code below also handles conversion between vectors and 10208 // non-scalars, we should break this down into fine grained specific checks 10209 // and emit proper diagnostics. 10210 QualType VecType = LHSVecType ? LHSType : RHSType; 10211 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10212 QualType OtherType = LHSVecType ? RHSType : LHSType; 10213 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10214 if (isLaxVectorConversion(OtherType, VecType)) { 10215 // If we're allowing lax vector conversions, only the total (data) size 10216 // needs to be the same. For non compound assignment, if one of the types is 10217 // scalar, the result is always the vector type. 10218 if (!IsCompAssign) { 10219 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10220 return VecType; 10221 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10222 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10223 // type. Note that this is already done by non-compound assignments in 10224 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10225 // <1 x T> -> T. The result is also a vector type. 10226 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10227 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10228 ExprResult *RHSExpr = &RHS; 10229 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10230 return VecType; 10231 } 10232 } 10233 10234 // Okay, the expression is invalid. 10235 10236 // If there's a non-vector, non-real operand, diagnose that. 10237 if ((!RHSVecType && !RHSType->isRealType()) || 10238 (!LHSVecType && !LHSType->isRealType())) { 10239 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10240 << LHSType << RHSType 10241 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10242 return QualType(); 10243 } 10244 10245 // OpenCL V1.1 6.2.6.p1: 10246 // If the operands are of more than one vector type, then an error shall 10247 // occur. Implicit conversions between vector types are not permitted, per 10248 // section 6.2.1. 10249 if (getLangOpts().OpenCL && 10250 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10251 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10252 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10253 << RHSType; 10254 return QualType(); 10255 } 10256 10257 10258 // If there is a vector type that is not a ExtVector and a scalar, we reach 10259 // this point if scalar could not be converted to the vector's element type 10260 // without truncation. 10261 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10262 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10263 QualType Scalar = LHSVecType ? RHSType : LHSType; 10264 QualType Vector = LHSVecType ? LHSType : RHSType; 10265 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10266 Diag(Loc, 10267 diag::err_typecheck_vector_not_convertable_implict_truncation) 10268 << ScalarOrVector << Scalar << Vector; 10269 10270 return QualType(); 10271 } 10272 10273 // Otherwise, use the generic diagnostic. 10274 Diag(Loc, DiagID) 10275 << LHSType << RHSType 10276 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10277 return QualType(); 10278 } 10279 10280 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10281 // expression. These are mainly cases where the null pointer is used as an 10282 // integer instead of a pointer. 10283 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10284 SourceLocation Loc, bool IsCompare) { 10285 // The canonical way to check for a GNU null is with isNullPointerConstant, 10286 // but we use a bit of a hack here for speed; this is a relatively 10287 // hot path, and isNullPointerConstant is slow. 10288 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10289 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10290 10291 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10292 10293 // Avoid analyzing cases where the result will either be invalid (and 10294 // diagnosed as such) or entirely valid and not something to warn about. 10295 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10296 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10297 return; 10298 10299 // Comparison operations would not make sense with a null pointer no matter 10300 // what the other expression is. 10301 if (!IsCompare) { 10302 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10303 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10304 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10305 return; 10306 } 10307 10308 // The rest of the operations only make sense with a null pointer 10309 // if the other expression is a pointer. 10310 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10311 NonNullType->canDecayToPointerType()) 10312 return; 10313 10314 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10315 << LHSNull /* LHS is NULL */ << NonNullType 10316 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10317 } 10318 10319 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10320 SourceLocation Loc) { 10321 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10322 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10323 if (!LUE || !RUE) 10324 return; 10325 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10326 RUE->getKind() != UETT_SizeOf) 10327 return; 10328 10329 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10330 QualType LHSTy = LHSArg->getType(); 10331 QualType RHSTy; 10332 10333 if (RUE->isArgumentType()) 10334 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10335 else 10336 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10337 10338 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10339 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10340 return; 10341 10342 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10343 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10344 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10345 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10346 << LHSArgDecl; 10347 } 10348 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10349 QualType ArrayElemTy = ArrayTy->getElementType(); 10350 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10351 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10352 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10353 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10354 return; 10355 S.Diag(Loc, diag::warn_division_sizeof_array) 10356 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10357 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10358 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10359 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10360 << LHSArgDecl; 10361 } 10362 10363 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10364 } 10365 } 10366 10367 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10368 ExprResult &RHS, 10369 SourceLocation Loc, bool IsDiv) { 10370 // Check for division/remainder by zero. 10371 Expr::EvalResult RHSValue; 10372 if (!RHS.get()->isValueDependent() && 10373 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10374 RHSValue.Val.getInt() == 0) 10375 S.DiagRuntimeBehavior(Loc, RHS.get(), 10376 S.PDiag(diag::warn_remainder_division_by_zero) 10377 << IsDiv << RHS.get()->getSourceRange()); 10378 } 10379 10380 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10381 SourceLocation Loc, 10382 bool IsCompAssign, bool IsDiv) { 10383 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10384 10385 QualType LHSTy = LHS.get()->getType(); 10386 QualType RHSTy = RHS.get()->getType(); 10387 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10388 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10389 /*AllowBothBool*/getLangOpts().AltiVec, 10390 /*AllowBoolConversions*/false); 10391 if (!IsDiv && 10392 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10393 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10394 // For division, only matrix-by-scalar is supported. Other combinations with 10395 // matrix types are invalid. 10396 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10397 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10398 10399 QualType compType = UsualArithmeticConversions( 10400 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10401 if (LHS.isInvalid() || RHS.isInvalid()) 10402 return QualType(); 10403 10404 10405 if (compType.isNull() || !compType->isArithmeticType()) 10406 return InvalidOperands(Loc, LHS, RHS); 10407 if (IsDiv) { 10408 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10409 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10410 } 10411 return compType; 10412 } 10413 10414 QualType Sema::CheckRemainderOperands( 10415 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10416 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10417 10418 if (LHS.get()->getType()->isVectorType() || 10419 RHS.get()->getType()->isVectorType()) { 10420 if (LHS.get()->getType()->hasIntegerRepresentation() && 10421 RHS.get()->getType()->hasIntegerRepresentation()) 10422 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10423 /*AllowBothBool*/getLangOpts().AltiVec, 10424 /*AllowBoolConversions*/false); 10425 return InvalidOperands(Loc, LHS, RHS); 10426 } 10427 10428 QualType compType = UsualArithmeticConversions( 10429 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10430 if (LHS.isInvalid() || RHS.isInvalid()) 10431 return QualType(); 10432 10433 if (compType.isNull() || !compType->isIntegerType()) 10434 return InvalidOperands(Loc, LHS, RHS); 10435 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10436 return compType; 10437 } 10438 10439 /// Diagnose invalid arithmetic on two void pointers. 10440 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10441 Expr *LHSExpr, Expr *RHSExpr) { 10442 S.Diag(Loc, S.getLangOpts().CPlusPlus 10443 ? diag::err_typecheck_pointer_arith_void_type 10444 : diag::ext_gnu_void_ptr) 10445 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10446 << RHSExpr->getSourceRange(); 10447 } 10448 10449 /// Diagnose invalid arithmetic on a void pointer. 10450 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10451 Expr *Pointer) { 10452 S.Diag(Loc, S.getLangOpts().CPlusPlus 10453 ? diag::err_typecheck_pointer_arith_void_type 10454 : diag::ext_gnu_void_ptr) 10455 << 0 /* one pointer */ << Pointer->getSourceRange(); 10456 } 10457 10458 /// Diagnose invalid arithmetic on a null pointer. 10459 /// 10460 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10461 /// idiom, which we recognize as a GNU extension. 10462 /// 10463 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10464 Expr *Pointer, bool IsGNUIdiom) { 10465 if (IsGNUIdiom) 10466 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10467 << Pointer->getSourceRange(); 10468 else 10469 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10470 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10471 } 10472 10473 /// Diagnose invalid subraction on a null pointer. 10474 /// 10475 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10476 Expr *Pointer, bool BothNull) { 10477 // Null - null is valid in C++ [expr.add]p7 10478 if (BothNull && S.getLangOpts().CPlusPlus) 10479 return; 10480 10481 // Is this s a macro from a system header? 10482 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10483 return; 10484 10485 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10486 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10487 } 10488 10489 /// Diagnose invalid arithmetic on two function pointers. 10490 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10491 Expr *LHS, Expr *RHS) { 10492 assert(LHS->getType()->isAnyPointerType()); 10493 assert(RHS->getType()->isAnyPointerType()); 10494 S.Diag(Loc, S.getLangOpts().CPlusPlus 10495 ? diag::err_typecheck_pointer_arith_function_type 10496 : diag::ext_gnu_ptr_func_arith) 10497 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10498 // We only show the second type if it differs from the first. 10499 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10500 RHS->getType()) 10501 << RHS->getType()->getPointeeType() 10502 << LHS->getSourceRange() << RHS->getSourceRange(); 10503 } 10504 10505 /// Diagnose invalid arithmetic on a function pointer. 10506 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10507 Expr *Pointer) { 10508 assert(Pointer->getType()->isAnyPointerType()); 10509 S.Diag(Loc, S.getLangOpts().CPlusPlus 10510 ? diag::err_typecheck_pointer_arith_function_type 10511 : diag::ext_gnu_ptr_func_arith) 10512 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10513 << 0 /* one pointer, so only one type */ 10514 << Pointer->getSourceRange(); 10515 } 10516 10517 /// Emit error if Operand is incomplete pointer type 10518 /// 10519 /// \returns True if pointer has incomplete type 10520 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10521 Expr *Operand) { 10522 QualType ResType = Operand->getType(); 10523 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10524 ResType = ResAtomicType->getValueType(); 10525 10526 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10527 QualType PointeeTy = ResType->getPointeeType(); 10528 return S.RequireCompleteSizedType( 10529 Loc, PointeeTy, 10530 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10531 Operand->getSourceRange()); 10532 } 10533 10534 /// Check the validity of an arithmetic pointer operand. 10535 /// 10536 /// If the operand has pointer type, this code will check for pointer types 10537 /// which are invalid in arithmetic operations. These will be diagnosed 10538 /// appropriately, including whether or not the use is supported as an 10539 /// extension. 10540 /// 10541 /// \returns True when the operand is valid to use (even if as an extension). 10542 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10543 Expr *Operand) { 10544 QualType ResType = Operand->getType(); 10545 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10546 ResType = ResAtomicType->getValueType(); 10547 10548 if (!ResType->isAnyPointerType()) return true; 10549 10550 QualType PointeeTy = ResType->getPointeeType(); 10551 if (PointeeTy->isVoidType()) { 10552 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10553 return !S.getLangOpts().CPlusPlus; 10554 } 10555 if (PointeeTy->isFunctionType()) { 10556 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10557 return !S.getLangOpts().CPlusPlus; 10558 } 10559 10560 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10561 10562 return true; 10563 } 10564 10565 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10566 /// operands. 10567 /// 10568 /// This routine will diagnose any invalid arithmetic on pointer operands much 10569 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10570 /// for emitting a single diagnostic even for operations where both LHS and RHS 10571 /// are (potentially problematic) pointers. 10572 /// 10573 /// \returns True when the operand is valid to use (even if as an extension). 10574 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10575 Expr *LHSExpr, Expr *RHSExpr) { 10576 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10577 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10578 if (!isLHSPointer && !isRHSPointer) return true; 10579 10580 QualType LHSPointeeTy, RHSPointeeTy; 10581 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10582 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10583 10584 // if both are pointers check if operation is valid wrt address spaces 10585 if (isLHSPointer && isRHSPointer) { 10586 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10587 S.Diag(Loc, 10588 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10589 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10590 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10591 return false; 10592 } 10593 } 10594 10595 // Check for arithmetic on pointers to incomplete types. 10596 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10597 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10598 if (isLHSVoidPtr || isRHSVoidPtr) { 10599 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10600 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10601 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10602 10603 return !S.getLangOpts().CPlusPlus; 10604 } 10605 10606 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10607 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10608 if (isLHSFuncPtr || isRHSFuncPtr) { 10609 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10610 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10611 RHSExpr); 10612 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10613 10614 return !S.getLangOpts().CPlusPlus; 10615 } 10616 10617 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10618 return false; 10619 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10620 return false; 10621 10622 return true; 10623 } 10624 10625 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10626 /// literal. 10627 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10628 Expr *LHSExpr, Expr *RHSExpr) { 10629 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10630 Expr* IndexExpr = RHSExpr; 10631 if (!StrExpr) { 10632 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10633 IndexExpr = LHSExpr; 10634 } 10635 10636 bool IsStringPlusInt = StrExpr && 10637 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10638 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10639 return; 10640 10641 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10642 Self.Diag(OpLoc, diag::warn_string_plus_int) 10643 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10644 10645 // Only print a fixit for "str" + int, not for int + "str". 10646 if (IndexExpr == RHSExpr) { 10647 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10648 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10649 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10650 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10651 << FixItHint::CreateInsertion(EndLoc, "]"); 10652 } else 10653 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10654 } 10655 10656 /// Emit a warning when adding a char literal to a string. 10657 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10658 Expr *LHSExpr, Expr *RHSExpr) { 10659 const Expr *StringRefExpr = LHSExpr; 10660 const CharacterLiteral *CharExpr = 10661 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10662 10663 if (!CharExpr) { 10664 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10665 StringRefExpr = RHSExpr; 10666 } 10667 10668 if (!CharExpr || !StringRefExpr) 10669 return; 10670 10671 const QualType StringType = StringRefExpr->getType(); 10672 10673 // Return if not a PointerType. 10674 if (!StringType->isAnyPointerType()) 10675 return; 10676 10677 // Return if not a CharacterType. 10678 if (!StringType->getPointeeType()->isAnyCharacterType()) 10679 return; 10680 10681 ASTContext &Ctx = Self.getASTContext(); 10682 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10683 10684 const QualType CharType = CharExpr->getType(); 10685 if (!CharType->isAnyCharacterType() && 10686 CharType->isIntegerType() && 10687 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10688 Self.Diag(OpLoc, diag::warn_string_plus_char) 10689 << DiagRange << Ctx.CharTy; 10690 } else { 10691 Self.Diag(OpLoc, diag::warn_string_plus_char) 10692 << DiagRange << CharExpr->getType(); 10693 } 10694 10695 // Only print a fixit for str + char, not for char + str. 10696 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10697 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10698 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10699 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10700 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10701 << FixItHint::CreateInsertion(EndLoc, "]"); 10702 } else { 10703 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10704 } 10705 } 10706 10707 /// Emit error when two pointers are incompatible. 10708 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10709 Expr *LHSExpr, Expr *RHSExpr) { 10710 assert(LHSExpr->getType()->isAnyPointerType()); 10711 assert(RHSExpr->getType()->isAnyPointerType()); 10712 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10713 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10714 << RHSExpr->getSourceRange(); 10715 } 10716 10717 // C99 6.5.6 10718 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10719 SourceLocation Loc, BinaryOperatorKind Opc, 10720 QualType* CompLHSTy) { 10721 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10722 10723 if (LHS.get()->getType()->isVectorType() || 10724 RHS.get()->getType()->isVectorType()) { 10725 QualType compType = CheckVectorOperands( 10726 LHS, RHS, Loc, CompLHSTy, 10727 /*AllowBothBool*/getLangOpts().AltiVec, 10728 /*AllowBoolConversions*/getLangOpts().ZVector); 10729 if (CompLHSTy) *CompLHSTy = compType; 10730 return compType; 10731 } 10732 10733 if (LHS.get()->getType()->isConstantMatrixType() || 10734 RHS.get()->getType()->isConstantMatrixType()) { 10735 QualType compType = 10736 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10737 if (CompLHSTy) 10738 *CompLHSTy = compType; 10739 return compType; 10740 } 10741 10742 QualType compType = UsualArithmeticConversions( 10743 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10744 if (LHS.isInvalid() || RHS.isInvalid()) 10745 return QualType(); 10746 10747 // Diagnose "string literal" '+' int and string '+' "char literal". 10748 if (Opc == BO_Add) { 10749 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10750 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10751 } 10752 10753 // handle the common case first (both operands are arithmetic). 10754 if (!compType.isNull() && compType->isArithmeticType()) { 10755 if (CompLHSTy) *CompLHSTy = compType; 10756 return compType; 10757 } 10758 10759 // Type-checking. Ultimately the pointer's going to be in PExp; 10760 // note that we bias towards the LHS being the pointer. 10761 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10762 10763 bool isObjCPointer; 10764 if (PExp->getType()->isPointerType()) { 10765 isObjCPointer = false; 10766 } else if (PExp->getType()->isObjCObjectPointerType()) { 10767 isObjCPointer = true; 10768 } else { 10769 std::swap(PExp, IExp); 10770 if (PExp->getType()->isPointerType()) { 10771 isObjCPointer = false; 10772 } else if (PExp->getType()->isObjCObjectPointerType()) { 10773 isObjCPointer = true; 10774 } else { 10775 return InvalidOperands(Loc, LHS, RHS); 10776 } 10777 } 10778 assert(PExp->getType()->isAnyPointerType()); 10779 10780 if (!IExp->getType()->isIntegerType()) 10781 return InvalidOperands(Loc, LHS, RHS); 10782 10783 // Adding to a null pointer results in undefined behavior. 10784 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10785 Context, Expr::NPC_ValueDependentIsNotNull)) { 10786 // In C++ adding zero to a null pointer is defined. 10787 Expr::EvalResult KnownVal; 10788 if (!getLangOpts().CPlusPlus || 10789 (!IExp->isValueDependent() && 10790 (!IExp->EvaluateAsInt(KnownVal, Context) || 10791 KnownVal.Val.getInt() != 0))) { 10792 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10793 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10794 Context, BO_Add, PExp, IExp); 10795 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10796 } 10797 } 10798 10799 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10800 return QualType(); 10801 10802 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10803 return QualType(); 10804 10805 // Check array bounds for pointer arithemtic 10806 CheckArrayAccess(PExp, IExp); 10807 10808 if (CompLHSTy) { 10809 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10810 if (LHSTy.isNull()) { 10811 LHSTy = LHS.get()->getType(); 10812 if (LHSTy->isPromotableIntegerType()) 10813 LHSTy = Context.getPromotedIntegerType(LHSTy); 10814 } 10815 *CompLHSTy = LHSTy; 10816 } 10817 10818 return PExp->getType(); 10819 } 10820 10821 // C99 6.5.6 10822 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10823 SourceLocation Loc, 10824 QualType* CompLHSTy) { 10825 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10826 10827 if (LHS.get()->getType()->isVectorType() || 10828 RHS.get()->getType()->isVectorType()) { 10829 QualType compType = CheckVectorOperands( 10830 LHS, RHS, Loc, CompLHSTy, 10831 /*AllowBothBool*/getLangOpts().AltiVec, 10832 /*AllowBoolConversions*/getLangOpts().ZVector); 10833 if (CompLHSTy) *CompLHSTy = compType; 10834 return compType; 10835 } 10836 10837 if (LHS.get()->getType()->isConstantMatrixType() || 10838 RHS.get()->getType()->isConstantMatrixType()) { 10839 QualType compType = 10840 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10841 if (CompLHSTy) 10842 *CompLHSTy = compType; 10843 return compType; 10844 } 10845 10846 QualType compType = UsualArithmeticConversions( 10847 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10848 if (LHS.isInvalid() || RHS.isInvalid()) 10849 return QualType(); 10850 10851 // Enforce type constraints: C99 6.5.6p3. 10852 10853 // Handle the common case first (both operands are arithmetic). 10854 if (!compType.isNull() && compType->isArithmeticType()) { 10855 if (CompLHSTy) *CompLHSTy = compType; 10856 return compType; 10857 } 10858 10859 // Either ptr - int or ptr - ptr. 10860 if (LHS.get()->getType()->isAnyPointerType()) { 10861 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10862 10863 // Diagnose bad cases where we step over interface counts. 10864 if (LHS.get()->getType()->isObjCObjectPointerType() && 10865 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10866 return QualType(); 10867 10868 // The result type of a pointer-int computation is the pointer type. 10869 if (RHS.get()->getType()->isIntegerType()) { 10870 // Subtracting from a null pointer should produce a warning. 10871 // The last argument to the diagnose call says this doesn't match the 10872 // GNU int-to-pointer idiom. 10873 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10874 Expr::NPC_ValueDependentIsNotNull)) { 10875 // In C++ adding zero to a null pointer is defined. 10876 Expr::EvalResult KnownVal; 10877 if (!getLangOpts().CPlusPlus || 10878 (!RHS.get()->isValueDependent() && 10879 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10880 KnownVal.Val.getInt() != 0))) { 10881 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10882 } 10883 } 10884 10885 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10886 return QualType(); 10887 10888 // Check array bounds for pointer arithemtic 10889 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10890 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10891 10892 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10893 return LHS.get()->getType(); 10894 } 10895 10896 // Handle pointer-pointer subtractions. 10897 if (const PointerType *RHSPTy 10898 = RHS.get()->getType()->getAs<PointerType>()) { 10899 QualType rpointee = RHSPTy->getPointeeType(); 10900 10901 if (getLangOpts().CPlusPlus) { 10902 // Pointee types must be the same: C++ [expr.add] 10903 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10904 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10905 } 10906 } else { 10907 // Pointee types must be compatible C99 6.5.6p3 10908 if (!Context.typesAreCompatible( 10909 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10910 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10911 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10912 return QualType(); 10913 } 10914 } 10915 10916 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10917 LHS.get(), RHS.get())) 10918 return QualType(); 10919 10920 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10921 Context, Expr::NPC_ValueDependentIsNotNull); 10922 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10923 Context, Expr::NPC_ValueDependentIsNotNull); 10924 10925 // Subtracting nullptr or from nullptr is suspect 10926 if (LHSIsNullPtr) 10927 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10928 if (RHSIsNullPtr) 10929 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10930 10931 // The pointee type may have zero size. As an extension, a structure or 10932 // union may have zero size or an array may have zero length. In this 10933 // case subtraction does not make sense. 10934 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10935 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10936 if (ElementSize.isZero()) { 10937 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10938 << rpointee.getUnqualifiedType() 10939 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10940 } 10941 } 10942 10943 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10944 return Context.getPointerDiffType(); 10945 } 10946 } 10947 10948 return InvalidOperands(Loc, LHS, RHS); 10949 } 10950 10951 static bool isScopedEnumerationType(QualType T) { 10952 if (const EnumType *ET = T->getAs<EnumType>()) 10953 return ET->getDecl()->isScoped(); 10954 return false; 10955 } 10956 10957 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10958 SourceLocation Loc, BinaryOperatorKind Opc, 10959 QualType LHSType) { 10960 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10961 // so skip remaining warnings as we don't want to modify values within Sema. 10962 if (S.getLangOpts().OpenCL) 10963 return; 10964 10965 // Check right/shifter operand 10966 Expr::EvalResult RHSResult; 10967 if (RHS.get()->isValueDependent() || 10968 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10969 return; 10970 llvm::APSInt Right = RHSResult.Val.getInt(); 10971 10972 if (Right.isNegative()) { 10973 S.DiagRuntimeBehavior(Loc, RHS.get(), 10974 S.PDiag(diag::warn_shift_negative) 10975 << RHS.get()->getSourceRange()); 10976 return; 10977 } 10978 10979 QualType LHSExprType = LHS.get()->getType(); 10980 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10981 if (LHSExprType->isBitIntType()) 10982 LeftSize = S.Context.getIntWidth(LHSExprType); 10983 else if (LHSExprType->isFixedPointType()) { 10984 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10985 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10986 } 10987 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10988 if (Right.uge(LeftBits)) { 10989 S.DiagRuntimeBehavior(Loc, RHS.get(), 10990 S.PDiag(diag::warn_shift_gt_typewidth) 10991 << RHS.get()->getSourceRange()); 10992 return; 10993 } 10994 10995 // FIXME: We probably need to handle fixed point types specially here. 10996 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10997 return; 10998 10999 // When left shifting an ICE which is signed, we can check for overflow which 11000 // according to C++ standards prior to C++2a has undefined behavior 11001 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 11002 // more than the maximum value representable in the result type, so never 11003 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11004 // expression is still probably a bug.) 11005 Expr::EvalResult LHSResult; 11006 if (LHS.get()->isValueDependent() || 11007 LHSType->hasUnsignedIntegerRepresentation() || 11008 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11009 return; 11010 llvm::APSInt Left = LHSResult.Val.getInt(); 11011 11012 // If LHS does not have a signed type and non-negative value 11013 // then, the behavior is undefined before C++2a. Warn about it. 11014 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11015 !S.getLangOpts().CPlusPlus20) { 11016 S.DiagRuntimeBehavior(Loc, LHS.get(), 11017 S.PDiag(diag::warn_shift_lhs_negative) 11018 << LHS.get()->getSourceRange()); 11019 return; 11020 } 11021 11022 llvm::APInt ResultBits = 11023 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11024 if (LeftBits.uge(ResultBits)) 11025 return; 11026 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11027 Result = Result.shl(Right); 11028 11029 // Print the bit representation of the signed integer as an unsigned 11030 // hexadecimal number. 11031 SmallString<40> HexResult; 11032 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11033 11034 // If we are only missing a sign bit, this is less likely to result in actual 11035 // bugs -- if the result is cast back to an unsigned type, it will have the 11036 // expected value. Thus we place this behind a different warning that can be 11037 // turned off separately if needed. 11038 if (LeftBits == ResultBits - 1) { 11039 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11040 << HexResult << LHSType 11041 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11042 return; 11043 } 11044 11045 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11046 << HexResult.str() << Result.getMinSignedBits() << LHSType 11047 << Left.getBitWidth() << LHS.get()->getSourceRange() 11048 << RHS.get()->getSourceRange(); 11049 } 11050 11051 /// Return the resulting type when a vector is shifted 11052 /// by a scalar or vector shift amount. 11053 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11054 SourceLocation Loc, bool IsCompAssign) { 11055 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11056 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11057 !LHS.get()->getType()->isVectorType()) { 11058 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11059 << RHS.get()->getType() << LHS.get()->getType() 11060 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11061 return QualType(); 11062 } 11063 11064 if (!IsCompAssign) { 11065 LHS = S.UsualUnaryConversions(LHS.get()); 11066 if (LHS.isInvalid()) return QualType(); 11067 } 11068 11069 RHS = S.UsualUnaryConversions(RHS.get()); 11070 if (RHS.isInvalid()) return QualType(); 11071 11072 QualType LHSType = LHS.get()->getType(); 11073 // Note that LHS might be a scalar because the routine calls not only in 11074 // OpenCL case. 11075 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11076 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11077 11078 // Note that RHS might not be a vector. 11079 QualType RHSType = RHS.get()->getType(); 11080 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11081 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11082 11083 // The operands need to be integers. 11084 if (!LHSEleType->isIntegerType()) { 11085 S.Diag(Loc, diag::err_typecheck_expect_int) 11086 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11087 return QualType(); 11088 } 11089 11090 if (!RHSEleType->isIntegerType()) { 11091 S.Diag(Loc, diag::err_typecheck_expect_int) 11092 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11093 return QualType(); 11094 } 11095 11096 if (!LHSVecTy) { 11097 assert(RHSVecTy); 11098 if (IsCompAssign) 11099 return RHSType; 11100 if (LHSEleType != RHSEleType) { 11101 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11102 LHSEleType = RHSEleType; 11103 } 11104 QualType VecTy = 11105 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11106 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11107 LHSType = VecTy; 11108 } else if (RHSVecTy) { 11109 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11110 // are applied component-wise. So if RHS is a vector, then ensure 11111 // that the number of elements is the same as LHS... 11112 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11113 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11114 << LHS.get()->getType() << RHS.get()->getType() 11115 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11116 return QualType(); 11117 } 11118 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11119 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11120 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11121 if (LHSBT != RHSBT && 11122 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11123 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11124 << LHS.get()->getType() << RHS.get()->getType() 11125 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11126 } 11127 } 11128 } else { 11129 // ...else expand RHS to match the number of elements in LHS. 11130 QualType VecTy = 11131 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11132 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11133 } 11134 11135 return LHSType; 11136 } 11137 11138 // C99 6.5.7 11139 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11140 SourceLocation Loc, BinaryOperatorKind Opc, 11141 bool IsCompAssign) { 11142 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11143 11144 // Vector shifts promote their scalar inputs to vector type. 11145 if (LHS.get()->getType()->isVectorType() || 11146 RHS.get()->getType()->isVectorType()) { 11147 if (LangOpts.ZVector) { 11148 // The shift operators for the z vector extensions work basically 11149 // like general shifts, except that neither the LHS nor the RHS is 11150 // allowed to be a "vector bool". 11151 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11152 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11153 return InvalidOperands(Loc, LHS, RHS); 11154 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11155 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11156 return InvalidOperands(Loc, LHS, RHS); 11157 } 11158 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11159 } 11160 11161 // Shifts don't perform usual arithmetic conversions, they just do integer 11162 // promotions on each operand. C99 6.5.7p3 11163 11164 // For the LHS, do usual unary conversions, but then reset them away 11165 // if this is a compound assignment. 11166 ExprResult OldLHS = LHS; 11167 LHS = UsualUnaryConversions(LHS.get()); 11168 if (LHS.isInvalid()) 11169 return QualType(); 11170 QualType LHSType = LHS.get()->getType(); 11171 if (IsCompAssign) LHS = OldLHS; 11172 11173 // The RHS is simpler. 11174 RHS = UsualUnaryConversions(RHS.get()); 11175 if (RHS.isInvalid()) 11176 return QualType(); 11177 QualType RHSType = RHS.get()->getType(); 11178 11179 // C99 6.5.7p2: Each of the operands shall have integer type. 11180 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11181 if ((!LHSType->isFixedPointOrIntegerType() && 11182 !LHSType->hasIntegerRepresentation()) || 11183 !RHSType->hasIntegerRepresentation()) 11184 return InvalidOperands(Loc, LHS, RHS); 11185 11186 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11187 // hasIntegerRepresentation() above instead of this. 11188 if (isScopedEnumerationType(LHSType) || 11189 isScopedEnumerationType(RHSType)) { 11190 return InvalidOperands(Loc, LHS, RHS); 11191 } 11192 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11193 11194 // "The type of the result is that of the promoted left operand." 11195 return LHSType; 11196 } 11197 11198 /// Diagnose bad pointer comparisons. 11199 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11200 ExprResult &LHS, ExprResult &RHS, 11201 bool IsError) { 11202 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11203 : diag::ext_typecheck_comparison_of_distinct_pointers) 11204 << LHS.get()->getType() << RHS.get()->getType() 11205 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11206 } 11207 11208 /// Returns false if the pointers are converted to a composite type, 11209 /// true otherwise. 11210 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11211 ExprResult &LHS, ExprResult &RHS) { 11212 // C++ [expr.rel]p2: 11213 // [...] Pointer conversions (4.10) and qualification 11214 // conversions (4.4) are performed on pointer operands (or on 11215 // a pointer operand and a null pointer constant) to bring 11216 // them to their composite pointer type. [...] 11217 // 11218 // C++ [expr.eq]p1 uses the same notion for (in)equality 11219 // comparisons of pointers. 11220 11221 QualType LHSType = LHS.get()->getType(); 11222 QualType RHSType = RHS.get()->getType(); 11223 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11224 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11225 11226 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11227 if (T.isNull()) { 11228 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11229 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11230 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11231 else 11232 S.InvalidOperands(Loc, LHS, RHS); 11233 return true; 11234 } 11235 11236 return false; 11237 } 11238 11239 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11240 ExprResult &LHS, 11241 ExprResult &RHS, 11242 bool IsError) { 11243 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11244 : diag::ext_typecheck_comparison_of_fptr_to_void) 11245 << LHS.get()->getType() << RHS.get()->getType() 11246 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11247 } 11248 11249 static bool isObjCObjectLiteral(ExprResult &E) { 11250 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11251 case Stmt::ObjCArrayLiteralClass: 11252 case Stmt::ObjCDictionaryLiteralClass: 11253 case Stmt::ObjCStringLiteralClass: 11254 case Stmt::ObjCBoxedExprClass: 11255 return true; 11256 default: 11257 // Note that ObjCBoolLiteral is NOT an object literal! 11258 return false; 11259 } 11260 } 11261 11262 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11263 const ObjCObjectPointerType *Type = 11264 LHS->getType()->getAs<ObjCObjectPointerType>(); 11265 11266 // If this is not actually an Objective-C object, bail out. 11267 if (!Type) 11268 return false; 11269 11270 // Get the LHS object's interface type. 11271 QualType InterfaceType = Type->getPointeeType(); 11272 11273 // If the RHS isn't an Objective-C object, bail out. 11274 if (!RHS->getType()->isObjCObjectPointerType()) 11275 return false; 11276 11277 // Try to find the -isEqual: method. 11278 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11279 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11280 InterfaceType, 11281 /*IsInstance=*/true); 11282 if (!Method) { 11283 if (Type->isObjCIdType()) { 11284 // For 'id', just check the global pool. 11285 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11286 /*receiverId=*/true); 11287 } else { 11288 // Check protocols. 11289 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11290 /*IsInstance=*/true); 11291 } 11292 } 11293 11294 if (!Method) 11295 return false; 11296 11297 QualType T = Method->parameters()[0]->getType(); 11298 if (!T->isObjCObjectPointerType()) 11299 return false; 11300 11301 QualType R = Method->getReturnType(); 11302 if (!R->isScalarType()) 11303 return false; 11304 11305 return true; 11306 } 11307 11308 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11309 FromE = FromE->IgnoreParenImpCasts(); 11310 switch (FromE->getStmtClass()) { 11311 default: 11312 break; 11313 case Stmt::ObjCStringLiteralClass: 11314 // "string literal" 11315 return LK_String; 11316 case Stmt::ObjCArrayLiteralClass: 11317 // "array literal" 11318 return LK_Array; 11319 case Stmt::ObjCDictionaryLiteralClass: 11320 // "dictionary literal" 11321 return LK_Dictionary; 11322 case Stmt::BlockExprClass: 11323 return LK_Block; 11324 case Stmt::ObjCBoxedExprClass: { 11325 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11326 switch (Inner->getStmtClass()) { 11327 case Stmt::IntegerLiteralClass: 11328 case Stmt::FloatingLiteralClass: 11329 case Stmt::CharacterLiteralClass: 11330 case Stmt::ObjCBoolLiteralExprClass: 11331 case Stmt::CXXBoolLiteralExprClass: 11332 // "numeric literal" 11333 return LK_Numeric; 11334 case Stmt::ImplicitCastExprClass: { 11335 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11336 // Boolean literals can be represented by implicit casts. 11337 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11338 return LK_Numeric; 11339 break; 11340 } 11341 default: 11342 break; 11343 } 11344 return LK_Boxed; 11345 } 11346 } 11347 return LK_None; 11348 } 11349 11350 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11351 ExprResult &LHS, ExprResult &RHS, 11352 BinaryOperator::Opcode Opc){ 11353 Expr *Literal; 11354 Expr *Other; 11355 if (isObjCObjectLiteral(LHS)) { 11356 Literal = LHS.get(); 11357 Other = RHS.get(); 11358 } else { 11359 Literal = RHS.get(); 11360 Other = LHS.get(); 11361 } 11362 11363 // Don't warn on comparisons against nil. 11364 Other = Other->IgnoreParenCasts(); 11365 if (Other->isNullPointerConstant(S.getASTContext(), 11366 Expr::NPC_ValueDependentIsNotNull)) 11367 return; 11368 11369 // This should be kept in sync with warn_objc_literal_comparison. 11370 // LK_String should always be after the other literals, since it has its own 11371 // warning flag. 11372 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11373 assert(LiteralKind != Sema::LK_Block); 11374 if (LiteralKind == Sema::LK_None) { 11375 llvm_unreachable("Unknown Objective-C object literal kind"); 11376 } 11377 11378 if (LiteralKind == Sema::LK_String) 11379 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11380 << Literal->getSourceRange(); 11381 else 11382 S.Diag(Loc, diag::warn_objc_literal_comparison) 11383 << LiteralKind << Literal->getSourceRange(); 11384 11385 if (BinaryOperator::isEqualityOp(Opc) && 11386 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11387 SourceLocation Start = LHS.get()->getBeginLoc(); 11388 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11389 CharSourceRange OpRange = 11390 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11391 11392 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11393 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11394 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11395 << FixItHint::CreateInsertion(End, "]"); 11396 } 11397 } 11398 11399 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11400 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11401 ExprResult &RHS, SourceLocation Loc, 11402 BinaryOperatorKind Opc) { 11403 // Check that left hand side is !something. 11404 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11405 if (!UO || UO->getOpcode() != UO_LNot) return; 11406 11407 // Only check if the right hand side is non-bool arithmetic type. 11408 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11409 11410 // Make sure that the something in !something is not bool. 11411 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11412 if (SubExpr->isKnownToHaveBooleanValue()) return; 11413 11414 // Emit warning. 11415 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11416 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11417 << Loc << IsBitwiseOp; 11418 11419 // First note suggest !(x < y) 11420 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11421 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11422 FirstClose = S.getLocForEndOfToken(FirstClose); 11423 if (FirstClose.isInvalid()) 11424 FirstOpen = SourceLocation(); 11425 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11426 << IsBitwiseOp 11427 << FixItHint::CreateInsertion(FirstOpen, "(") 11428 << FixItHint::CreateInsertion(FirstClose, ")"); 11429 11430 // Second note suggests (!x) < y 11431 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11432 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11433 SecondClose = S.getLocForEndOfToken(SecondClose); 11434 if (SecondClose.isInvalid()) 11435 SecondOpen = SourceLocation(); 11436 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11437 << FixItHint::CreateInsertion(SecondOpen, "(") 11438 << FixItHint::CreateInsertion(SecondClose, ")"); 11439 } 11440 11441 // Returns true if E refers to a non-weak array. 11442 static bool checkForArray(const Expr *E) { 11443 const ValueDecl *D = nullptr; 11444 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11445 D = DR->getDecl(); 11446 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11447 if (Mem->isImplicitAccess()) 11448 D = Mem->getMemberDecl(); 11449 } 11450 if (!D) 11451 return false; 11452 return D->getType()->isArrayType() && !D->isWeak(); 11453 } 11454 11455 /// Diagnose some forms of syntactically-obvious tautological comparison. 11456 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11457 Expr *LHS, Expr *RHS, 11458 BinaryOperatorKind Opc) { 11459 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11460 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11461 11462 QualType LHSType = LHS->getType(); 11463 QualType RHSType = RHS->getType(); 11464 if (LHSType->hasFloatingRepresentation() || 11465 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11466 S.inTemplateInstantiation()) 11467 return; 11468 11469 // Comparisons between two array types are ill-formed for operator<=>, so 11470 // we shouldn't emit any additional warnings about it. 11471 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11472 return; 11473 11474 // For non-floating point types, check for self-comparisons of the form 11475 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11476 // often indicate logic errors in the program. 11477 // 11478 // NOTE: Don't warn about comparison expressions resulting from macro 11479 // expansion. Also don't warn about comparisons which are only self 11480 // comparisons within a template instantiation. The warnings should catch 11481 // obvious cases in the definition of the template anyways. The idea is to 11482 // warn when the typed comparison operator will always evaluate to the same 11483 // result. 11484 11485 // Used for indexing into %select in warn_comparison_always 11486 enum { 11487 AlwaysConstant, 11488 AlwaysTrue, 11489 AlwaysFalse, 11490 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11491 }; 11492 11493 // C++2a [depr.array.comp]: 11494 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11495 // operands of array type are deprecated. 11496 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11497 RHSStripped->getType()->isArrayType()) { 11498 S.Diag(Loc, diag::warn_depr_array_comparison) 11499 << LHS->getSourceRange() << RHS->getSourceRange() 11500 << LHSStripped->getType() << RHSStripped->getType(); 11501 // Carry on to produce the tautological comparison warning, if this 11502 // expression is potentially-evaluated, we can resolve the array to a 11503 // non-weak declaration, and so on. 11504 } 11505 11506 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11507 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11508 unsigned Result; 11509 switch (Opc) { 11510 case BO_EQ: 11511 case BO_LE: 11512 case BO_GE: 11513 Result = AlwaysTrue; 11514 break; 11515 case BO_NE: 11516 case BO_LT: 11517 case BO_GT: 11518 Result = AlwaysFalse; 11519 break; 11520 case BO_Cmp: 11521 Result = AlwaysEqual; 11522 break; 11523 default: 11524 Result = AlwaysConstant; 11525 break; 11526 } 11527 S.DiagRuntimeBehavior(Loc, nullptr, 11528 S.PDiag(diag::warn_comparison_always) 11529 << 0 /*self-comparison*/ 11530 << Result); 11531 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11532 // What is it always going to evaluate to? 11533 unsigned Result; 11534 switch (Opc) { 11535 case BO_EQ: // e.g. array1 == array2 11536 Result = AlwaysFalse; 11537 break; 11538 case BO_NE: // e.g. array1 != array2 11539 Result = AlwaysTrue; 11540 break; 11541 default: // e.g. array1 <= array2 11542 // The best we can say is 'a constant' 11543 Result = AlwaysConstant; 11544 break; 11545 } 11546 S.DiagRuntimeBehavior(Loc, nullptr, 11547 S.PDiag(diag::warn_comparison_always) 11548 << 1 /*array comparison*/ 11549 << Result); 11550 } 11551 } 11552 11553 if (isa<CastExpr>(LHSStripped)) 11554 LHSStripped = LHSStripped->IgnoreParenCasts(); 11555 if (isa<CastExpr>(RHSStripped)) 11556 RHSStripped = RHSStripped->IgnoreParenCasts(); 11557 11558 // Warn about comparisons against a string constant (unless the other 11559 // operand is null); the user probably wants string comparison function. 11560 Expr *LiteralString = nullptr; 11561 Expr *LiteralStringStripped = nullptr; 11562 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11563 !RHSStripped->isNullPointerConstant(S.Context, 11564 Expr::NPC_ValueDependentIsNull)) { 11565 LiteralString = LHS; 11566 LiteralStringStripped = LHSStripped; 11567 } else if ((isa<StringLiteral>(RHSStripped) || 11568 isa<ObjCEncodeExpr>(RHSStripped)) && 11569 !LHSStripped->isNullPointerConstant(S.Context, 11570 Expr::NPC_ValueDependentIsNull)) { 11571 LiteralString = RHS; 11572 LiteralStringStripped = RHSStripped; 11573 } 11574 11575 if (LiteralString) { 11576 S.DiagRuntimeBehavior(Loc, nullptr, 11577 S.PDiag(diag::warn_stringcompare) 11578 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11579 << LiteralString->getSourceRange()); 11580 } 11581 } 11582 11583 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11584 switch (CK) { 11585 default: { 11586 #ifndef NDEBUG 11587 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11588 << "\n"; 11589 #endif 11590 llvm_unreachable("unhandled cast kind"); 11591 } 11592 case CK_UserDefinedConversion: 11593 return ICK_Identity; 11594 case CK_LValueToRValue: 11595 return ICK_Lvalue_To_Rvalue; 11596 case CK_ArrayToPointerDecay: 11597 return ICK_Array_To_Pointer; 11598 case CK_FunctionToPointerDecay: 11599 return ICK_Function_To_Pointer; 11600 case CK_IntegralCast: 11601 return ICK_Integral_Conversion; 11602 case CK_FloatingCast: 11603 return ICK_Floating_Conversion; 11604 case CK_IntegralToFloating: 11605 case CK_FloatingToIntegral: 11606 return ICK_Floating_Integral; 11607 case CK_IntegralComplexCast: 11608 case CK_FloatingComplexCast: 11609 case CK_FloatingComplexToIntegralComplex: 11610 case CK_IntegralComplexToFloatingComplex: 11611 return ICK_Complex_Conversion; 11612 case CK_FloatingComplexToReal: 11613 case CK_FloatingRealToComplex: 11614 case CK_IntegralComplexToReal: 11615 case CK_IntegralRealToComplex: 11616 return ICK_Complex_Real; 11617 } 11618 } 11619 11620 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11621 QualType FromType, 11622 SourceLocation Loc) { 11623 // Check for a narrowing implicit conversion. 11624 StandardConversionSequence SCS; 11625 SCS.setAsIdentityConversion(); 11626 SCS.setToType(0, FromType); 11627 SCS.setToType(1, ToType); 11628 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11629 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11630 11631 APValue PreNarrowingValue; 11632 QualType PreNarrowingType; 11633 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11634 PreNarrowingType, 11635 /*IgnoreFloatToIntegralConversion*/ true)) { 11636 case NK_Dependent_Narrowing: 11637 // Implicit conversion to a narrower type, but the expression is 11638 // value-dependent so we can't tell whether it's actually narrowing. 11639 case NK_Not_Narrowing: 11640 return false; 11641 11642 case NK_Constant_Narrowing: 11643 // Implicit conversion to a narrower type, and the value is not a constant 11644 // expression. 11645 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11646 << /*Constant*/ 1 11647 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11648 return true; 11649 11650 case NK_Variable_Narrowing: 11651 // Implicit conversion to a narrower type, and the value is not a constant 11652 // expression. 11653 case NK_Type_Narrowing: 11654 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11655 << /*Constant*/ 0 << FromType << ToType; 11656 // TODO: It's not a constant expression, but what if the user intended it 11657 // to be? Can we produce notes to help them figure out why it isn't? 11658 return true; 11659 } 11660 llvm_unreachable("unhandled case in switch"); 11661 } 11662 11663 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11664 ExprResult &LHS, 11665 ExprResult &RHS, 11666 SourceLocation Loc) { 11667 QualType LHSType = LHS.get()->getType(); 11668 QualType RHSType = RHS.get()->getType(); 11669 // Dig out the original argument type and expression before implicit casts 11670 // were applied. These are the types/expressions we need to check the 11671 // [expr.spaceship] requirements against. 11672 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11673 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11674 QualType LHSStrippedType = LHSStripped.get()->getType(); 11675 QualType RHSStrippedType = RHSStripped.get()->getType(); 11676 11677 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11678 // other is not, the program is ill-formed. 11679 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11680 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11681 return QualType(); 11682 } 11683 11684 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11685 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11686 RHSStrippedType->isEnumeralType(); 11687 if (NumEnumArgs == 1) { 11688 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11689 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11690 if (OtherTy->hasFloatingRepresentation()) { 11691 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11692 return QualType(); 11693 } 11694 } 11695 if (NumEnumArgs == 2) { 11696 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11697 // type E, the operator yields the result of converting the operands 11698 // to the underlying type of E and applying <=> to the converted operands. 11699 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11700 S.InvalidOperands(Loc, LHS, RHS); 11701 return QualType(); 11702 } 11703 QualType IntType = 11704 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11705 assert(IntType->isArithmeticType()); 11706 11707 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11708 // promote the boolean type, and all other promotable integer types, to 11709 // avoid this. 11710 if (IntType->isPromotableIntegerType()) 11711 IntType = S.Context.getPromotedIntegerType(IntType); 11712 11713 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11714 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11715 LHSType = RHSType = IntType; 11716 } 11717 11718 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11719 // usual arithmetic conversions are applied to the operands. 11720 QualType Type = 11721 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11722 if (LHS.isInvalid() || RHS.isInvalid()) 11723 return QualType(); 11724 if (Type.isNull()) 11725 return S.InvalidOperands(Loc, LHS, RHS); 11726 11727 Optional<ComparisonCategoryType> CCT = 11728 getComparisonCategoryForBuiltinCmp(Type); 11729 if (!CCT) 11730 return S.InvalidOperands(Loc, LHS, RHS); 11731 11732 bool HasNarrowing = checkThreeWayNarrowingConversion( 11733 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11734 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11735 RHS.get()->getBeginLoc()); 11736 if (HasNarrowing) 11737 return QualType(); 11738 11739 assert(!Type.isNull() && "composite type for <=> has not been set"); 11740 11741 return S.CheckComparisonCategoryType( 11742 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11743 } 11744 11745 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11746 ExprResult &RHS, 11747 SourceLocation Loc, 11748 BinaryOperatorKind Opc) { 11749 if (Opc == BO_Cmp) 11750 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11751 11752 // C99 6.5.8p3 / C99 6.5.9p4 11753 QualType Type = 11754 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11755 if (LHS.isInvalid() || RHS.isInvalid()) 11756 return QualType(); 11757 if (Type.isNull()) 11758 return S.InvalidOperands(Loc, LHS, RHS); 11759 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11760 11761 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11762 return S.InvalidOperands(Loc, LHS, RHS); 11763 11764 // Check for comparisons of floating point operands using != and ==. 11765 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11766 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11767 11768 // The result of comparisons is 'bool' in C++, 'int' in C. 11769 return S.Context.getLogicalOperationType(); 11770 } 11771 11772 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11773 if (!NullE.get()->getType()->isAnyPointerType()) 11774 return; 11775 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11776 if (!E.get()->getType()->isAnyPointerType() && 11777 E.get()->isNullPointerConstant(Context, 11778 Expr::NPC_ValueDependentIsNotNull) == 11779 Expr::NPCK_ZeroExpression) { 11780 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11781 if (CL->getValue() == 0) 11782 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11783 << NullValue 11784 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11785 NullValue ? "NULL" : "(void *)0"); 11786 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11787 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11788 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11789 if (T == Context.CharTy) 11790 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11791 << NullValue 11792 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11793 NullValue ? "NULL" : "(void *)0"); 11794 } 11795 } 11796 } 11797 11798 // C99 6.5.8, C++ [expr.rel] 11799 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11800 SourceLocation Loc, 11801 BinaryOperatorKind Opc) { 11802 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11803 bool IsThreeWay = Opc == BO_Cmp; 11804 bool IsOrdered = IsRelational || IsThreeWay; 11805 auto IsAnyPointerType = [](ExprResult E) { 11806 QualType Ty = E.get()->getType(); 11807 return Ty->isPointerType() || Ty->isMemberPointerType(); 11808 }; 11809 11810 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11811 // type, array-to-pointer, ..., conversions are performed on both operands to 11812 // bring them to their composite type. 11813 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11814 // any type-related checks. 11815 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11816 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11817 if (LHS.isInvalid()) 11818 return QualType(); 11819 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11820 if (RHS.isInvalid()) 11821 return QualType(); 11822 } else { 11823 LHS = DefaultLvalueConversion(LHS.get()); 11824 if (LHS.isInvalid()) 11825 return QualType(); 11826 RHS = DefaultLvalueConversion(RHS.get()); 11827 if (RHS.isInvalid()) 11828 return QualType(); 11829 } 11830 11831 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11832 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11833 CheckPtrComparisonWithNullChar(LHS, RHS); 11834 CheckPtrComparisonWithNullChar(RHS, LHS); 11835 } 11836 11837 // Handle vector comparisons separately. 11838 if (LHS.get()->getType()->isVectorType() || 11839 RHS.get()->getType()->isVectorType()) 11840 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11841 11842 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11843 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11844 11845 QualType LHSType = LHS.get()->getType(); 11846 QualType RHSType = RHS.get()->getType(); 11847 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11848 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11849 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11850 11851 const Expr::NullPointerConstantKind LHSNullKind = 11852 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11853 const Expr::NullPointerConstantKind RHSNullKind = 11854 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11855 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11856 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11857 11858 auto computeResultTy = [&]() { 11859 if (Opc != BO_Cmp) 11860 return Context.getLogicalOperationType(); 11861 assert(getLangOpts().CPlusPlus); 11862 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11863 11864 QualType CompositeTy = LHS.get()->getType(); 11865 assert(!CompositeTy->isReferenceType()); 11866 11867 Optional<ComparisonCategoryType> CCT = 11868 getComparisonCategoryForBuiltinCmp(CompositeTy); 11869 if (!CCT) 11870 return InvalidOperands(Loc, LHS, RHS); 11871 11872 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11873 // P0946R0: Comparisons between a null pointer constant and an object 11874 // pointer result in std::strong_equality, which is ill-formed under 11875 // P1959R0. 11876 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11877 << (LHSIsNull ? LHS.get()->getSourceRange() 11878 : RHS.get()->getSourceRange()); 11879 return QualType(); 11880 } 11881 11882 return CheckComparisonCategoryType( 11883 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11884 }; 11885 11886 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11887 bool IsEquality = Opc == BO_EQ; 11888 if (RHSIsNull) 11889 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11890 RHS.get()->getSourceRange()); 11891 else 11892 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11893 LHS.get()->getSourceRange()); 11894 } 11895 11896 if (IsOrdered && LHSType->isFunctionPointerType() && 11897 RHSType->isFunctionPointerType()) { 11898 // Valid unless a relational comparison of function pointers 11899 bool IsError = Opc == BO_Cmp; 11900 auto DiagID = 11901 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11902 : getLangOpts().CPlusPlus 11903 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11904 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11905 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11906 << RHS.get()->getSourceRange(); 11907 if (IsError) 11908 return QualType(); 11909 } 11910 11911 if ((LHSType->isIntegerType() && !LHSIsNull) || 11912 (RHSType->isIntegerType() && !RHSIsNull)) { 11913 // Skip normal pointer conversion checks in this case; we have better 11914 // diagnostics for this below. 11915 } else if (getLangOpts().CPlusPlus) { 11916 // Equality comparison of a function pointer to a void pointer is invalid, 11917 // but we allow it as an extension. 11918 // FIXME: If we really want to allow this, should it be part of composite 11919 // pointer type computation so it works in conditionals too? 11920 if (!IsOrdered && 11921 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11922 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11923 // This is a gcc extension compatibility comparison. 11924 // In a SFINAE context, we treat this as a hard error to maintain 11925 // conformance with the C++ standard. 11926 diagnoseFunctionPointerToVoidComparison( 11927 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11928 11929 if (isSFINAEContext()) 11930 return QualType(); 11931 11932 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11933 return computeResultTy(); 11934 } 11935 11936 // C++ [expr.eq]p2: 11937 // If at least one operand is a pointer [...] bring them to their 11938 // composite pointer type. 11939 // C++ [expr.spaceship]p6 11940 // If at least one of the operands is of pointer type, [...] bring them 11941 // to their composite pointer type. 11942 // C++ [expr.rel]p2: 11943 // If both operands are pointers, [...] bring them to their composite 11944 // pointer type. 11945 // For <=>, the only valid non-pointer types are arrays and functions, and 11946 // we already decayed those, so this is really the same as the relational 11947 // comparison rule. 11948 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11949 (IsOrdered ? 2 : 1) && 11950 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11951 RHSType->isObjCObjectPointerType()))) { 11952 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11953 return QualType(); 11954 return computeResultTy(); 11955 } 11956 } else if (LHSType->isPointerType() && 11957 RHSType->isPointerType()) { // C99 6.5.8p2 11958 // All of the following pointer-related warnings are GCC extensions, except 11959 // when handling null pointer constants. 11960 QualType LCanPointeeTy = 11961 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11962 QualType RCanPointeeTy = 11963 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11964 11965 // C99 6.5.9p2 and C99 6.5.8p2 11966 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11967 RCanPointeeTy.getUnqualifiedType())) { 11968 if (IsRelational) { 11969 // Pointers both need to point to complete or incomplete types 11970 if ((LCanPointeeTy->isIncompleteType() != 11971 RCanPointeeTy->isIncompleteType()) && 11972 !getLangOpts().C11) { 11973 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11974 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11975 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11976 << RCanPointeeTy->isIncompleteType(); 11977 } 11978 } 11979 } else if (!IsRelational && 11980 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11981 // Valid unless comparison between non-null pointer and function pointer 11982 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11983 && !LHSIsNull && !RHSIsNull) 11984 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11985 /*isError*/false); 11986 } else { 11987 // Invalid 11988 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11989 } 11990 if (LCanPointeeTy != RCanPointeeTy) { 11991 // Treat NULL constant as a special case in OpenCL. 11992 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11993 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11994 Diag(Loc, 11995 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11996 << LHSType << RHSType << 0 /* comparison */ 11997 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11998 } 11999 } 12000 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 12001 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12002 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12003 : CK_BitCast; 12004 if (LHSIsNull && !RHSIsNull) 12005 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12006 else 12007 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12008 } 12009 return computeResultTy(); 12010 } 12011 12012 if (getLangOpts().CPlusPlus) { 12013 // C++ [expr.eq]p4: 12014 // Two operands of type std::nullptr_t or one operand of type 12015 // std::nullptr_t and the other a null pointer constant compare equal. 12016 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12017 if (LHSType->isNullPtrType()) { 12018 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12019 return computeResultTy(); 12020 } 12021 if (RHSType->isNullPtrType()) { 12022 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12023 return computeResultTy(); 12024 } 12025 } 12026 12027 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12028 // These aren't covered by the composite pointer type rules. 12029 if (!IsOrdered && RHSType->isNullPtrType() && 12030 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12031 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12032 return computeResultTy(); 12033 } 12034 if (!IsOrdered && LHSType->isNullPtrType() && 12035 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12036 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12037 return computeResultTy(); 12038 } 12039 12040 if (IsRelational && 12041 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12042 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12043 // HACK: Relational comparison of nullptr_t against a pointer type is 12044 // invalid per DR583, but we allow it within std::less<> and friends, 12045 // since otherwise common uses of it break. 12046 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12047 // friends to have std::nullptr_t overload candidates. 12048 DeclContext *DC = CurContext; 12049 if (isa<FunctionDecl>(DC)) 12050 DC = DC->getParent(); 12051 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12052 if (CTSD->isInStdNamespace() && 12053 llvm::StringSwitch<bool>(CTSD->getName()) 12054 .Cases("less", "less_equal", "greater", "greater_equal", true) 12055 .Default(false)) { 12056 if (RHSType->isNullPtrType()) 12057 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12058 else 12059 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12060 return computeResultTy(); 12061 } 12062 } 12063 } 12064 12065 // C++ [expr.eq]p2: 12066 // If at least one operand is a pointer to member, [...] bring them to 12067 // their composite pointer type. 12068 if (!IsOrdered && 12069 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12070 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12071 return QualType(); 12072 else 12073 return computeResultTy(); 12074 } 12075 } 12076 12077 // Handle block pointer types. 12078 if (!IsOrdered && LHSType->isBlockPointerType() && 12079 RHSType->isBlockPointerType()) { 12080 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12081 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12082 12083 if (!LHSIsNull && !RHSIsNull && 12084 !Context.typesAreCompatible(lpointee, rpointee)) { 12085 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12086 << LHSType << RHSType << LHS.get()->getSourceRange() 12087 << RHS.get()->getSourceRange(); 12088 } 12089 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12090 return computeResultTy(); 12091 } 12092 12093 // Allow block pointers to be compared with null pointer constants. 12094 if (!IsOrdered 12095 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12096 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12097 if (!LHSIsNull && !RHSIsNull) { 12098 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12099 ->getPointeeType()->isVoidType()) 12100 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12101 ->getPointeeType()->isVoidType()))) 12102 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12103 << LHSType << RHSType << LHS.get()->getSourceRange() 12104 << RHS.get()->getSourceRange(); 12105 } 12106 if (LHSIsNull && !RHSIsNull) 12107 LHS = ImpCastExprToType(LHS.get(), RHSType, 12108 RHSType->isPointerType() ? CK_BitCast 12109 : CK_AnyPointerToBlockPointerCast); 12110 else 12111 RHS = ImpCastExprToType(RHS.get(), LHSType, 12112 LHSType->isPointerType() ? CK_BitCast 12113 : CK_AnyPointerToBlockPointerCast); 12114 return computeResultTy(); 12115 } 12116 12117 if (LHSType->isObjCObjectPointerType() || 12118 RHSType->isObjCObjectPointerType()) { 12119 const PointerType *LPT = LHSType->getAs<PointerType>(); 12120 const PointerType *RPT = RHSType->getAs<PointerType>(); 12121 if (LPT || RPT) { 12122 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12123 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12124 12125 if (!LPtrToVoid && !RPtrToVoid && 12126 !Context.typesAreCompatible(LHSType, RHSType)) { 12127 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12128 /*isError*/false); 12129 } 12130 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12131 // the RHS, but we have test coverage for this behavior. 12132 // FIXME: Consider using convertPointersToCompositeType in C++. 12133 if (LHSIsNull && !RHSIsNull) { 12134 Expr *E = LHS.get(); 12135 if (getLangOpts().ObjCAutoRefCount) 12136 CheckObjCConversion(SourceRange(), RHSType, E, 12137 CCK_ImplicitConversion); 12138 LHS = ImpCastExprToType(E, RHSType, 12139 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12140 } 12141 else { 12142 Expr *E = RHS.get(); 12143 if (getLangOpts().ObjCAutoRefCount) 12144 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12145 /*Diagnose=*/true, 12146 /*DiagnoseCFAudited=*/false, Opc); 12147 RHS = ImpCastExprToType(E, LHSType, 12148 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12149 } 12150 return computeResultTy(); 12151 } 12152 if (LHSType->isObjCObjectPointerType() && 12153 RHSType->isObjCObjectPointerType()) { 12154 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12155 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12156 /*isError*/false); 12157 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12158 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12159 12160 if (LHSIsNull && !RHSIsNull) 12161 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12162 else 12163 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12164 return computeResultTy(); 12165 } 12166 12167 if (!IsOrdered && LHSType->isBlockPointerType() && 12168 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12169 LHS = ImpCastExprToType(LHS.get(), RHSType, 12170 CK_BlockPointerToObjCPointerCast); 12171 return computeResultTy(); 12172 } else if (!IsOrdered && 12173 LHSType->isBlockCompatibleObjCPointerType(Context) && 12174 RHSType->isBlockPointerType()) { 12175 RHS = ImpCastExprToType(RHS.get(), LHSType, 12176 CK_BlockPointerToObjCPointerCast); 12177 return computeResultTy(); 12178 } 12179 } 12180 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12181 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12182 unsigned DiagID = 0; 12183 bool isError = false; 12184 if (LangOpts.DebuggerSupport) { 12185 // Under a debugger, allow the comparison of pointers to integers, 12186 // since users tend to want to compare addresses. 12187 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12188 (RHSIsNull && RHSType->isIntegerType())) { 12189 if (IsOrdered) { 12190 isError = getLangOpts().CPlusPlus; 12191 DiagID = 12192 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12193 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12194 } 12195 } else if (getLangOpts().CPlusPlus) { 12196 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12197 isError = true; 12198 } else if (IsOrdered) 12199 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12200 else 12201 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12202 12203 if (DiagID) { 12204 Diag(Loc, DiagID) 12205 << LHSType << RHSType << LHS.get()->getSourceRange() 12206 << RHS.get()->getSourceRange(); 12207 if (isError) 12208 return QualType(); 12209 } 12210 12211 if (LHSType->isIntegerType()) 12212 LHS = ImpCastExprToType(LHS.get(), RHSType, 12213 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12214 else 12215 RHS = ImpCastExprToType(RHS.get(), LHSType, 12216 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12217 return computeResultTy(); 12218 } 12219 12220 // Handle block pointers. 12221 if (!IsOrdered && RHSIsNull 12222 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12223 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12224 return computeResultTy(); 12225 } 12226 if (!IsOrdered && LHSIsNull 12227 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12228 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12229 return computeResultTy(); 12230 } 12231 12232 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12233 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12234 return computeResultTy(); 12235 } 12236 12237 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12238 return computeResultTy(); 12239 } 12240 12241 if (LHSIsNull && RHSType->isQueueT()) { 12242 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12243 return computeResultTy(); 12244 } 12245 12246 if (LHSType->isQueueT() && RHSIsNull) { 12247 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12248 return computeResultTy(); 12249 } 12250 } 12251 12252 return InvalidOperands(Loc, LHS, RHS); 12253 } 12254 12255 // Return a signed ext_vector_type that is of identical size and number of 12256 // elements. For floating point vectors, return an integer type of identical 12257 // size and number of elements. In the non ext_vector_type case, search from 12258 // the largest type to the smallest type to avoid cases where long long == long, 12259 // where long gets picked over long long. 12260 QualType Sema::GetSignedVectorType(QualType V) { 12261 const VectorType *VTy = V->castAs<VectorType>(); 12262 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12263 12264 if (isa<ExtVectorType>(VTy)) { 12265 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12266 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12267 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12268 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12269 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12270 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12271 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12272 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); 12273 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12274 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12275 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12276 "Unhandled vector element size in vector compare"); 12277 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12278 } 12279 12280 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12281 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), 12282 VectorType::GenericVector); 12283 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12284 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12285 VectorType::GenericVector); 12286 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12287 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12288 VectorType::GenericVector); 12289 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12290 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12291 VectorType::GenericVector); 12292 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12293 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12294 VectorType::GenericVector); 12295 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12296 "Unhandled vector element size in vector compare"); 12297 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12298 VectorType::GenericVector); 12299 } 12300 12301 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12302 /// operates on extended vector types. Instead of producing an IntTy result, 12303 /// like a scalar comparison, a vector comparison produces a vector of integer 12304 /// types. 12305 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12306 SourceLocation Loc, 12307 BinaryOperatorKind Opc) { 12308 if (Opc == BO_Cmp) { 12309 Diag(Loc, diag::err_three_way_vector_comparison); 12310 return QualType(); 12311 } 12312 12313 // Check to make sure we're operating on vectors of the same type and width, 12314 // Allowing one side to be a scalar of element type. 12315 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12316 /*AllowBothBool*/true, 12317 /*AllowBoolConversions*/getLangOpts().ZVector); 12318 if (vType.isNull()) 12319 return vType; 12320 12321 QualType LHSType = LHS.get()->getType(); 12322 12323 // Determine the return type of a vector compare. By default clang will return 12324 // a scalar for all vector compares except vector bool and vector pixel. 12325 // With the gcc compiler we will always return a vector type and with the xl 12326 // compiler we will always return a scalar type. This switch allows choosing 12327 // which behavior is prefered. 12328 if (getLangOpts().AltiVec) { 12329 switch (getLangOpts().getAltivecSrcCompat()) { 12330 case LangOptions::AltivecSrcCompatKind::Mixed: 12331 // If AltiVec, the comparison results in a numeric type, i.e. 12332 // bool for C++, int for C 12333 if (vType->castAs<VectorType>()->getVectorKind() == 12334 VectorType::AltiVecVector) 12335 return Context.getLogicalOperationType(); 12336 else 12337 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12338 break; 12339 case LangOptions::AltivecSrcCompatKind::GCC: 12340 // For GCC we always return the vector type. 12341 break; 12342 case LangOptions::AltivecSrcCompatKind::XL: 12343 return Context.getLogicalOperationType(); 12344 break; 12345 } 12346 } 12347 12348 // For non-floating point types, check for self-comparisons of the form 12349 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12350 // often indicate logic errors in the program. 12351 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12352 12353 // Check for comparisons of floating point operands using != and ==. 12354 if (BinaryOperator::isEqualityOp(Opc) && 12355 LHSType->hasFloatingRepresentation()) { 12356 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12357 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12358 } 12359 12360 // Return a signed type for the vector. 12361 return GetSignedVectorType(vType); 12362 } 12363 12364 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12365 const ExprResult &XorRHS, 12366 const SourceLocation Loc) { 12367 // Do not diagnose macros. 12368 if (Loc.isMacroID()) 12369 return; 12370 12371 // Do not diagnose if both LHS and RHS are macros. 12372 if (XorLHS.get()->getExprLoc().isMacroID() && 12373 XorRHS.get()->getExprLoc().isMacroID()) 12374 return; 12375 12376 bool Negative = false; 12377 bool ExplicitPlus = false; 12378 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12379 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12380 12381 if (!LHSInt) 12382 return; 12383 if (!RHSInt) { 12384 // Check negative literals. 12385 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12386 UnaryOperatorKind Opc = UO->getOpcode(); 12387 if (Opc != UO_Minus && Opc != UO_Plus) 12388 return; 12389 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12390 if (!RHSInt) 12391 return; 12392 Negative = (Opc == UO_Minus); 12393 ExplicitPlus = !Negative; 12394 } else { 12395 return; 12396 } 12397 } 12398 12399 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12400 llvm::APInt RightSideValue = RHSInt->getValue(); 12401 if (LeftSideValue != 2 && LeftSideValue != 10) 12402 return; 12403 12404 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12405 return; 12406 12407 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12408 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12409 llvm::StringRef ExprStr = 12410 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12411 12412 CharSourceRange XorRange = 12413 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12414 llvm::StringRef XorStr = 12415 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12416 // Do not diagnose if xor keyword/macro is used. 12417 if (XorStr == "xor") 12418 return; 12419 12420 std::string LHSStr = std::string(Lexer::getSourceText( 12421 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12422 S.getSourceManager(), S.getLangOpts())); 12423 std::string RHSStr = std::string(Lexer::getSourceText( 12424 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12425 S.getSourceManager(), S.getLangOpts())); 12426 12427 if (Negative) { 12428 RightSideValue = -RightSideValue; 12429 RHSStr = "-" + RHSStr; 12430 } else if (ExplicitPlus) { 12431 RHSStr = "+" + RHSStr; 12432 } 12433 12434 StringRef LHSStrRef = LHSStr; 12435 StringRef RHSStrRef = RHSStr; 12436 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12437 // literals. 12438 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12439 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12440 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12441 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12442 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12443 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12444 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12445 return; 12446 12447 bool SuggestXor = 12448 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12449 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12450 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12451 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12452 std::string SuggestedExpr = "1 << " + RHSStr; 12453 bool Overflow = false; 12454 llvm::APInt One = (LeftSideValue - 1); 12455 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12456 if (Overflow) { 12457 if (RightSideIntValue < 64) 12458 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12459 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12460 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12461 else if (RightSideIntValue == 64) 12462 S.Diag(Loc, diag::warn_xor_used_as_pow) 12463 << ExprStr << toString(XorValue, 10, true); 12464 else 12465 return; 12466 } else { 12467 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12468 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12469 << toString(PowValue, 10, true) 12470 << FixItHint::CreateReplacement( 12471 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12472 } 12473 12474 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12475 << ("0x2 ^ " + RHSStr) << SuggestXor; 12476 } else if (LeftSideValue == 10) { 12477 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12478 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12479 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12480 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12481 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12482 << ("0xA ^ " + RHSStr) << SuggestXor; 12483 } 12484 } 12485 12486 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12487 SourceLocation Loc) { 12488 // Ensure that either both operands are of the same vector type, or 12489 // one operand is of a vector type and the other is of its element type. 12490 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12491 /*AllowBothBool*/true, 12492 /*AllowBoolConversions*/false); 12493 if (vType.isNull()) 12494 return InvalidOperands(Loc, LHS, RHS); 12495 if (getLangOpts().OpenCL && 12496 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12497 vType->hasFloatingRepresentation()) 12498 return InvalidOperands(Loc, LHS, RHS); 12499 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12500 // usage of the logical operators && and || with vectors in C. This 12501 // check could be notionally dropped. 12502 if (!getLangOpts().CPlusPlus && 12503 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12504 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12505 12506 return GetSignedVectorType(LHS.get()->getType()); 12507 } 12508 12509 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12510 SourceLocation Loc, 12511 bool IsCompAssign) { 12512 if (!IsCompAssign) { 12513 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12514 if (LHS.isInvalid()) 12515 return QualType(); 12516 } 12517 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12518 if (RHS.isInvalid()) 12519 return QualType(); 12520 12521 // For conversion purposes, we ignore any qualifiers. 12522 // For example, "const float" and "float" are equivalent. 12523 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12524 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12525 12526 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12527 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12528 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12529 12530 if (Context.hasSameType(LHSType, RHSType)) 12531 return LHSType; 12532 12533 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12534 // case we have to return InvalidOperands. 12535 ExprResult OriginalLHS = LHS; 12536 ExprResult OriginalRHS = RHS; 12537 if (LHSMatType && !RHSMatType) { 12538 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12539 if (!RHS.isInvalid()) 12540 return LHSType; 12541 12542 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12543 } 12544 12545 if (!LHSMatType && RHSMatType) { 12546 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12547 if (!LHS.isInvalid()) 12548 return RHSType; 12549 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12550 } 12551 12552 return InvalidOperands(Loc, LHS, RHS); 12553 } 12554 12555 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12556 SourceLocation Loc, 12557 bool IsCompAssign) { 12558 if (!IsCompAssign) { 12559 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12560 if (LHS.isInvalid()) 12561 return QualType(); 12562 } 12563 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12564 if (RHS.isInvalid()) 12565 return QualType(); 12566 12567 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12568 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12569 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12570 12571 if (LHSMatType && RHSMatType) { 12572 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12573 return InvalidOperands(Loc, LHS, RHS); 12574 12575 if (!Context.hasSameType(LHSMatType->getElementType(), 12576 RHSMatType->getElementType())) 12577 return InvalidOperands(Loc, LHS, RHS); 12578 12579 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12580 LHSMatType->getNumRows(), 12581 RHSMatType->getNumColumns()); 12582 } 12583 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12584 } 12585 12586 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12587 SourceLocation Loc, 12588 BinaryOperatorKind Opc) { 12589 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12590 12591 bool IsCompAssign = 12592 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12593 12594 if (LHS.get()->getType()->isVectorType() || 12595 RHS.get()->getType()->isVectorType()) { 12596 if (LHS.get()->getType()->hasIntegerRepresentation() && 12597 RHS.get()->getType()->hasIntegerRepresentation()) 12598 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12599 /*AllowBothBool*/true, 12600 /*AllowBoolConversions*/getLangOpts().ZVector); 12601 return InvalidOperands(Loc, LHS, RHS); 12602 } 12603 12604 if (Opc == BO_And) 12605 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12606 12607 if (LHS.get()->getType()->hasFloatingRepresentation() || 12608 RHS.get()->getType()->hasFloatingRepresentation()) 12609 return InvalidOperands(Loc, LHS, RHS); 12610 12611 ExprResult LHSResult = LHS, RHSResult = RHS; 12612 QualType compType = UsualArithmeticConversions( 12613 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12614 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12615 return QualType(); 12616 LHS = LHSResult.get(); 12617 RHS = RHSResult.get(); 12618 12619 if (Opc == BO_Xor) 12620 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12621 12622 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12623 return compType; 12624 return InvalidOperands(Loc, LHS, RHS); 12625 } 12626 12627 // C99 6.5.[13,14] 12628 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12629 SourceLocation Loc, 12630 BinaryOperatorKind Opc) { 12631 // Check vector operands differently. 12632 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12633 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12634 12635 bool EnumConstantInBoolContext = false; 12636 for (const ExprResult &HS : {LHS, RHS}) { 12637 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12638 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12639 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12640 EnumConstantInBoolContext = true; 12641 } 12642 } 12643 12644 if (EnumConstantInBoolContext) 12645 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12646 12647 // Diagnose cases where the user write a logical and/or but probably meant a 12648 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12649 // is a constant. 12650 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12651 !LHS.get()->getType()->isBooleanType() && 12652 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12653 // Don't warn in macros or template instantiations. 12654 !Loc.isMacroID() && !inTemplateInstantiation()) { 12655 // If the RHS can be constant folded, and if it constant folds to something 12656 // that isn't 0 or 1 (which indicate a potential logical operation that 12657 // happened to fold to true/false) then warn. 12658 // Parens on the RHS are ignored. 12659 Expr::EvalResult EVResult; 12660 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12661 llvm::APSInt Result = EVResult.Val.getInt(); 12662 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12663 !RHS.get()->getExprLoc().isMacroID()) || 12664 (Result != 0 && Result != 1)) { 12665 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12666 << RHS.get()->getSourceRange() 12667 << (Opc == BO_LAnd ? "&&" : "||"); 12668 // Suggest replacing the logical operator with the bitwise version 12669 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12670 << (Opc == BO_LAnd ? "&" : "|") 12671 << FixItHint::CreateReplacement(SourceRange( 12672 Loc, getLocForEndOfToken(Loc)), 12673 Opc == BO_LAnd ? "&" : "|"); 12674 if (Opc == BO_LAnd) 12675 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12676 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12677 << FixItHint::CreateRemoval( 12678 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12679 RHS.get()->getEndLoc())); 12680 } 12681 } 12682 } 12683 12684 if (!Context.getLangOpts().CPlusPlus) { 12685 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12686 // not operate on the built-in scalar and vector float types. 12687 if (Context.getLangOpts().OpenCL && 12688 Context.getLangOpts().OpenCLVersion < 120) { 12689 if (LHS.get()->getType()->isFloatingType() || 12690 RHS.get()->getType()->isFloatingType()) 12691 return InvalidOperands(Loc, LHS, RHS); 12692 } 12693 12694 LHS = UsualUnaryConversions(LHS.get()); 12695 if (LHS.isInvalid()) 12696 return QualType(); 12697 12698 RHS = UsualUnaryConversions(RHS.get()); 12699 if (RHS.isInvalid()) 12700 return QualType(); 12701 12702 if (!LHS.get()->getType()->isScalarType() || 12703 !RHS.get()->getType()->isScalarType()) 12704 return InvalidOperands(Loc, LHS, RHS); 12705 12706 return Context.IntTy; 12707 } 12708 12709 // The following is safe because we only use this method for 12710 // non-overloadable operands. 12711 12712 // C++ [expr.log.and]p1 12713 // C++ [expr.log.or]p1 12714 // The operands are both contextually converted to type bool. 12715 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12716 if (LHSRes.isInvalid()) 12717 return InvalidOperands(Loc, LHS, RHS); 12718 LHS = LHSRes; 12719 12720 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12721 if (RHSRes.isInvalid()) 12722 return InvalidOperands(Loc, LHS, RHS); 12723 RHS = RHSRes; 12724 12725 // C++ [expr.log.and]p2 12726 // C++ [expr.log.or]p2 12727 // The result is a bool. 12728 return Context.BoolTy; 12729 } 12730 12731 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12732 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12733 if (!ME) return false; 12734 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12735 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12736 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12737 if (!Base) return false; 12738 return Base->getMethodDecl() != nullptr; 12739 } 12740 12741 /// Is the given expression (which must be 'const') a reference to a 12742 /// variable which was originally non-const, but which has become 12743 /// 'const' due to being captured within a block? 12744 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12745 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12746 assert(E->isLValue() && E->getType().isConstQualified()); 12747 E = E->IgnoreParens(); 12748 12749 // Must be a reference to a declaration from an enclosing scope. 12750 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12751 if (!DRE) return NCCK_None; 12752 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12753 12754 // The declaration must be a variable which is not declared 'const'. 12755 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12756 if (!var) return NCCK_None; 12757 if (var->getType().isConstQualified()) return NCCK_None; 12758 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12759 12760 // Decide whether the first capture was for a block or a lambda. 12761 DeclContext *DC = S.CurContext, *Prev = nullptr; 12762 // Decide whether the first capture was for a block or a lambda. 12763 while (DC) { 12764 // For init-capture, it is possible that the variable belongs to the 12765 // template pattern of the current context. 12766 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12767 if (var->isInitCapture() && 12768 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12769 break; 12770 if (DC == var->getDeclContext()) 12771 break; 12772 Prev = DC; 12773 DC = DC->getParent(); 12774 } 12775 // Unless we have an init-capture, we've gone one step too far. 12776 if (!var->isInitCapture()) 12777 DC = Prev; 12778 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12779 } 12780 12781 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12782 Ty = Ty.getNonReferenceType(); 12783 if (IsDereference && Ty->isPointerType()) 12784 Ty = Ty->getPointeeType(); 12785 return !Ty.isConstQualified(); 12786 } 12787 12788 // Update err_typecheck_assign_const and note_typecheck_assign_const 12789 // when this enum is changed. 12790 enum { 12791 ConstFunction, 12792 ConstVariable, 12793 ConstMember, 12794 ConstMethod, 12795 NestedConstMember, 12796 ConstUnknown, // Keep as last element 12797 }; 12798 12799 /// Emit the "read-only variable not assignable" error and print notes to give 12800 /// more information about why the variable is not assignable, such as pointing 12801 /// to the declaration of a const variable, showing that a method is const, or 12802 /// that the function is returning a const reference. 12803 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12804 SourceLocation Loc) { 12805 SourceRange ExprRange = E->getSourceRange(); 12806 12807 // Only emit one error on the first const found. All other consts will emit 12808 // a note to the error. 12809 bool DiagnosticEmitted = false; 12810 12811 // Track if the current expression is the result of a dereference, and if the 12812 // next checked expression is the result of a dereference. 12813 bool IsDereference = false; 12814 bool NextIsDereference = false; 12815 12816 // Loop to process MemberExpr chains. 12817 while (true) { 12818 IsDereference = NextIsDereference; 12819 12820 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12821 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12822 NextIsDereference = ME->isArrow(); 12823 const ValueDecl *VD = ME->getMemberDecl(); 12824 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12825 // Mutable fields can be modified even if the class is const. 12826 if (Field->isMutable()) { 12827 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12828 break; 12829 } 12830 12831 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12832 if (!DiagnosticEmitted) { 12833 S.Diag(Loc, diag::err_typecheck_assign_const) 12834 << ExprRange << ConstMember << false /*static*/ << Field 12835 << Field->getType(); 12836 DiagnosticEmitted = true; 12837 } 12838 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12839 << ConstMember << false /*static*/ << Field << Field->getType() 12840 << Field->getSourceRange(); 12841 } 12842 E = ME->getBase(); 12843 continue; 12844 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12845 if (VDecl->getType().isConstQualified()) { 12846 if (!DiagnosticEmitted) { 12847 S.Diag(Loc, diag::err_typecheck_assign_const) 12848 << ExprRange << ConstMember << true /*static*/ << VDecl 12849 << VDecl->getType(); 12850 DiagnosticEmitted = true; 12851 } 12852 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12853 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12854 << VDecl->getSourceRange(); 12855 } 12856 // Static fields do not inherit constness from parents. 12857 break; 12858 } 12859 break; // End MemberExpr 12860 } else if (const ArraySubscriptExpr *ASE = 12861 dyn_cast<ArraySubscriptExpr>(E)) { 12862 E = ASE->getBase()->IgnoreParenImpCasts(); 12863 continue; 12864 } else if (const ExtVectorElementExpr *EVE = 12865 dyn_cast<ExtVectorElementExpr>(E)) { 12866 E = EVE->getBase()->IgnoreParenImpCasts(); 12867 continue; 12868 } 12869 break; 12870 } 12871 12872 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12873 // Function calls 12874 const FunctionDecl *FD = CE->getDirectCallee(); 12875 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12876 if (!DiagnosticEmitted) { 12877 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12878 << ConstFunction << FD; 12879 DiagnosticEmitted = true; 12880 } 12881 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12882 diag::note_typecheck_assign_const) 12883 << ConstFunction << FD << FD->getReturnType() 12884 << FD->getReturnTypeSourceRange(); 12885 } 12886 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12887 // Point to variable declaration. 12888 if (const ValueDecl *VD = DRE->getDecl()) { 12889 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12890 if (!DiagnosticEmitted) { 12891 S.Diag(Loc, diag::err_typecheck_assign_const) 12892 << ExprRange << ConstVariable << VD << VD->getType(); 12893 DiagnosticEmitted = true; 12894 } 12895 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12896 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12897 } 12898 } 12899 } else if (isa<CXXThisExpr>(E)) { 12900 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12901 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12902 if (MD->isConst()) { 12903 if (!DiagnosticEmitted) { 12904 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12905 << ConstMethod << MD; 12906 DiagnosticEmitted = true; 12907 } 12908 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12909 << ConstMethod << MD << MD->getSourceRange(); 12910 } 12911 } 12912 } 12913 } 12914 12915 if (DiagnosticEmitted) 12916 return; 12917 12918 // Can't determine a more specific message, so display the generic error. 12919 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12920 } 12921 12922 enum OriginalExprKind { 12923 OEK_Variable, 12924 OEK_Member, 12925 OEK_LValue 12926 }; 12927 12928 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12929 const RecordType *Ty, 12930 SourceLocation Loc, SourceRange Range, 12931 OriginalExprKind OEK, 12932 bool &DiagnosticEmitted) { 12933 std::vector<const RecordType *> RecordTypeList; 12934 RecordTypeList.push_back(Ty); 12935 unsigned NextToCheckIndex = 0; 12936 // We walk the record hierarchy breadth-first to ensure that we print 12937 // diagnostics in field nesting order. 12938 while (RecordTypeList.size() > NextToCheckIndex) { 12939 bool IsNested = NextToCheckIndex > 0; 12940 for (const FieldDecl *Field : 12941 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12942 // First, check every field for constness. 12943 QualType FieldTy = Field->getType(); 12944 if (FieldTy.isConstQualified()) { 12945 if (!DiagnosticEmitted) { 12946 S.Diag(Loc, diag::err_typecheck_assign_const) 12947 << Range << NestedConstMember << OEK << VD 12948 << IsNested << Field; 12949 DiagnosticEmitted = true; 12950 } 12951 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12952 << NestedConstMember << IsNested << Field 12953 << FieldTy << Field->getSourceRange(); 12954 } 12955 12956 // Then we append it to the list to check next in order. 12957 FieldTy = FieldTy.getCanonicalType(); 12958 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12959 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 12960 RecordTypeList.push_back(FieldRecTy); 12961 } 12962 } 12963 ++NextToCheckIndex; 12964 } 12965 } 12966 12967 /// Emit an error for the case where a record we are trying to assign to has a 12968 /// const-qualified field somewhere in its hierarchy. 12969 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12970 SourceLocation Loc) { 12971 QualType Ty = E->getType(); 12972 assert(Ty->isRecordType() && "lvalue was not record?"); 12973 SourceRange Range = E->getSourceRange(); 12974 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12975 bool DiagEmitted = false; 12976 12977 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12978 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12979 Range, OEK_Member, DiagEmitted); 12980 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12981 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12982 Range, OEK_Variable, DiagEmitted); 12983 else 12984 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12985 Range, OEK_LValue, DiagEmitted); 12986 if (!DiagEmitted) 12987 DiagnoseConstAssignment(S, E, Loc); 12988 } 12989 12990 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12991 /// emit an error and return true. If so, return false. 12992 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12993 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12994 12995 S.CheckShadowingDeclModification(E, Loc); 12996 12997 SourceLocation OrigLoc = Loc; 12998 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12999 &Loc); 13000 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 13001 IsLV = Expr::MLV_InvalidMessageExpression; 13002 if (IsLV == Expr::MLV_Valid) 13003 return false; 13004 13005 unsigned DiagID = 0; 13006 bool NeedType = false; 13007 switch (IsLV) { // C99 6.5.16p2 13008 case Expr::MLV_ConstQualified: 13009 // Use a specialized diagnostic when we're assigning to an object 13010 // from an enclosing function or block. 13011 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13012 if (NCCK == NCCK_Block) 13013 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13014 else 13015 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13016 break; 13017 } 13018 13019 // In ARC, use some specialized diagnostics for occasions where we 13020 // infer 'const'. These are always pseudo-strong variables. 13021 if (S.getLangOpts().ObjCAutoRefCount) { 13022 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13023 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13024 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13025 13026 // Use the normal diagnostic if it's pseudo-__strong but the 13027 // user actually wrote 'const'. 13028 if (var->isARCPseudoStrong() && 13029 (!var->getTypeSourceInfo() || 13030 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13031 // There are three pseudo-strong cases: 13032 // - self 13033 ObjCMethodDecl *method = S.getCurMethodDecl(); 13034 if (method && var == method->getSelfDecl()) { 13035 DiagID = method->isClassMethod() 13036 ? diag::err_typecheck_arc_assign_self_class_method 13037 : diag::err_typecheck_arc_assign_self; 13038 13039 // - Objective-C externally_retained attribute. 13040 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13041 isa<ParmVarDecl>(var)) { 13042 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13043 13044 // - fast enumeration variables 13045 } else { 13046 DiagID = diag::err_typecheck_arr_assign_enumeration; 13047 } 13048 13049 SourceRange Assign; 13050 if (Loc != OrigLoc) 13051 Assign = SourceRange(OrigLoc, OrigLoc); 13052 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13053 // We need to preserve the AST regardless, so migration tool 13054 // can do its job. 13055 return false; 13056 } 13057 } 13058 } 13059 13060 // If none of the special cases above are triggered, then this is a 13061 // simple const assignment. 13062 if (DiagID == 0) { 13063 DiagnoseConstAssignment(S, E, Loc); 13064 return true; 13065 } 13066 13067 break; 13068 case Expr::MLV_ConstAddrSpace: 13069 DiagnoseConstAssignment(S, E, Loc); 13070 return true; 13071 case Expr::MLV_ConstQualifiedField: 13072 DiagnoseRecursiveConstFields(S, E, Loc); 13073 return true; 13074 case Expr::MLV_ArrayType: 13075 case Expr::MLV_ArrayTemporary: 13076 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13077 NeedType = true; 13078 break; 13079 case Expr::MLV_NotObjectType: 13080 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13081 NeedType = true; 13082 break; 13083 case Expr::MLV_LValueCast: 13084 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13085 break; 13086 case Expr::MLV_Valid: 13087 llvm_unreachable("did not take early return for MLV_Valid"); 13088 case Expr::MLV_InvalidExpression: 13089 case Expr::MLV_MemberFunction: 13090 case Expr::MLV_ClassTemporary: 13091 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13092 break; 13093 case Expr::MLV_IncompleteType: 13094 case Expr::MLV_IncompleteVoidType: 13095 return S.RequireCompleteType(Loc, E->getType(), 13096 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13097 case Expr::MLV_DuplicateVectorComponents: 13098 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13099 break; 13100 case Expr::MLV_NoSetterProperty: 13101 llvm_unreachable("readonly properties should be processed differently"); 13102 case Expr::MLV_InvalidMessageExpression: 13103 DiagID = diag::err_readonly_message_assignment; 13104 break; 13105 case Expr::MLV_SubObjCPropertySetting: 13106 DiagID = diag::err_no_subobject_property_setting; 13107 break; 13108 } 13109 13110 SourceRange Assign; 13111 if (Loc != OrigLoc) 13112 Assign = SourceRange(OrigLoc, OrigLoc); 13113 if (NeedType) 13114 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13115 else 13116 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13117 return true; 13118 } 13119 13120 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13121 SourceLocation Loc, 13122 Sema &Sema) { 13123 if (Sema.inTemplateInstantiation()) 13124 return; 13125 if (Sema.isUnevaluatedContext()) 13126 return; 13127 if (Loc.isInvalid() || Loc.isMacroID()) 13128 return; 13129 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13130 return; 13131 13132 // C / C++ fields 13133 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13134 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13135 if (ML && MR) { 13136 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13137 return; 13138 const ValueDecl *LHSDecl = 13139 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13140 const ValueDecl *RHSDecl = 13141 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13142 if (LHSDecl != RHSDecl) 13143 return; 13144 if (LHSDecl->getType().isVolatileQualified()) 13145 return; 13146 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13147 if (RefTy->getPointeeType().isVolatileQualified()) 13148 return; 13149 13150 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13151 } 13152 13153 // Objective-C instance variables 13154 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13155 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13156 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13157 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13158 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13159 if (RL && RR && RL->getDecl() == RR->getDecl()) 13160 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13161 } 13162 } 13163 13164 // C99 6.5.16.1 13165 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13166 SourceLocation Loc, 13167 QualType CompoundType) { 13168 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13169 13170 // Verify that LHS is a modifiable lvalue, and emit error if not. 13171 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13172 return QualType(); 13173 13174 QualType LHSType = LHSExpr->getType(); 13175 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13176 CompoundType; 13177 // OpenCL v1.2 s6.1.1.1 p2: 13178 // The half data type can only be used to declare a pointer to a buffer that 13179 // contains half values 13180 if (getLangOpts().OpenCL && 13181 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13182 LHSType->isHalfType()) { 13183 Diag(Loc, diag::err_opencl_half_load_store) << 1 13184 << LHSType.getUnqualifiedType(); 13185 return QualType(); 13186 } 13187 13188 AssignConvertType ConvTy; 13189 if (CompoundType.isNull()) { 13190 Expr *RHSCheck = RHS.get(); 13191 13192 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13193 13194 QualType LHSTy(LHSType); 13195 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13196 if (RHS.isInvalid()) 13197 return QualType(); 13198 // Special case of NSObject attributes on c-style pointer types. 13199 if (ConvTy == IncompatiblePointer && 13200 ((Context.isObjCNSObjectType(LHSType) && 13201 RHSType->isObjCObjectPointerType()) || 13202 (Context.isObjCNSObjectType(RHSType) && 13203 LHSType->isObjCObjectPointerType()))) 13204 ConvTy = Compatible; 13205 13206 if (ConvTy == Compatible && 13207 LHSType->isObjCObjectType()) 13208 Diag(Loc, diag::err_objc_object_assignment) 13209 << LHSType; 13210 13211 // If the RHS is a unary plus or minus, check to see if they = and + are 13212 // right next to each other. If so, the user may have typo'd "x =+ 4" 13213 // instead of "x += 4". 13214 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13215 RHSCheck = ICE->getSubExpr(); 13216 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13217 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13218 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13219 // Only if the two operators are exactly adjacent. 13220 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13221 // And there is a space or other character before the subexpr of the 13222 // unary +/-. We don't want to warn on "x=-1". 13223 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13224 UO->getSubExpr()->getBeginLoc().isFileID()) { 13225 Diag(Loc, diag::warn_not_compound_assign) 13226 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13227 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13228 } 13229 } 13230 13231 if (ConvTy == Compatible) { 13232 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13233 // Warn about retain cycles where a block captures the LHS, but 13234 // not if the LHS is a simple variable into which the block is 13235 // being stored...unless that variable can be captured by reference! 13236 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13237 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13238 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13239 checkRetainCycles(LHSExpr, RHS.get()); 13240 } 13241 13242 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13243 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13244 // It is safe to assign a weak reference into a strong variable. 13245 // Although this code can still have problems: 13246 // id x = self.weakProp; 13247 // id y = self.weakProp; 13248 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13249 // paths through the function. This should be revisited if 13250 // -Wrepeated-use-of-weak is made flow-sensitive. 13251 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13252 // variable, which will be valid for the current autorelease scope. 13253 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13254 RHS.get()->getBeginLoc())) 13255 getCurFunction()->markSafeWeakUse(RHS.get()); 13256 13257 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13258 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13259 } 13260 } 13261 } else { 13262 // Compound assignment "x += y" 13263 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13264 } 13265 13266 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13267 RHS.get(), AA_Assigning)) 13268 return QualType(); 13269 13270 CheckForNullPointerDereference(*this, LHSExpr); 13271 13272 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13273 if (CompoundType.isNull()) { 13274 // C++2a [expr.ass]p5: 13275 // A simple-assignment whose left operand is of a volatile-qualified 13276 // type is deprecated unless the assignment is either a discarded-value 13277 // expression or an unevaluated operand 13278 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13279 } else { 13280 // C++2a [expr.ass]p6: 13281 // [Compound-assignment] expressions are deprecated if E1 has 13282 // volatile-qualified type 13283 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13284 } 13285 } 13286 13287 // C99 6.5.16p3: The type of an assignment expression is the type of the 13288 // left operand unless the left operand has qualified type, in which case 13289 // it is the unqualified version of the type of the left operand. 13290 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13291 // is converted to the type of the assignment expression (above). 13292 // C++ 5.17p1: the type of the assignment expression is that of its left 13293 // operand. 13294 return (getLangOpts().CPlusPlus 13295 ? LHSType : LHSType.getUnqualifiedType()); 13296 } 13297 13298 // Only ignore explicit casts to void. 13299 static bool IgnoreCommaOperand(const Expr *E) { 13300 E = E->IgnoreParens(); 13301 13302 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13303 if (CE->getCastKind() == CK_ToVoid) { 13304 return true; 13305 } 13306 13307 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13308 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13309 CE->getSubExpr()->getType()->isDependentType()) { 13310 return true; 13311 } 13312 } 13313 13314 return false; 13315 } 13316 13317 // Look for instances where it is likely the comma operator is confused with 13318 // another operator. There is an explicit list of acceptable expressions for 13319 // the left hand side of the comma operator, otherwise emit a warning. 13320 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13321 // No warnings in macros 13322 if (Loc.isMacroID()) 13323 return; 13324 13325 // Don't warn in template instantiations. 13326 if (inTemplateInstantiation()) 13327 return; 13328 13329 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13330 // instead, skip more than needed, then call back into here with the 13331 // CommaVisitor in SemaStmt.cpp. 13332 // The listed locations are the initialization and increment portions 13333 // of a for loop. The additional checks are on the condition of 13334 // if statements, do/while loops, and for loops. 13335 // Differences in scope flags for C89 mode requires the extra logic. 13336 const unsigned ForIncrementFlags = 13337 getLangOpts().C99 || getLangOpts().CPlusPlus 13338 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13339 : Scope::ContinueScope | Scope::BreakScope; 13340 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13341 const unsigned ScopeFlags = getCurScope()->getFlags(); 13342 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13343 (ScopeFlags & ForInitFlags) == ForInitFlags) 13344 return; 13345 13346 // If there are multiple comma operators used together, get the RHS of the 13347 // of the comma operator as the LHS. 13348 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13349 if (BO->getOpcode() != BO_Comma) 13350 break; 13351 LHS = BO->getRHS(); 13352 } 13353 13354 // Only allow some expressions on LHS to not warn. 13355 if (IgnoreCommaOperand(LHS)) 13356 return; 13357 13358 Diag(Loc, diag::warn_comma_operator); 13359 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13360 << LHS->getSourceRange() 13361 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13362 LangOpts.CPlusPlus ? "static_cast<void>(" 13363 : "(void)(") 13364 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13365 ")"); 13366 } 13367 13368 // C99 6.5.17 13369 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13370 SourceLocation Loc) { 13371 LHS = S.CheckPlaceholderExpr(LHS.get()); 13372 RHS = S.CheckPlaceholderExpr(RHS.get()); 13373 if (LHS.isInvalid() || RHS.isInvalid()) 13374 return QualType(); 13375 13376 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13377 // operands, but not unary promotions. 13378 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13379 13380 // So we treat the LHS as a ignored value, and in C++ we allow the 13381 // containing site to determine what should be done with the RHS. 13382 LHS = S.IgnoredValueConversions(LHS.get()); 13383 if (LHS.isInvalid()) 13384 return QualType(); 13385 13386 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13387 13388 if (!S.getLangOpts().CPlusPlus) { 13389 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13390 if (RHS.isInvalid()) 13391 return QualType(); 13392 if (!RHS.get()->getType()->isVoidType()) 13393 S.RequireCompleteType(Loc, RHS.get()->getType(), 13394 diag::err_incomplete_type); 13395 } 13396 13397 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13398 S.DiagnoseCommaOperator(LHS.get(), Loc); 13399 13400 return RHS.get()->getType(); 13401 } 13402 13403 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13404 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13405 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13406 ExprValueKind &VK, 13407 ExprObjectKind &OK, 13408 SourceLocation OpLoc, 13409 bool IsInc, bool IsPrefix) { 13410 if (Op->isTypeDependent()) 13411 return S.Context.DependentTy; 13412 13413 QualType ResType = Op->getType(); 13414 // Atomic types can be used for increment / decrement where the non-atomic 13415 // versions can, so ignore the _Atomic() specifier for the purpose of 13416 // checking. 13417 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13418 ResType = ResAtomicType->getValueType(); 13419 13420 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13421 13422 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13423 // Decrement of bool is not allowed. 13424 if (!IsInc) { 13425 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13426 return QualType(); 13427 } 13428 // Increment of bool sets it to true, but is deprecated. 13429 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13430 : diag::warn_increment_bool) 13431 << Op->getSourceRange(); 13432 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13433 // Error on enum increments and decrements in C++ mode 13434 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13435 return QualType(); 13436 } else if (ResType->isRealType()) { 13437 // OK! 13438 } else if (ResType->isPointerType()) { 13439 // C99 6.5.2.4p2, 6.5.6p2 13440 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13441 return QualType(); 13442 } else if (ResType->isObjCObjectPointerType()) { 13443 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13444 // Otherwise, we just need a complete type. 13445 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13446 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13447 return QualType(); 13448 } else if (ResType->isAnyComplexType()) { 13449 // C99 does not support ++/-- on complex types, we allow as an extension. 13450 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13451 << ResType << Op->getSourceRange(); 13452 } else if (ResType->isPlaceholderType()) { 13453 ExprResult PR = S.CheckPlaceholderExpr(Op); 13454 if (PR.isInvalid()) return QualType(); 13455 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13456 IsInc, IsPrefix); 13457 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13458 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13459 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13460 (ResType->castAs<VectorType>()->getVectorKind() != 13461 VectorType::AltiVecBool)) { 13462 // The z vector extensions allow ++ and -- for non-bool vectors. 13463 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13464 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13465 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13466 } else { 13467 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13468 << ResType << int(IsInc) << Op->getSourceRange(); 13469 return QualType(); 13470 } 13471 // At this point, we know we have a real, complex or pointer type. 13472 // Now make sure the operand is a modifiable lvalue. 13473 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13474 return QualType(); 13475 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13476 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13477 // An operand with volatile-qualified type is deprecated 13478 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13479 << IsInc << ResType; 13480 } 13481 // In C++, a prefix increment is the same type as the operand. Otherwise 13482 // (in C or with postfix), the increment is the unqualified type of the 13483 // operand. 13484 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13485 VK = VK_LValue; 13486 OK = Op->getObjectKind(); 13487 return ResType; 13488 } else { 13489 VK = VK_PRValue; 13490 return ResType.getUnqualifiedType(); 13491 } 13492 } 13493 13494 13495 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13496 /// This routine allows us to typecheck complex/recursive expressions 13497 /// where the declaration is needed for type checking. We only need to 13498 /// handle cases when the expression references a function designator 13499 /// or is an lvalue. Here are some examples: 13500 /// - &(x) => x 13501 /// - &*****f => f for f a function designator. 13502 /// - &s.xx => s 13503 /// - &s.zz[1].yy -> s, if zz is an array 13504 /// - *(x + 1) -> x, if x is an array 13505 /// - &"123"[2] -> 0 13506 /// - & __real__ x -> x 13507 /// 13508 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13509 /// members. 13510 static ValueDecl *getPrimaryDecl(Expr *E) { 13511 switch (E->getStmtClass()) { 13512 case Stmt::DeclRefExprClass: 13513 return cast<DeclRefExpr>(E)->getDecl(); 13514 case Stmt::MemberExprClass: 13515 // If this is an arrow operator, the address is an offset from 13516 // the base's value, so the object the base refers to is 13517 // irrelevant. 13518 if (cast<MemberExpr>(E)->isArrow()) 13519 return nullptr; 13520 // Otherwise, the expression refers to a part of the base 13521 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13522 case Stmt::ArraySubscriptExprClass: { 13523 // FIXME: This code shouldn't be necessary! We should catch the implicit 13524 // promotion of register arrays earlier. 13525 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13526 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13527 if (ICE->getSubExpr()->getType()->isArrayType()) 13528 return getPrimaryDecl(ICE->getSubExpr()); 13529 } 13530 return nullptr; 13531 } 13532 case Stmt::UnaryOperatorClass: { 13533 UnaryOperator *UO = cast<UnaryOperator>(E); 13534 13535 switch(UO->getOpcode()) { 13536 case UO_Real: 13537 case UO_Imag: 13538 case UO_Extension: 13539 return getPrimaryDecl(UO->getSubExpr()); 13540 default: 13541 return nullptr; 13542 } 13543 } 13544 case Stmt::ParenExprClass: 13545 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13546 case Stmt::ImplicitCastExprClass: 13547 // If the result of an implicit cast is an l-value, we care about 13548 // the sub-expression; otherwise, the result here doesn't matter. 13549 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13550 case Stmt::CXXUuidofExprClass: 13551 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13552 default: 13553 return nullptr; 13554 } 13555 } 13556 13557 namespace { 13558 enum { 13559 AO_Bit_Field = 0, 13560 AO_Vector_Element = 1, 13561 AO_Property_Expansion = 2, 13562 AO_Register_Variable = 3, 13563 AO_Matrix_Element = 4, 13564 AO_No_Error = 5 13565 }; 13566 } 13567 /// Diagnose invalid operand for address of operations. 13568 /// 13569 /// \param Type The type of operand which cannot have its address taken. 13570 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13571 Expr *E, unsigned Type) { 13572 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13573 } 13574 13575 /// CheckAddressOfOperand - The operand of & must be either a function 13576 /// designator or an lvalue designating an object. If it is an lvalue, the 13577 /// object cannot be declared with storage class register or be a bit field. 13578 /// Note: The usual conversions are *not* applied to the operand of the & 13579 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13580 /// In C++, the operand might be an overloaded function name, in which case 13581 /// we allow the '&' but retain the overloaded-function type. 13582 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13583 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13584 if (PTy->getKind() == BuiltinType::Overload) { 13585 Expr *E = OrigOp.get()->IgnoreParens(); 13586 if (!isa<OverloadExpr>(E)) { 13587 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13588 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13589 << OrigOp.get()->getSourceRange(); 13590 return QualType(); 13591 } 13592 13593 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13594 if (isa<UnresolvedMemberExpr>(Ovl)) 13595 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13596 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13597 << OrigOp.get()->getSourceRange(); 13598 return QualType(); 13599 } 13600 13601 return Context.OverloadTy; 13602 } 13603 13604 if (PTy->getKind() == BuiltinType::UnknownAny) 13605 return Context.UnknownAnyTy; 13606 13607 if (PTy->getKind() == BuiltinType::BoundMember) { 13608 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13609 << OrigOp.get()->getSourceRange(); 13610 return QualType(); 13611 } 13612 13613 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13614 if (OrigOp.isInvalid()) return QualType(); 13615 } 13616 13617 if (OrigOp.get()->isTypeDependent()) 13618 return Context.DependentTy; 13619 13620 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13621 13622 // Make sure to ignore parentheses in subsequent checks 13623 Expr *op = OrigOp.get()->IgnoreParens(); 13624 13625 // In OpenCL captures for blocks called as lambda functions 13626 // are located in the private address space. Blocks used in 13627 // enqueue_kernel can be located in a different address space 13628 // depending on a vendor implementation. Thus preventing 13629 // taking an address of the capture to avoid invalid AS casts. 13630 if (LangOpts.OpenCL) { 13631 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13632 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13633 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13634 return QualType(); 13635 } 13636 } 13637 13638 if (getLangOpts().C99) { 13639 // Implement C99-only parts of addressof rules. 13640 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13641 if (uOp->getOpcode() == UO_Deref) 13642 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13643 // (assuming the deref expression is valid). 13644 return uOp->getSubExpr()->getType(); 13645 } 13646 // Technically, there should be a check for array subscript 13647 // expressions here, but the result of one is always an lvalue anyway. 13648 } 13649 ValueDecl *dcl = getPrimaryDecl(op); 13650 13651 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13652 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13653 op->getBeginLoc())) 13654 return QualType(); 13655 13656 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13657 unsigned AddressOfError = AO_No_Error; 13658 13659 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13660 bool sfinae = (bool)isSFINAEContext(); 13661 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13662 : diag::ext_typecheck_addrof_temporary) 13663 << op->getType() << op->getSourceRange(); 13664 if (sfinae) 13665 return QualType(); 13666 // Materialize the temporary as an lvalue so that we can take its address. 13667 OrigOp = op = 13668 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13669 } else if (isa<ObjCSelectorExpr>(op)) { 13670 return Context.getPointerType(op->getType()); 13671 } else if (lval == Expr::LV_MemberFunction) { 13672 // If it's an instance method, make a member pointer. 13673 // The expression must have exactly the form &A::foo. 13674 13675 // If the underlying expression isn't a decl ref, give up. 13676 if (!isa<DeclRefExpr>(op)) { 13677 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13678 << OrigOp.get()->getSourceRange(); 13679 return QualType(); 13680 } 13681 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13682 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13683 13684 // The id-expression was parenthesized. 13685 if (OrigOp.get() != DRE) { 13686 Diag(OpLoc, diag::err_parens_pointer_member_function) 13687 << OrigOp.get()->getSourceRange(); 13688 13689 // The method was named without a qualifier. 13690 } else if (!DRE->getQualifier()) { 13691 if (MD->getParent()->getName().empty()) 13692 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13693 << op->getSourceRange(); 13694 else { 13695 SmallString<32> Str; 13696 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13697 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13698 << op->getSourceRange() 13699 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13700 } 13701 } 13702 13703 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13704 if (isa<CXXDestructorDecl>(MD)) 13705 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13706 13707 QualType MPTy = Context.getMemberPointerType( 13708 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13709 // Under the MS ABI, lock down the inheritance model now. 13710 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13711 (void)isCompleteType(OpLoc, MPTy); 13712 return MPTy; 13713 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13714 // C99 6.5.3.2p1 13715 // The operand must be either an l-value or a function designator 13716 if (!op->getType()->isFunctionType()) { 13717 // Use a special diagnostic for loads from property references. 13718 if (isa<PseudoObjectExpr>(op)) { 13719 AddressOfError = AO_Property_Expansion; 13720 } else { 13721 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13722 << op->getType() << op->getSourceRange(); 13723 return QualType(); 13724 } 13725 } 13726 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13727 // The operand cannot be a bit-field 13728 AddressOfError = AO_Bit_Field; 13729 } else if (op->getObjectKind() == OK_VectorComponent) { 13730 // The operand cannot be an element of a vector 13731 AddressOfError = AO_Vector_Element; 13732 } else if (op->getObjectKind() == OK_MatrixComponent) { 13733 // The operand cannot be an element of a matrix. 13734 AddressOfError = AO_Matrix_Element; 13735 } else if (dcl) { // C99 6.5.3.2p1 13736 // We have an lvalue with a decl. Make sure the decl is not declared 13737 // with the register storage-class specifier. 13738 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13739 // in C++ it is not error to take address of a register 13740 // variable (c++03 7.1.1P3) 13741 if (vd->getStorageClass() == SC_Register && 13742 !getLangOpts().CPlusPlus) { 13743 AddressOfError = AO_Register_Variable; 13744 } 13745 } else if (isa<MSPropertyDecl>(dcl)) { 13746 AddressOfError = AO_Property_Expansion; 13747 } else if (isa<FunctionTemplateDecl>(dcl)) { 13748 return Context.OverloadTy; 13749 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13750 // Okay: we can take the address of a field. 13751 // Could be a pointer to member, though, if there is an explicit 13752 // scope qualifier for the class. 13753 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13754 DeclContext *Ctx = dcl->getDeclContext(); 13755 if (Ctx && Ctx->isRecord()) { 13756 if (dcl->getType()->isReferenceType()) { 13757 Diag(OpLoc, 13758 diag::err_cannot_form_pointer_to_member_of_reference_type) 13759 << dcl->getDeclName() << dcl->getType(); 13760 return QualType(); 13761 } 13762 13763 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13764 Ctx = Ctx->getParent(); 13765 13766 QualType MPTy = Context.getMemberPointerType( 13767 op->getType(), 13768 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13769 // Under the MS ABI, lock down the inheritance model now. 13770 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13771 (void)isCompleteType(OpLoc, MPTy); 13772 return MPTy; 13773 } 13774 } 13775 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13776 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13777 llvm_unreachable("Unknown/unexpected decl type"); 13778 } 13779 13780 if (AddressOfError != AO_No_Error) { 13781 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13782 return QualType(); 13783 } 13784 13785 if (lval == Expr::LV_IncompleteVoidType) { 13786 // Taking the address of a void variable is technically illegal, but we 13787 // allow it in cases which are otherwise valid. 13788 // Example: "extern void x; void* y = &x;". 13789 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13790 } 13791 13792 // If the operand has type "type", the result has type "pointer to type". 13793 if (op->getType()->isObjCObjectType()) 13794 return Context.getObjCObjectPointerType(op->getType()); 13795 13796 CheckAddressOfPackedMember(op); 13797 13798 return Context.getPointerType(op->getType()); 13799 } 13800 13801 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13802 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13803 if (!DRE) 13804 return; 13805 const Decl *D = DRE->getDecl(); 13806 if (!D) 13807 return; 13808 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13809 if (!Param) 13810 return; 13811 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13812 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13813 return; 13814 if (FunctionScopeInfo *FD = S.getCurFunction()) 13815 if (!FD->ModifiedNonNullParams.count(Param)) 13816 FD->ModifiedNonNullParams.insert(Param); 13817 } 13818 13819 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13820 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13821 SourceLocation OpLoc) { 13822 if (Op->isTypeDependent()) 13823 return S.Context.DependentTy; 13824 13825 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13826 if (ConvResult.isInvalid()) 13827 return QualType(); 13828 Op = ConvResult.get(); 13829 QualType OpTy = Op->getType(); 13830 QualType Result; 13831 13832 if (isa<CXXReinterpretCastExpr>(Op)) { 13833 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13834 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13835 Op->getSourceRange()); 13836 } 13837 13838 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13839 { 13840 Result = PT->getPointeeType(); 13841 } 13842 else if (const ObjCObjectPointerType *OPT = 13843 OpTy->getAs<ObjCObjectPointerType>()) 13844 Result = OPT->getPointeeType(); 13845 else { 13846 ExprResult PR = S.CheckPlaceholderExpr(Op); 13847 if (PR.isInvalid()) return QualType(); 13848 if (PR.get() != Op) 13849 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13850 } 13851 13852 if (Result.isNull()) { 13853 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13854 << OpTy << Op->getSourceRange(); 13855 return QualType(); 13856 } 13857 13858 // Note that per both C89 and C99, indirection is always legal, even if Result 13859 // is an incomplete type or void. It would be possible to warn about 13860 // dereferencing a void pointer, but it's completely well-defined, and such a 13861 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13862 // for pointers to 'void' but is fine for any other pointer type: 13863 // 13864 // C++ [expr.unary.op]p1: 13865 // [...] the expression to which [the unary * operator] is applied shall 13866 // be a pointer to an object type, or a pointer to a function type 13867 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13868 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13869 << OpTy << Op->getSourceRange(); 13870 13871 // Dereferences are usually l-values... 13872 VK = VK_LValue; 13873 13874 // ...except that certain expressions are never l-values in C. 13875 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13876 VK = VK_PRValue; 13877 13878 return Result; 13879 } 13880 13881 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13882 BinaryOperatorKind Opc; 13883 switch (Kind) { 13884 default: llvm_unreachable("Unknown binop!"); 13885 case tok::periodstar: Opc = BO_PtrMemD; break; 13886 case tok::arrowstar: Opc = BO_PtrMemI; break; 13887 case tok::star: Opc = BO_Mul; break; 13888 case tok::slash: Opc = BO_Div; break; 13889 case tok::percent: Opc = BO_Rem; break; 13890 case tok::plus: Opc = BO_Add; break; 13891 case tok::minus: Opc = BO_Sub; break; 13892 case tok::lessless: Opc = BO_Shl; break; 13893 case tok::greatergreater: Opc = BO_Shr; break; 13894 case tok::lessequal: Opc = BO_LE; break; 13895 case tok::less: Opc = BO_LT; break; 13896 case tok::greaterequal: Opc = BO_GE; break; 13897 case tok::greater: Opc = BO_GT; break; 13898 case tok::exclaimequal: Opc = BO_NE; break; 13899 case tok::equalequal: Opc = BO_EQ; break; 13900 case tok::spaceship: Opc = BO_Cmp; break; 13901 case tok::amp: Opc = BO_And; break; 13902 case tok::caret: Opc = BO_Xor; break; 13903 case tok::pipe: Opc = BO_Or; break; 13904 case tok::ampamp: Opc = BO_LAnd; break; 13905 case tok::pipepipe: Opc = BO_LOr; break; 13906 case tok::equal: Opc = BO_Assign; break; 13907 case tok::starequal: Opc = BO_MulAssign; break; 13908 case tok::slashequal: Opc = BO_DivAssign; break; 13909 case tok::percentequal: Opc = BO_RemAssign; break; 13910 case tok::plusequal: Opc = BO_AddAssign; break; 13911 case tok::minusequal: Opc = BO_SubAssign; break; 13912 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13913 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13914 case tok::ampequal: Opc = BO_AndAssign; break; 13915 case tok::caretequal: Opc = BO_XorAssign; break; 13916 case tok::pipeequal: Opc = BO_OrAssign; break; 13917 case tok::comma: Opc = BO_Comma; break; 13918 } 13919 return Opc; 13920 } 13921 13922 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13923 tok::TokenKind Kind) { 13924 UnaryOperatorKind Opc; 13925 switch (Kind) { 13926 default: llvm_unreachable("Unknown unary op!"); 13927 case tok::plusplus: Opc = UO_PreInc; break; 13928 case tok::minusminus: Opc = UO_PreDec; break; 13929 case tok::amp: Opc = UO_AddrOf; break; 13930 case tok::star: Opc = UO_Deref; break; 13931 case tok::plus: Opc = UO_Plus; break; 13932 case tok::minus: Opc = UO_Minus; break; 13933 case tok::tilde: Opc = UO_Not; break; 13934 case tok::exclaim: Opc = UO_LNot; break; 13935 case tok::kw___real: Opc = UO_Real; break; 13936 case tok::kw___imag: Opc = UO_Imag; break; 13937 case tok::kw___extension__: Opc = UO_Extension; break; 13938 } 13939 return Opc; 13940 } 13941 13942 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13943 /// This warning suppressed in the event of macro expansions. 13944 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13945 SourceLocation OpLoc, bool IsBuiltin) { 13946 if (S.inTemplateInstantiation()) 13947 return; 13948 if (S.isUnevaluatedContext()) 13949 return; 13950 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13951 return; 13952 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13953 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13954 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13955 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13956 if (!LHSDeclRef || !RHSDeclRef || 13957 LHSDeclRef->getLocation().isMacroID() || 13958 RHSDeclRef->getLocation().isMacroID()) 13959 return; 13960 const ValueDecl *LHSDecl = 13961 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13962 const ValueDecl *RHSDecl = 13963 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13964 if (LHSDecl != RHSDecl) 13965 return; 13966 if (LHSDecl->getType().isVolatileQualified()) 13967 return; 13968 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13969 if (RefTy->getPointeeType().isVolatileQualified()) 13970 return; 13971 13972 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13973 : diag::warn_self_assignment_overloaded) 13974 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13975 << RHSExpr->getSourceRange(); 13976 } 13977 13978 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13979 /// is usually indicative of introspection within the Objective-C pointer. 13980 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13981 SourceLocation OpLoc) { 13982 if (!S.getLangOpts().ObjC) 13983 return; 13984 13985 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13986 const Expr *LHS = L.get(); 13987 const Expr *RHS = R.get(); 13988 13989 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13990 ObjCPointerExpr = LHS; 13991 OtherExpr = RHS; 13992 } 13993 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13994 ObjCPointerExpr = RHS; 13995 OtherExpr = LHS; 13996 } 13997 13998 // This warning is deliberately made very specific to reduce false 13999 // positives with logic that uses '&' for hashing. This logic mainly 14000 // looks for code trying to introspect into tagged pointers, which 14001 // code should generally never do. 14002 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 14003 unsigned Diag = diag::warn_objc_pointer_masking; 14004 // Determine if we are introspecting the result of performSelectorXXX. 14005 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 14006 // Special case messages to -performSelector and friends, which 14007 // can return non-pointer values boxed in a pointer value. 14008 // Some clients may wish to silence warnings in this subcase. 14009 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14010 Selector S = ME->getSelector(); 14011 StringRef SelArg0 = S.getNameForSlot(0); 14012 if (SelArg0.startswith("performSelector")) 14013 Diag = diag::warn_objc_pointer_masking_performSelector; 14014 } 14015 14016 S.Diag(OpLoc, Diag) 14017 << ObjCPointerExpr->getSourceRange(); 14018 } 14019 } 14020 14021 static NamedDecl *getDeclFromExpr(Expr *E) { 14022 if (!E) 14023 return nullptr; 14024 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14025 return DRE->getDecl(); 14026 if (auto *ME = dyn_cast<MemberExpr>(E)) 14027 return ME->getMemberDecl(); 14028 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14029 return IRE->getDecl(); 14030 return nullptr; 14031 } 14032 14033 // This helper function promotes a binary operator's operands (which are of a 14034 // half vector type) to a vector of floats and then truncates the result to 14035 // a vector of either half or short. 14036 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14037 BinaryOperatorKind Opc, QualType ResultTy, 14038 ExprValueKind VK, ExprObjectKind OK, 14039 bool IsCompAssign, SourceLocation OpLoc, 14040 FPOptionsOverride FPFeatures) { 14041 auto &Context = S.getASTContext(); 14042 assert((isVector(ResultTy, Context.HalfTy) || 14043 isVector(ResultTy, Context.ShortTy)) && 14044 "Result must be a vector of half or short"); 14045 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14046 isVector(RHS.get()->getType(), Context.HalfTy) && 14047 "both operands expected to be a half vector"); 14048 14049 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14050 QualType BinOpResTy = RHS.get()->getType(); 14051 14052 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14053 // change BinOpResTy to a vector of ints. 14054 if (isVector(ResultTy, Context.ShortTy)) 14055 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14056 14057 if (IsCompAssign) 14058 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14059 ResultTy, VK, OK, OpLoc, FPFeatures, 14060 BinOpResTy, BinOpResTy); 14061 14062 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14063 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14064 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14065 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14066 } 14067 14068 static std::pair<ExprResult, ExprResult> 14069 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14070 Expr *RHSExpr) { 14071 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14072 if (!S.Context.isDependenceAllowed()) { 14073 // C cannot handle TypoExpr nodes on either side of a binop because it 14074 // doesn't handle dependent types properly, so make sure any TypoExprs have 14075 // been dealt with before checking the operands. 14076 LHS = S.CorrectDelayedTyposInExpr(LHS); 14077 RHS = S.CorrectDelayedTyposInExpr( 14078 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14079 [Opc, LHS](Expr *E) { 14080 if (Opc != BO_Assign) 14081 return ExprResult(E); 14082 // Avoid correcting the RHS to the same Expr as the LHS. 14083 Decl *D = getDeclFromExpr(E); 14084 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14085 }); 14086 } 14087 return std::make_pair(LHS, RHS); 14088 } 14089 14090 /// Returns true if conversion between vectors of halfs and vectors of floats 14091 /// is needed. 14092 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14093 Expr *E0, Expr *E1 = nullptr) { 14094 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14095 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14096 return false; 14097 14098 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14099 QualType Ty = E->IgnoreImplicit()->getType(); 14100 14101 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14102 // to vectors of floats. Although the element type of the vectors is __fp16, 14103 // the vectors shouldn't be treated as storage-only types. See the 14104 // discussion here: https://reviews.llvm.org/rG825235c140e7 14105 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14106 if (VT->getVectorKind() == VectorType::NeonVector) 14107 return false; 14108 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14109 } 14110 return false; 14111 }; 14112 14113 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14114 } 14115 14116 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14117 /// operator @p Opc at location @c TokLoc. This routine only supports 14118 /// built-in operations; ActOnBinOp handles overloaded operators. 14119 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14120 BinaryOperatorKind Opc, 14121 Expr *LHSExpr, Expr *RHSExpr) { 14122 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14123 // The syntax only allows initializer lists on the RHS of assignment, 14124 // so we don't need to worry about accepting invalid code for 14125 // non-assignment operators. 14126 // C++11 5.17p9: 14127 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14128 // of x = {} is x = T(). 14129 InitializationKind Kind = InitializationKind::CreateDirectList( 14130 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14131 InitializedEntity Entity = 14132 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14133 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14134 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14135 if (Init.isInvalid()) 14136 return Init; 14137 RHSExpr = Init.get(); 14138 } 14139 14140 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14141 QualType ResultTy; // Result type of the binary operator. 14142 // The following two variables are used for compound assignment operators 14143 QualType CompLHSTy; // Type of LHS after promotions for computation 14144 QualType CompResultTy; // Type of computation result 14145 ExprValueKind VK = VK_PRValue; 14146 ExprObjectKind OK = OK_Ordinary; 14147 bool ConvertHalfVec = false; 14148 14149 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14150 if (!LHS.isUsable() || !RHS.isUsable()) 14151 return ExprError(); 14152 14153 if (getLangOpts().OpenCL) { 14154 QualType LHSTy = LHSExpr->getType(); 14155 QualType RHSTy = RHSExpr->getType(); 14156 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14157 // the ATOMIC_VAR_INIT macro. 14158 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14159 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14160 if (BO_Assign == Opc) 14161 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14162 else 14163 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14164 return ExprError(); 14165 } 14166 14167 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14168 // only with a builtin functions and therefore should be disallowed here. 14169 if (LHSTy->isImageType() || RHSTy->isImageType() || 14170 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14171 LHSTy->isPipeType() || RHSTy->isPipeType() || 14172 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14173 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14174 return ExprError(); 14175 } 14176 } 14177 14178 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14179 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14180 14181 switch (Opc) { 14182 case BO_Assign: 14183 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14184 if (getLangOpts().CPlusPlus && 14185 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14186 VK = LHS.get()->getValueKind(); 14187 OK = LHS.get()->getObjectKind(); 14188 } 14189 if (!ResultTy.isNull()) { 14190 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14191 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14192 14193 // Avoid copying a block to the heap if the block is assigned to a local 14194 // auto variable that is declared in the same scope as the block. This 14195 // optimization is unsafe if the local variable is declared in an outer 14196 // scope. For example: 14197 // 14198 // BlockTy b; 14199 // { 14200 // b = ^{...}; 14201 // } 14202 // // It is unsafe to invoke the block here if it wasn't copied to the 14203 // // heap. 14204 // b(); 14205 14206 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14207 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14208 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14209 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14210 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14211 14212 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14213 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14214 NTCUC_Assignment, NTCUK_Copy); 14215 } 14216 RecordModifiableNonNullParam(*this, LHS.get()); 14217 break; 14218 case BO_PtrMemD: 14219 case BO_PtrMemI: 14220 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14221 Opc == BO_PtrMemI); 14222 break; 14223 case BO_Mul: 14224 case BO_Div: 14225 ConvertHalfVec = true; 14226 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14227 Opc == BO_Div); 14228 break; 14229 case BO_Rem: 14230 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14231 break; 14232 case BO_Add: 14233 ConvertHalfVec = true; 14234 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14235 break; 14236 case BO_Sub: 14237 ConvertHalfVec = true; 14238 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14239 break; 14240 case BO_Shl: 14241 case BO_Shr: 14242 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14243 break; 14244 case BO_LE: 14245 case BO_LT: 14246 case BO_GE: 14247 case BO_GT: 14248 ConvertHalfVec = true; 14249 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14250 break; 14251 case BO_EQ: 14252 case BO_NE: 14253 ConvertHalfVec = true; 14254 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14255 break; 14256 case BO_Cmp: 14257 ConvertHalfVec = true; 14258 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14259 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14260 break; 14261 case BO_And: 14262 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14263 LLVM_FALLTHROUGH; 14264 case BO_Xor: 14265 case BO_Or: 14266 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14267 break; 14268 case BO_LAnd: 14269 case BO_LOr: 14270 ConvertHalfVec = true; 14271 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14272 break; 14273 case BO_MulAssign: 14274 case BO_DivAssign: 14275 ConvertHalfVec = true; 14276 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14277 Opc == BO_DivAssign); 14278 CompLHSTy = CompResultTy; 14279 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14280 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14281 break; 14282 case BO_RemAssign: 14283 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14284 CompLHSTy = CompResultTy; 14285 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14286 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14287 break; 14288 case BO_AddAssign: 14289 ConvertHalfVec = true; 14290 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14291 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14292 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14293 break; 14294 case BO_SubAssign: 14295 ConvertHalfVec = true; 14296 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14297 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14298 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14299 break; 14300 case BO_ShlAssign: 14301 case BO_ShrAssign: 14302 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14303 CompLHSTy = CompResultTy; 14304 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14305 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14306 break; 14307 case BO_AndAssign: 14308 case BO_OrAssign: // fallthrough 14309 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14310 LLVM_FALLTHROUGH; 14311 case BO_XorAssign: 14312 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14313 CompLHSTy = CompResultTy; 14314 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14315 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14316 break; 14317 case BO_Comma: 14318 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14319 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14320 VK = RHS.get()->getValueKind(); 14321 OK = RHS.get()->getObjectKind(); 14322 } 14323 break; 14324 } 14325 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14326 return ExprError(); 14327 14328 // Some of the binary operations require promoting operands of half vector to 14329 // float vectors and truncating the result back to half vector. For now, we do 14330 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14331 // arm64). 14332 assert( 14333 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14334 isVector(LHS.get()->getType(), Context.HalfTy)) && 14335 "both sides are half vectors or neither sides are"); 14336 ConvertHalfVec = 14337 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14338 14339 // Check for array bounds violations for both sides of the BinaryOperator 14340 CheckArrayAccess(LHS.get()); 14341 CheckArrayAccess(RHS.get()); 14342 14343 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14344 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14345 &Context.Idents.get("object_setClass"), 14346 SourceLocation(), LookupOrdinaryName); 14347 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14348 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14349 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14350 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14351 "object_setClass(") 14352 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14353 ",") 14354 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14355 } 14356 else 14357 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14358 } 14359 else if (const ObjCIvarRefExpr *OIRE = 14360 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14361 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14362 14363 // Opc is not a compound assignment if CompResultTy is null. 14364 if (CompResultTy.isNull()) { 14365 if (ConvertHalfVec) 14366 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14367 OpLoc, CurFPFeatureOverrides()); 14368 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14369 VK, OK, OpLoc, CurFPFeatureOverrides()); 14370 } 14371 14372 // Handle compound assignments. 14373 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14374 OK_ObjCProperty) { 14375 VK = VK_LValue; 14376 OK = LHS.get()->getObjectKind(); 14377 } 14378 14379 // The LHS is not converted to the result type for fixed-point compound 14380 // assignment as the common type is computed on demand. Reset the CompLHSTy 14381 // to the LHS type we would have gotten after unary conversions. 14382 if (CompResultTy->isFixedPointType()) 14383 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14384 14385 if (ConvertHalfVec) 14386 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14387 OpLoc, CurFPFeatureOverrides()); 14388 14389 return CompoundAssignOperator::Create( 14390 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14391 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14392 } 14393 14394 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14395 /// operators are mixed in a way that suggests that the programmer forgot that 14396 /// comparison operators have higher precedence. The most typical example of 14397 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14398 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14399 SourceLocation OpLoc, Expr *LHSExpr, 14400 Expr *RHSExpr) { 14401 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14402 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14403 14404 // Check that one of the sides is a comparison operator and the other isn't. 14405 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14406 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14407 if (isLeftComp == isRightComp) 14408 return; 14409 14410 // Bitwise operations are sometimes used as eager logical ops. 14411 // Don't diagnose this. 14412 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14413 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14414 if (isLeftBitwise || isRightBitwise) 14415 return; 14416 14417 SourceRange DiagRange = isLeftComp 14418 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14419 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14420 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14421 SourceRange ParensRange = 14422 isLeftComp 14423 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14424 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14425 14426 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14427 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14428 SuggestParentheses(Self, OpLoc, 14429 Self.PDiag(diag::note_precedence_silence) << OpStr, 14430 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14431 SuggestParentheses(Self, OpLoc, 14432 Self.PDiag(diag::note_precedence_bitwise_first) 14433 << BinaryOperator::getOpcodeStr(Opc), 14434 ParensRange); 14435 } 14436 14437 /// It accepts a '&&' expr that is inside a '||' one. 14438 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14439 /// in parentheses. 14440 static void 14441 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14442 BinaryOperator *Bop) { 14443 assert(Bop->getOpcode() == BO_LAnd); 14444 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14445 << Bop->getSourceRange() << OpLoc; 14446 SuggestParentheses(Self, Bop->getOperatorLoc(), 14447 Self.PDiag(diag::note_precedence_silence) 14448 << Bop->getOpcodeStr(), 14449 Bop->getSourceRange()); 14450 } 14451 14452 /// Returns true if the given expression can be evaluated as a constant 14453 /// 'true'. 14454 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14455 bool Res; 14456 return !E->isValueDependent() && 14457 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14458 } 14459 14460 /// Returns true if the given expression can be evaluated as a constant 14461 /// 'false'. 14462 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14463 bool Res; 14464 return !E->isValueDependent() && 14465 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14466 } 14467 14468 /// Look for '&&' in the left hand of a '||' expr. 14469 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14470 Expr *LHSExpr, Expr *RHSExpr) { 14471 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14472 if (Bop->getOpcode() == BO_LAnd) { 14473 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14474 if (EvaluatesAsFalse(S, RHSExpr)) 14475 return; 14476 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14477 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14478 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14479 } else if (Bop->getOpcode() == BO_LOr) { 14480 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14481 // If it's "a || b && 1 || c" we didn't warn earlier for 14482 // "a || b && 1", but warn now. 14483 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14484 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14485 } 14486 } 14487 } 14488 } 14489 14490 /// Look for '&&' in the right hand of a '||' expr. 14491 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14492 Expr *LHSExpr, Expr *RHSExpr) { 14493 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14494 if (Bop->getOpcode() == BO_LAnd) { 14495 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14496 if (EvaluatesAsFalse(S, LHSExpr)) 14497 return; 14498 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14499 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14500 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14501 } 14502 } 14503 } 14504 14505 /// Look for bitwise op in the left or right hand of a bitwise op with 14506 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14507 /// the '&' expression in parentheses. 14508 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14509 SourceLocation OpLoc, Expr *SubExpr) { 14510 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14511 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14512 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14513 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14514 << Bop->getSourceRange() << OpLoc; 14515 SuggestParentheses(S, Bop->getOperatorLoc(), 14516 S.PDiag(diag::note_precedence_silence) 14517 << Bop->getOpcodeStr(), 14518 Bop->getSourceRange()); 14519 } 14520 } 14521 } 14522 14523 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14524 Expr *SubExpr, StringRef Shift) { 14525 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14526 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14527 StringRef Op = Bop->getOpcodeStr(); 14528 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14529 << Bop->getSourceRange() << OpLoc << Shift << Op; 14530 SuggestParentheses(S, Bop->getOperatorLoc(), 14531 S.PDiag(diag::note_precedence_silence) << Op, 14532 Bop->getSourceRange()); 14533 } 14534 } 14535 } 14536 14537 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14538 Expr *LHSExpr, Expr *RHSExpr) { 14539 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14540 if (!OCE) 14541 return; 14542 14543 FunctionDecl *FD = OCE->getDirectCallee(); 14544 if (!FD || !FD->isOverloadedOperator()) 14545 return; 14546 14547 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14548 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14549 return; 14550 14551 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14552 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14553 << (Kind == OO_LessLess); 14554 SuggestParentheses(S, OCE->getOperatorLoc(), 14555 S.PDiag(diag::note_precedence_silence) 14556 << (Kind == OO_LessLess ? "<<" : ">>"), 14557 OCE->getSourceRange()); 14558 SuggestParentheses( 14559 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14560 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14561 } 14562 14563 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14564 /// precedence. 14565 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14566 SourceLocation OpLoc, Expr *LHSExpr, 14567 Expr *RHSExpr){ 14568 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14569 if (BinaryOperator::isBitwiseOp(Opc)) 14570 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14571 14572 // Diagnose "arg1 & arg2 | arg3" 14573 if ((Opc == BO_Or || Opc == BO_Xor) && 14574 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14575 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14576 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14577 } 14578 14579 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14580 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14581 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14582 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14583 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14584 } 14585 14586 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14587 || Opc == BO_Shr) { 14588 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14589 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14590 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14591 } 14592 14593 // Warn on overloaded shift operators and comparisons, such as: 14594 // cout << 5 == 4; 14595 if (BinaryOperator::isComparisonOp(Opc)) 14596 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14597 } 14598 14599 // Binary Operators. 'Tok' is the token for the operator. 14600 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14601 tok::TokenKind Kind, 14602 Expr *LHSExpr, Expr *RHSExpr) { 14603 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14604 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14605 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14606 14607 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14608 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14609 14610 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14611 } 14612 14613 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14614 UnresolvedSetImpl &Functions) { 14615 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14616 if (OverOp != OO_None && OverOp != OO_Equal) 14617 LookupOverloadedOperatorName(OverOp, S, Functions); 14618 14619 // In C++20 onwards, we may have a second operator to look up. 14620 if (getLangOpts().CPlusPlus20) { 14621 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14622 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14623 } 14624 } 14625 14626 /// Build an overloaded binary operator expression in the given scope. 14627 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14628 BinaryOperatorKind Opc, 14629 Expr *LHS, Expr *RHS) { 14630 switch (Opc) { 14631 case BO_Assign: 14632 case BO_DivAssign: 14633 case BO_RemAssign: 14634 case BO_SubAssign: 14635 case BO_AndAssign: 14636 case BO_OrAssign: 14637 case BO_XorAssign: 14638 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14639 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14640 break; 14641 default: 14642 break; 14643 } 14644 14645 // Find all of the overloaded operators visible from this point. 14646 UnresolvedSet<16> Functions; 14647 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14648 14649 // Build the (potentially-overloaded, potentially-dependent) 14650 // binary operation. 14651 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14652 } 14653 14654 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14655 BinaryOperatorKind Opc, 14656 Expr *LHSExpr, Expr *RHSExpr) { 14657 ExprResult LHS, RHS; 14658 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14659 if (!LHS.isUsable() || !RHS.isUsable()) 14660 return ExprError(); 14661 LHSExpr = LHS.get(); 14662 RHSExpr = RHS.get(); 14663 14664 // We want to end up calling one of checkPseudoObjectAssignment 14665 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14666 // both expressions are overloadable or either is type-dependent), 14667 // or CreateBuiltinBinOp (in any other case). We also want to get 14668 // any placeholder types out of the way. 14669 14670 // Handle pseudo-objects in the LHS. 14671 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14672 // Assignments with a pseudo-object l-value need special analysis. 14673 if (pty->getKind() == BuiltinType::PseudoObject && 14674 BinaryOperator::isAssignmentOp(Opc)) 14675 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14676 14677 // Don't resolve overloads if the other type is overloadable. 14678 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14679 // We can't actually test that if we still have a placeholder, 14680 // though. Fortunately, none of the exceptions we see in that 14681 // code below are valid when the LHS is an overload set. Note 14682 // that an overload set can be dependently-typed, but it never 14683 // instantiates to having an overloadable type. 14684 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14685 if (resolvedRHS.isInvalid()) return ExprError(); 14686 RHSExpr = resolvedRHS.get(); 14687 14688 if (RHSExpr->isTypeDependent() || 14689 RHSExpr->getType()->isOverloadableType()) 14690 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14691 } 14692 14693 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14694 // template, diagnose the missing 'template' keyword instead of diagnosing 14695 // an invalid use of a bound member function. 14696 // 14697 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14698 // to C++1z [over.over]/1.4, but we already checked for that case above. 14699 if (Opc == BO_LT && inTemplateInstantiation() && 14700 (pty->getKind() == BuiltinType::BoundMember || 14701 pty->getKind() == BuiltinType::Overload)) { 14702 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14703 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14704 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14705 return isa<FunctionTemplateDecl>(ND); 14706 })) { 14707 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14708 : OE->getNameLoc(), 14709 diag::err_template_kw_missing) 14710 << OE->getName().getAsString() << ""; 14711 return ExprError(); 14712 } 14713 } 14714 14715 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14716 if (LHS.isInvalid()) return ExprError(); 14717 LHSExpr = LHS.get(); 14718 } 14719 14720 // Handle pseudo-objects in the RHS. 14721 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14722 // An overload in the RHS can potentially be resolved by the type 14723 // being assigned to. 14724 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14725 if (getLangOpts().CPlusPlus && 14726 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14727 LHSExpr->getType()->isOverloadableType())) 14728 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14729 14730 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14731 } 14732 14733 // Don't resolve overloads if the other type is overloadable. 14734 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14735 LHSExpr->getType()->isOverloadableType()) 14736 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14737 14738 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14739 if (!resolvedRHS.isUsable()) return ExprError(); 14740 RHSExpr = resolvedRHS.get(); 14741 } 14742 14743 if (getLangOpts().CPlusPlus) { 14744 // If either expression is type-dependent, always build an 14745 // overloaded op. 14746 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14747 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14748 14749 // Otherwise, build an overloaded op if either expression has an 14750 // overloadable type. 14751 if (LHSExpr->getType()->isOverloadableType() || 14752 RHSExpr->getType()->isOverloadableType()) 14753 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14754 } 14755 14756 if (getLangOpts().RecoveryAST && 14757 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14758 assert(!getLangOpts().CPlusPlus); 14759 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14760 "Should only occur in error-recovery path."); 14761 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14762 // C [6.15.16] p3: 14763 // An assignment expression has the value of the left operand after the 14764 // assignment, but is not an lvalue. 14765 return CompoundAssignOperator::Create( 14766 Context, LHSExpr, RHSExpr, Opc, 14767 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14768 OpLoc, CurFPFeatureOverrides()); 14769 QualType ResultType; 14770 switch (Opc) { 14771 case BO_Assign: 14772 ResultType = LHSExpr->getType().getUnqualifiedType(); 14773 break; 14774 case BO_LT: 14775 case BO_GT: 14776 case BO_LE: 14777 case BO_GE: 14778 case BO_EQ: 14779 case BO_NE: 14780 case BO_LAnd: 14781 case BO_LOr: 14782 // These operators have a fixed result type regardless of operands. 14783 ResultType = Context.IntTy; 14784 break; 14785 case BO_Comma: 14786 ResultType = RHSExpr->getType(); 14787 break; 14788 default: 14789 ResultType = Context.DependentTy; 14790 break; 14791 } 14792 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14793 VK_PRValue, OK_Ordinary, OpLoc, 14794 CurFPFeatureOverrides()); 14795 } 14796 14797 // Build a built-in binary operation. 14798 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14799 } 14800 14801 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14802 if (T.isNull() || T->isDependentType()) 14803 return false; 14804 14805 if (!T->isPromotableIntegerType()) 14806 return true; 14807 14808 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14809 } 14810 14811 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14812 UnaryOperatorKind Opc, 14813 Expr *InputExpr) { 14814 ExprResult Input = InputExpr; 14815 ExprValueKind VK = VK_PRValue; 14816 ExprObjectKind OK = OK_Ordinary; 14817 QualType resultType; 14818 bool CanOverflow = false; 14819 14820 bool ConvertHalfVec = false; 14821 if (getLangOpts().OpenCL) { 14822 QualType Ty = InputExpr->getType(); 14823 // The only legal unary operation for atomics is '&'. 14824 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14825 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14826 // only with a builtin functions and therefore should be disallowed here. 14827 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14828 || Ty->isBlockPointerType())) { 14829 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14830 << InputExpr->getType() 14831 << Input.get()->getSourceRange()); 14832 } 14833 } 14834 14835 switch (Opc) { 14836 case UO_PreInc: 14837 case UO_PreDec: 14838 case UO_PostInc: 14839 case UO_PostDec: 14840 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14841 OpLoc, 14842 Opc == UO_PreInc || 14843 Opc == UO_PostInc, 14844 Opc == UO_PreInc || 14845 Opc == UO_PreDec); 14846 CanOverflow = isOverflowingIntegerType(Context, resultType); 14847 break; 14848 case UO_AddrOf: 14849 resultType = CheckAddressOfOperand(Input, OpLoc); 14850 CheckAddressOfNoDeref(InputExpr); 14851 RecordModifiableNonNullParam(*this, InputExpr); 14852 break; 14853 case UO_Deref: { 14854 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14855 if (Input.isInvalid()) return ExprError(); 14856 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14857 break; 14858 } 14859 case UO_Plus: 14860 case UO_Minus: 14861 CanOverflow = Opc == UO_Minus && 14862 isOverflowingIntegerType(Context, Input.get()->getType()); 14863 Input = UsualUnaryConversions(Input.get()); 14864 if (Input.isInvalid()) return ExprError(); 14865 // Unary plus and minus require promoting an operand of half vector to a 14866 // float vector and truncating the result back to a half vector. For now, we 14867 // do this only when HalfArgsAndReturns is set (that is, when the target is 14868 // arm or arm64). 14869 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14870 14871 // If the operand is a half vector, promote it to a float vector. 14872 if (ConvertHalfVec) 14873 Input = convertVector(Input.get(), Context.FloatTy, *this); 14874 resultType = Input.get()->getType(); 14875 if (resultType->isDependentType()) 14876 break; 14877 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14878 break; 14879 else if (resultType->isVectorType() && 14880 // The z vector extensions don't allow + or - with bool vectors. 14881 (!Context.getLangOpts().ZVector || 14882 resultType->castAs<VectorType>()->getVectorKind() != 14883 VectorType::AltiVecBool)) 14884 break; 14885 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14886 Opc == UO_Plus && 14887 resultType->isPointerType()) 14888 break; 14889 14890 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14891 << resultType << Input.get()->getSourceRange()); 14892 14893 case UO_Not: // bitwise complement 14894 Input = UsualUnaryConversions(Input.get()); 14895 if (Input.isInvalid()) 14896 return ExprError(); 14897 resultType = Input.get()->getType(); 14898 if (resultType->isDependentType()) 14899 break; 14900 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14901 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14902 // C99 does not support '~' for complex conjugation. 14903 Diag(OpLoc, diag::ext_integer_complement_complex) 14904 << resultType << Input.get()->getSourceRange(); 14905 else if (resultType->hasIntegerRepresentation()) 14906 break; 14907 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14908 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14909 // 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 } else { 14915 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14916 << resultType << Input.get()->getSourceRange()); 14917 } 14918 break; 14919 14920 case UO_LNot: // logical negation 14921 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14922 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14923 if (Input.isInvalid()) return ExprError(); 14924 resultType = Input.get()->getType(); 14925 14926 // Though we still have to promote half FP to float... 14927 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14928 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14929 resultType = Context.FloatTy; 14930 } 14931 14932 if (resultType->isDependentType()) 14933 break; 14934 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14935 // C99 6.5.3.3p1: ok, fallthrough; 14936 if (Context.getLangOpts().CPlusPlus) { 14937 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14938 // operand contextually converted to bool. 14939 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14940 ScalarTypeToBooleanCastKind(resultType)); 14941 } else if (Context.getLangOpts().OpenCL && 14942 Context.getLangOpts().OpenCLVersion < 120) { 14943 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14944 // operate on scalar float types. 14945 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14946 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14947 << resultType << Input.get()->getSourceRange()); 14948 } 14949 } else if (resultType->isExtVectorType()) { 14950 if (Context.getLangOpts().OpenCL && 14951 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 14952 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14953 // operate on vector float types. 14954 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14955 if (!T->isIntegerType()) 14956 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14957 << resultType << Input.get()->getSourceRange()); 14958 } 14959 // Vector logical not returns the signed variant of the operand type. 14960 resultType = GetSignedVectorType(resultType); 14961 break; 14962 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14963 const VectorType *VTy = resultType->castAs<VectorType>(); 14964 if (VTy->getVectorKind() != VectorType::GenericVector) 14965 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14966 << resultType << Input.get()->getSourceRange()); 14967 14968 // Vector logical not returns the signed variant of the operand type. 14969 resultType = GetSignedVectorType(resultType); 14970 break; 14971 } else { 14972 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14973 << resultType << Input.get()->getSourceRange()); 14974 } 14975 14976 // LNot always has type int. C99 6.5.3.3p5. 14977 // In C++, it's bool. C++ 5.3.1p8 14978 resultType = Context.getLogicalOperationType(); 14979 break; 14980 case UO_Real: 14981 case UO_Imag: 14982 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14983 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14984 // complex l-values to ordinary l-values and all other values to r-values. 14985 if (Input.isInvalid()) return ExprError(); 14986 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14987 if (Input.get()->isGLValue() && 14988 Input.get()->getObjectKind() == OK_Ordinary) 14989 VK = Input.get()->getValueKind(); 14990 } else if (!getLangOpts().CPlusPlus) { 14991 // In C, a volatile scalar is read by __imag. In C++, it is not. 14992 Input = DefaultLvalueConversion(Input.get()); 14993 } 14994 break; 14995 case UO_Extension: 14996 resultType = Input.get()->getType(); 14997 VK = Input.get()->getValueKind(); 14998 OK = Input.get()->getObjectKind(); 14999 break; 15000 case UO_Coawait: 15001 // It's unnecessary to represent the pass-through operator co_await in the 15002 // AST; just return the input expression instead. 15003 assert(!Input.get()->getType()->isDependentType() && 15004 "the co_await expression must be non-dependant before " 15005 "building operator co_await"); 15006 return Input; 15007 } 15008 if (resultType.isNull() || Input.isInvalid()) 15009 return ExprError(); 15010 15011 // Check for array bounds violations in the operand of the UnaryOperator, 15012 // except for the '*' and '&' operators that have to be handled specially 15013 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15014 // that are explicitly defined as valid by the standard). 15015 if (Opc != UO_AddrOf && Opc != UO_Deref) 15016 CheckArrayAccess(Input.get()); 15017 15018 auto *UO = 15019 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15020 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15021 15022 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15023 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15024 !isUnevaluatedContext()) 15025 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15026 15027 // Convert the result back to a half vector. 15028 if (ConvertHalfVec) 15029 return convertVector(UO, Context.HalfTy, *this); 15030 return UO; 15031 } 15032 15033 /// Determine whether the given expression is a qualified member 15034 /// access expression, of a form that could be turned into a pointer to member 15035 /// with the address-of operator. 15036 bool Sema::isQualifiedMemberAccess(Expr *E) { 15037 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15038 if (!DRE->getQualifier()) 15039 return false; 15040 15041 ValueDecl *VD = DRE->getDecl(); 15042 if (!VD->isCXXClassMember()) 15043 return false; 15044 15045 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15046 return true; 15047 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15048 return Method->isInstance(); 15049 15050 return false; 15051 } 15052 15053 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15054 if (!ULE->getQualifier()) 15055 return false; 15056 15057 for (NamedDecl *D : ULE->decls()) { 15058 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15059 if (Method->isInstance()) 15060 return true; 15061 } else { 15062 // Overload set does not contain methods. 15063 break; 15064 } 15065 } 15066 15067 return false; 15068 } 15069 15070 return false; 15071 } 15072 15073 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15074 UnaryOperatorKind Opc, Expr *Input) { 15075 // First things first: handle placeholders so that the 15076 // overloaded-operator check considers the right type. 15077 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15078 // Increment and decrement of pseudo-object references. 15079 if (pty->getKind() == BuiltinType::PseudoObject && 15080 UnaryOperator::isIncrementDecrementOp(Opc)) 15081 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15082 15083 // extension is always a builtin operator. 15084 if (Opc == UO_Extension) 15085 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15086 15087 // & gets special logic for several kinds of placeholder. 15088 // The builtin code knows what to do. 15089 if (Opc == UO_AddrOf && 15090 (pty->getKind() == BuiltinType::Overload || 15091 pty->getKind() == BuiltinType::UnknownAny || 15092 pty->getKind() == BuiltinType::BoundMember)) 15093 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15094 15095 // Anything else needs to be handled now. 15096 ExprResult Result = CheckPlaceholderExpr(Input); 15097 if (Result.isInvalid()) return ExprError(); 15098 Input = Result.get(); 15099 } 15100 15101 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15102 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15103 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15104 // Find all of the overloaded operators visible from this point. 15105 UnresolvedSet<16> Functions; 15106 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15107 if (S && OverOp != OO_None) 15108 LookupOverloadedOperatorName(OverOp, S, Functions); 15109 15110 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15111 } 15112 15113 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15114 } 15115 15116 // Unary Operators. 'Tok' is the token for the operator. 15117 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15118 tok::TokenKind Op, Expr *Input) { 15119 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15120 } 15121 15122 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15123 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15124 LabelDecl *TheDecl) { 15125 TheDecl->markUsed(Context); 15126 // Create the AST node. The address of a label always has type 'void*'. 15127 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15128 Context.getPointerType(Context.VoidTy)); 15129 } 15130 15131 void Sema::ActOnStartStmtExpr() { 15132 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15133 } 15134 15135 void Sema::ActOnStmtExprError() { 15136 // Note that function is also called by TreeTransform when leaving a 15137 // StmtExpr scope without rebuilding anything. 15138 15139 DiscardCleanupsInEvaluationContext(); 15140 PopExpressionEvaluationContext(); 15141 } 15142 15143 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15144 SourceLocation RPLoc) { 15145 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15146 } 15147 15148 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15149 SourceLocation RPLoc, unsigned TemplateDepth) { 15150 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15151 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15152 15153 if (hasAnyUnrecoverableErrorsInThisFunction()) 15154 DiscardCleanupsInEvaluationContext(); 15155 assert(!Cleanup.exprNeedsCleanups() && 15156 "cleanups within StmtExpr not correctly bound!"); 15157 PopExpressionEvaluationContext(); 15158 15159 // FIXME: there are a variety of strange constraints to enforce here, for 15160 // example, it is not possible to goto into a stmt expression apparently. 15161 // More semantic analysis is needed. 15162 15163 // If there are sub-stmts in the compound stmt, take the type of the last one 15164 // as the type of the stmtexpr. 15165 QualType Ty = Context.VoidTy; 15166 bool StmtExprMayBindToTemp = false; 15167 if (!Compound->body_empty()) { 15168 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15169 if (const auto *LastStmt = 15170 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15171 if (const Expr *Value = LastStmt->getExprStmt()) { 15172 StmtExprMayBindToTemp = true; 15173 Ty = Value->getType(); 15174 } 15175 } 15176 } 15177 15178 // FIXME: Check that expression type is complete/non-abstract; statement 15179 // expressions are not lvalues. 15180 Expr *ResStmtExpr = 15181 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15182 if (StmtExprMayBindToTemp) 15183 return MaybeBindToTemporary(ResStmtExpr); 15184 return ResStmtExpr; 15185 } 15186 15187 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15188 if (ER.isInvalid()) 15189 return ExprError(); 15190 15191 // Do function/array conversion on the last expression, but not 15192 // lvalue-to-rvalue. However, initialize an unqualified type. 15193 ER = DefaultFunctionArrayConversion(ER.get()); 15194 if (ER.isInvalid()) 15195 return ExprError(); 15196 Expr *E = ER.get(); 15197 15198 if (E->isTypeDependent()) 15199 return E; 15200 15201 // In ARC, if the final expression ends in a consume, splice 15202 // the consume out and bind it later. In the alternate case 15203 // (when dealing with a retainable type), the result 15204 // initialization will create a produce. In both cases the 15205 // result will be +1, and we'll need to balance that out with 15206 // a bind. 15207 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15208 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15209 return Cast->getSubExpr(); 15210 15211 // FIXME: Provide a better location for the initialization. 15212 return PerformCopyInitialization( 15213 InitializedEntity::InitializeStmtExprResult( 15214 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15215 SourceLocation(), E); 15216 } 15217 15218 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15219 TypeSourceInfo *TInfo, 15220 ArrayRef<OffsetOfComponent> Components, 15221 SourceLocation RParenLoc) { 15222 QualType ArgTy = TInfo->getType(); 15223 bool Dependent = ArgTy->isDependentType(); 15224 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15225 15226 // We must have at least one component that refers to the type, and the first 15227 // one is known to be a field designator. Verify that the ArgTy represents 15228 // a struct/union/class. 15229 if (!Dependent && !ArgTy->isRecordType()) 15230 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15231 << ArgTy << TypeRange); 15232 15233 // Type must be complete per C99 7.17p3 because a declaring a variable 15234 // with an incomplete type would be ill-formed. 15235 if (!Dependent 15236 && RequireCompleteType(BuiltinLoc, ArgTy, 15237 diag::err_offsetof_incomplete_type, TypeRange)) 15238 return ExprError(); 15239 15240 bool DidWarnAboutNonPOD = false; 15241 QualType CurrentType = ArgTy; 15242 SmallVector<OffsetOfNode, 4> Comps; 15243 SmallVector<Expr*, 4> Exprs; 15244 for (const OffsetOfComponent &OC : Components) { 15245 if (OC.isBrackets) { 15246 // Offset of an array sub-field. TODO: Should we allow vector elements? 15247 if (!CurrentType->isDependentType()) { 15248 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15249 if(!AT) 15250 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15251 << CurrentType); 15252 CurrentType = AT->getElementType(); 15253 } else 15254 CurrentType = Context.DependentTy; 15255 15256 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15257 if (IdxRval.isInvalid()) 15258 return ExprError(); 15259 Expr *Idx = IdxRval.get(); 15260 15261 // The expression must be an integral expression. 15262 // FIXME: An integral constant expression? 15263 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15264 !Idx->getType()->isIntegerType()) 15265 return ExprError( 15266 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15267 << Idx->getSourceRange()); 15268 15269 // Record this array index. 15270 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15271 Exprs.push_back(Idx); 15272 continue; 15273 } 15274 15275 // Offset of a field. 15276 if (CurrentType->isDependentType()) { 15277 // We have the offset of a field, but we can't look into the dependent 15278 // type. Just record the identifier of the field. 15279 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15280 CurrentType = Context.DependentTy; 15281 continue; 15282 } 15283 15284 // We need to have a complete type to look into. 15285 if (RequireCompleteType(OC.LocStart, CurrentType, 15286 diag::err_offsetof_incomplete_type)) 15287 return ExprError(); 15288 15289 // Look for the designated field. 15290 const RecordType *RC = CurrentType->getAs<RecordType>(); 15291 if (!RC) 15292 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15293 << CurrentType); 15294 RecordDecl *RD = RC->getDecl(); 15295 15296 // C++ [lib.support.types]p5: 15297 // The macro offsetof accepts a restricted set of type arguments in this 15298 // International Standard. type shall be a POD structure or a POD union 15299 // (clause 9). 15300 // C++11 [support.types]p4: 15301 // If type is not a standard-layout class (Clause 9), the results are 15302 // undefined. 15303 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15304 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15305 unsigned DiagID = 15306 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15307 : diag::ext_offsetof_non_pod_type; 15308 15309 if (!IsSafe && !DidWarnAboutNonPOD && 15310 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15311 PDiag(DiagID) 15312 << SourceRange(Components[0].LocStart, OC.LocEnd) 15313 << CurrentType)) 15314 DidWarnAboutNonPOD = true; 15315 } 15316 15317 // Look for the field. 15318 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15319 LookupQualifiedName(R, RD); 15320 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15321 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15322 if (!MemberDecl) { 15323 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15324 MemberDecl = IndirectMemberDecl->getAnonField(); 15325 } 15326 15327 if (!MemberDecl) 15328 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15329 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15330 OC.LocEnd)); 15331 15332 // C99 7.17p3: 15333 // (If the specified member is a bit-field, the behavior is undefined.) 15334 // 15335 // We diagnose this as an error. 15336 if (MemberDecl->isBitField()) { 15337 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15338 << MemberDecl->getDeclName() 15339 << SourceRange(BuiltinLoc, RParenLoc); 15340 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15341 return ExprError(); 15342 } 15343 15344 RecordDecl *Parent = MemberDecl->getParent(); 15345 if (IndirectMemberDecl) 15346 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15347 15348 // If the member was found in a base class, introduce OffsetOfNodes for 15349 // the base class indirections. 15350 CXXBasePaths Paths; 15351 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15352 Paths)) { 15353 if (Paths.getDetectedVirtual()) { 15354 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15355 << MemberDecl->getDeclName() 15356 << SourceRange(BuiltinLoc, RParenLoc); 15357 return ExprError(); 15358 } 15359 15360 CXXBasePath &Path = Paths.front(); 15361 for (const CXXBasePathElement &B : Path) 15362 Comps.push_back(OffsetOfNode(B.Base)); 15363 } 15364 15365 if (IndirectMemberDecl) { 15366 for (auto *FI : IndirectMemberDecl->chain()) { 15367 assert(isa<FieldDecl>(FI)); 15368 Comps.push_back(OffsetOfNode(OC.LocStart, 15369 cast<FieldDecl>(FI), OC.LocEnd)); 15370 } 15371 } else 15372 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15373 15374 CurrentType = MemberDecl->getType().getNonReferenceType(); 15375 } 15376 15377 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15378 Comps, Exprs, RParenLoc); 15379 } 15380 15381 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15382 SourceLocation BuiltinLoc, 15383 SourceLocation TypeLoc, 15384 ParsedType ParsedArgTy, 15385 ArrayRef<OffsetOfComponent> Components, 15386 SourceLocation RParenLoc) { 15387 15388 TypeSourceInfo *ArgTInfo; 15389 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15390 if (ArgTy.isNull()) 15391 return ExprError(); 15392 15393 if (!ArgTInfo) 15394 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15395 15396 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15397 } 15398 15399 15400 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15401 Expr *CondExpr, 15402 Expr *LHSExpr, Expr *RHSExpr, 15403 SourceLocation RPLoc) { 15404 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15405 15406 ExprValueKind VK = VK_PRValue; 15407 ExprObjectKind OK = OK_Ordinary; 15408 QualType resType; 15409 bool CondIsTrue = false; 15410 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15411 resType = Context.DependentTy; 15412 } else { 15413 // The conditional expression is required to be a constant expression. 15414 llvm::APSInt condEval(32); 15415 ExprResult CondICE = VerifyIntegerConstantExpression( 15416 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15417 if (CondICE.isInvalid()) 15418 return ExprError(); 15419 CondExpr = CondICE.get(); 15420 CondIsTrue = condEval.getZExtValue(); 15421 15422 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15423 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15424 15425 resType = ActiveExpr->getType(); 15426 VK = ActiveExpr->getValueKind(); 15427 OK = ActiveExpr->getObjectKind(); 15428 } 15429 15430 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15431 resType, VK, OK, RPLoc, CondIsTrue); 15432 } 15433 15434 //===----------------------------------------------------------------------===// 15435 // Clang Extensions. 15436 //===----------------------------------------------------------------------===// 15437 15438 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15439 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15440 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15441 15442 if (LangOpts.CPlusPlus) { 15443 MangleNumberingContext *MCtx; 15444 Decl *ManglingContextDecl; 15445 std::tie(MCtx, ManglingContextDecl) = 15446 getCurrentMangleNumberContext(Block->getDeclContext()); 15447 if (MCtx) { 15448 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15449 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15450 } 15451 } 15452 15453 PushBlockScope(CurScope, Block); 15454 CurContext->addDecl(Block); 15455 if (CurScope) 15456 PushDeclContext(CurScope, Block); 15457 else 15458 CurContext = Block; 15459 15460 getCurBlock()->HasImplicitReturnType = true; 15461 15462 // Enter a new evaluation context to insulate the block from any 15463 // cleanups from the enclosing full-expression. 15464 PushExpressionEvaluationContext( 15465 ExpressionEvaluationContext::PotentiallyEvaluated); 15466 } 15467 15468 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15469 Scope *CurScope) { 15470 assert(ParamInfo.getIdentifier() == nullptr && 15471 "block-id should have no identifier!"); 15472 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15473 BlockScopeInfo *CurBlock = getCurBlock(); 15474 15475 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15476 QualType T = Sig->getType(); 15477 15478 // FIXME: We should allow unexpanded parameter packs here, but that would, 15479 // in turn, make the block expression contain unexpanded parameter packs. 15480 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15481 // Drop the parameters. 15482 FunctionProtoType::ExtProtoInfo EPI; 15483 EPI.HasTrailingReturn = false; 15484 EPI.TypeQuals.addConst(); 15485 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15486 Sig = Context.getTrivialTypeSourceInfo(T); 15487 } 15488 15489 // GetTypeForDeclarator always produces a function type for a block 15490 // literal signature. Furthermore, it is always a FunctionProtoType 15491 // unless the function was written with a typedef. 15492 assert(T->isFunctionType() && 15493 "GetTypeForDeclarator made a non-function block signature"); 15494 15495 // Look for an explicit signature in that function type. 15496 FunctionProtoTypeLoc ExplicitSignature; 15497 15498 if ((ExplicitSignature = Sig->getTypeLoc() 15499 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15500 15501 // Check whether that explicit signature was synthesized by 15502 // GetTypeForDeclarator. If so, don't save that as part of the 15503 // written signature. 15504 if (ExplicitSignature.getLocalRangeBegin() == 15505 ExplicitSignature.getLocalRangeEnd()) { 15506 // This would be much cheaper if we stored TypeLocs instead of 15507 // TypeSourceInfos. 15508 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15509 unsigned Size = Result.getFullDataSize(); 15510 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15511 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15512 15513 ExplicitSignature = FunctionProtoTypeLoc(); 15514 } 15515 } 15516 15517 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15518 CurBlock->FunctionType = T; 15519 15520 const auto *Fn = T->castAs<FunctionType>(); 15521 QualType RetTy = Fn->getReturnType(); 15522 bool isVariadic = 15523 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15524 15525 CurBlock->TheDecl->setIsVariadic(isVariadic); 15526 15527 // Context.DependentTy is used as a placeholder for a missing block 15528 // return type. TODO: what should we do with declarators like: 15529 // ^ * { ... } 15530 // If the answer is "apply template argument deduction".... 15531 if (RetTy != Context.DependentTy) { 15532 CurBlock->ReturnType = RetTy; 15533 CurBlock->TheDecl->setBlockMissingReturnType(false); 15534 CurBlock->HasImplicitReturnType = false; 15535 } 15536 15537 // Push block parameters from the declarator if we had them. 15538 SmallVector<ParmVarDecl*, 8> Params; 15539 if (ExplicitSignature) { 15540 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15541 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15542 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15543 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15544 // Diagnose this as an extension in C17 and earlier. 15545 if (!getLangOpts().C2x) 15546 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15547 } 15548 Params.push_back(Param); 15549 } 15550 15551 // Fake up parameter variables if we have a typedef, like 15552 // ^ fntype { ... } 15553 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15554 for (const auto &I : Fn->param_types()) { 15555 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15556 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15557 Params.push_back(Param); 15558 } 15559 } 15560 15561 // Set the parameters on the block decl. 15562 if (!Params.empty()) { 15563 CurBlock->TheDecl->setParams(Params); 15564 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15565 /*CheckParameterNames=*/false); 15566 } 15567 15568 // Finally we can process decl attributes. 15569 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15570 15571 // Put the parameter variables in scope. 15572 for (auto AI : CurBlock->TheDecl->parameters()) { 15573 AI->setOwningFunction(CurBlock->TheDecl); 15574 15575 // If this has an identifier, add it to the scope stack. 15576 if (AI->getIdentifier()) { 15577 CheckShadow(CurBlock->TheScope, AI); 15578 15579 PushOnScopeChains(AI, CurBlock->TheScope); 15580 } 15581 } 15582 } 15583 15584 /// ActOnBlockError - If there is an error parsing a block, this callback 15585 /// is invoked to pop the information about the block from the action impl. 15586 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15587 // Leave the expression-evaluation context. 15588 DiscardCleanupsInEvaluationContext(); 15589 PopExpressionEvaluationContext(); 15590 15591 // Pop off CurBlock, handle nested blocks. 15592 PopDeclContext(); 15593 PopFunctionScopeInfo(); 15594 } 15595 15596 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15597 /// literal was successfully completed. ^(int x){...} 15598 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15599 Stmt *Body, Scope *CurScope) { 15600 // If blocks are disabled, emit an error. 15601 if (!LangOpts.Blocks) 15602 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15603 15604 // Leave the expression-evaluation context. 15605 if (hasAnyUnrecoverableErrorsInThisFunction()) 15606 DiscardCleanupsInEvaluationContext(); 15607 assert(!Cleanup.exprNeedsCleanups() && 15608 "cleanups within block not correctly bound!"); 15609 PopExpressionEvaluationContext(); 15610 15611 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15612 BlockDecl *BD = BSI->TheDecl; 15613 15614 if (BSI->HasImplicitReturnType) 15615 deduceClosureReturnType(*BSI); 15616 15617 QualType RetTy = Context.VoidTy; 15618 if (!BSI->ReturnType.isNull()) 15619 RetTy = BSI->ReturnType; 15620 15621 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15622 QualType BlockTy; 15623 15624 // If the user wrote a function type in some form, try to use that. 15625 if (!BSI->FunctionType.isNull()) { 15626 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15627 15628 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15629 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15630 15631 // Turn protoless block types into nullary block types. 15632 if (isa<FunctionNoProtoType>(FTy)) { 15633 FunctionProtoType::ExtProtoInfo EPI; 15634 EPI.ExtInfo = Ext; 15635 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15636 15637 // Otherwise, if we don't need to change anything about the function type, 15638 // preserve its sugar structure. 15639 } else if (FTy->getReturnType() == RetTy && 15640 (!NoReturn || FTy->getNoReturnAttr())) { 15641 BlockTy = BSI->FunctionType; 15642 15643 // Otherwise, make the minimal modifications to the function type. 15644 } else { 15645 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15646 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15647 EPI.TypeQuals = Qualifiers(); 15648 EPI.ExtInfo = Ext; 15649 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15650 } 15651 15652 // If we don't have a function type, just build one from nothing. 15653 } else { 15654 FunctionProtoType::ExtProtoInfo EPI; 15655 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15656 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15657 } 15658 15659 DiagnoseUnusedParameters(BD->parameters()); 15660 BlockTy = Context.getBlockPointerType(BlockTy); 15661 15662 // If needed, diagnose invalid gotos and switches in the block. 15663 if (getCurFunction()->NeedsScopeChecking() && 15664 !PP.isCodeCompletionEnabled()) 15665 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15666 15667 BD->setBody(cast<CompoundStmt>(Body)); 15668 15669 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15670 DiagnoseUnguardedAvailabilityViolations(BD); 15671 15672 // Try to apply the named return value optimization. We have to check again 15673 // if we can do this, though, because blocks keep return statements around 15674 // to deduce an implicit return type. 15675 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15676 !BD->isDependentContext()) 15677 computeNRVO(Body, BSI); 15678 15679 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15680 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15681 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15682 NTCUK_Destruct|NTCUK_Copy); 15683 15684 PopDeclContext(); 15685 15686 // Set the captured variables on the block. 15687 SmallVector<BlockDecl::Capture, 4> Captures; 15688 for (Capture &Cap : BSI->Captures) { 15689 if (Cap.isInvalid() || Cap.isThisCapture()) 15690 continue; 15691 15692 VarDecl *Var = Cap.getVariable(); 15693 Expr *CopyExpr = nullptr; 15694 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15695 if (const RecordType *Record = 15696 Cap.getCaptureType()->getAs<RecordType>()) { 15697 // The capture logic needs the destructor, so make sure we mark it. 15698 // Usually this is unnecessary because most local variables have 15699 // their destructors marked at declaration time, but parameters are 15700 // an exception because it's technically only the call site that 15701 // actually requires the destructor. 15702 if (isa<ParmVarDecl>(Var)) 15703 FinalizeVarWithDestructor(Var, Record); 15704 15705 // Enter a separate potentially-evaluated context while building block 15706 // initializers to isolate their cleanups from those of the block 15707 // itself. 15708 // FIXME: Is this appropriate even when the block itself occurs in an 15709 // unevaluated operand? 15710 EnterExpressionEvaluationContext EvalContext( 15711 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15712 15713 SourceLocation Loc = Cap.getLocation(); 15714 15715 ExprResult Result = BuildDeclarationNameExpr( 15716 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15717 15718 // According to the blocks spec, the capture of a variable from 15719 // the stack requires a const copy constructor. This is not true 15720 // of the copy/move done to move a __block variable to the heap. 15721 if (!Result.isInvalid() && 15722 !Result.get()->getType().isConstQualified()) { 15723 Result = ImpCastExprToType(Result.get(), 15724 Result.get()->getType().withConst(), 15725 CK_NoOp, VK_LValue); 15726 } 15727 15728 if (!Result.isInvalid()) { 15729 Result = PerformCopyInitialization( 15730 InitializedEntity::InitializeBlock(Var->getLocation(), 15731 Cap.getCaptureType()), 15732 Loc, Result.get()); 15733 } 15734 15735 // Build a full-expression copy expression if initialization 15736 // succeeded and used a non-trivial constructor. Recover from 15737 // errors by pretending that the copy isn't necessary. 15738 if (!Result.isInvalid() && 15739 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15740 ->isTrivial()) { 15741 Result = MaybeCreateExprWithCleanups(Result); 15742 CopyExpr = Result.get(); 15743 } 15744 } 15745 } 15746 15747 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15748 CopyExpr); 15749 Captures.push_back(NewCap); 15750 } 15751 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15752 15753 // Pop the block scope now but keep it alive to the end of this function. 15754 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15755 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15756 15757 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15758 15759 // If the block isn't obviously global, i.e. it captures anything at 15760 // all, then we need to do a few things in the surrounding context: 15761 if (Result->getBlockDecl()->hasCaptures()) { 15762 // First, this expression has a new cleanup object. 15763 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15764 Cleanup.setExprNeedsCleanups(true); 15765 15766 // It also gets a branch-protected scope if any of the captured 15767 // variables needs destruction. 15768 for (const auto &CI : Result->getBlockDecl()->captures()) { 15769 const VarDecl *var = CI.getVariable(); 15770 if (var->getType().isDestructedType() != QualType::DK_none) { 15771 setFunctionHasBranchProtectedScope(); 15772 break; 15773 } 15774 } 15775 } 15776 15777 if (getCurFunction()) 15778 getCurFunction()->addBlock(BD); 15779 15780 return Result; 15781 } 15782 15783 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15784 SourceLocation RPLoc) { 15785 TypeSourceInfo *TInfo; 15786 GetTypeFromParser(Ty, &TInfo); 15787 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15788 } 15789 15790 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15791 Expr *E, TypeSourceInfo *TInfo, 15792 SourceLocation RPLoc) { 15793 Expr *OrigExpr = E; 15794 bool IsMS = false; 15795 15796 // CUDA device code does not support varargs. 15797 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15798 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15799 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15800 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15801 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15802 } 15803 } 15804 15805 // NVPTX does not support va_arg expression. 15806 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15807 Context.getTargetInfo().getTriple().isNVPTX()) 15808 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15809 15810 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15811 // as Microsoft ABI on an actual Microsoft platform, where 15812 // __builtin_ms_va_list and __builtin_va_list are the same.) 15813 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15814 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15815 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15816 if (Context.hasSameType(MSVaListType, E->getType())) { 15817 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15818 return ExprError(); 15819 IsMS = true; 15820 } 15821 } 15822 15823 // Get the va_list type 15824 QualType VaListType = Context.getBuiltinVaListType(); 15825 if (!IsMS) { 15826 if (VaListType->isArrayType()) { 15827 // Deal with implicit array decay; for example, on x86-64, 15828 // va_list is an array, but it's supposed to decay to 15829 // a pointer for va_arg. 15830 VaListType = Context.getArrayDecayedType(VaListType); 15831 // Make sure the input expression also decays appropriately. 15832 ExprResult Result = UsualUnaryConversions(E); 15833 if (Result.isInvalid()) 15834 return ExprError(); 15835 E = Result.get(); 15836 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15837 // If va_list is a record type and we are compiling in C++ mode, 15838 // check the argument using reference binding. 15839 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15840 Context, Context.getLValueReferenceType(VaListType), false); 15841 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15842 if (Init.isInvalid()) 15843 return ExprError(); 15844 E = Init.getAs<Expr>(); 15845 } else { 15846 // Otherwise, the va_list argument must be an l-value because 15847 // it is modified by va_arg. 15848 if (!E->isTypeDependent() && 15849 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15850 return ExprError(); 15851 } 15852 } 15853 15854 if (!IsMS && !E->isTypeDependent() && 15855 !Context.hasSameType(VaListType, E->getType())) 15856 return ExprError( 15857 Diag(E->getBeginLoc(), 15858 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15859 << OrigExpr->getType() << E->getSourceRange()); 15860 15861 if (!TInfo->getType()->isDependentType()) { 15862 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15863 diag::err_second_parameter_to_va_arg_incomplete, 15864 TInfo->getTypeLoc())) 15865 return ExprError(); 15866 15867 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15868 TInfo->getType(), 15869 diag::err_second_parameter_to_va_arg_abstract, 15870 TInfo->getTypeLoc())) 15871 return ExprError(); 15872 15873 if (!TInfo->getType().isPODType(Context)) { 15874 Diag(TInfo->getTypeLoc().getBeginLoc(), 15875 TInfo->getType()->isObjCLifetimeType() 15876 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15877 : diag::warn_second_parameter_to_va_arg_not_pod) 15878 << TInfo->getType() 15879 << TInfo->getTypeLoc().getSourceRange(); 15880 } 15881 15882 // Check for va_arg where arguments of the given type will be promoted 15883 // (i.e. this va_arg is guaranteed to have undefined behavior). 15884 QualType PromoteType; 15885 if (TInfo->getType()->isPromotableIntegerType()) { 15886 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15887 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15888 // and C2x 7.16.1.1p2 says, in part: 15889 // If type is not compatible with the type of the actual next argument 15890 // (as promoted according to the default argument promotions), the 15891 // behavior is undefined, except for the following cases: 15892 // - both types are pointers to qualified or unqualified versions of 15893 // compatible types; 15894 // - one type is a signed integer type, the other type is the 15895 // corresponding unsigned integer type, and the value is 15896 // representable in both types; 15897 // - one type is pointer to qualified or unqualified void and the 15898 // other is a pointer to a qualified or unqualified character type. 15899 // Given that type compatibility is the primary requirement (ignoring 15900 // qualifications), you would think we could call typesAreCompatible() 15901 // directly to test this. However, in C++, that checks for *same type*, 15902 // which causes false positives when passing an enumeration type to 15903 // va_arg. Instead, get the underlying type of the enumeration and pass 15904 // that. 15905 QualType UnderlyingType = TInfo->getType(); 15906 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15907 UnderlyingType = ET->getDecl()->getIntegerType(); 15908 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15909 /*CompareUnqualified*/ true)) 15910 PromoteType = QualType(); 15911 15912 // If the types are still not compatible, we need to test whether the 15913 // promoted type and the underlying type are the same except for 15914 // signedness. Ask the AST for the correctly corresponding type and see 15915 // if that's compatible. 15916 if (!PromoteType.isNull() && 15917 PromoteType->isUnsignedIntegerType() != 15918 UnderlyingType->isUnsignedIntegerType()) { 15919 UnderlyingType = 15920 UnderlyingType->isUnsignedIntegerType() 15921 ? Context.getCorrespondingSignedType(UnderlyingType) 15922 : Context.getCorrespondingUnsignedType(UnderlyingType); 15923 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15924 /*CompareUnqualified*/ true)) 15925 PromoteType = QualType(); 15926 } 15927 } 15928 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15929 PromoteType = Context.DoubleTy; 15930 if (!PromoteType.isNull()) 15931 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15932 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15933 << TInfo->getType() 15934 << PromoteType 15935 << TInfo->getTypeLoc().getSourceRange()); 15936 } 15937 15938 QualType T = TInfo->getType().getNonLValueExprType(Context); 15939 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15940 } 15941 15942 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15943 // The type of __null will be int or long, depending on the size of 15944 // pointers on the target. 15945 QualType Ty; 15946 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15947 if (pw == Context.getTargetInfo().getIntWidth()) 15948 Ty = Context.IntTy; 15949 else if (pw == Context.getTargetInfo().getLongWidth()) 15950 Ty = Context.LongTy; 15951 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15952 Ty = Context.LongLongTy; 15953 else { 15954 llvm_unreachable("I don't know size of pointer!"); 15955 } 15956 15957 return new (Context) GNUNullExpr(Ty, TokenLoc); 15958 } 15959 15960 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15961 SourceLocation BuiltinLoc, 15962 SourceLocation RPLoc) { 15963 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15964 } 15965 15966 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15967 SourceLocation BuiltinLoc, 15968 SourceLocation RPLoc, 15969 DeclContext *ParentContext) { 15970 return new (Context) 15971 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15972 } 15973 15974 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15975 bool Diagnose) { 15976 if (!getLangOpts().ObjC) 15977 return false; 15978 15979 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15980 if (!PT) 15981 return false; 15982 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15983 15984 // Ignore any parens, implicit casts (should only be 15985 // array-to-pointer decays), and not-so-opaque values. The last is 15986 // important for making this trigger for property assignments. 15987 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15988 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15989 if (OV->getSourceExpr()) 15990 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15991 15992 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15993 if (!PT->isObjCIdType() && 15994 !(ID && ID->getIdentifier()->isStr("NSString"))) 15995 return false; 15996 if (!SL->isAscii()) 15997 return false; 15998 15999 if (Diagnose) { 16000 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 16001 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 16002 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 16003 } 16004 return true; 16005 } 16006 16007 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16008 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16009 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16010 !SrcExpr->isNullPointerConstant( 16011 getASTContext(), Expr::NPC_NeverValueDependent)) { 16012 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16013 return false; 16014 if (Diagnose) { 16015 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16016 << /*number*/1 16017 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16018 Expr *NumLit = 16019 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16020 if (NumLit) 16021 Exp = NumLit; 16022 } 16023 return true; 16024 } 16025 16026 return false; 16027 } 16028 16029 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16030 const Expr *SrcExpr) { 16031 if (!DstType->isFunctionPointerType() || 16032 !SrcExpr->getType()->isFunctionType()) 16033 return false; 16034 16035 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16036 if (!DRE) 16037 return false; 16038 16039 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16040 if (!FD) 16041 return false; 16042 16043 return !S.checkAddressOfFunctionIsAvailable(FD, 16044 /*Complain=*/true, 16045 SrcExpr->getBeginLoc()); 16046 } 16047 16048 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16049 SourceLocation Loc, 16050 QualType DstType, QualType SrcType, 16051 Expr *SrcExpr, AssignmentAction Action, 16052 bool *Complained) { 16053 if (Complained) 16054 *Complained = false; 16055 16056 // Decode the result (notice that AST's are still created for extensions). 16057 bool CheckInferredResultType = false; 16058 bool isInvalid = false; 16059 unsigned DiagKind = 0; 16060 ConversionFixItGenerator ConvHints; 16061 bool MayHaveConvFixit = false; 16062 bool MayHaveFunctionDiff = false; 16063 const ObjCInterfaceDecl *IFace = nullptr; 16064 const ObjCProtocolDecl *PDecl = nullptr; 16065 16066 switch (ConvTy) { 16067 case Compatible: 16068 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16069 return false; 16070 16071 case PointerToInt: 16072 if (getLangOpts().CPlusPlus) { 16073 DiagKind = diag::err_typecheck_convert_pointer_int; 16074 isInvalid = true; 16075 } else { 16076 DiagKind = diag::ext_typecheck_convert_pointer_int; 16077 } 16078 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16079 MayHaveConvFixit = true; 16080 break; 16081 case IntToPointer: 16082 if (getLangOpts().CPlusPlus) { 16083 DiagKind = diag::err_typecheck_convert_int_pointer; 16084 isInvalid = true; 16085 } else { 16086 DiagKind = diag::ext_typecheck_convert_int_pointer; 16087 } 16088 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16089 MayHaveConvFixit = true; 16090 break; 16091 case IncompatibleFunctionPointer: 16092 if (getLangOpts().CPlusPlus) { 16093 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16094 isInvalid = true; 16095 } else { 16096 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16097 } 16098 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16099 MayHaveConvFixit = true; 16100 break; 16101 case IncompatiblePointer: 16102 if (Action == AA_Passing_CFAudited) { 16103 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16104 } else if (getLangOpts().CPlusPlus) { 16105 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16106 isInvalid = true; 16107 } else { 16108 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16109 } 16110 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16111 SrcType->isObjCObjectPointerType(); 16112 if (!CheckInferredResultType) { 16113 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16114 } else if (CheckInferredResultType) { 16115 SrcType = SrcType.getUnqualifiedType(); 16116 DstType = DstType.getUnqualifiedType(); 16117 } 16118 MayHaveConvFixit = true; 16119 break; 16120 case IncompatiblePointerSign: 16121 if (getLangOpts().CPlusPlus) { 16122 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16123 isInvalid = true; 16124 } else { 16125 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16126 } 16127 break; 16128 case FunctionVoidPointer: 16129 if (getLangOpts().CPlusPlus) { 16130 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16131 isInvalid = true; 16132 } else { 16133 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16134 } 16135 break; 16136 case IncompatiblePointerDiscardsQualifiers: { 16137 // Perform array-to-pointer decay if necessary. 16138 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16139 16140 isInvalid = true; 16141 16142 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16143 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16144 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16145 DiagKind = diag::err_typecheck_incompatible_address_space; 16146 break; 16147 16148 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16149 DiagKind = diag::err_typecheck_incompatible_ownership; 16150 break; 16151 } 16152 16153 llvm_unreachable("unknown error case for discarding qualifiers!"); 16154 // fallthrough 16155 } 16156 case CompatiblePointerDiscardsQualifiers: 16157 // If the qualifiers lost were because we were applying the 16158 // (deprecated) C++ conversion from a string literal to a char* 16159 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16160 // Ideally, this check would be performed in 16161 // checkPointerTypesForAssignment. However, that would require a 16162 // bit of refactoring (so that the second argument is an 16163 // expression, rather than a type), which should be done as part 16164 // of a larger effort to fix checkPointerTypesForAssignment for 16165 // C++ semantics. 16166 if (getLangOpts().CPlusPlus && 16167 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16168 return false; 16169 if (getLangOpts().CPlusPlus) { 16170 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16171 isInvalid = true; 16172 } else { 16173 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16174 } 16175 16176 break; 16177 case IncompatibleNestedPointerQualifiers: 16178 if (getLangOpts().CPlusPlus) { 16179 isInvalid = true; 16180 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16181 } else { 16182 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16183 } 16184 break; 16185 case IncompatibleNestedPointerAddressSpaceMismatch: 16186 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16187 isInvalid = true; 16188 break; 16189 case IntToBlockPointer: 16190 DiagKind = diag::err_int_to_block_pointer; 16191 isInvalid = true; 16192 break; 16193 case IncompatibleBlockPointer: 16194 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16195 isInvalid = true; 16196 break; 16197 case IncompatibleObjCQualifiedId: { 16198 if (SrcType->isObjCQualifiedIdType()) { 16199 const ObjCObjectPointerType *srcOPT = 16200 SrcType->castAs<ObjCObjectPointerType>(); 16201 for (auto *srcProto : srcOPT->quals()) { 16202 PDecl = srcProto; 16203 break; 16204 } 16205 if (const ObjCInterfaceType *IFaceT = 16206 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16207 IFace = IFaceT->getDecl(); 16208 } 16209 else if (DstType->isObjCQualifiedIdType()) { 16210 const ObjCObjectPointerType *dstOPT = 16211 DstType->castAs<ObjCObjectPointerType>(); 16212 for (auto *dstProto : dstOPT->quals()) { 16213 PDecl = dstProto; 16214 break; 16215 } 16216 if (const ObjCInterfaceType *IFaceT = 16217 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16218 IFace = IFaceT->getDecl(); 16219 } 16220 if (getLangOpts().CPlusPlus) { 16221 DiagKind = diag::err_incompatible_qualified_id; 16222 isInvalid = true; 16223 } else { 16224 DiagKind = diag::warn_incompatible_qualified_id; 16225 } 16226 break; 16227 } 16228 case IncompatibleVectors: 16229 if (getLangOpts().CPlusPlus) { 16230 DiagKind = diag::err_incompatible_vectors; 16231 isInvalid = true; 16232 } else { 16233 DiagKind = diag::warn_incompatible_vectors; 16234 } 16235 break; 16236 case IncompatibleObjCWeakRef: 16237 DiagKind = diag::err_arc_weak_unavailable_assign; 16238 isInvalid = true; 16239 break; 16240 case Incompatible: 16241 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16242 if (Complained) 16243 *Complained = true; 16244 return true; 16245 } 16246 16247 DiagKind = diag::err_typecheck_convert_incompatible; 16248 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16249 MayHaveConvFixit = true; 16250 isInvalid = true; 16251 MayHaveFunctionDiff = true; 16252 break; 16253 } 16254 16255 QualType FirstType, SecondType; 16256 switch (Action) { 16257 case AA_Assigning: 16258 case AA_Initializing: 16259 // The destination type comes first. 16260 FirstType = DstType; 16261 SecondType = SrcType; 16262 break; 16263 16264 case AA_Returning: 16265 case AA_Passing: 16266 case AA_Passing_CFAudited: 16267 case AA_Converting: 16268 case AA_Sending: 16269 case AA_Casting: 16270 // The source type comes first. 16271 FirstType = SrcType; 16272 SecondType = DstType; 16273 break; 16274 } 16275 16276 PartialDiagnostic FDiag = PDiag(DiagKind); 16277 if (Action == AA_Passing_CFAudited) 16278 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16279 else 16280 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16281 16282 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16283 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16284 auto isPlainChar = [](const clang::Type *Type) { 16285 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16286 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16287 }; 16288 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16289 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16290 } 16291 16292 // If we can fix the conversion, suggest the FixIts. 16293 if (!ConvHints.isNull()) { 16294 for (FixItHint &H : ConvHints.Hints) 16295 FDiag << H; 16296 } 16297 16298 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16299 16300 if (MayHaveFunctionDiff) 16301 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16302 16303 Diag(Loc, FDiag); 16304 if ((DiagKind == diag::warn_incompatible_qualified_id || 16305 DiagKind == diag::err_incompatible_qualified_id) && 16306 PDecl && IFace && !IFace->hasDefinition()) 16307 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16308 << IFace << PDecl; 16309 16310 if (SecondType == Context.OverloadTy) 16311 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16312 FirstType, /*TakingAddress=*/true); 16313 16314 if (CheckInferredResultType) 16315 EmitRelatedResultTypeNote(SrcExpr); 16316 16317 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16318 EmitRelatedResultTypeNoteForReturn(DstType); 16319 16320 if (Complained) 16321 *Complained = true; 16322 return isInvalid; 16323 } 16324 16325 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16326 llvm::APSInt *Result, 16327 AllowFoldKind CanFold) { 16328 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16329 public: 16330 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16331 QualType T) override { 16332 return S.Diag(Loc, diag::err_ice_not_integral) 16333 << T << S.LangOpts.CPlusPlus; 16334 } 16335 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16336 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16337 } 16338 } Diagnoser; 16339 16340 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16341 } 16342 16343 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16344 llvm::APSInt *Result, 16345 unsigned DiagID, 16346 AllowFoldKind CanFold) { 16347 class IDDiagnoser : public VerifyICEDiagnoser { 16348 unsigned DiagID; 16349 16350 public: 16351 IDDiagnoser(unsigned DiagID) 16352 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16353 16354 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16355 return S.Diag(Loc, DiagID); 16356 } 16357 } Diagnoser(DiagID); 16358 16359 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16360 } 16361 16362 Sema::SemaDiagnosticBuilder 16363 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16364 QualType T) { 16365 return diagnoseNotICE(S, Loc); 16366 } 16367 16368 Sema::SemaDiagnosticBuilder 16369 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16370 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16371 } 16372 16373 ExprResult 16374 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16375 VerifyICEDiagnoser &Diagnoser, 16376 AllowFoldKind CanFold) { 16377 SourceLocation DiagLoc = E->getBeginLoc(); 16378 16379 if (getLangOpts().CPlusPlus11) { 16380 // C++11 [expr.const]p5: 16381 // If an expression of literal class type is used in a context where an 16382 // integral constant expression is required, then that class type shall 16383 // have a single non-explicit conversion function to an integral or 16384 // unscoped enumeration type 16385 ExprResult Converted; 16386 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16387 VerifyICEDiagnoser &BaseDiagnoser; 16388 public: 16389 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16390 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16391 BaseDiagnoser.Suppress, true), 16392 BaseDiagnoser(BaseDiagnoser) {} 16393 16394 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16395 QualType T) override { 16396 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16397 } 16398 16399 SemaDiagnosticBuilder diagnoseIncomplete( 16400 Sema &S, SourceLocation Loc, QualType T) override { 16401 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16402 } 16403 16404 SemaDiagnosticBuilder diagnoseExplicitConv( 16405 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16406 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16407 } 16408 16409 SemaDiagnosticBuilder noteExplicitConv( 16410 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16411 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16412 << ConvTy->isEnumeralType() << ConvTy; 16413 } 16414 16415 SemaDiagnosticBuilder diagnoseAmbiguous( 16416 Sema &S, SourceLocation Loc, QualType T) override { 16417 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16418 } 16419 16420 SemaDiagnosticBuilder noteAmbiguous( 16421 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16422 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16423 << ConvTy->isEnumeralType() << ConvTy; 16424 } 16425 16426 SemaDiagnosticBuilder diagnoseConversion( 16427 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16428 llvm_unreachable("conversion functions are permitted"); 16429 } 16430 } ConvertDiagnoser(Diagnoser); 16431 16432 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16433 ConvertDiagnoser); 16434 if (Converted.isInvalid()) 16435 return Converted; 16436 E = Converted.get(); 16437 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16438 return ExprError(); 16439 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16440 // An ICE must be of integral or unscoped enumeration type. 16441 if (!Diagnoser.Suppress) 16442 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16443 << E->getSourceRange(); 16444 return ExprError(); 16445 } 16446 16447 ExprResult RValueExpr = DefaultLvalueConversion(E); 16448 if (RValueExpr.isInvalid()) 16449 return ExprError(); 16450 16451 E = RValueExpr.get(); 16452 16453 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16454 // in the non-ICE case. 16455 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16456 if (Result) 16457 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16458 if (!isa<ConstantExpr>(E)) 16459 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16460 : ConstantExpr::Create(Context, E); 16461 return E; 16462 } 16463 16464 Expr::EvalResult EvalResult; 16465 SmallVector<PartialDiagnosticAt, 8> Notes; 16466 EvalResult.Diag = &Notes; 16467 16468 // Try to evaluate the expression, and produce diagnostics explaining why it's 16469 // not a constant expression as a side-effect. 16470 bool Folded = 16471 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16472 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16473 16474 if (!isa<ConstantExpr>(E)) 16475 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16476 16477 // In C++11, we can rely on diagnostics being produced for any expression 16478 // which is not a constant expression. If no diagnostics were produced, then 16479 // this is a constant expression. 16480 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16481 if (Result) 16482 *Result = EvalResult.Val.getInt(); 16483 return E; 16484 } 16485 16486 // If our only note is the usual "invalid subexpression" note, just point 16487 // the caret at its location rather than producing an essentially 16488 // redundant note. 16489 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16490 diag::note_invalid_subexpr_in_const_expr) { 16491 DiagLoc = Notes[0].first; 16492 Notes.clear(); 16493 } 16494 16495 if (!Folded || !CanFold) { 16496 if (!Diagnoser.Suppress) { 16497 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16498 for (const PartialDiagnosticAt &Note : Notes) 16499 Diag(Note.first, Note.second); 16500 } 16501 16502 return ExprError(); 16503 } 16504 16505 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16506 for (const PartialDiagnosticAt &Note : Notes) 16507 Diag(Note.first, Note.second); 16508 16509 if (Result) 16510 *Result = EvalResult.Val.getInt(); 16511 return E; 16512 } 16513 16514 namespace { 16515 // Handle the case where we conclude a expression which we speculatively 16516 // considered to be unevaluated is actually evaluated. 16517 class TransformToPE : public TreeTransform<TransformToPE> { 16518 typedef TreeTransform<TransformToPE> BaseTransform; 16519 16520 public: 16521 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16522 16523 // Make sure we redo semantic analysis 16524 bool AlwaysRebuild() { return true; } 16525 bool ReplacingOriginal() { return true; } 16526 16527 // We need to special-case DeclRefExprs referring to FieldDecls which 16528 // are not part of a member pointer formation; normal TreeTransforming 16529 // doesn't catch this case because of the way we represent them in the AST. 16530 // FIXME: This is a bit ugly; is it really the best way to handle this 16531 // case? 16532 // 16533 // Error on DeclRefExprs referring to FieldDecls. 16534 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16535 if (isa<FieldDecl>(E->getDecl()) && 16536 !SemaRef.isUnevaluatedContext()) 16537 return SemaRef.Diag(E->getLocation(), 16538 diag::err_invalid_non_static_member_use) 16539 << E->getDecl() << E->getSourceRange(); 16540 16541 return BaseTransform::TransformDeclRefExpr(E); 16542 } 16543 16544 // Exception: filter out member pointer formation 16545 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16546 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16547 return E; 16548 16549 return BaseTransform::TransformUnaryOperator(E); 16550 } 16551 16552 // The body of a lambda-expression is in a separate expression evaluation 16553 // context so never needs to be transformed. 16554 // FIXME: Ideally we wouldn't transform the closure type either, and would 16555 // just recreate the capture expressions and lambda expression. 16556 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16557 return SkipLambdaBody(E, Body); 16558 } 16559 }; 16560 } 16561 16562 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16563 assert(isUnevaluatedContext() && 16564 "Should only transform unevaluated expressions"); 16565 ExprEvalContexts.back().Context = 16566 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16567 if (isUnevaluatedContext()) 16568 return E; 16569 return TransformToPE(*this).TransformExpr(E); 16570 } 16571 16572 void 16573 Sema::PushExpressionEvaluationContext( 16574 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16575 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16576 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16577 LambdaContextDecl, ExprContext); 16578 16579 // Discarded statements and immediate contexts nested in other 16580 // discarded statements or immediate context are themselves 16581 // a discarded statement or an immediate context, respectively. 16582 ExprEvalContexts.back().InDiscardedStatement = 16583 ExprEvalContexts[ExprEvalContexts.size() - 2] 16584 .isDiscardedStatementContext(); 16585 ExprEvalContexts.back().InImmediateFunctionContext = 16586 ExprEvalContexts[ExprEvalContexts.size() - 2] 16587 .isImmediateFunctionContext(); 16588 16589 Cleanup.reset(); 16590 if (!MaybeODRUseExprs.empty()) 16591 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16592 } 16593 16594 void 16595 Sema::PushExpressionEvaluationContext( 16596 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16597 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16598 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16599 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16600 } 16601 16602 namespace { 16603 16604 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16605 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16606 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16607 if (E->getOpcode() == UO_Deref) 16608 return CheckPossibleDeref(S, E->getSubExpr()); 16609 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16610 return CheckPossibleDeref(S, E->getBase()); 16611 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16612 return CheckPossibleDeref(S, E->getBase()); 16613 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16614 QualType Inner; 16615 QualType Ty = E->getType(); 16616 if (const auto *Ptr = Ty->getAs<PointerType>()) 16617 Inner = Ptr->getPointeeType(); 16618 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16619 Inner = Arr->getElementType(); 16620 else 16621 return nullptr; 16622 16623 if (Inner->hasAttr(attr::NoDeref)) 16624 return E; 16625 } 16626 return nullptr; 16627 } 16628 16629 } // namespace 16630 16631 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16632 for (const Expr *E : Rec.PossibleDerefs) { 16633 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16634 if (DeclRef) { 16635 const ValueDecl *Decl = DeclRef->getDecl(); 16636 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16637 << Decl->getName() << E->getSourceRange(); 16638 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16639 } else { 16640 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16641 << E->getSourceRange(); 16642 } 16643 } 16644 Rec.PossibleDerefs.clear(); 16645 } 16646 16647 /// Check whether E, which is either a discarded-value expression or an 16648 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16649 /// and if so, remove it from the list of volatile-qualified assignments that 16650 /// we are going to warn are deprecated. 16651 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16652 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16653 return; 16654 16655 // Note: ignoring parens here is not justified by the standard rules, but 16656 // ignoring parentheses seems like a more reasonable approach, and this only 16657 // drives a deprecation warning so doesn't affect conformance. 16658 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16659 if (BO->getOpcode() == BO_Assign) { 16660 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16661 llvm::erase_value(LHSs, BO->getLHS()); 16662 } 16663 } 16664 } 16665 16666 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16667 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16668 !Decl->isConsteval() || isConstantEvaluated() || 16669 RebuildingImmediateInvocation || isImmediateFunctionContext()) 16670 return E; 16671 16672 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16673 /// It's OK if this fails; we'll also remove this in 16674 /// HandleImmediateInvocations, but catching it here allows us to avoid 16675 /// walking the AST looking for it in simple cases. 16676 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16677 if (auto *DeclRef = 16678 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16679 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16680 16681 E = MaybeCreateExprWithCleanups(E); 16682 16683 ConstantExpr *Res = ConstantExpr::Create( 16684 getASTContext(), E.get(), 16685 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16686 getASTContext()), 16687 /*IsImmediateInvocation*/ true); 16688 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16689 return Res; 16690 } 16691 16692 static void EvaluateAndDiagnoseImmediateInvocation( 16693 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16694 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16695 Expr::EvalResult Eval; 16696 Eval.Diag = &Notes; 16697 ConstantExpr *CE = Candidate.getPointer(); 16698 bool Result = CE->EvaluateAsConstantExpr( 16699 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16700 if (!Result || !Notes.empty()) { 16701 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16702 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16703 InnerExpr = FunctionalCast->getSubExpr(); 16704 FunctionDecl *FD = nullptr; 16705 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16706 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16707 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16708 FD = Call->getConstructor(); 16709 else 16710 llvm_unreachable("unhandled decl kind"); 16711 assert(FD->isConsteval()); 16712 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16713 for (auto &Note : Notes) 16714 SemaRef.Diag(Note.first, Note.second); 16715 return; 16716 } 16717 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16718 } 16719 16720 static void RemoveNestedImmediateInvocation( 16721 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16722 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16723 struct ComplexRemove : TreeTransform<ComplexRemove> { 16724 using Base = TreeTransform<ComplexRemove>; 16725 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16726 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16727 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16728 CurrentII; 16729 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16730 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16731 SmallVector<Sema::ImmediateInvocationCandidate, 16732 4>::reverse_iterator Current) 16733 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16734 void RemoveImmediateInvocation(ConstantExpr* E) { 16735 auto It = std::find_if(CurrentII, IISet.rend(), 16736 [E](Sema::ImmediateInvocationCandidate Elem) { 16737 return Elem.getPointer() == E; 16738 }); 16739 assert(It != IISet.rend() && 16740 "ConstantExpr marked IsImmediateInvocation should " 16741 "be present"); 16742 It->setInt(1); // Mark as deleted 16743 } 16744 ExprResult TransformConstantExpr(ConstantExpr *E) { 16745 if (!E->isImmediateInvocation()) 16746 return Base::TransformConstantExpr(E); 16747 RemoveImmediateInvocation(E); 16748 return Base::TransformExpr(E->getSubExpr()); 16749 } 16750 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16751 /// we need to remove its DeclRefExpr from the DRSet. 16752 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16753 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16754 return Base::TransformCXXOperatorCallExpr(E); 16755 } 16756 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16757 /// here. 16758 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16759 if (!Init) 16760 return Init; 16761 /// ConstantExpr are the first layer of implicit node to be removed so if 16762 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16763 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16764 if (CE->isImmediateInvocation()) 16765 RemoveImmediateInvocation(CE); 16766 return Base::TransformInitializer(Init, NotCopyInit); 16767 } 16768 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16769 DRSet.erase(E); 16770 return E; 16771 } 16772 bool AlwaysRebuild() { return false; } 16773 bool ReplacingOriginal() { return true; } 16774 bool AllowSkippingCXXConstructExpr() { 16775 bool Res = AllowSkippingFirstCXXConstructExpr; 16776 AllowSkippingFirstCXXConstructExpr = true; 16777 return Res; 16778 } 16779 bool AllowSkippingFirstCXXConstructExpr = true; 16780 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16781 Rec.ImmediateInvocationCandidates, It); 16782 16783 /// CXXConstructExpr with a single argument are getting skipped by 16784 /// TreeTransform in some situtation because they could be implicit. This 16785 /// can only occur for the top-level CXXConstructExpr because it is used 16786 /// nowhere in the expression being transformed therefore will not be rebuilt. 16787 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16788 /// skipping the first CXXConstructExpr. 16789 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16790 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16791 16792 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16793 assert(Res.isUsable()); 16794 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16795 It->getPointer()->setSubExpr(Res.get()); 16796 } 16797 16798 static void 16799 HandleImmediateInvocations(Sema &SemaRef, 16800 Sema::ExpressionEvaluationContextRecord &Rec) { 16801 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16802 Rec.ReferenceToConsteval.size() == 0) || 16803 SemaRef.RebuildingImmediateInvocation) 16804 return; 16805 16806 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16807 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16808 /// need to remove ReferenceToConsteval in the immediate invocation. 16809 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16810 16811 /// Prevent sema calls during the tree transform from adding pointers that 16812 /// are already in the sets. 16813 llvm::SaveAndRestore<bool> DisableIITracking( 16814 SemaRef.RebuildingImmediateInvocation, true); 16815 16816 /// Prevent diagnostic during tree transfrom as they are duplicates 16817 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16818 16819 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16820 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16821 if (!It->getInt()) 16822 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16823 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16824 Rec.ReferenceToConsteval.size()) { 16825 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16826 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16827 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16828 bool VisitDeclRefExpr(DeclRefExpr *E) { 16829 DRSet.erase(E); 16830 return DRSet.size(); 16831 } 16832 } Visitor(Rec.ReferenceToConsteval); 16833 Visitor.TraverseStmt( 16834 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16835 } 16836 for (auto CE : Rec.ImmediateInvocationCandidates) 16837 if (!CE.getInt()) 16838 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16839 for (auto DR : Rec.ReferenceToConsteval) { 16840 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16841 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16842 << FD; 16843 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16844 } 16845 } 16846 16847 void Sema::PopExpressionEvaluationContext() { 16848 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16849 unsigned NumTypos = Rec.NumTypos; 16850 16851 if (!Rec.Lambdas.empty()) { 16852 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16853 if (!getLangOpts().CPlusPlus20 && 16854 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16855 Rec.isUnevaluated() || 16856 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16857 unsigned D; 16858 if (Rec.isUnevaluated()) { 16859 // C++11 [expr.prim.lambda]p2: 16860 // A lambda-expression shall not appear in an unevaluated operand 16861 // (Clause 5). 16862 D = diag::err_lambda_unevaluated_operand; 16863 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16864 // C++1y [expr.const]p2: 16865 // A conditional-expression e is a core constant expression unless the 16866 // evaluation of e, following the rules of the abstract machine, would 16867 // evaluate [...] a lambda-expression. 16868 D = diag::err_lambda_in_constant_expression; 16869 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16870 // C++17 [expr.prim.lamda]p2: 16871 // A lambda-expression shall not appear [...] in a template-argument. 16872 D = diag::err_lambda_in_invalid_context; 16873 } else 16874 llvm_unreachable("Couldn't infer lambda error message."); 16875 16876 for (const auto *L : Rec.Lambdas) 16877 Diag(L->getBeginLoc(), D); 16878 } 16879 } 16880 16881 WarnOnPendingNoDerefs(Rec); 16882 HandleImmediateInvocations(*this, Rec); 16883 16884 // Warn on any volatile-qualified simple-assignments that are not discarded- 16885 // value expressions nor unevaluated operands (those cases get removed from 16886 // this list by CheckUnusedVolatileAssignment). 16887 for (auto *BO : Rec.VolatileAssignmentLHSs) 16888 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16889 << BO->getType(); 16890 16891 // When are coming out of an unevaluated context, clear out any 16892 // temporaries that we may have created as part of the evaluation of 16893 // the expression in that context: they aren't relevant because they 16894 // will never be constructed. 16895 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16896 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16897 ExprCleanupObjects.end()); 16898 Cleanup = Rec.ParentCleanup; 16899 CleanupVarDeclMarking(); 16900 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16901 // Otherwise, merge the contexts together. 16902 } else { 16903 Cleanup.mergeFrom(Rec.ParentCleanup); 16904 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16905 Rec.SavedMaybeODRUseExprs.end()); 16906 } 16907 16908 // Pop the current expression evaluation context off the stack. 16909 ExprEvalContexts.pop_back(); 16910 16911 // The global expression evaluation context record is never popped. 16912 ExprEvalContexts.back().NumTypos += NumTypos; 16913 } 16914 16915 void Sema::DiscardCleanupsInEvaluationContext() { 16916 ExprCleanupObjects.erase( 16917 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16918 ExprCleanupObjects.end()); 16919 Cleanup.reset(); 16920 MaybeODRUseExprs.clear(); 16921 } 16922 16923 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16924 ExprResult Result = CheckPlaceholderExpr(E); 16925 if (Result.isInvalid()) 16926 return ExprError(); 16927 E = Result.get(); 16928 if (!E->getType()->isVariablyModifiedType()) 16929 return E; 16930 return TransformToPotentiallyEvaluated(E); 16931 } 16932 16933 /// Are we in a context that is potentially constant evaluated per C++20 16934 /// [expr.const]p12? 16935 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16936 /// C++2a [expr.const]p12: 16937 // An expression or conversion is potentially constant evaluated if it is 16938 switch (SemaRef.ExprEvalContexts.back().Context) { 16939 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16940 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 16941 16942 // -- a manifestly constant-evaluated expression, 16943 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16944 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16945 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16946 // -- a potentially-evaluated expression, 16947 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16948 // -- an immediate subexpression of a braced-init-list, 16949 16950 // -- [FIXME] an expression of the form & cast-expression that occurs 16951 // within a templated entity 16952 // -- a subexpression of one of the above that is not a subexpression of 16953 // a nested unevaluated operand. 16954 return true; 16955 16956 case Sema::ExpressionEvaluationContext::Unevaluated: 16957 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16958 // Expressions in this context are never evaluated. 16959 return false; 16960 } 16961 llvm_unreachable("Invalid context"); 16962 } 16963 16964 /// Return true if this function has a calling convention that requires mangling 16965 /// in the size of the parameter pack. 16966 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16967 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16968 // we don't need parameter type sizes. 16969 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16970 if (!TT.isOSWindows() || !TT.isX86()) 16971 return false; 16972 16973 // If this is C++ and this isn't an extern "C" function, parameters do not 16974 // need to be complete. In this case, C++ mangling will apply, which doesn't 16975 // use the size of the parameters. 16976 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16977 return false; 16978 16979 // Stdcall, fastcall, and vectorcall need this special treatment. 16980 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16981 switch (CC) { 16982 case CC_X86StdCall: 16983 case CC_X86FastCall: 16984 case CC_X86VectorCall: 16985 return true; 16986 default: 16987 break; 16988 } 16989 return false; 16990 } 16991 16992 /// Require that all of the parameter types of function be complete. Normally, 16993 /// parameter types are only required to be complete when a function is called 16994 /// or defined, but to mangle functions with certain calling conventions, the 16995 /// mangler needs to know the size of the parameter list. In this situation, 16996 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16997 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16998 /// result in a linker error. Clang doesn't implement this behavior, and instead 16999 /// attempts to error at compile time. 17000 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 17001 SourceLocation Loc) { 17002 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 17003 FunctionDecl *FD; 17004 ParmVarDecl *Param; 17005 17006 public: 17007 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 17008 : FD(FD), Param(Param) {} 17009 17010 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17011 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17012 StringRef CCName; 17013 switch (CC) { 17014 case CC_X86StdCall: 17015 CCName = "stdcall"; 17016 break; 17017 case CC_X86FastCall: 17018 CCName = "fastcall"; 17019 break; 17020 case CC_X86VectorCall: 17021 CCName = "vectorcall"; 17022 break; 17023 default: 17024 llvm_unreachable("CC does not need mangling"); 17025 } 17026 17027 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17028 << Param->getDeclName() << FD->getDeclName() << CCName; 17029 } 17030 }; 17031 17032 for (ParmVarDecl *Param : FD->parameters()) { 17033 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17034 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17035 } 17036 } 17037 17038 namespace { 17039 enum class OdrUseContext { 17040 /// Declarations in this context are not odr-used. 17041 None, 17042 /// Declarations in this context are formally odr-used, but this is a 17043 /// dependent context. 17044 Dependent, 17045 /// Declarations in this context are odr-used but not actually used (yet). 17046 FormallyOdrUsed, 17047 /// Declarations in this context are used. 17048 Used 17049 }; 17050 } 17051 17052 /// Are we within a context in which references to resolved functions or to 17053 /// variables result in odr-use? 17054 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17055 OdrUseContext Result; 17056 17057 switch (SemaRef.ExprEvalContexts.back().Context) { 17058 case Sema::ExpressionEvaluationContext::Unevaluated: 17059 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17060 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17061 return OdrUseContext::None; 17062 17063 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17064 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17065 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17066 Result = OdrUseContext::Used; 17067 break; 17068 17069 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17070 Result = OdrUseContext::FormallyOdrUsed; 17071 break; 17072 17073 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17074 // A default argument formally results in odr-use, but doesn't actually 17075 // result in a use in any real sense until it itself is used. 17076 Result = OdrUseContext::FormallyOdrUsed; 17077 break; 17078 } 17079 17080 if (SemaRef.CurContext->isDependentContext()) 17081 return OdrUseContext::Dependent; 17082 17083 return Result; 17084 } 17085 17086 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17087 if (!Func->isConstexpr()) 17088 return false; 17089 17090 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17091 return true; 17092 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17093 return CCD && CCD->getInheritedConstructor(); 17094 } 17095 17096 /// Mark a function referenced, and check whether it is odr-used 17097 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17098 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17099 bool MightBeOdrUse) { 17100 assert(Func && "No function?"); 17101 17102 Func->setReferenced(); 17103 17104 // Recursive functions aren't really used until they're used from some other 17105 // context. 17106 bool IsRecursiveCall = CurContext == Func; 17107 17108 // C++11 [basic.def.odr]p3: 17109 // A function whose name appears as a potentially-evaluated expression is 17110 // odr-used if it is the unique lookup result or the selected member of a 17111 // set of overloaded functions [...]. 17112 // 17113 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17114 // can just check that here. 17115 OdrUseContext OdrUse = 17116 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17117 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17118 OdrUse = OdrUseContext::FormallyOdrUsed; 17119 17120 // Trivial default constructors and destructors are never actually used. 17121 // FIXME: What about other special members? 17122 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17123 OdrUse == OdrUseContext::Used) { 17124 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17125 if (Constructor->isDefaultConstructor()) 17126 OdrUse = OdrUseContext::FormallyOdrUsed; 17127 if (isa<CXXDestructorDecl>(Func)) 17128 OdrUse = OdrUseContext::FormallyOdrUsed; 17129 } 17130 17131 // C++20 [expr.const]p12: 17132 // A function [...] is needed for constant evaluation if it is [...] a 17133 // constexpr function that is named by an expression that is potentially 17134 // constant evaluated 17135 bool NeededForConstantEvaluation = 17136 isPotentiallyConstantEvaluatedContext(*this) && 17137 isImplicitlyDefinableConstexprFunction(Func); 17138 17139 // Determine whether we require a function definition to exist, per 17140 // C++11 [temp.inst]p3: 17141 // Unless a function template specialization has been explicitly 17142 // instantiated or explicitly specialized, the function template 17143 // specialization is implicitly instantiated when the specialization is 17144 // referenced in a context that requires a function definition to exist. 17145 // C++20 [temp.inst]p7: 17146 // The existence of a definition of a [...] function is considered to 17147 // affect the semantics of the program if the [...] function is needed for 17148 // constant evaluation by an expression 17149 // C++20 [basic.def.odr]p10: 17150 // Every program shall contain exactly one definition of every non-inline 17151 // function or variable that is odr-used in that program outside of a 17152 // discarded statement 17153 // C++20 [special]p1: 17154 // The implementation will implicitly define [defaulted special members] 17155 // if they are odr-used or needed for constant evaluation. 17156 // 17157 // Note that we skip the implicit instantiation of templates that are only 17158 // used in unused default arguments or by recursive calls to themselves. 17159 // This is formally non-conforming, but seems reasonable in practice. 17160 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17161 NeededForConstantEvaluation); 17162 17163 // C++14 [temp.expl.spec]p6: 17164 // If a template [...] is explicitly specialized then that specialization 17165 // shall be declared before the first use of that specialization that would 17166 // cause an implicit instantiation to take place, in every translation unit 17167 // in which such a use occurs 17168 if (NeedDefinition && 17169 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17170 Func->getMemberSpecializationInfo())) 17171 checkSpecializationVisibility(Loc, Func); 17172 17173 if (getLangOpts().CUDA) 17174 CheckCUDACall(Loc, Func); 17175 17176 if (getLangOpts().SYCLIsDevice) 17177 checkSYCLDeviceFunction(Loc, Func); 17178 17179 // If we need a definition, try to create one. 17180 if (NeedDefinition && !Func->getBody()) { 17181 runWithSufficientStackSpace(Loc, [&] { 17182 if (CXXConstructorDecl *Constructor = 17183 dyn_cast<CXXConstructorDecl>(Func)) { 17184 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17185 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17186 if (Constructor->isDefaultConstructor()) { 17187 if (Constructor->isTrivial() && 17188 !Constructor->hasAttr<DLLExportAttr>()) 17189 return; 17190 DefineImplicitDefaultConstructor(Loc, Constructor); 17191 } else if (Constructor->isCopyConstructor()) { 17192 DefineImplicitCopyConstructor(Loc, Constructor); 17193 } else if (Constructor->isMoveConstructor()) { 17194 DefineImplicitMoveConstructor(Loc, Constructor); 17195 } 17196 } else if (Constructor->getInheritedConstructor()) { 17197 DefineInheritingConstructor(Loc, Constructor); 17198 } 17199 } else if (CXXDestructorDecl *Destructor = 17200 dyn_cast<CXXDestructorDecl>(Func)) { 17201 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17202 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17203 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17204 return; 17205 DefineImplicitDestructor(Loc, Destructor); 17206 } 17207 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17208 MarkVTableUsed(Loc, Destructor->getParent()); 17209 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17210 if (MethodDecl->isOverloadedOperator() && 17211 MethodDecl->getOverloadedOperator() == OO_Equal) { 17212 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17213 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17214 if (MethodDecl->isCopyAssignmentOperator()) 17215 DefineImplicitCopyAssignment(Loc, MethodDecl); 17216 else if (MethodDecl->isMoveAssignmentOperator()) 17217 DefineImplicitMoveAssignment(Loc, MethodDecl); 17218 } 17219 } else if (isa<CXXConversionDecl>(MethodDecl) && 17220 MethodDecl->getParent()->isLambda()) { 17221 CXXConversionDecl *Conversion = 17222 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17223 if (Conversion->isLambdaToBlockPointerConversion()) 17224 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17225 else 17226 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17227 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17228 MarkVTableUsed(Loc, MethodDecl->getParent()); 17229 } 17230 17231 if (Func->isDefaulted() && !Func->isDeleted()) { 17232 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17233 if (DCK != DefaultedComparisonKind::None) 17234 DefineDefaultedComparison(Loc, Func, DCK); 17235 } 17236 17237 // Implicit instantiation of function templates and member functions of 17238 // class templates. 17239 if (Func->isImplicitlyInstantiable()) { 17240 TemplateSpecializationKind TSK = 17241 Func->getTemplateSpecializationKindForInstantiation(); 17242 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17243 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17244 if (FirstInstantiation) { 17245 PointOfInstantiation = Loc; 17246 if (auto *MSI = Func->getMemberSpecializationInfo()) 17247 MSI->setPointOfInstantiation(Loc); 17248 // FIXME: Notify listener. 17249 else 17250 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17251 } else if (TSK != TSK_ImplicitInstantiation) { 17252 // Use the point of use as the point of instantiation, instead of the 17253 // point of explicit instantiation (which we track as the actual point 17254 // of instantiation). This gives better backtraces in diagnostics. 17255 PointOfInstantiation = Loc; 17256 } 17257 17258 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17259 Func->isConstexpr()) { 17260 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17261 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17262 CodeSynthesisContexts.size()) 17263 PendingLocalImplicitInstantiations.push_back( 17264 std::make_pair(Func, PointOfInstantiation)); 17265 else if (Func->isConstexpr()) 17266 // Do not defer instantiations of constexpr functions, to avoid the 17267 // expression evaluator needing to call back into Sema if it sees a 17268 // call to such a function. 17269 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17270 else { 17271 Func->setInstantiationIsPending(true); 17272 PendingInstantiations.push_back( 17273 std::make_pair(Func, PointOfInstantiation)); 17274 // Notify the consumer that a function was implicitly instantiated. 17275 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17276 } 17277 } 17278 } else { 17279 // Walk redefinitions, as some of them may be instantiable. 17280 for (auto i : Func->redecls()) { 17281 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17282 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17283 } 17284 } 17285 }); 17286 } 17287 17288 // C++14 [except.spec]p17: 17289 // An exception-specification is considered to be needed when: 17290 // - the function is odr-used or, if it appears in an unevaluated operand, 17291 // would be odr-used if the expression were potentially-evaluated; 17292 // 17293 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17294 // function is a pure virtual function we're calling, and in that case the 17295 // function was selected by overload resolution and we need to resolve its 17296 // exception specification for a different reason. 17297 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17298 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17299 ResolveExceptionSpec(Loc, FPT); 17300 17301 // If this is the first "real" use, act on that. 17302 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17303 // Keep track of used but undefined functions. 17304 if (!Func->isDefined()) { 17305 if (mightHaveNonExternalLinkage(Func)) 17306 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17307 else if (Func->getMostRecentDecl()->isInlined() && 17308 !LangOpts.GNUInline && 17309 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17310 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17311 else if (isExternalWithNoLinkageType(Func)) 17312 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17313 } 17314 17315 // Some x86 Windows calling conventions mangle the size of the parameter 17316 // pack into the name. Computing the size of the parameters requires the 17317 // parameter types to be complete. Check that now. 17318 if (funcHasParameterSizeMangling(*this, Func)) 17319 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17320 17321 // In the MS C++ ABI, the compiler emits destructor variants where they are 17322 // used. If the destructor is used here but defined elsewhere, mark the 17323 // virtual base destructors referenced. If those virtual base destructors 17324 // are inline, this will ensure they are defined when emitting the complete 17325 // destructor variant. This checking may be redundant if the destructor is 17326 // provided later in this TU. 17327 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17328 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17329 CXXRecordDecl *Parent = Dtor->getParent(); 17330 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17331 CheckCompleteDestructorVariant(Loc, Dtor); 17332 } 17333 } 17334 17335 Func->markUsed(Context); 17336 } 17337 } 17338 17339 /// Directly mark a variable odr-used. Given a choice, prefer to use 17340 /// MarkVariableReferenced since it does additional checks and then 17341 /// calls MarkVarDeclODRUsed. 17342 /// If the variable must be captured: 17343 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17344 /// - else capture it in the DeclContext that maps to the 17345 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17346 static void 17347 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17348 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17349 // Keep track of used but undefined variables. 17350 // FIXME: We shouldn't suppress this warning for static data members. 17351 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17352 (!Var->isExternallyVisible() || Var->isInline() || 17353 SemaRef.isExternalWithNoLinkageType(Var)) && 17354 !(Var->isStaticDataMember() && Var->hasInit())) { 17355 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17356 if (old.isInvalid()) 17357 old = Loc; 17358 } 17359 QualType CaptureType, DeclRefType; 17360 if (SemaRef.LangOpts.OpenMP) 17361 SemaRef.tryCaptureOpenMPLambdas(Var); 17362 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17363 /*EllipsisLoc*/ SourceLocation(), 17364 /*BuildAndDiagnose*/ true, 17365 CaptureType, DeclRefType, 17366 FunctionScopeIndexToStopAt); 17367 17368 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17369 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17370 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17371 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17372 if (VarTarget == Sema::CVT_Host && 17373 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17374 UserTarget == Sema::CFT_Global)) { 17375 // Diagnose ODR-use of host global variables in device functions. 17376 // Reference of device global variables in host functions is allowed 17377 // through shadow variables therefore it is not diagnosed. 17378 if (SemaRef.LangOpts.CUDAIsDevice) { 17379 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17380 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17381 SemaRef.targetDiag(Var->getLocation(), 17382 Var->getType().isConstQualified() 17383 ? diag::note_cuda_const_var_unpromoted 17384 : diag::note_cuda_host_var); 17385 } 17386 } else if (VarTarget == Sema::CVT_Device && 17387 (UserTarget == Sema::CFT_Host || 17388 UserTarget == Sema::CFT_HostDevice) && 17389 !Var->hasExternalStorage()) { 17390 // Record a CUDA/HIP device side variable if it is ODR-used 17391 // by host code. This is done conservatively, when the variable is 17392 // referenced in any of the following contexts: 17393 // - a non-function context 17394 // - a host function 17395 // - a host device function 17396 // This makes the ODR-use of the device side variable by host code to 17397 // be visible in the device compilation for the compiler to be able to 17398 // emit template variables instantiated by host code only and to 17399 // externalize the static device side variable ODR-used by host code. 17400 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17401 } 17402 } 17403 17404 Var->markUsed(SemaRef.Context); 17405 } 17406 17407 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17408 SourceLocation Loc, 17409 unsigned CapturingScopeIndex) { 17410 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17411 } 17412 17413 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17414 ValueDecl *var) { 17415 DeclContext *VarDC = var->getDeclContext(); 17416 17417 // If the parameter still belongs to the translation unit, then 17418 // we're actually just using one parameter in the declaration of 17419 // the next. 17420 if (isa<ParmVarDecl>(var) && 17421 isa<TranslationUnitDecl>(VarDC)) 17422 return; 17423 17424 // For C code, don't diagnose about capture if we're not actually in code 17425 // right now; it's impossible to write a non-constant expression outside of 17426 // function context, so we'll get other (more useful) diagnostics later. 17427 // 17428 // For C++, things get a bit more nasty... it would be nice to suppress this 17429 // diagnostic for certain cases like using a local variable in an array bound 17430 // for a member of a local class, but the correct predicate is not obvious. 17431 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17432 return; 17433 17434 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17435 unsigned ContextKind = 3; // unknown 17436 if (isa<CXXMethodDecl>(VarDC) && 17437 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17438 ContextKind = 2; 17439 } else if (isa<FunctionDecl>(VarDC)) { 17440 ContextKind = 0; 17441 } else if (isa<BlockDecl>(VarDC)) { 17442 ContextKind = 1; 17443 } 17444 17445 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17446 << var << ValueKind << ContextKind << VarDC; 17447 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17448 << var; 17449 17450 // FIXME: Add additional diagnostic info about class etc. which prevents 17451 // capture. 17452 } 17453 17454 17455 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17456 bool &SubCapturesAreNested, 17457 QualType &CaptureType, 17458 QualType &DeclRefType) { 17459 // Check whether we've already captured it. 17460 if (CSI->CaptureMap.count(Var)) { 17461 // If we found a capture, any subcaptures are nested. 17462 SubCapturesAreNested = true; 17463 17464 // Retrieve the capture type for this variable. 17465 CaptureType = CSI->getCapture(Var).getCaptureType(); 17466 17467 // Compute the type of an expression that refers to this variable. 17468 DeclRefType = CaptureType.getNonReferenceType(); 17469 17470 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17471 // are mutable in the sense that user can change their value - they are 17472 // private instances of the captured declarations. 17473 const Capture &Cap = CSI->getCapture(Var); 17474 if (Cap.isCopyCapture() && 17475 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17476 !(isa<CapturedRegionScopeInfo>(CSI) && 17477 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17478 DeclRefType.addConst(); 17479 return true; 17480 } 17481 return false; 17482 } 17483 17484 // Only block literals, captured statements, and lambda expressions can 17485 // capture; other scopes don't work. 17486 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17487 SourceLocation Loc, 17488 const bool Diagnose, Sema &S) { 17489 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17490 return getLambdaAwareParentOfDeclContext(DC); 17491 else if (Var->hasLocalStorage()) { 17492 if (Diagnose) 17493 diagnoseUncapturableValueReference(S, Loc, Var); 17494 } 17495 return nullptr; 17496 } 17497 17498 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17499 // certain types of variables (unnamed, variably modified types etc.) 17500 // so check for eligibility. 17501 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17502 SourceLocation Loc, 17503 const bool Diagnose, Sema &S) { 17504 17505 bool IsBlock = isa<BlockScopeInfo>(CSI); 17506 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17507 17508 // Lambdas are not allowed to capture unnamed variables 17509 // (e.g. anonymous unions). 17510 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17511 // assuming that's the intent. 17512 if (IsLambda && !Var->getDeclName()) { 17513 if (Diagnose) { 17514 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17515 S.Diag(Var->getLocation(), diag::note_declared_at); 17516 } 17517 return false; 17518 } 17519 17520 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17521 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17522 if (Diagnose) { 17523 S.Diag(Loc, diag::err_ref_vm_type); 17524 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17525 } 17526 return false; 17527 } 17528 // Prohibit structs with flexible array members too. 17529 // We cannot capture what is in the tail end of the struct. 17530 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17531 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17532 if (Diagnose) { 17533 if (IsBlock) 17534 S.Diag(Loc, diag::err_ref_flexarray_type); 17535 else 17536 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17537 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17538 } 17539 return false; 17540 } 17541 } 17542 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17543 // Lambdas and captured statements are not allowed to capture __block 17544 // variables; they don't support the expected semantics. 17545 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17546 if (Diagnose) { 17547 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17548 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17549 } 17550 return false; 17551 } 17552 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17553 if (S.getLangOpts().OpenCL && IsBlock && 17554 Var->getType()->isBlockPointerType()) { 17555 if (Diagnose) 17556 S.Diag(Loc, diag::err_opencl_block_ref_block); 17557 return false; 17558 } 17559 17560 return true; 17561 } 17562 17563 // Returns true if the capture by block was successful. 17564 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17565 SourceLocation Loc, 17566 const bool BuildAndDiagnose, 17567 QualType &CaptureType, 17568 QualType &DeclRefType, 17569 const bool Nested, 17570 Sema &S, bool Invalid) { 17571 bool ByRef = false; 17572 17573 // Blocks are not allowed to capture arrays, excepting OpenCL. 17574 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17575 // (decayed to pointers). 17576 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17577 if (BuildAndDiagnose) { 17578 S.Diag(Loc, diag::err_ref_array_type); 17579 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17580 Invalid = true; 17581 } else { 17582 return false; 17583 } 17584 } 17585 17586 // Forbid the block-capture of autoreleasing variables. 17587 if (!Invalid && 17588 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17589 if (BuildAndDiagnose) { 17590 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17591 << /*block*/ 0; 17592 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17593 Invalid = true; 17594 } else { 17595 return false; 17596 } 17597 } 17598 17599 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17600 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17601 QualType PointeeTy = PT->getPointeeType(); 17602 17603 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17604 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17605 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17606 if (BuildAndDiagnose) { 17607 SourceLocation VarLoc = Var->getLocation(); 17608 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17609 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17610 } 17611 } 17612 } 17613 17614 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17615 if (HasBlocksAttr || CaptureType->isReferenceType() || 17616 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17617 // Block capture by reference does not change the capture or 17618 // declaration reference types. 17619 ByRef = true; 17620 } else { 17621 // Block capture by copy introduces 'const'. 17622 CaptureType = CaptureType.getNonReferenceType().withConst(); 17623 DeclRefType = CaptureType; 17624 } 17625 17626 // Actually capture the variable. 17627 if (BuildAndDiagnose) 17628 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17629 CaptureType, Invalid); 17630 17631 return !Invalid; 17632 } 17633 17634 17635 /// Capture the given variable in the captured region. 17636 static bool captureInCapturedRegion( 17637 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17638 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17639 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17640 bool IsTopScope, Sema &S, bool Invalid) { 17641 // By default, capture variables by reference. 17642 bool ByRef = true; 17643 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17644 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17645 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17646 // Using an LValue reference type is consistent with Lambdas (see below). 17647 if (S.isOpenMPCapturedDecl(Var)) { 17648 bool HasConst = DeclRefType.isConstQualified(); 17649 DeclRefType = DeclRefType.getUnqualifiedType(); 17650 // Don't lose diagnostics about assignments to const. 17651 if (HasConst) 17652 DeclRefType.addConst(); 17653 } 17654 // Do not capture firstprivates in tasks. 17655 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17656 OMPC_unknown) 17657 return true; 17658 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17659 RSI->OpenMPCaptureLevel); 17660 } 17661 17662 if (ByRef) 17663 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17664 else 17665 CaptureType = DeclRefType; 17666 17667 // Actually capture the variable. 17668 if (BuildAndDiagnose) 17669 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17670 Loc, SourceLocation(), CaptureType, Invalid); 17671 17672 return !Invalid; 17673 } 17674 17675 /// Capture the given variable in the lambda. 17676 static bool captureInLambda(LambdaScopeInfo *LSI, 17677 VarDecl *Var, 17678 SourceLocation Loc, 17679 const bool BuildAndDiagnose, 17680 QualType &CaptureType, 17681 QualType &DeclRefType, 17682 const bool RefersToCapturedVariable, 17683 const Sema::TryCaptureKind Kind, 17684 SourceLocation EllipsisLoc, 17685 const bool IsTopScope, 17686 Sema &S, bool Invalid) { 17687 // Determine whether we are capturing by reference or by value. 17688 bool ByRef = false; 17689 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17690 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17691 } else { 17692 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17693 } 17694 17695 // Compute the type of the field that will capture this variable. 17696 if (ByRef) { 17697 // C++11 [expr.prim.lambda]p15: 17698 // An entity is captured by reference if it is implicitly or 17699 // explicitly captured but not captured by copy. It is 17700 // unspecified whether additional unnamed non-static data 17701 // members are declared in the closure type for entities 17702 // captured by reference. 17703 // 17704 // FIXME: It is not clear whether we want to build an lvalue reference 17705 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17706 // to do the former, while EDG does the latter. Core issue 1249 will 17707 // clarify, but for now we follow GCC because it's a more permissive and 17708 // easily defensible position. 17709 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17710 } else { 17711 // C++11 [expr.prim.lambda]p14: 17712 // For each entity captured by copy, an unnamed non-static 17713 // data member is declared in the closure type. The 17714 // declaration order of these members is unspecified. The type 17715 // of such a data member is the type of the corresponding 17716 // captured entity if the entity is not a reference to an 17717 // object, or the referenced type otherwise. [Note: If the 17718 // captured entity is a reference to a function, the 17719 // corresponding data member is also a reference to a 17720 // function. - end note ] 17721 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17722 if (!RefType->getPointeeType()->isFunctionType()) 17723 CaptureType = RefType->getPointeeType(); 17724 } 17725 17726 // Forbid the lambda copy-capture of autoreleasing variables. 17727 if (!Invalid && 17728 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17729 if (BuildAndDiagnose) { 17730 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17731 S.Diag(Var->getLocation(), diag::note_previous_decl) 17732 << Var->getDeclName(); 17733 Invalid = true; 17734 } else { 17735 return false; 17736 } 17737 } 17738 17739 // Make sure that by-copy captures are of a complete and non-abstract type. 17740 if (!Invalid && BuildAndDiagnose) { 17741 if (!CaptureType->isDependentType() && 17742 S.RequireCompleteSizedType( 17743 Loc, CaptureType, 17744 diag::err_capture_of_incomplete_or_sizeless_type, 17745 Var->getDeclName())) 17746 Invalid = true; 17747 else if (S.RequireNonAbstractType(Loc, CaptureType, 17748 diag::err_capture_of_abstract_type)) 17749 Invalid = true; 17750 } 17751 } 17752 17753 // Compute the type of a reference to this captured variable. 17754 if (ByRef) 17755 DeclRefType = CaptureType.getNonReferenceType(); 17756 else { 17757 // C++ [expr.prim.lambda]p5: 17758 // The closure type for a lambda-expression has a public inline 17759 // function call operator [...]. This function call operator is 17760 // declared const (9.3.1) if and only if the lambda-expression's 17761 // parameter-declaration-clause is not followed by mutable. 17762 DeclRefType = CaptureType.getNonReferenceType(); 17763 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17764 DeclRefType.addConst(); 17765 } 17766 17767 // Add the capture. 17768 if (BuildAndDiagnose) 17769 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17770 Loc, EllipsisLoc, CaptureType, Invalid); 17771 17772 return !Invalid; 17773 } 17774 17775 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17776 // Offer a Copy fix even if the type is dependent. 17777 if (Var->getType()->isDependentType()) 17778 return true; 17779 QualType T = Var->getType().getNonReferenceType(); 17780 if (T.isTriviallyCopyableType(Context)) 17781 return true; 17782 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17783 17784 if (!(RD = RD->getDefinition())) 17785 return false; 17786 if (RD->hasSimpleCopyConstructor()) 17787 return true; 17788 if (RD->hasUserDeclaredCopyConstructor()) 17789 for (CXXConstructorDecl *Ctor : RD->ctors()) 17790 if (Ctor->isCopyConstructor()) 17791 return !Ctor->isDeleted(); 17792 } 17793 return false; 17794 } 17795 17796 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17797 /// default capture. Fixes may be omitted if they aren't allowed by the 17798 /// standard, for example we can't emit a default copy capture fix-it if we 17799 /// already explicitly copy capture capture another variable. 17800 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17801 VarDecl *Var) { 17802 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17803 // Don't offer Capture by copy of default capture by copy fixes if Var is 17804 // known not to be copy constructible. 17805 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17806 17807 SmallString<32> FixBuffer; 17808 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17809 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17810 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17811 if (ShouldOfferCopyFix) { 17812 // Offer fixes to insert an explicit capture for the variable. 17813 // [] -> [VarName] 17814 // [OtherCapture] -> [OtherCapture, VarName] 17815 FixBuffer.assign({Separator, Var->getName()}); 17816 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17817 << Var << /*value*/ 0 17818 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17819 } 17820 // As above but capture by reference. 17821 FixBuffer.assign({Separator, "&", Var->getName()}); 17822 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17823 << Var << /*reference*/ 1 17824 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17825 } 17826 17827 // Only try to offer default capture if there are no captures excluding this 17828 // and init captures. 17829 // [this]: OK. 17830 // [X = Y]: OK. 17831 // [&A, &B]: Don't offer. 17832 // [A, B]: Don't offer. 17833 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17834 return !C.isThisCapture() && !C.isInitCapture(); 17835 })) 17836 return; 17837 17838 // The default capture specifiers, '=' or '&', must appear first in the 17839 // capture body. 17840 SourceLocation DefaultInsertLoc = 17841 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17842 17843 if (ShouldOfferCopyFix) { 17844 bool CanDefaultCopyCapture = true; 17845 // [=, *this] OK since c++17 17846 // [=, this] OK since c++20 17847 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17848 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17849 ? LSI->getCXXThisCapture().isCopyCapture() 17850 : false; 17851 // We can't use default capture by copy if any captures already specified 17852 // capture by copy. 17853 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17854 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17855 })) { 17856 FixBuffer.assign({"=", Separator}); 17857 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17858 << /*value*/ 0 17859 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17860 } 17861 } 17862 17863 // We can't use default capture by reference if any captures already specified 17864 // capture by reference. 17865 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17866 return !C.isInitCapture() && C.isReferenceCapture() && 17867 !C.isThisCapture(); 17868 })) { 17869 FixBuffer.assign({"&", Separator}); 17870 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17871 << /*reference*/ 1 17872 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17873 } 17874 } 17875 17876 bool Sema::tryCaptureVariable( 17877 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17878 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17879 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17880 // An init-capture is notionally from the context surrounding its 17881 // declaration, but its parent DC is the lambda class. 17882 DeclContext *VarDC = Var->getDeclContext(); 17883 if (Var->isInitCapture()) 17884 VarDC = VarDC->getParent(); 17885 17886 DeclContext *DC = CurContext; 17887 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17888 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17889 // We need to sync up the Declaration Context with the 17890 // FunctionScopeIndexToStopAt 17891 if (FunctionScopeIndexToStopAt) { 17892 unsigned FSIndex = FunctionScopes.size() - 1; 17893 while (FSIndex != MaxFunctionScopesIndex) { 17894 DC = getLambdaAwareParentOfDeclContext(DC); 17895 --FSIndex; 17896 } 17897 } 17898 17899 17900 // If the variable is declared in the current context, there is no need to 17901 // capture it. 17902 if (VarDC == DC) return true; 17903 17904 // Capture global variables if it is required to use private copy of this 17905 // variable. 17906 bool IsGlobal = !Var->hasLocalStorage(); 17907 if (IsGlobal && 17908 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17909 MaxFunctionScopesIndex))) 17910 return true; 17911 Var = Var->getCanonicalDecl(); 17912 17913 // Walk up the stack to determine whether we can capture the variable, 17914 // performing the "simple" checks that don't depend on type. We stop when 17915 // we've either hit the declared scope of the variable or find an existing 17916 // capture of that variable. We start from the innermost capturing-entity 17917 // (the DC) and ensure that all intervening capturing-entities 17918 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17919 // declcontext can either capture the variable or have already captured 17920 // the variable. 17921 CaptureType = Var->getType(); 17922 DeclRefType = CaptureType.getNonReferenceType(); 17923 bool Nested = false; 17924 bool Explicit = (Kind != TryCapture_Implicit); 17925 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17926 do { 17927 // Only block literals, captured statements, and lambda expressions can 17928 // capture; other scopes don't work. 17929 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17930 ExprLoc, 17931 BuildAndDiagnose, 17932 *this); 17933 // We need to check for the parent *first* because, if we *have* 17934 // private-captured a global variable, we need to recursively capture it in 17935 // intermediate blocks, lambdas, etc. 17936 if (!ParentDC) { 17937 if (IsGlobal) { 17938 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17939 break; 17940 } 17941 return true; 17942 } 17943 17944 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17945 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17946 17947 17948 // Check whether we've already captured it. 17949 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17950 DeclRefType)) { 17951 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17952 break; 17953 } 17954 // If we are instantiating a generic lambda call operator body, 17955 // we do not want to capture new variables. What was captured 17956 // during either a lambdas transformation or initial parsing 17957 // should be used. 17958 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17959 if (BuildAndDiagnose) { 17960 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17961 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17962 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17963 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17964 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17965 buildLambdaCaptureFixit(*this, LSI, Var); 17966 } else 17967 diagnoseUncapturableValueReference(*this, ExprLoc, Var); 17968 } 17969 return true; 17970 } 17971 17972 // Try to capture variable-length arrays types. 17973 if (Var->getType()->isVariablyModifiedType()) { 17974 // We're going to walk down into the type and look for VLA 17975 // expressions. 17976 QualType QTy = Var->getType(); 17977 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17978 QTy = PVD->getOriginalType(); 17979 captureVariablyModifiedType(Context, QTy, CSI); 17980 } 17981 17982 if (getLangOpts().OpenMP) { 17983 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17984 // OpenMP private variables should not be captured in outer scope, so 17985 // just break here. Similarly, global variables that are captured in a 17986 // target region should not be captured outside the scope of the region. 17987 if (RSI->CapRegionKind == CR_OpenMP) { 17988 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17989 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17990 // If the variable is private (i.e. not captured) and has variably 17991 // modified type, we still need to capture the type for correct 17992 // codegen in all regions, associated with the construct. Currently, 17993 // it is captured in the innermost captured region only. 17994 if (IsOpenMPPrivateDecl != OMPC_unknown && 17995 Var->getType()->isVariablyModifiedType()) { 17996 QualType QTy = Var->getType(); 17997 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17998 QTy = PVD->getOriginalType(); 17999 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 18000 I < E; ++I) { 18001 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 18002 FunctionScopes[FunctionScopesIndex - I]); 18003 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 18004 "Wrong number of captured regions associated with the " 18005 "OpenMP construct."); 18006 captureVariablyModifiedType(Context, QTy, OuterRSI); 18007 } 18008 } 18009 bool IsTargetCap = 18010 IsOpenMPPrivateDecl != OMPC_private && 18011 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 18012 RSI->OpenMPCaptureLevel); 18013 // Do not capture global if it is not privatized in outer regions. 18014 bool IsGlobalCap = 18015 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 18016 RSI->OpenMPCaptureLevel); 18017 18018 // When we detect target captures we are looking from inside the 18019 // target region, therefore we need to propagate the capture from the 18020 // enclosing region. Therefore, the capture is not initially nested. 18021 if (IsTargetCap) 18022 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18023 18024 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18025 (IsGlobal && !IsGlobalCap)) { 18026 Nested = !IsTargetCap; 18027 bool HasConst = DeclRefType.isConstQualified(); 18028 DeclRefType = DeclRefType.getUnqualifiedType(); 18029 // Don't lose diagnostics about assignments to const. 18030 if (HasConst) 18031 DeclRefType.addConst(); 18032 CaptureType = Context.getLValueReferenceType(DeclRefType); 18033 break; 18034 } 18035 } 18036 } 18037 } 18038 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18039 // No capture-default, and this is not an explicit capture 18040 // so cannot capture this variable. 18041 if (BuildAndDiagnose) { 18042 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18043 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18044 auto *LSI = cast<LambdaScopeInfo>(CSI); 18045 if (LSI->Lambda) { 18046 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18047 buildLambdaCaptureFixit(*this, LSI, Var); 18048 } 18049 // FIXME: If we error out because an outer lambda can not implicitly 18050 // capture a variable that an inner lambda explicitly captures, we 18051 // should have the inner lambda do the explicit capture - because 18052 // it makes for cleaner diagnostics later. This would purely be done 18053 // so that the diagnostic does not misleadingly claim that a variable 18054 // can not be captured by a lambda implicitly even though it is captured 18055 // explicitly. Suggestion: 18056 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18057 // at the function head 18058 // - cache the StartingDeclContext - this must be a lambda 18059 // - captureInLambda in the innermost lambda the variable. 18060 } 18061 return true; 18062 } 18063 18064 FunctionScopesIndex--; 18065 DC = ParentDC; 18066 Explicit = false; 18067 } while (!VarDC->Equals(DC)); 18068 18069 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18070 // computing the type of the capture at each step, checking type-specific 18071 // requirements, and adding captures if requested. 18072 // If the variable had already been captured previously, we start capturing 18073 // at the lambda nested within that one. 18074 bool Invalid = false; 18075 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18076 ++I) { 18077 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18078 18079 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18080 // certain types of variables (unnamed, variably modified types etc.) 18081 // so check for eligibility. 18082 if (!Invalid) 18083 Invalid = 18084 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18085 18086 // After encountering an error, if we're actually supposed to capture, keep 18087 // capturing in nested contexts to suppress any follow-on diagnostics. 18088 if (Invalid && !BuildAndDiagnose) 18089 return true; 18090 18091 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18092 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18093 DeclRefType, Nested, *this, Invalid); 18094 Nested = true; 18095 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18096 Invalid = !captureInCapturedRegion( 18097 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18098 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18099 Nested = true; 18100 } else { 18101 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18102 Invalid = 18103 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18104 DeclRefType, Nested, Kind, EllipsisLoc, 18105 /*IsTopScope*/ I == N - 1, *this, Invalid); 18106 Nested = true; 18107 } 18108 18109 if (Invalid && !BuildAndDiagnose) 18110 return true; 18111 } 18112 return Invalid; 18113 } 18114 18115 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18116 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18117 QualType CaptureType; 18118 QualType DeclRefType; 18119 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18120 /*BuildAndDiagnose=*/true, CaptureType, 18121 DeclRefType, nullptr); 18122 } 18123 18124 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18125 QualType CaptureType; 18126 QualType DeclRefType; 18127 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18128 /*BuildAndDiagnose=*/false, CaptureType, 18129 DeclRefType, nullptr); 18130 } 18131 18132 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18133 QualType CaptureType; 18134 QualType DeclRefType; 18135 18136 // Determine whether we can capture this variable. 18137 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18138 /*BuildAndDiagnose=*/false, CaptureType, 18139 DeclRefType, nullptr)) 18140 return QualType(); 18141 18142 return DeclRefType; 18143 } 18144 18145 namespace { 18146 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18147 // The produced TemplateArgumentListInfo* points to data stored within this 18148 // object, so should only be used in contexts where the pointer will not be 18149 // used after the CopiedTemplateArgs object is destroyed. 18150 class CopiedTemplateArgs { 18151 bool HasArgs; 18152 TemplateArgumentListInfo TemplateArgStorage; 18153 public: 18154 template<typename RefExpr> 18155 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18156 if (HasArgs) 18157 E->copyTemplateArgumentsInto(TemplateArgStorage); 18158 } 18159 operator TemplateArgumentListInfo*() 18160 #ifdef __has_cpp_attribute 18161 #if __has_cpp_attribute(clang::lifetimebound) 18162 [[clang::lifetimebound]] 18163 #endif 18164 #endif 18165 { 18166 return HasArgs ? &TemplateArgStorage : nullptr; 18167 } 18168 }; 18169 } 18170 18171 /// Walk the set of potential results of an expression and mark them all as 18172 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18173 /// 18174 /// \return A new expression if we found any potential results, ExprEmpty() if 18175 /// not, and ExprError() if we diagnosed an error. 18176 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18177 NonOdrUseReason NOUR) { 18178 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18179 // an object that satisfies the requirements for appearing in a 18180 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18181 // is immediately applied." This function handles the lvalue-to-rvalue 18182 // conversion part. 18183 // 18184 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18185 // transform it into the relevant kind of non-odr-use node and rebuild the 18186 // tree of nodes leading to it. 18187 // 18188 // This is a mini-TreeTransform that only transforms a restricted subset of 18189 // nodes (and only certain operands of them). 18190 18191 // Rebuild a subexpression. 18192 auto Rebuild = [&](Expr *Sub) { 18193 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18194 }; 18195 18196 // Check whether a potential result satisfies the requirements of NOUR. 18197 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18198 // Any entity other than a VarDecl is always odr-used whenever it's named 18199 // in a potentially-evaluated expression. 18200 auto *VD = dyn_cast<VarDecl>(D); 18201 if (!VD) 18202 return true; 18203 18204 // C++2a [basic.def.odr]p4: 18205 // A variable x whose name appears as a potentially-evalauted expression 18206 // e is odr-used by e unless 18207 // -- x is a reference that is usable in constant expressions, or 18208 // -- x is a variable of non-reference type that is usable in constant 18209 // expressions and has no mutable subobjects, and e is an element of 18210 // the set of potential results of an expression of 18211 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18212 // conversion is applied, or 18213 // -- x is a variable of non-reference type, and e is an element of the 18214 // set of potential results of a discarded-value expression to which 18215 // the lvalue-to-rvalue conversion is not applied 18216 // 18217 // We check the first bullet and the "potentially-evaluated" condition in 18218 // BuildDeclRefExpr. We check the type requirements in the second bullet 18219 // in CheckLValueToRValueConversionOperand below. 18220 switch (NOUR) { 18221 case NOUR_None: 18222 case NOUR_Unevaluated: 18223 llvm_unreachable("unexpected non-odr-use-reason"); 18224 18225 case NOUR_Constant: 18226 // Constant references were handled when they were built. 18227 if (VD->getType()->isReferenceType()) 18228 return true; 18229 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18230 if (RD->hasMutableFields()) 18231 return true; 18232 if (!VD->isUsableInConstantExpressions(S.Context)) 18233 return true; 18234 break; 18235 18236 case NOUR_Discarded: 18237 if (VD->getType()->isReferenceType()) 18238 return true; 18239 break; 18240 } 18241 return false; 18242 }; 18243 18244 // Mark that this expression does not constitute an odr-use. 18245 auto MarkNotOdrUsed = [&] { 18246 S.MaybeODRUseExprs.remove(E); 18247 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18248 LSI->markVariableExprAsNonODRUsed(E); 18249 }; 18250 18251 // C++2a [basic.def.odr]p2: 18252 // The set of potential results of an expression e is defined as follows: 18253 switch (E->getStmtClass()) { 18254 // -- If e is an id-expression, ... 18255 case Expr::DeclRefExprClass: { 18256 auto *DRE = cast<DeclRefExpr>(E); 18257 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18258 break; 18259 18260 // Rebuild as a non-odr-use DeclRefExpr. 18261 MarkNotOdrUsed(); 18262 return DeclRefExpr::Create( 18263 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18264 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18265 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18266 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18267 } 18268 18269 case Expr::FunctionParmPackExprClass: { 18270 auto *FPPE = cast<FunctionParmPackExpr>(E); 18271 // If any of the declarations in the pack is odr-used, then the expression 18272 // as a whole constitutes an odr-use. 18273 for (VarDecl *D : *FPPE) 18274 if (IsPotentialResultOdrUsed(D)) 18275 return ExprEmpty(); 18276 18277 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18278 // nothing cares about whether we marked this as an odr-use, but it might 18279 // be useful for non-compiler tools. 18280 MarkNotOdrUsed(); 18281 break; 18282 } 18283 18284 // -- If e is a subscripting operation with an array operand... 18285 case Expr::ArraySubscriptExprClass: { 18286 auto *ASE = cast<ArraySubscriptExpr>(E); 18287 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18288 if (!OldBase->getType()->isArrayType()) 18289 break; 18290 ExprResult Base = Rebuild(OldBase); 18291 if (!Base.isUsable()) 18292 return Base; 18293 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18294 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18295 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18296 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18297 ASE->getRBracketLoc()); 18298 } 18299 18300 case Expr::MemberExprClass: { 18301 auto *ME = cast<MemberExpr>(E); 18302 // -- If e is a class member access expression [...] naming a non-static 18303 // data member... 18304 if (isa<FieldDecl>(ME->getMemberDecl())) { 18305 ExprResult Base = Rebuild(ME->getBase()); 18306 if (!Base.isUsable()) 18307 return Base; 18308 return MemberExpr::Create( 18309 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18310 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18311 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18312 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18313 ME->getObjectKind(), ME->isNonOdrUse()); 18314 } 18315 18316 if (ME->getMemberDecl()->isCXXInstanceMember()) 18317 break; 18318 18319 // -- If e is a class member access expression naming a static data member, 18320 // ... 18321 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18322 break; 18323 18324 // Rebuild as a non-odr-use MemberExpr. 18325 MarkNotOdrUsed(); 18326 return MemberExpr::Create( 18327 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18328 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18329 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18330 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18331 } 18332 18333 case Expr::BinaryOperatorClass: { 18334 auto *BO = cast<BinaryOperator>(E); 18335 Expr *LHS = BO->getLHS(); 18336 Expr *RHS = BO->getRHS(); 18337 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18338 if (BO->getOpcode() == BO_PtrMemD) { 18339 ExprResult Sub = Rebuild(LHS); 18340 if (!Sub.isUsable()) 18341 return Sub; 18342 LHS = Sub.get(); 18343 // -- If e is a comma expression, ... 18344 } else if (BO->getOpcode() == BO_Comma) { 18345 ExprResult Sub = Rebuild(RHS); 18346 if (!Sub.isUsable()) 18347 return Sub; 18348 RHS = Sub.get(); 18349 } else { 18350 break; 18351 } 18352 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18353 LHS, RHS); 18354 } 18355 18356 // -- If e has the form (e1)... 18357 case Expr::ParenExprClass: { 18358 auto *PE = cast<ParenExpr>(E); 18359 ExprResult Sub = Rebuild(PE->getSubExpr()); 18360 if (!Sub.isUsable()) 18361 return Sub; 18362 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18363 } 18364 18365 // -- If e is a glvalue conditional expression, ... 18366 // We don't apply this to a binary conditional operator. FIXME: Should we? 18367 case Expr::ConditionalOperatorClass: { 18368 auto *CO = cast<ConditionalOperator>(E); 18369 ExprResult LHS = Rebuild(CO->getLHS()); 18370 if (LHS.isInvalid()) 18371 return ExprError(); 18372 ExprResult RHS = Rebuild(CO->getRHS()); 18373 if (RHS.isInvalid()) 18374 return ExprError(); 18375 if (!LHS.isUsable() && !RHS.isUsable()) 18376 return ExprEmpty(); 18377 if (!LHS.isUsable()) 18378 LHS = CO->getLHS(); 18379 if (!RHS.isUsable()) 18380 RHS = CO->getRHS(); 18381 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18382 CO->getCond(), LHS.get(), RHS.get()); 18383 } 18384 18385 // [Clang extension] 18386 // -- If e has the form __extension__ e1... 18387 case Expr::UnaryOperatorClass: { 18388 auto *UO = cast<UnaryOperator>(E); 18389 if (UO->getOpcode() != UO_Extension) 18390 break; 18391 ExprResult Sub = Rebuild(UO->getSubExpr()); 18392 if (!Sub.isUsable()) 18393 return Sub; 18394 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18395 Sub.get()); 18396 } 18397 18398 // [Clang extension] 18399 // -- If e has the form _Generic(...), the set of potential results is the 18400 // union of the sets of potential results of the associated expressions. 18401 case Expr::GenericSelectionExprClass: { 18402 auto *GSE = cast<GenericSelectionExpr>(E); 18403 18404 SmallVector<Expr *, 4> AssocExprs; 18405 bool AnyChanged = false; 18406 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18407 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18408 if (AssocExpr.isInvalid()) 18409 return ExprError(); 18410 if (AssocExpr.isUsable()) { 18411 AssocExprs.push_back(AssocExpr.get()); 18412 AnyChanged = true; 18413 } else { 18414 AssocExprs.push_back(OrigAssocExpr); 18415 } 18416 } 18417 18418 return AnyChanged ? S.CreateGenericSelectionExpr( 18419 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18420 GSE->getRParenLoc(), GSE->getControllingExpr(), 18421 GSE->getAssocTypeSourceInfos(), AssocExprs) 18422 : ExprEmpty(); 18423 } 18424 18425 // [Clang extension] 18426 // -- If e has the form __builtin_choose_expr(...), the set of potential 18427 // results is the union of the sets of potential results of the 18428 // second and third subexpressions. 18429 case Expr::ChooseExprClass: { 18430 auto *CE = cast<ChooseExpr>(E); 18431 18432 ExprResult LHS = Rebuild(CE->getLHS()); 18433 if (LHS.isInvalid()) 18434 return ExprError(); 18435 18436 ExprResult RHS = Rebuild(CE->getLHS()); 18437 if (RHS.isInvalid()) 18438 return ExprError(); 18439 18440 if (!LHS.get() && !RHS.get()) 18441 return ExprEmpty(); 18442 if (!LHS.isUsable()) 18443 LHS = CE->getLHS(); 18444 if (!RHS.isUsable()) 18445 RHS = CE->getRHS(); 18446 18447 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18448 RHS.get(), CE->getRParenLoc()); 18449 } 18450 18451 // Step through non-syntactic nodes. 18452 case Expr::ConstantExprClass: { 18453 auto *CE = cast<ConstantExpr>(E); 18454 ExprResult Sub = Rebuild(CE->getSubExpr()); 18455 if (!Sub.isUsable()) 18456 return Sub; 18457 return ConstantExpr::Create(S.Context, Sub.get()); 18458 } 18459 18460 // We could mostly rely on the recursive rebuilding to rebuild implicit 18461 // casts, but not at the top level, so rebuild them here. 18462 case Expr::ImplicitCastExprClass: { 18463 auto *ICE = cast<ImplicitCastExpr>(E); 18464 // Only step through the narrow set of cast kinds we expect to encounter. 18465 // Anything else suggests we've left the region in which potential results 18466 // can be found. 18467 switch (ICE->getCastKind()) { 18468 case CK_NoOp: 18469 case CK_DerivedToBase: 18470 case CK_UncheckedDerivedToBase: { 18471 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18472 if (!Sub.isUsable()) 18473 return Sub; 18474 CXXCastPath Path(ICE->path()); 18475 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18476 ICE->getValueKind(), &Path); 18477 } 18478 18479 default: 18480 break; 18481 } 18482 break; 18483 } 18484 18485 default: 18486 break; 18487 } 18488 18489 // Can't traverse through this node. Nothing to do. 18490 return ExprEmpty(); 18491 } 18492 18493 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18494 // Check whether the operand is or contains an object of non-trivial C union 18495 // type. 18496 if (E->getType().isVolatileQualified() && 18497 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18498 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18499 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18500 Sema::NTCUC_LValueToRValueVolatile, 18501 NTCUK_Destruct|NTCUK_Copy); 18502 18503 // C++2a [basic.def.odr]p4: 18504 // [...] an expression of non-volatile-qualified non-class type to which 18505 // the lvalue-to-rvalue conversion is applied [...] 18506 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18507 return E; 18508 18509 ExprResult Result = 18510 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18511 if (Result.isInvalid()) 18512 return ExprError(); 18513 return Result.get() ? Result : E; 18514 } 18515 18516 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18517 Res = CorrectDelayedTyposInExpr(Res); 18518 18519 if (!Res.isUsable()) 18520 return Res; 18521 18522 // If a constant-expression is a reference to a variable where we delay 18523 // deciding whether it is an odr-use, just assume we will apply the 18524 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18525 // (a non-type template argument), we have special handling anyway. 18526 return CheckLValueToRValueConversionOperand(Res.get()); 18527 } 18528 18529 void Sema::CleanupVarDeclMarking() { 18530 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18531 // call. 18532 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18533 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18534 18535 for (Expr *E : LocalMaybeODRUseExprs) { 18536 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18537 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18538 DRE->getLocation(), *this); 18539 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18540 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18541 *this); 18542 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18543 for (VarDecl *VD : *FP) 18544 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18545 } else { 18546 llvm_unreachable("Unexpected expression"); 18547 } 18548 } 18549 18550 assert(MaybeODRUseExprs.empty() && 18551 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18552 } 18553 18554 static void DoMarkVarDeclReferenced( 18555 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18556 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18557 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18558 isa<FunctionParmPackExpr>(E)) && 18559 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18560 Var->setReferenced(); 18561 18562 if (Var->isInvalidDecl()) 18563 return; 18564 18565 auto *MSI = Var->getMemberSpecializationInfo(); 18566 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18567 : Var->getTemplateSpecializationKind(); 18568 18569 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18570 bool UsableInConstantExpr = 18571 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18572 18573 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18574 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18575 } 18576 18577 // C++20 [expr.const]p12: 18578 // A variable [...] is needed for constant evaluation if it is [...] a 18579 // variable whose name appears as a potentially constant evaluated 18580 // expression that is either a contexpr variable or is of non-volatile 18581 // const-qualified integral type or of reference type 18582 bool NeededForConstantEvaluation = 18583 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18584 18585 bool NeedDefinition = 18586 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18587 18588 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18589 "Can't instantiate a partial template specialization."); 18590 18591 // If this might be a member specialization of a static data member, check 18592 // the specialization is visible. We already did the checks for variable 18593 // template specializations when we created them. 18594 if (NeedDefinition && TSK != TSK_Undeclared && 18595 !isa<VarTemplateSpecializationDecl>(Var)) 18596 SemaRef.checkSpecializationVisibility(Loc, Var); 18597 18598 // Perform implicit instantiation of static data members, static data member 18599 // templates of class templates, and variable template specializations. Delay 18600 // instantiations of variable templates, except for those that could be used 18601 // in a constant expression. 18602 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18603 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18604 // instantiation declaration if a variable is usable in a constant 18605 // expression (among other cases). 18606 bool TryInstantiating = 18607 TSK == TSK_ImplicitInstantiation || 18608 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18609 18610 if (TryInstantiating) { 18611 SourceLocation PointOfInstantiation = 18612 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18613 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18614 if (FirstInstantiation) { 18615 PointOfInstantiation = Loc; 18616 if (MSI) 18617 MSI->setPointOfInstantiation(PointOfInstantiation); 18618 // FIXME: Notify listener. 18619 else 18620 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18621 } 18622 18623 if (UsableInConstantExpr) { 18624 // Do not defer instantiations of variables that could be used in a 18625 // constant expression. 18626 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18627 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18628 }); 18629 18630 // Re-set the member to trigger a recomputation of the dependence bits 18631 // for the expression. 18632 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18633 DRE->setDecl(DRE->getDecl()); 18634 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18635 ME->setMemberDecl(ME->getMemberDecl()); 18636 } else if (FirstInstantiation || 18637 isa<VarTemplateSpecializationDecl>(Var)) { 18638 // FIXME: For a specialization of a variable template, we don't 18639 // distinguish between "declaration and type implicitly instantiated" 18640 // and "implicit instantiation of definition requested", so we have 18641 // no direct way to avoid enqueueing the pending instantiation 18642 // multiple times. 18643 SemaRef.PendingInstantiations 18644 .push_back(std::make_pair(Var, PointOfInstantiation)); 18645 } 18646 } 18647 } 18648 18649 // C++2a [basic.def.odr]p4: 18650 // A variable x whose name appears as a potentially-evaluated expression e 18651 // is odr-used by e unless 18652 // -- x is a reference that is usable in constant expressions 18653 // -- x is a variable of non-reference type that is usable in constant 18654 // expressions and has no mutable subobjects [FIXME], and e is an 18655 // element of the set of potential results of an expression of 18656 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18657 // conversion is applied 18658 // -- x is a variable of non-reference type, and e is an element of the set 18659 // of potential results of a discarded-value expression to which the 18660 // lvalue-to-rvalue conversion is not applied [FIXME] 18661 // 18662 // We check the first part of the second bullet here, and 18663 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18664 // FIXME: To get the third bullet right, we need to delay this even for 18665 // variables that are not usable in constant expressions. 18666 18667 // If we already know this isn't an odr-use, there's nothing more to do. 18668 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18669 if (DRE->isNonOdrUse()) 18670 return; 18671 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18672 if (ME->isNonOdrUse()) 18673 return; 18674 18675 switch (OdrUse) { 18676 case OdrUseContext::None: 18677 assert((!E || isa<FunctionParmPackExpr>(E)) && 18678 "missing non-odr-use marking for unevaluated decl ref"); 18679 break; 18680 18681 case OdrUseContext::FormallyOdrUsed: 18682 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18683 // behavior. 18684 break; 18685 18686 case OdrUseContext::Used: 18687 // If we might later find that this expression isn't actually an odr-use, 18688 // delay the marking. 18689 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18690 SemaRef.MaybeODRUseExprs.insert(E); 18691 else 18692 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18693 break; 18694 18695 case OdrUseContext::Dependent: 18696 // If this is a dependent context, we don't need to mark variables as 18697 // odr-used, but we may still need to track them for lambda capture. 18698 // FIXME: Do we also need to do this inside dependent typeid expressions 18699 // (which are modeled as unevaluated at this point)? 18700 const bool RefersToEnclosingScope = 18701 (SemaRef.CurContext != Var->getDeclContext() && 18702 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18703 if (RefersToEnclosingScope) { 18704 LambdaScopeInfo *const LSI = 18705 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18706 if (LSI && (!LSI->CallOperator || 18707 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18708 // If a variable could potentially be odr-used, defer marking it so 18709 // until we finish analyzing the full expression for any 18710 // lvalue-to-rvalue 18711 // or discarded value conversions that would obviate odr-use. 18712 // Add it to the list of potential captures that will be analyzed 18713 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18714 // unless the variable is a reference that was initialized by a constant 18715 // expression (this will never need to be captured or odr-used). 18716 // 18717 // FIXME: We can simplify this a lot after implementing P0588R1. 18718 assert(E && "Capture variable should be used in an expression."); 18719 if (!Var->getType()->isReferenceType() || 18720 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18721 LSI->addPotentialCapture(E->IgnoreParens()); 18722 } 18723 } 18724 break; 18725 } 18726 } 18727 18728 /// Mark a variable referenced, and check whether it is odr-used 18729 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18730 /// used directly for normal expressions referring to VarDecl. 18731 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18732 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18733 } 18734 18735 static void 18736 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18737 bool MightBeOdrUse, 18738 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18739 if (SemaRef.isInOpenMPDeclareTargetContext()) 18740 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18741 18742 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18743 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18744 return; 18745 } 18746 18747 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18748 18749 // If this is a call to a method via a cast, also mark the method in the 18750 // derived class used in case codegen can devirtualize the call. 18751 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18752 if (!ME) 18753 return; 18754 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18755 if (!MD) 18756 return; 18757 // Only attempt to devirtualize if this is truly a virtual call. 18758 bool IsVirtualCall = MD->isVirtual() && 18759 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18760 if (!IsVirtualCall) 18761 return; 18762 18763 // If it's possible to devirtualize the call, mark the called function 18764 // referenced. 18765 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18766 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18767 if (DM) 18768 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18769 } 18770 18771 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18772 /// 18773 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18774 /// handled with care if the DeclRefExpr is not newly-created. 18775 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18776 // TODO: update this with DR# once a defect report is filed. 18777 // C++11 defect. The address of a pure member should not be an ODR use, even 18778 // if it's a qualified reference. 18779 bool OdrUse = true; 18780 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18781 if (Method->isVirtual() && 18782 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18783 OdrUse = false; 18784 18785 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18786 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18787 FD->isConsteval() && !RebuildingImmediateInvocation) 18788 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18789 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18790 RefsMinusAssignments); 18791 } 18792 18793 /// Perform reference-marking and odr-use handling for a MemberExpr. 18794 void Sema::MarkMemberReferenced(MemberExpr *E) { 18795 // C++11 [basic.def.odr]p2: 18796 // A non-overloaded function whose name appears as a potentially-evaluated 18797 // expression or a member of a set of candidate functions, if selected by 18798 // overload resolution when referred to from a potentially-evaluated 18799 // expression, is odr-used, unless it is a pure virtual function and its 18800 // name is not explicitly qualified. 18801 bool MightBeOdrUse = true; 18802 if (E->performsVirtualDispatch(getLangOpts())) { 18803 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18804 if (Method->isPure()) 18805 MightBeOdrUse = false; 18806 } 18807 SourceLocation Loc = 18808 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18809 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18810 RefsMinusAssignments); 18811 } 18812 18813 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18814 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18815 for (VarDecl *VD : *E) 18816 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18817 RefsMinusAssignments); 18818 } 18819 18820 /// Perform marking for a reference to an arbitrary declaration. It 18821 /// marks the declaration referenced, and performs odr-use checking for 18822 /// functions and variables. This method should not be used when building a 18823 /// normal expression which refers to a variable. 18824 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18825 bool MightBeOdrUse) { 18826 if (MightBeOdrUse) { 18827 if (auto *VD = dyn_cast<VarDecl>(D)) { 18828 MarkVariableReferenced(Loc, VD); 18829 return; 18830 } 18831 } 18832 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18833 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18834 return; 18835 } 18836 D->setReferenced(); 18837 } 18838 18839 namespace { 18840 // Mark all of the declarations used by a type as referenced. 18841 // FIXME: Not fully implemented yet! We need to have a better understanding 18842 // of when we're entering a context we should not recurse into. 18843 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18844 // TreeTransforms rebuilding the type in a new context. Rather than 18845 // duplicating the TreeTransform logic, we should consider reusing it here. 18846 // Currently that causes problems when rebuilding LambdaExprs. 18847 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18848 Sema &S; 18849 SourceLocation Loc; 18850 18851 public: 18852 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18853 18854 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18855 18856 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18857 }; 18858 } 18859 18860 bool MarkReferencedDecls::TraverseTemplateArgument( 18861 const TemplateArgument &Arg) { 18862 { 18863 // A non-type template argument is a constant-evaluated context. 18864 EnterExpressionEvaluationContext Evaluated( 18865 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18866 if (Arg.getKind() == TemplateArgument::Declaration) { 18867 if (Decl *D = Arg.getAsDecl()) 18868 S.MarkAnyDeclReferenced(Loc, D, true); 18869 } else if (Arg.getKind() == TemplateArgument::Expression) { 18870 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18871 } 18872 } 18873 18874 return Inherited::TraverseTemplateArgument(Arg); 18875 } 18876 18877 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18878 MarkReferencedDecls Marker(*this, Loc); 18879 Marker.TraverseType(T); 18880 } 18881 18882 namespace { 18883 /// Helper class that marks all of the declarations referenced by 18884 /// potentially-evaluated subexpressions as "referenced". 18885 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18886 public: 18887 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18888 bool SkipLocalVariables; 18889 ArrayRef<const Expr *> StopAt; 18890 18891 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 18892 ArrayRef<const Expr *> StopAt) 18893 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 18894 18895 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18896 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18897 } 18898 18899 void Visit(Expr *E) { 18900 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end()) 18901 return; 18902 Inherited::Visit(E); 18903 } 18904 18905 void VisitDeclRefExpr(DeclRefExpr *E) { 18906 // If we were asked not to visit local variables, don't. 18907 if (SkipLocalVariables) { 18908 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18909 if (VD->hasLocalStorage()) 18910 return; 18911 } 18912 18913 // FIXME: This can trigger the instantiation of the initializer of a 18914 // variable, which can cause the expression to become value-dependent 18915 // or error-dependent. Do we need to propagate the new dependence bits? 18916 S.MarkDeclRefReferenced(E); 18917 } 18918 18919 void VisitMemberExpr(MemberExpr *E) { 18920 S.MarkMemberReferenced(E); 18921 Visit(E->getBase()); 18922 } 18923 }; 18924 } // namespace 18925 18926 /// Mark any declarations that appear within this expression or any 18927 /// potentially-evaluated subexpressions as "referenced". 18928 /// 18929 /// \param SkipLocalVariables If true, don't mark local variables as 18930 /// 'referenced'. 18931 /// \param StopAt Subexpressions that we shouldn't recurse into. 18932 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18933 bool SkipLocalVariables, 18934 ArrayRef<const Expr*> StopAt) { 18935 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 18936 } 18937 18938 /// Emit a diagnostic when statements are reachable. 18939 /// FIXME: check for reachability even in expressions for which we don't build a 18940 /// CFG (eg, in the initializer of a global or in a constant expression). 18941 /// For example, 18942 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 18943 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 18944 const PartialDiagnostic &PD) { 18945 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18946 if (!FunctionScopes.empty()) 18947 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 18948 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18949 return true; 18950 } 18951 18952 // The initializer of a constexpr variable or of the first declaration of a 18953 // static data member is not syntactically a constant evaluated constant, 18954 // but nonetheless is always required to be a constant expression, so we 18955 // can skip diagnosing. 18956 // FIXME: Using the mangling context here is a hack. 18957 if (auto *VD = dyn_cast_or_null<VarDecl>( 18958 ExprEvalContexts.back().ManglingContextDecl)) { 18959 if (VD->isConstexpr() || 18960 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18961 return false; 18962 // FIXME: For any other kind of variable, we should build a CFG for its 18963 // initializer and check whether the context in question is reachable. 18964 } 18965 18966 Diag(Loc, PD); 18967 return true; 18968 } 18969 18970 /// Emit a diagnostic that describes an effect on the run-time behavior 18971 /// of the program being compiled. 18972 /// 18973 /// This routine emits the given diagnostic when the code currently being 18974 /// type-checked is "potentially evaluated", meaning that there is a 18975 /// possibility that the code will actually be executable. Code in sizeof() 18976 /// expressions, code used only during overload resolution, etc., are not 18977 /// potentially evaluated. This routine will suppress such diagnostics or, 18978 /// in the absolutely nutty case of potentially potentially evaluated 18979 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18980 /// later. 18981 /// 18982 /// This routine should be used for all diagnostics that describe the run-time 18983 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18984 /// Failure to do so will likely result in spurious diagnostics or failures 18985 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18986 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18987 const PartialDiagnostic &PD) { 18988 18989 if (ExprEvalContexts.back().isDiscardedStatementContext()) 18990 return false; 18991 18992 switch (ExprEvalContexts.back().Context) { 18993 case ExpressionEvaluationContext::Unevaluated: 18994 case ExpressionEvaluationContext::UnevaluatedList: 18995 case ExpressionEvaluationContext::UnevaluatedAbstract: 18996 case ExpressionEvaluationContext::DiscardedStatement: 18997 // The argument will never be evaluated, so don't complain. 18998 break; 18999 19000 case ExpressionEvaluationContext::ConstantEvaluated: 19001 case ExpressionEvaluationContext::ImmediateFunctionContext: 19002 // Relevant diagnostics should be produced by constant evaluation. 19003 break; 19004 19005 case ExpressionEvaluationContext::PotentiallyEvaluated: 19006 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 19007 return DiagIfReachable(Loc, Stmts, PD); 19008 } 19009 19010 return false; 19011 } 19012 19013 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 19014 const PartialDiagnostic &PD) { 19015 return DiagRuntimeBehavior( 19016 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 19017 } 19018 19019 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 19020 CallExpr *CE, FunctionDecl *FD) { 19021 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 19022 return false; 19023 19024 // If we're inside a decltype's expression, don't check for a valid return 19025 // type or construct temporaries until we know whether this is the last call. 19026 if (ExprEvalContexts.back().ExprContext == 19027 ExpressionEvaluationContextRecord::EK_Decltype) { 19028 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 19029 return false; 19030 } 19031 19032 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19033 FunctionDecl *FD; 19034 CallExpr *CE; 19035 19036 public: 19037 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19038 : FD(FD), CE(CE) { } 19039 19040 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19041 if (!FD) { 19042 S.Diag(Loc, diag::err_call_incomplete_return) 19043 << T << CE->getSourceRange(); 19044 return; 19045 } 19046 19047 S.Diag(Loc, diag::err_call_function_incomplete_return) 19048 << CE->getSourceRange() << FD << T; 19049 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19050 << FD->getDeclName(); 19051 } 19052 } Diagnoser(FD, CE); 19053 19054 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19055 return true; 19056 19057 return false; 19058 } 19059 19060 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19061 // will prevent this condition from triggering, which is what we want. 19062 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19063 SourceLocation Loc; 19064 19065 unsigned diagnostic = diag::warn_condition_is_assignment; 19066 bool IsOrAssign = false; 19067 19068 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19069 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19070 return; 19071 19072 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19073 19074 // Greylist some idioms by putting them into a warning subcategory. 19075 if (ObjCMessageExpr *ME 19076 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19077 Selector Sel = ME->getSelector(); 19078 19079 // self = [<foo> init...] 19080 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19081 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19082 19083 // <foo> = [<bar> nextObject] 19084 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19085 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19086 } 19087 19088 Loc = Op->getOperatorLoc(); 19089 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19090 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19091 return; 19092 19093 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19094 Loc = Op->getOperatorLoc(); 19095 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19096 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19097 else { 19098 // Not an assignment. 19099 return; 19100 } 19101 19102 Diag(Loc, diagnostic) << E->getSourceRange(); 19103 19104 SourceLocation Open = E->getBeginLoc(); 19105 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19106 Diag(Loc, diag::note_condition_assign_silence) 19107 << FixItHint::CreateInsertion(Open, "(") 19108 << FixItHint::CreateInsertion(Close, ")"); 19109 19110 if (IsOrAssign) 19111 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19112 << FixItHint::CreateReplacement(Loc, "!="); 19113 else 19114 Diag(Loc, diag::note_condition_assign_to_comparison) 19115 << FixItHint::CreateReplacement(Loc, "=="); 19116 } 19117 19118 /// Redundant parentheses over an equality comparison can indicate 19119 /// that the user intended an assignment used as condition. 19120 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19121 // Don't warn if the parens came from a macro. 19122 SourceLocation parenLoc = ParenE->getBeginLoc(); 19123 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19124 return; 19125 // Don't warn for dependent expressions. 19126 if (ParenE->isTypeDependent()) 19127 return; 19128 19129 Expr *E = ParenE->IgnoreParens(); 19130 19131 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19132 if (opE->getOpcode() == BO_EQ && 19133 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19134 == Expr::MLV_Valid) { 19135 SourceLocation Loc = opE->getOperatorLoc(); 19136 19137 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19138 SourceRange ParenERange = ParenE->getSourceRange(); 19139 Diag(Loc, diag::note_equality_comparison_silence) 19140 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19141 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19142 Diag(Loc, diag::note_equality_comparison_to_assign) 19143 << FixItHint::CreateReplacement(Loc, "="); 19144 } 19145 } 19146 19147 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19148 bool IsConstexpr) { 19149 DiagnoseAssignmentAsCondition(E); 19150 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19151 DiagnoseEqualityWithExtraParens(parenE); 19152 19153 ExprResult result = CheckPlaceholderExpr(E); 19154 if (result.isInvalid()) return ExprError(); 19155 E = result.get(); 19156 19157 if (!E->isTypeDependent()) { 19158 if (getLangOpts().CPlusPlus) 19159 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19160 19161 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19162 if (ERes.isInvalid()) 19163 return ExprError(); 19164 E = ERes.get(); 19165 19166 QualType T = E->getType(); 19167 if (!T->isScalarType()) { // C99 6.8.4.1p1 19168 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19169 << T << E->getSourceRange(); 19170 return ExprError(); 19171 } 19172 CheckBoolLikeConversion(E, Loc); 19173 } 19174 19175 return E; 19176 } 19177 19178 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19179 Expr *SubExpr, ConditionKind CK) { 19180 // Empty conditions are valid in for-statements. 19181 if (!SubExpr) 19182 return ConditionResult(); 19183 19184 ExprResult Cond; 19185 switch (CK) { 19186 case ConditionKind::Boolean: 19187 Cond = CheckBooleanCondition(Loc, SubExpr); 19188 break; 19189 19190 case ConditionKind::ConstexprIf: 19191 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19192 break; 19193 19194 case ConditionKind::Switch: 19195 Cond = CheckSwitchCondition(Loc, SubExpr); 19196 break; 19197 } 19198 if (Cond.isInvalid()) { 19199 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19200 {SubExpr}); 19201 if (!Cond.get()) 19202 return ConditionError(); 19203 } 19204 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19205 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19206 if (!FullExpr.get()) 19207 return ConditionError(); 19208 19209 return ConditionResult(*this, nullptr, FullExpr, 19210 CK == ConditionKind::ConstexprIf); 19211 } 19212 19213 namespace { 19214 /// A visitor for rebuilding a call to an __unknown_any expression 19215 /// to have an appropriate type. 19216 struct RebuildUnknownAnyFunction 19217 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19218 19219 Sema &S; 19220 19221 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19222 19223 ExprResult VisitStmt(Stmt *S) { 19224 llvm_unreachable("unexpected statement!"); 19225 } 19226 19227 ExprResult VisitExpr(Expr *E) { 19228 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19229 << E->getSourceRange(); 19230 return ExprError(); 19231 } 19232 19233 /// Rebuild an expression which simply semantically wraps another 19234 /// expression which it shares the type and value kind of. 19235 template <class T> ExprResult rebuildSugarExpr(T *E) { 19236 ExprResult SubResult = Visit(E->getSubExpr()); 19237 if (SubResult.isInvalid()) return ExprError(); 19238 19239 Expr *SubExpr = SubResult.get(); 19240 E->setSubExpr(SubExpr); 19241 E->setType(SubExpr->getType()); 19242 E->setValueKind(SubExpr->getValueKind()); 19243 assert(E->getObjectKind() == OK_Ordinary); 19244 return E; 19245 } 19246 19247 ExprResult VisitParenExpr(ParenExpr *E) { 19248 return rebuildSugarExpr(E); 19249 } 19250 19251 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19252 return rebuildSugarExpr(E); 19253 } 19254 19255 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19256 ExprResult SubResult = Visit(E->getSubExpr()); 19257 if (SubResult.isInvalid()) return ExprError(); 19258 19259 Expr *SubExpr = SubResult.get(); 19260 E->setSubExpr(SubExpr); 19261 E->setType(S.Context.getPointerType(SubExpr->getType())); 19262 assert(E->isPRValue()); 19263 assert(E->getObjectKind() == OK_Ordinary); 19264 return E; 19265 } 19266 19267 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19268 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19269 19270 E->setType(VD->getType()); 19271 19272 assert(E->isPRValue()); 19273 if (S.getLangOpts().CPlusPlus && 19274 !(isa<CXXMethodDecl>(VD) && 19275 cast<CXXMethodDecl>(VD)->isInstance())) 19276 E->setValueKind(VK_LValue); 19277 19278 return E; 19279 } 19280 19281 ExprResult VisitMemberExpr(MemberExpr *E) { 19282 return resolveDecl(E, E->getMemberDecl()); 19283 } 19284 19285 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19286 return resolveDecl(E, E->getDecl()); 19287 } 19288 }; 19289 } 19290 19291 /// Given a function expression of unknown-any type, try to rebuild it 19292 /// to have a function type. 19293 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19294 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19295 if (Result.isInvalid()) return ExprError(); 19296 return S.DefaultFunctionArrayConversion(Result.get()); 19297 } 19298 19299 namespace { 19300 /// A visitor for rebuilding an expression of type __unknown_anytype 19301 /// into one which resolves the type directly on the referring 19302 /// expression. Strict preservation of the original source 19303 /// structure is not a goal. 19304 struct RebuildUnknownAnyExpr 19305 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19306 19307 Sema &S; 19308 19309 /// The current destination type. 19310 QualType DestType; 19311 19312 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19313 : S(S), DestType(CastType) {} 19314 19315 ExprResult VisitStmt(Stmt *S) { 19316 llvm_unreachable("unexpected statement!"); 19317 } 19318 19319 ExprResult VisitExpr(Expr *E) { 19320 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19321 << E->getSourceRange(); 19322 return ExprError(); 19323 } 19324 19325 ExprResult VisitCallExpr(CallExpr *E); 19326 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19327 19328 /// Rebuild an expression which simply semantically wraps another 19329 /// expression which it shares the type and value kind of. 19330 template <class T> ExprResult rebuildSugarExpr(T *E) { 19331 ExprResult SubResult = Visit(E->getSubExpr()); 19332 if (SubResult.isInvalid()) return ExprError(); 19333 Expr *SubExpr = SubResult.get(); 19334 E->setSubExpr(SubExpr); 19335 E->setType(SubExpr->getType()); 19336 E->setValueKind(SubExpr->getValueKind()); 19337 assert(E->getObjectKind() == OK_Ordinary); 19338 return E; 19339 } 19340 19341 ExprResult VisitParenExpr(ParenExpr *E) { 19342 return rebuildSugarExpr(E); 19343 } 19344 19345 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19346 return rebuildSugarExpr(E); 19347 } 19348 19349 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19350 const PointerType *Ptr = DestType->getAs<PointerType>(); 19351 if (!Ptr) { 19352 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19353 << E->getSourceRange(); 19354 return ExprError(); 19355 } 19356 19357 if (isa<CallExpr>(E->getSubExpr())) { 19358 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19359 << E->getSourceRange(); 19360 return ExprError(); 19361 } 19362 19363 assert(E->isPRValue()); 19364 assert(E->getObjectKind() == OK_Ordinary); 19365 E->setType(DestType); 19366 19367 // Build the sub-expression as if it were an object of the pointee type. 19368 DestType = Ptr->getPointeeType(); 19369 ExprResult SubResult = Visit(E->getSubExpr()); 19370 if (SubResult.isInvalid()) return ExprError(); 19371 E->setSubExpr(SubResult.get()); 19372 return E; 19373 } 19374 19375 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19376 19377 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19378 19379 ExprResult VisitMemberExpr(MemberExpr *E) { 19380 return resolveDecl(E, E->getMemberDecl()); 19381 } 19382 19383 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19384 return resolveDecl(E, E->getDecl()); 19385 } 19386 }; 19387 } 19388 19389 /// Rebuilds a call expression which yielded __unknown_anytype. 19390 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19391 Expr *CalleeExpr = E->getCallee(); 19392 19393 enum FnKind { 19394 FK_MemberFunction, 19395 FK_FunctionPointer, 19396 FK_BlockPointer 19397 }; 19398 19399 FnKind Kind; 19400 QualType CalleeType = CalleeExpr->getType(); 19401 if (CalleeType == S.Context.BoundMemberTy) { 19402 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19403 Kind = FK_MemberFunction; 19404 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19405 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19406 CalleeType = Ptr->getPointeeType(); 19407 Kind = FK_FunctionPointer; 19408 } else { 19409 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19410 Kind = FK_BlockPointer; 19411 } 19412 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19413 19414 // Verify that this is a legal result type of a function. 19415 if (DestType->isArrayType() || DestType->isFunctionType()) { 19416 unsigned diagID = diag::err_func_returning_array_function; 19417 if (Kind == FK_BlockPointer) 19418 diagID = diag::err_block_returning_array_function; 19419 19420 S.Diag(E->getExprLoc(), diagID) 19421 << DestType->isFunctionType() << DestType; 19422 return ExprError(); 19423 } 19424 19425 // Otherwise, go ahead and set DestType as the call's result. 19426 E->setType(DestType.getNonLValueExprType(S.Context)); 19427 E->setValueKind(Expr::getValueKindForType(DestType)); 19428 assert(E->getObjectKind() == OK_Ordinary); 19429 19430 // Rebuild the function type, replacing the result type with DestType. 19431 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19432 if (Proto) { 19433 // __unknown_anytype(...) is a special case used by the debugger when 19434 // it has no idea what a function's signature is. 19435 // 19436 // We want to build this call essentially under the K&R 19437 // unprototyped rules, but making a FunctionNoProtoType in C++ 19438 // would foul up all sorts of assumptions. However, we cannot 19439 // simply pass all arguments as variadic arguments, nor can we 19440 // portably just call the function under a non-variadic type; see 19441 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19442 // However, it turns out that in practice it is generally safe to 19443 // call a function declared as "A foo(B,C,D);" under the prototype 19444 // "A foo(B,C,D,...);". The only known exception is with the 19445 // Windows ABI, where any variadic function is implicitly cdecl 19446 // regardless of its normal CC. Therefore we change the parameter 19447 // types to match the types of the arguments. 19448 // 19449 // This is a hack, but it is far superior to moving the 19450 // corresponding target-specific code from IR-gen to Sema/AST. 19451 19452 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19453 SmallVector<QualType, 8> ArgTypes; 19454 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19455 ArgTypes.reserve(E->getNumArgs()); 19456 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19457 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19458 } 19459 ParamTypes = ArgTypes; 19460 } 19461 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19462 Proto->getExtProtoInfo()); 19463 } else { 19464 DestType = S.Context.getFunctionNoProtoType(DestType, 19465 FnType->getExtInfo()); 19466 } 19467 19468 // Rebuild the appropriate pointer-to-function type. 19469 switch (Kind) { 19470 case FK_MemberFunction: 19471 // Nothing to do. 19472 break; 19473 19474 case FK_FunctionPointer: 19475 DestType = S.Context.getPointerType(DestType); 19476 break; 19477 19478 case FK_BlockPointer: 19479 DestType = S.Context.getBlockPointerType(DestType); 19480 break; 19481 } 19482 19483 // Finally, we can recurse. 19484 ExprResult CalleeResult = Visit(CalleeExpr); 19485 if (!CalleeResult.isUsable()) return ExprError(); 19486 E->setCallee(CalleeResult.get()); 19487 19488 // Bind a temporary if necessary. 19489 return S.MaybeBindToTemporary(E); 19490 } 19491 19492 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19493 // Verify that this is a legal result type of a call. 19494 if (DestType->isArrayType() || DestType->isFunctionType()) { 19495 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19496 << DestType->isFunctionType() << DestType; 19497 return ExprError(); 19498 } 19499 19500 // Rewrite the method result type if available. 19501 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19502 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19503 Method->setReturnType(DestType); 19504 } 19505 19506 // Change the type of the message. 19507 E->setType(DestType.getNonReferenceType()); 19508 E->setValueKind(Expr::getValueKindForType(DestType)); 19509 19510 return S.MaybeBindToTemporary(E); 19511 } 19512 19513 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19514 // The only case we should ever see here is a function-to-pointer decay. 19515 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19516 assert(E->isPRValue()); 19517 assert(E->getObjectKind() == OK_Ordinary); 19518 19519 E->setType(DestType); 19520 19521 // Rebuild the sub-expression as the pointee (function) type. 19522 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19523 19524 ExprResult Result = Visit(E->getSubExpr()); 19525 if (!Result.isUsable()) return ExprError(); 19526 19527 E->setSubExpr(Result.get()); 19528 return E; 19529 } else if (E->getCastKind() == CK_LValueToRValue) { 19530 assert(E->isPRValue()); 19531 assert(E->getObjectKind() == OK_Ordinary); 19532 19533 assert(isa<BlockPointerType>(E->getType())); 19534 19535 E->setType(DestType); 19536 19537 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19538 DestType = S.Context.getLValueReferenceType(DestType); 19539 19540 ExprResult Result = Visit(E->getSubExpr()); 19541 if (!Result.isUsable()) return ExprError(); 19542 19543 E->setSubExpr(Result.get()); 19544 return E; 19545 } else { 19546 llvm_unreachable("Unhandled cast type!"); 19547 } 19548 } 19549 19550 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19551 ExprValueKind ValueKind = VK_LValue; 19552 QualType Type = DestType; 19553 19554 // We know how to make this work for certain kinds of decls: 19555 19556 // - functions 19557 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19558 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19559 DestType = Ptr->getPointeeType(); 19560 ExprResult Result = resolveDecl(E, VD); 19561 if (Result.isInvalid()) return ExprError(); 19562 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19563 VK_PRValue); 19564 } 19565 19566 if (!Type->isFunctionType()) { 19567 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19568 << VD << E->getSourceRange(); 19569 return ExprError(); 19570 } 19571 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19572 // We must match the FunctionDecl's type to the hack introduced in 19573 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19574 // type. See the lengthy commentary in that routine. 19575 QualType FDT = FD->getType(); 19576 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19577 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19578 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19579 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19580 SourceLocation Loc = FD->getLocation(); 19581 FunctionDecl *NewFD = FunctionDecl::Create( 19582 S.Context, FD->getDeclContext(), Loc, Loc, 19583 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19584 SC_None, S.getCurFPFeatures().isFPConstrained(), 19585 false /*isInlineSpecified*/, FD->hasPrototype(), 19586 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19587 19588 if (FD->getQualifier()) 19589 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19590 19591 SmallVector<ParmVarDecl*, 16> Params; 19592 for (const auto &AI : FT->param_types()) { 19593 ParmVarDecl *Param = 19594 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19595 Param->setScopeInfo(0, Params.size()); 19596 Params.push_back(Param); 19597 } 19598 NewFD->setParams(Params); 19599 DRE->setDecl(NewFD); 19600 VD = DRE->getDecl(); 19601 } 19602 } 19603 19604 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19605 if (MD->isInstance()) { 19606 ValueKind = VK_PRValue; 19607 Type = S.Context.BoundMemberTy; 19608 } 19609 19610 // Function references aren't l-values in C. 19611 if (!S.getLangOpts().CPlusPlus) 19612 ValueKind = VK_PRValue; 19613 19614 // - variables 19615 } else if (isa<VarDecl>(VD)) { 19616 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19617 Type = RefTy->getPointeeType(); 19618 } else if (Type->isFunctionType()) { 19619 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19620 << VD << E->getSourceRange(); 19621 return ExprError(); 19622 } 19623 19624 // - nothing else 19625 } else { 19626 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19627 << VD << E->getSourceRange(); 19628 return ExprError(); 19629 } 19630 19631 // Modifying the declaration like this is friendly to IR-gen but 19632 // also really dangerous. 19633 VD->setType(DestType); 19634 E->setType(Type); 19635 E->setValueKind(ValueKind); 19636 return E; 19637 } 19638 19639 /// Check a cast of an unknown-any type. We intentionally only 19640 /// trigger this for C-style casts. 19641 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19642 Expr *CastExpr, CastKind &CastKind, 19643 ExprValueKind &VK, CXXCastPath &Path) { 19644 // The type we're casting to must be either void or complete. 19645 if (!CastType->isVoidType() && 19646 RequireCompleteType(TypeRange.getBegin(), CastType, 19647 diag::err_typecheck_cast_to_incomplete)) 19648 return ExprError(); 19649 19650 // Rewrite the casted expression from scratch. 19651 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19652 if (!result.isUsable()) return ExprError(); 19653 19654 CastExpr = result.get(); 19655 VK = CastExpr->getValueKind(); 19656 CastKind = CK_NoOp; 19657 19658 return CastExpr; 19659 } 19660 19661 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19662 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19663 } 19664 19665 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19666 Expr *arg, QualType ¶mType) { 19667 // If the syntactic form of the argument is not an explicit cast of 19668 // any sort, just do default argument promotion. 19669 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19670 if (!castArg) { 19671 ExprResult result = DefaultArgumentPromotion(arg); 19672 if (result.isInvalid()) return ExprError(); 19673 paramType = result.get()->getType(); 19674 return result; 19675 } 19676 19677 // Otherwise, use the type that was written in the explicit cast. 19678 assert(!arg->hasPlaceholderType()); 19679 paramType = castArg->getTypeAsWritten(); 19680 19681 // Copy-initialize a parameter of that type. 19682 InitializedEntity entity = 19683 InitializedEntity::InitializeParameter(Context, paramType, 19684 /*consumed*/ false); 19685 return PerformCopyInitialization(entity, callLoc, arg); 19686 } 19687 19688 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19689 Expr *orig = E; 19690 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19691 while (true) { 19692 E = E->IgnoreParenImpCasts(); 19693 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19694 E = call->getCallee(); 19695 diagID = diag::err_uncasted_call_of_unknown_any; 19696 } else { 19697 break; 19698 } 19699 } 19700 19701 SourceLocation loc; 19702 NamedDecl *d; 19703 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19704 loc = ref->getLocation(); 19705 d = ref->getDecl(); 19706 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19707 loc = mem->getMemberLoc(); 19708 d = mem->getMemberDecl(); 19709 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19710 diagID = diag::err_uncasted_call_of_unknown_any; 19711 loc = msg->getSelectorStartLoc(); 19712 d = msg->getMethodDecl(); 19713 if (!d) { 19714 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19715 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19716 << orig->getSourceRange(); 19717 return ExprError(); 19718 } 19719 } else { 19720 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19721 << E->getSourceRange(); 19722 return ExprError(); 19723 } 19724 19725 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19726 19727 // Never recoverable. 19728 return ExprError(); 19729 } 19730 19731 /// Check for operands with placeholder types and complain if found. 19732 /// Returns ExprError() if there was an error and no recovery was possible. 19733 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19734 if (!Context.isDependenceAllowed()) { 19735 // C cannot handle TypoExpr nodes on either side of a binop because it 19736 // doesn't handle dependent types properly, so make sure any TypoExprs have 19737 // been dealt with before checking the operands. 19738 ExprResult Result = CorrectDelayedTyposInExpr(E); 19739 if (!Result.isUsable()) return ExprError(); 19740 E = Result.get(); 19741 } 19742 19743 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19744 if (!placeholderType) return E; 19745 19746 switch (placeholderType->getKind()) { 19747 19748 // Overloaded expressions. 19749 case BuiltinType::Overload: { 19750 // Try to resolve a single function template specialization. 19751 // This is obligatory. 19752 ExprResult Result = E; 19753 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19754 return Result; 19755 19756 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19757 // leaves Result unchanged on failure. 19758 Result = E; 19759 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19760 return Result; 19761 19762 // If that failed, try to recover with a call. 19763 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19764 /*complain*/ true); 19765 return Result; 19766 } 19767 19768 // Bound member functions. 19769 case BuiltinType::BoundMember: { 19770 ExprResult result = E; 19771 const Expr *BME = E->IgnoreParens(); 19772 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19773 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19774 if (isa<CXXPseudoDestructorExpr>(BME)) { 19775 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19776 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19777 if (ME->getMemberNameInfo().getName().getNameKind() == 19778 DeclarationName::CXXDestructorName) 19779 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19780 } 19781 tryToRecoverWithCall(result, PD, 19782 /*complain*/ true); 19783 return result; 19784 } 19785 19786 // ARC unbridged casts. 19787 case BuiltinType::ARCUnbridgedCast: { 19788 Expr *realCast = stripARCUnbridgedCast(E); 19789 diagnoseARCUnbridgedCast(realCast); 19790 return realCast; 19791 } 19792 19793 // Expressions of unknown type. 19794 case BuiltinType::UnknownAny: 19795 return diagnoseUnknownAnyExpr(*this, E); 19796 19797 // Pseudo-objects. 19798 case BuiltinType::PseudoObject: 19799 return checkPseudoObjectRValue(E); 19800 19801 case BuiltinType::BuiltinFn: { 19802 // Accept __noop without parens by implicitly converting it to a call expr. 19803 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19804 if (DRE) { 19805 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19806 if (FD->getBuiltinID() == Builtin::BI__noop) { 19807 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19808 CK_BuiltinFnToFnPtr) 19809 .get(); 19810 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19811 VK_PRValue, SourceLocation(), 19812 FPOptionsOverride()); 19813 } 19814 } 19815 19816 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19817 return ExprError(); 19818 } 19819 19820 case BuiltinType::IncompleteMatrixIdx: 19821 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19822 ->getRowIdx() 19823 ->getBeginLoc(), 19824 diag::err_matrix_incomplete_index); 19825 return ExprError(); 19826 19827 // Expressions of unknown type. 19828 case BuiltinType::OMPArraySection: 19829 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19830 return ExprError(); 19831 19832 // Expressions of unknown type. 19833 case BuiltinType::OMPArrayShaping: 19834 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19835 19836 case BuiltinType::OMPIterator: 19837 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19838 19839 // Everything else should be impossible. 19840 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19841 case BuiltinType::Id: 19842 #include "clang/Basic/OpenCLImageTypes.def" 19843 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19844 case BuiltinType::Id: 19845 #include "clang/Basic/OpenCLExtensionTypes.def" 19846 #define SVE_TYPE(Name, Id, SingletonId) \ 19847 case BuiltinType::Id: 19848 #include "clang/Basic/AArch64SVEACLETypes.def" 19849 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19850 case BuiltinType::Id: 19851 #include "clang/Basic/PPCTypes.def" 19852 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19853 #include "clang/Basic/RISCVVTypes.def" 19854 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19855 #define PLACEHOLDER_TYPE(Id, SingletonId) 19856 #include "clang/AST/BuiltinTypes.def" 19857 break; 19858 } 19859 19860 llvm_unreachable("invalid placeholder type!"); 19861 } 19862 19863 bool Sema::CheckCaseExpression(Expr *E) { 19864 if (E->isTypeDependent()) 19865 return true; 19866 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19867 return E->getType()->isIntegralOrEnumerationType(); 19868 return false; 19869 } 19870 19871 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19872 ExprResult 19873 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19874 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19875 "Unknown Objective-C Boolean value!"); 19876 QualType BoolT = Context.ObjCBuiltinBoolTy; 19877 if (!Context.getBOOLDecl()) { 19878 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19879 Sema::LookupOrdinaryName); 19880 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19881 NamedDecl *ND = Result.getFoundDecl(); 19882 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19883 Context.setBOOLDecl(TD); 19884 } 19885 } 19886 if (Context.getBOOLDecl()) 19887 BoolT = Context.getBOOLType(); 19888 return new (Context) 19889 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19890 } 19891 19892 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19893 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19894 SourceLocation RParen) { 19895 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19896 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19897 return Spec.getPlatform() == Platform; 19898 }); 19899 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19900 // for "maccatalyst" if "maccatalyst" is not specified. 19901 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19902 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19903 return Spec.getPlatform() == "ios"; 19904 }); 19905 } 19906 if (Spec == AvailSpecs.end()) 19907 return None; 19908 return Spec->getVersion(); 19909 }; 19910 19911 VersionTuple Version; 19912 if (auto MaybeVersion = 19913 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19914 Version = *MaybeVersion; 19915 19916 // The use of `@available` in the enclosing context should be analyzed to 19917 // warn when it's used inappropriately (i.e. not if(@available)). 19918 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19919 Context->HasPotentialAvailabilityViolations = true; 19920 19921 return new (Context) 19922 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19923 } 19924 19925 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19926 ArrayRef<Expr *> SubExprs, QualType T) { 19927 if (!Context.getLangOpts().RecoveryAST) 19928 return ExprError(); 19929 19930 if (isSFINAEContext()) 19931 return ExprError(); 19932 19933 if (T.isNull() || T->isUndeducedType() || 19934 !Context.getLangOpts().RecoveryASTType) 19935 // We don't know the concrete type, fallback to dependent type. 19936 T = Context.DependentTy; 19937 19938 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19939 } 19940