1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/OperationKinds.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/Builtins.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/ADT/STLExtras.h" 50 #include "llvm/Support/ConvertUTF.h" 51 #include "llvm/Support/SaveAndRestore.h" 52 using namespace clang; 53 using namespace sema; 54 using llvm::RoundingMode; 55 56 /// Determine whether the use of this declaration is valid, without 57 /// emitting diagnostics. 58 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 59 // See if this is an auto-typed variable whose initializer we are parsing. 60 if (ParsingInitForAutoVars.count(D)) 61 return false; 62 63 // See if this is a deleted function. 64 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 65 if (FD->isDeleted()) 66 return false; 67 68 // If the function has a deduced return type, and we can't deduce it, 69 // then we can't use it either. 70 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 71 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 72 return false; 73 74 // See if this is an aligned allocation/deallocation function that is 75 // unavailable. 76 if (TreatUnavailableAsInvalid && 77 isUnavailableAlignedAllocationFunction(*FD)) 78 return false; 79 } 80 81 // See if this function is unavailable. 82 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 83 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 84 return false; 85 86 return true; 87 } 88 89 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 90 // Warn if this is used but marked unused. 91 if (const auto *A = D->getAttr<UnusedAttr>()) { 92 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 93 // should diagnose them. 94 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 95 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 96 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 97 if (DC && !DC->hasAttr<UnusedAttr>()) 98 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 99 } 100 } 101 } 102 103 /// Emit a note explaining that this function is deleted. 104 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 105 assert(Decl && Decl->isDeleted()); 106 107 if (Decl->isDefaulted()) { 108 // If the method was explicitly defaulted, point at that declaration. 109 if (!Decl->isImplicit()) 110 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 111 112 // Try to diagnose why this special member function was implicitly 113 // deleted. This might fail, if that reason no longer applies. 114 DiagnoseDeletedDefaultedFunction(Decl); 115 return; 116 } 117 118 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 119 if (Ctor && Ctor->isInheritingConstructor()) 120 return NoteDeletedInheritingConstructor(Ctor); 121 122 Diag(Decl->getLocation(), diag::note_availability_specified_here) 123 << Decl << 1; 124 } 125 126 /// Determine whether a FunctionDecl was ever declared with an 127 /// explicit storage class. 128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 129 for (auto I : D->redecls()) { 130 if (I->getStorageClass() != SC_None) 131 return true; 132 } 133 return false; 134 } 135 136 /// Check whether we're in an extern inline function and referring to a 137 /// variable or function with internal linkage (C11 6.7.4p3). 138 /// 139 /// This is only a warning because we used to silently accept this code, but 140 /// in many cases it will not behave correctly. This is not enabled in C++ mode 141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 142 /// and so while there may still be user mistakes, most of the time we can't 143 /// prove that there are errors. 144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 145 const NamedDecl *D, 146 SourceLocation Loc) { 147 // This is disabled under C++; there are too many ways for this to fire in 148 // contexts where the warning is a false positive, or where it is technically 149 // correct but benign. 150 if (S.getLangOpts().CPlusPlus) 151 return; 152 153 // Check if this is an inlined function or method. 154 FunctionDecl *Current = S.getCurFunctionDecl(); 155 if (!Current) 156 return; 157 if (!Current->isInlined()) 158 return; 159 if (!Current->isExternallyVisible()) 160 return; 161 162 // Check if the decl has internal linkage. 163 if (D->getFormalLinkage() != InternalLinkage) 164 return; 165 166 // Downgrade from ExtWarn to Extension if 167 // (1) the supposedly external inline function is in the main file, 168 // and probably won't be included anywhere else. 169 // (2) the thing we're referencing is a pure function. 170 // (3) the thing we're referencing is another inline function. 171 // This last can give us false negatives, but it's better than warning on 172 // wrappers for simple C library functions. 173 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 174 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 175 if (!DowngradeWarning && UsedFn) 176 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 177 178 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 179 : diag::ext_internal_in_extern_inline) 180 << /*IsVar=*/!UsedFn << D; 181 182 S.MaybeSuggestAddingStaticToDecl(Current); 183 184 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 185 << D; 186 } 187 188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 189 const FunctionDecl *First = Cur->getFirstDecl(); 190 191 // Suggest "static" on the function, if possible. 192 if (!hasAnyExplicitStorageClass(First)) { 193 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 194 Diag(DeclBegin, diag::note_convert_inline_to_static) 195 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 196 } 197 } 198 199 /// Determine whether the use of this declaration is valid, and 200 /// emit any corresponding diagnostics. 201 /// 202 /// This routine diagnoses various problems with referencing 203 /// declarations that can occur when using a declaration. For example, 204 /// it might warn if a deprecated or unavailable declaration is being 205 /// used, or produce an error (and return true) if a C++0x deleted 206 /// function is being used. 207 /// 208 /// \returns true if there was an error (this declaration cannot be 209 /// referenced), false otherwise. 210 /// 211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 212 const ObjCInterfaceDecl *UnknownObjCClass, 213 bool ObjCPropertyAccess, 214 bool AvoidPartialAvailabilityChecks, 215 ObjCInterfaceDecl *ClassReceiver) { 216 SourceLocation Loc = Locs.front(); 217 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 218 // If there were any diagnostics suppressed by template argument deduction, 219 // emit them now. 220 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 221 if (Pos != SuppressedDiagnostics.end()) { 222 for (const PartialDiagnosticAt &Suppressed : Pos->second) 223 Diag(Suppressed.first, Suppressed.second); 224 225 // Clear out the list of suppressed diagnostics, so that we don't emit 226 // them again for this specialization. However, we don't obsolete this 227 // entry from the table, because we want to avoid ever emitting these 228 // diagnostics again. 229 Pos->second.clear(); 230 } 231 232 // C++ [basic.start.main]p3: 233 // The function 'main' shall not be used within a program. 234 if (cast<FunctionDecl>(D)->isMain()) 235 Diag(Loc, diag::ext_main_used); 236 237 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 238 } 239 240 // See if this is an auto-typed variable whose initializer we are parsing. 241 if (ParsingInitForAutoVars.count(D)) { 242 if (isa<BindingDecl>(D)) { 243 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 244 << D->getDeclName(); 245 } else { 246 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 247 << D->getDeclName() << cast<VarDecl>(D)->getType(); 248 } 249 return true; 250 } 251 252 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 253 // See if this is a deleted function. 254 if (FD->isDeleted()) { 255 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 256 if (Ctor && Ctor->isInheritingConstructor()) 257 Diag(Loc, diag::err_deleted_inherited_ctor_use) 258 << Ctor->getParent() 259 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 260 else 261 Diag(Loc, diag::err_deleted_function_use); 262 NoteDeletedFunction(FD); 263 return true; 264 } 265 266 // [expr.prim.id]p4 267 // A program that refers explicitly or implicitly to a function with a 268 // trailing requires-clause whose constraint-expression is not satisfied, 269 // other than to declare it, is ill-formed. [...] 270 // 271 // See if this is a function with constraints that need to be satisfied. 272 // Check this before deducing the return type, as it might instantiate the 273 // definition. 274 if (FD->getTrailingRequiresClause()) { 275 ConstraintSatisfaction Satisfaction; 276 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 277 // A diagnostic will have already been generated (non-constant 278 // constraint expression, for example) 279 return true; 280 if (!Satisfaction.IsSatisfied) { 281 Diag(Loc, 282 diag::err_reference_to_function_with_unsatisfied_constraints) 283 << D; 284 DiagnoseUnsatisfiedConstraint(Satisfaction); 285 return true; 286 } 287 } 288 289 // If the function has a deduced return type, and we can't deduce it, 290 // then we can't use it either. 291 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 292 DeduceReturnType(FD, Loc)) 293 return true; 294 295 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 296 return true; 297 298 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 299 return true; 300 } 301 302 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 303 // Lambdas are only default-constructible or assignable in C++2a onwards. 304 if (MD->getParent()->isLambda() && 305 ((isa<CXXConstructorDecl>(MD) && 306 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 307 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 308 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 309 << !isa<CXXConstructorDecl>(MD); 310 } 311 } 312 313 auto getReferencedObjCProp = [](const NamedDecl *D) -> 314 const ObjCPropertyDecl * { 315 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 316 return MD->findPropertyDecl(); 317 return nullptr; 318 }; 319 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 320 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 321 return true; 322 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 323 return true; 324 } 325 326 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 327 // Only the variables omp_in and omp_out are allowed in the combiner. 328 // Only the variables omp_priv and omp_orig are allowed in the 329 // initializer-clause. 330 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 331 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 332 isa<VarDecl>(D)) { 333 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 334 << getCurFunction()->HasOMPDeclareReductionCombiner; 335 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 336 return true; 337 } 338 339 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 340 // List-items in map clauses on this construct may only refer to the declared 341 // variable var and entities that could be referenced by a procedure defined 342 // at the same location 343 if (LangOpts.OpenMP && isa<VarDecl>(D) && 344 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 346 << getOpenMPDeclareMapperVarName(); 347 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 348 return true; 349 } 350 351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 352 AvoidPartialAvailabilityChecks, ClassReceiver); 353 354 DiagnoseUnusedOfDecl(*this, D, Loc); 355 356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 357 358 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 359 if (auto *VD = dyn_cast<ValueDecl>(D)) 360 checkDeviceDecl(VD, Loc); 361 362 if (!Context.getTargetInfo().isTLSSupported()) 363 if (const auto *VD = dyn_cast<VarDecl>(D)) 364 if (VD->getTLSKind() != VarDecl::TLS_None) 365 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 366 } 367 368 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 369 !isUnevaluatedContext()) { 370 // C++ [expr.prim.req.nested] p3 371 // A local parameter shall only appear as an unevaluated operand 372 // (Clause 8) within the constraint-expression. 373 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 374 << D; 375 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 376 return true; 377 } 378 379 return false; 380 } 381 382 /// DiagnoseSentinelCalls - This routine checks whether a call or 383 /// message-send is to a declaration with the sentinel attribute, and 384 /// if so, it checks that the requirements of the sentinel are 385 /// satisfied. 386 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 387 ArrayRef<Expr *> Args) { 388 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 389 if (!attr) 390 return; 391 392 // The number of formal parameters of the declaration. 393 unsigned numFormalParams; 394 395 // The kind of declaration. This is also an index into a %select in 396 // the diagnostic. 397 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 398 399 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 400 numFormalParams = MD->param_size(); 401 calleeType = CT_Method; 402 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 403 numFormalParams = FD->param_size(); 404 calleeType = CT_Function; 405 } else if (isa<VarDecl>(D)) { 406 QualType type = cast<ValueDecl>(D)->getType(); 407 const FunctionType *fn = nullptr; 408 if (const PointerType *ptr = type->getAs<PointerType>()) { 409 fn = ptr->getPointeeType()->getAs<FunctionType>(); 410 if (!fn) return; 411 calleeType = CT_Function; 412 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 413 fn = ptr->getPointeeType()->castAs<FunctionType>(); 414 calleeType = CT_Block; 415 } else { 416 return; 417 } 418 419 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 420 numFormalParams = proto->getNumParams(); 421 } else { 422 numFormalParams = 0; 423 } 424 } else { 425 return; 426 } 427 428 // "nullPos" is the number of formal parameters at the end which 429 // effectively count as part of the variadic arguments. This is 430 // useful if you would prefer to not have *any* formal parameters, 431 // but the language forces you to have at least one. 432 unsigned nullPos = attr->getNullPos(); 433 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 434 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 435 436 // The number of arguments which should follow the sentinel. 437 unsigned numArgsAfterSentinel = attr->getSentinel(); 438 439 // If there aren't enough arguments for all the formal parameters, 440 // the sentinel, and the args after the sentinel, complain. 441 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 442 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 443 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 444 return; 445 } 446 447 // Otherwise, find the sentinel expression. 448 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 449 if (!sentinelExpr) return; 450 if (sentinelExpr->isValueDependent()) return; 451 if (Context.isSentinelNullExpr(sentinelExpr)) return; 452 453 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 454 // or 'NULL' if those are actually defined in the context. Only use 455 // 'nil' for ObjC methods, where it's much more likely that the 456 // variadic arguments form a list of object pointers. 457 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 458 std::string NullValue; 459 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 460 NullValue = "nil"; 461 else if (getLangOpts().CPlusPlus11) 462 NullValue = "nullptr"; 463 else if (PP.isMacroDefined("NULL")) 464 NullValue = "NULL"; 465 else 466 NullValue = "(void*) 0"; 467 468 if (MissingNilLoc.isInvalid()) 469 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 470 else 471 Diag(MissingNilLoc, diag::warn_missing_sentinel) 472 << int(calleeType) 473 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 474 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 475 } 476 477 SourceRange Sema::getExprRange(Expr *E) const { 478 return E ? E->getSourceRange() : SourceRange(); 479 } 480 481 //===----------------------------------------------------------------------===// 482 // Standard Promotions and Conversions 483 //===----------------------------------------------------------------------===// 484 485 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 486 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 487 // Handle any placeholder expressions which made it here. 488 if (E->getType()->isPlaceholderType()) { 489 ExprResult result = CheckPlaceholderExpr(E); 490 if (result.isInvalid()) return ExprError(); 491 E = result.get(); 492 } 493 494 QualType Ty = E->getType(); 495 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 496 497 if (Ty->isFunctionType()) { 498 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 499 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 500 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 501 return ExprError(); 502 503 E = ImpCastExprToType(E, Context.getPointerType(Ty), 504 CK_FunctionToPointerDecay).get(); 505 } else if (Ty->isArrayType()) { 506 // In C90 mode, arrays only promote to pointers if the array expression is 507 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 508 // type 'array of type' is converted to an expression that has type 'pointer 509 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 510 // that has type 'array of type' ...". The relevant change is "an lvalue" 511 // (C90) to "an expression" (C99). 512 // 513 // C++ 4.2p1: 514 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 515 // T" can be converted to an rvalue of type "pointer to T". 516 // 517 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 518 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 519 CK_ArrayToPointerDecay).get(); 520 } 521 return E; 522 } 523 524 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 525 // Check to see if we are dereferencing a null pointer. If so, 526 // and if not volatile-qualified, this is undefined behavior that the 527 // optimizer will delete, so warn about it. People sometimes try to use this 528 // to get a deterministic trap and are surprised by clang's behavior. This 529 // only handles the pattern "*null", which is a very syntactic check. 530 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 531 if (UO && UO->getOpcode() == UO_Deref && 532 UO->getSubExpr()->getType()->isPointerType()) { 533 const LangAS AS = 534 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 535 if ((!isTargetAddressSpace(AS) || 536 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 537 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 538 S.Context, Expr::NPC_ValueDependentIsNotNull) && 539 !UO->getType().isVolatileQualified()) { 540 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 541 S.PDiag(diag::warn_indirection_through_null) 542 << UO->getSubExpr()->getSourceRange()); 543 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 544 S.PDiag(diag::note_indirection_through_null)); 545 } 546 } 547 } 548 549 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 550 SourceLocation AssignLoc, 551 const Expr* RHS) { 552 const ObjCIvarDecl *IV = OIRE->getDecl(); 553 if (!IV) 554 return; 555 556 DeclarationName MemberName = IV->getDeclName(); 557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 558 if (!Member || !Member->isStr("isa")) 559 return; 560 561 const Expr *Base = OIRE->getBase(); 562 QualType BaseType = Base->getType(); 563 if (OIRE->isArrow()) 564 BaseType = BaseType->getPointeeType(); 565 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 566 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 567 ObjCInterfaceDecl *ClassDeclared = nullptr; 568 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 569 if (!ClassDeclared->getSuperClass() 570 && (*ClassDeclared->ivar_begin()) == IV) { 571 if (RHS) { 572 NamedDecl *ObjectSetClass = 573 S.LookupSingleName(S.TUScope, 574 &S.Context.Idents.get("object_setClass"), 575 SourceLocation(), S.LookupOrdinaryName); 576 if (ObjectSetClass) { 577 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 580 "object_setClass(") 581 << FixItHint::CreateReplacement( 582 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 583 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 584 } 585 else 586 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 587 } else { 588 NamedDecl *ObjectGetClass = 589 S.LookupSingleName(S.TUScope, 590 &S.Context.Idents.get("object_getClass"), 591 SourceLocation(), S.LookupOrdinaryName); 592 if (ObjectGetClass) 593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 595 "object_getClass(") 596 << FixItHint::CreateReplacement( 597 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 598 else 599 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 600 } 601 S.Diag(IV->getLocation(), diag::note_ivar_decl); 602 } 603 } 604 } 605 606 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 607 // Handle any placeholder expressions which made it here. 608 if (E->getType()->isPlaceholderType()) { 609 ExprResult result = CheckPlaceholderExpr(E); 610 if (result.isInvalid()) return ExprError(); 611 E = result.get(); 612 } 613 614 // C++ [conv.lval]p1: 615 // A glvalue of a non-function, non-array type T can be 616 // converted to a prvalue. 617 if (!E->isGLValue()) return E; 618 619 QualType T = E->getType(); 620 assert(!T.isNull() && "r-value conversion on typeless expression?"); 621 622 // lvalue-to-rvalue conversion cannot be applied to function or array types. 623 if (T->isFunctionType() || T->isArrayType()) 624 return E; 625 626 // We don't want to throw lvalue-to-rvalue casts on top of 627 // expressions of certain types in C++. 628 if (getLangOpts().CPlusPlus && 629 (E->getType() == Context.OverloadTy || 630 T->isDependentType() || 631 T->isRecordType())) 632 return E; 633 634 // The C standard is actually really unclear on this point, and 635 // DR106 tells us what the result should be but not why. It's 636 // generally best to say that void types just doesn't undergo 637 // lvalue-to-rvalue at all. Note that expressions of unqualified 638 // 'void' type are never l-values, but qualified void can be. 639 if (T->isVoidType()) 640 return E; 641 642 // OpenCL usually rejects direct accesses to values of 'half' type. 643 if (getLangOpts().OpenCL && 644 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 645 T->isHalfType()) { 646 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 647 << 0 << T; 648 return ExprError(); 649 } 650 651 CheckForNullPointerDereference(*this, E); 652 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 653 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 654 &Context.Idents.get("object_getClass"), 655 SourceLocation(), LookupOrdinaryName); 656 if (ObjectGetClass) 657 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 658 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 659 << FixItHint::CreateReplacement( 660 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 661 else 662 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 663 } 664 else if (const ObjCIvarRefExpr *OIRE = 665 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 666 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 667 668 // C++ [conv.lval]p1: 669 // [...] If T is a non-class type, the type of the prvalue is the 670 // cv-unqualified version of T. Otherwise, the type of the 671 // rvalue is T. 672 // 673 // C99 6.3.2.1p2: 674 // If the lvalue has qualified type, the value has the unqualified 675 // version of the type of the lvalue; otherwise, the value has the 676 // type of the lvalue. 677 if (T.hasQualifiers()) 678 T = T.getUnqualifiedType(); 679 680 // Under the MS ABI, lock down the inheritance model now. 681 if (T->isMemberPointerType() && 682 Context.getTargetInfo().getCXXABI().isMicrosoft()) 683 (void)isCompleteType(E->getExprLoc(), T); 684 685 ExprResult Res = CheckLValueToRValueConversionOperand(E); 686 if (Res.isInvalid()) 687 return Res; 688 E = Res.get(); 689 690 // Loading a __weak object implicitly retains the value, so we need a cleanup to 691 // balance that. 692 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 693 Cleanup.setExprNeedsCleanups(true); 694 695 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 696 Cleanup.setExprNeedsCleanups(true); 697 698 // C++ [conv.lval]p3: 699 // If T is cv std::nullptr_t, the result is a null pointer constant. 700 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 701 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, 702 CurFPFeatureOverrides()); 703 704 // C11 6.3.2.1p2: 705 // ... if the lvalue has atomic type, the value has the non-atomic version 706 // of the type of the lvalue ... 707 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 708 T = Atomic->getValueType().getUnqualifiedType(); 709 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 710 nullptr, VK_RValue, FPOptionsOverride()); 711 } 712 713 return Res; 714 } 715 716 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 717 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 718 if (Res.isInvalid()) 719 return ExprError(); 720 Res = DefaultLvalueConversion(Res.get()); 721 if (Res.isInvalid()) 722 return ExprError(); 723 return Res; 724 } 725 726 /// CallExprUnaryConversions - a special case of an unary conversion 727 /// performed on a function designator of a call expression. 728 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 729 QualType Ty = E->getType(); 730 ExprResult Res = E; 731 // Only do implicit cast for a function type, but not for a pointer 732 // to function type. 733 if (Ty->isFunctionType()) { 734 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 735 CK_FunctionToPointerDecay); 736 if (Res.isInvalid()) 737 return ExprError(); 738 } 739 Res = DefaultLvalueConversion(Res.get()); 740 if (Res.isInvalid()) 741 return ExprError(); 742 return Res.get(); 743 } 744 745 /// UsualUnaryConversions - Performs various conversions that are common to most 746 /// operators (C99 6.3). The conversions of array and function types are 747 /// sometimes suppressed. For example, the array->pointer conversion doesn't 748 /// apply if the array is an argument to the sizeof or address (&) operators. 749 /// In these instances, this routine should *not* be called. 750 ExprResult Sema::UsualUnaryConversions(Expr *E) { 751 // First, convert to an r-value. 752 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 753 if (Res.isInvalid()) 754 return ExprError(); 755 E = Res.get(); 756 757 QualType Ty = E->getType(); 758 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 759 760 // Half FP have to be promoted to float unless it is natively supported 761 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 762 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 763 764 // Try to perform integral promotions if the object has a theoretically 765 // promotable type. 766 if (Ty->isIntegralOrUnscopedEnumerationType()) { 767 // C99 6.3.1.1p2: 768 // 769 // The following may be used in an expression wherever an int or 770 // unsigned int may be used: 771 // - an object or expression with an integer type whose integer 772 // conversion rank is less than or equal to the rank of int 773 // and unsigned int. 774 // - A bit-field of type _Bool, int, signed int, or unsigned int. 775 // 776 // If an int can represent all values of the original type, the 777 // value is converted to an int; otherwise, it is converted to an 778 // unsigned int. These are called the integer promotions. All 779 // other types are unchanged by the integer promotions. 780 781 QualType PTy = Context.isPromotableBitField(E); 782 if (!PTy.isNull()) { 783 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 784 return E; 785 } 786 if (Ty->isPromotableIntegerType()) { 787 QualType PT = Context.getPromotedIntegerType(Ty); 788 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 789 return E; 790 } 791 } 792 return E; 793 } 794 795 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 796 /// do not have a prototype. Arguments that have type float or __fp16 797 /// are promoted to double. All other argument types are converted by 798 /// UsualUnaryConversions(). 799 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 800 QualType Ty = E->getType(); 801 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 802 803 ExprResult Res = UsualUnaryConversions(E); 804 if (Res.isInvalid()) 805 return ExprError(); 806 E = Res.get(); 807 808 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 809 // promote to double. 810 // Note that default argument promotion applies only to float (and 811 // half/fp16); it does not apply to _Float16. 812 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 813 if (BTy && (BTy->getKind() == BuiltinType::Half || 814 BTy->getKind() == BuiltinType::Float)) { 815 if (getLangOpts().OpenCL && 816 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 817 if (BTy->getKind() == BuiltinType::Half) { 818 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 819 } 820 } else { 821 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 822 } 823 } 824 if (BTy && 825 getLangOpts().getExtendIntArgs() == 826 LangOptions::ExtendArgsKind::ExtendTo64 && 827 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 828 Context.getTypeSizeInChars(BTy) < 829 Context.getTypeSizeInChars(Context.LongLongTy)) { 830 E = (Ty->isUnsignedIntegerType()) 831 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 832 .get() 833 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 834 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 835 "Unexpected typesize for LongLongTy"); 836 } 837 838 // C++ performs lvalue-to-rvalue conversion as a default argument 839 // promotion, even on class types, but note: 840 // C++11 [conv.lval]p2: 841 // When an lvalue-to-rvalue conversion occurs in an unevaluated 842 // operand or a subexpression thereof the value contained in the 843 // referenced object is not accessed. Otherwise, if the glvalue 844 // has a class type, the conversion copy-initializes a temporary 845 // of type T from the glvalue and the result of the conversion 846 // is a prvalue for the temporary. 847 // FIXME: add some way to gate this entire thing for correctness in 848 // potentially potentially evaluated contexts. 849 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 850 ExprResult Temp = PerformCopyInitialization( 851 InitializedEntity::InitializeTemporary(E->getType()), 852 E->getExprLoc(), E); 853 if (Temp.isInvalid()) 854 return ExprError(); 855 E = Temp.get(); 856 } 857 858 return E; 859 } 860 861 /// Determine the degree of POD-ness for an expression. 862 /// Incomplete types are considered POD, since this check can be performed 863 /// when we're in an unevaluated context. 864 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 865 if (Ty->isIncompleteType()) { 866 // C++11 [expr.call]p7: 867 // After these conversions, if the argument does not have arithmetic, 868 // enumeration, pointer, pointer to member, or class type, the program 869 // is ill-formed. 870 // 871 // Since we've already performed array-to-pointer and function-to-pointer 872 // decay, the only such type in C++ is cv void. This also handles 873 // initializer lists as variadic arguments. 874 if (Ty->isVoidType()) 875 return VAK_Invalid; 876 877 if (Ty->isObjCObjectType()) 878 return VAK_Invalid; 879 return VAK_Valid; 880 } 881 882 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 883 return VAK_Invalid; 884 885 if (Ty.isCXX98PODType(Context)) 886 return VAK_Valid; 887 888 // C++11 [expr.call]p7: 889 // Passing a potentially-evaluated argument of class type (Clause 9) 890 // having a non-trivial copy constructor, a non-trivial move constructor, 891 // or a non-trivial destructor, with no corresponding parameter, 892 // is conditionally-supported with implementation-defined semantics. 893 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 894 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 895 if (!Record->hasNonTrivialCopyConstructor() && 896 !Record->hasNonTrivialMoveConstructor() && 897 !Record->hasNonTrivialDestructor()) 898 return VAK_ValidInCXX11; 899 900 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 901 return VAK_Valid; 902 903 if (Ty->isObjCObjectType()) 904 return VAK_Invalid; 905 906 if (getLangOpts().MSVCCompat) 907 return VAK_MSVCUndefined; 908 909 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 910 // permitted to reject them. We should consider doing so. 911 return VAK_Undefined; 912 } 913 914 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 915 // Don't allow one to pass an Objective-C interface to a vararg. 916 const QualType &Ty = E->getType(); 917 VarArgKind VAK = isValidVarArgType(Ty); 918 919 // Complain about passing non-POD types through varargs. 920 switch (VAK) { 921 case VAK_ValidInCXX11: 922 DiagRuntimeBehavior( 923 E->getBeginLoc(), nullptr, 924 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 925 LLVM_FALLTHROUGH; 926 case VAK_Valid: 927 if (Ty->isRecordType()) { 928 // This is unlikely to be what the user intended. If the class has a 929 // 'c_str' member function, the user probably meant to call that. 930 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 931 PDiag(diag::warn_pass_class_arg_to_vararg) 932 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 933 } 934 break; 935 936 case VAK_Undefined: 937 case VAK_MSVCUndefined: 938 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 939 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 940 << getLangOpts().CPlusPlus11 << Ty << CT); 941 break; 942 943 case VAK_Invalid: 944 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 945 Diag(E->getBeginLoc(), 946 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 947 << Ty << CT; 948 else if (Ty->isObjCObjectType()) 949 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 950 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 951 << Ty << CT); 952 else 953 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 954 << isa<InitListExpr>(E) << Ty << CT; 955 break; 956 } 957 } 958 959 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 960 /// will create a trap if the resulting type is not a POD type. 961 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 962 FunctionDecl *FDecl) { 963 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 964 // Strip the unbridged-cast placeholder expression off, if applicable. 965 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 966 (CT == VariadicMethod || 967 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 968 E = stripARCUnbridgedCast(E); 969 970 // Otherwise, do normal placeholder checking. 971 } else { 972 ExprResult ExprRes = CheckPlaceholderExpr(E); 973 if (ExprRes.isInvalid()) 974 return ExprError(); 975 E = ExprRes.get(); 976 } 977 } 978 979 ExprResult ExprRes = DefaultArgumentPromotion(E); 980 if (ExprRes.isInvalid()) 981 return ExprError(); 982 983 // Copy blocks to the heap. 984 if (ExprRes.get()->getType()->isBlockPointerType()) 985 maybeExtendBlockObject(ExprRes); 986 987 E = ExprRes.get(); 988 989 // Diagnostics regarding non-POD argument types are 990 // emitted along with format string checking in Sema::CheckFunctionCall(). 991 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 992 // Turn this into a trap. 993 CXXScopeSpec SS; 994 SourceLocation TemplateKWLoc; 995 UnqualifiedId Name; 996 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 997 E->getBeginLoc()); 998 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 999 /*HasTrailingLParen=*/true, 1000 /*IsAddressOfOperand=*/false); 1001 if (TrapFn.isInvalid()) 1002 return ExprError(); 1003 1004 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1005 None, E->getEndLoc()); 1006 if (Call.isInvalid()) 1007 return ExprError(); 1008 1009 ExprResult Comma = 1010 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1011 if (Comma.isInvalid()) 1012 return ExprError(); 1013 return Comma.get(); 1014 } 1015 1016 if (!getLangOpts().CPlusPlus && 1017 RequireCompleteType(E->getExprLoc(), E->getType(), 1018 diag::err_call_incomplete_argument)) 1019 return ExprError(); 1020 1021 return E; 1022 } 1023 1024 /// Converts an integer to complex float type. Helper function of 1025 /// UsualArithmeticConversions() 1026 /// 1027 /// \return false if the integer expression is an integer type and is 1028 /// successfully converted to the complex type. 1029 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1030 ExprResult &ComplexExpr, 1031 QualType IntTy, 1032 QualType ComplexTy, 1033 bool SkipCast) { 1034 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1035 if (SkipCast) return false; 1036 if (IntTy->isIntegerType()) { 1037 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1038 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1039 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1040 CK_FloatingRealToComplex); 1041 } else { 1042 assert(IntTy->isComplexIntegerType()); 1043 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1044 CK_IntegralComplexToFloatingComplex); 1045 } 1046 return false; 1047 } 1048 1049 /// Handle arithmetic conversion with complex types. Helper function of 1050 /// UsualArithmeticConversions() 1051 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1052 ExprResult &RHS, QualType LHSType, 1053 QualType RHSType, 1054 bool IsCompAssign) { 1055 // if we have an integer operand, the result is the complex type. 1056 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1057 /*skipCast*/false)) 1058 return LHSType; 1059 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1060 /*skipCast*/IsCompAssign)) 1061 return RHSType; 1062 1063 // This handles complex/complex, complex/float, or float/complex. 1064 // When both operands are complex, the shorter operand is converted to the 1065 // type of the longer, and that is the type of the result. This corresponds 1066 // to what is done when combining two real floating-point operands. 1067 // The fun begins when size promotion occur across type domains. 1068 // From H&S 6.3.4: When one operand is complex and the other is a real 1069 // floating-point type, the less precise type is converted, within it's 1070 // real or complex domain, to the precision of the other type. For example, 1071 // when combining a "long double" with a "double _Complex", the 1072 // "double _Complex" is promoted to "long double _Complex". 1073 1074 // Compute the rank of the two types, regardless of whether they are complex. 1075 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1076 1077 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1078 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1079 QualType LHSElementType = 1080 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1081 QualType RHSElementType = 1082 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1083 1084 QualType ResultType = S.Context.getComplexType(LHSElementType); 1085 if (Order < 0) { 1086 // Promote the precision of the LHS if not an assignment. 1087 ResultType = S.Context.getComplexType(RHSElementType); 1088 if (!IsCompAssign) { 1089 if (LHSComplexType) 1090 LHS = 1091 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1092 else 1093 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1094 } 1095 } else if (Order > 0) { 1096 // Promote the precision of the RHS. 1097 if (RHSComplexType) 1098 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1099 else 1100 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1101 } 1102 return ResultType; 1103 } 1104 1105 /// Handle arithmetic conversion from integer to float. Helper function 1106 /// of UsualArithmeticConversions() 1107 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1108 ExprResult &IntExpr, 1109 QualType FloatTy, QualType IntTy, 1110 bool ConvertFloat, bool ConvertInt) { 1111 if (IntTy->isIntegerType()) { 1112 if (ConvertInt) 1113 // Convert intExpr to the lhs floating point type. 1114 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1115 CK_IntegralToFloating); 1116 return FloatTy; 1117 } 1118 1119 // Convert both sides to the appropriate complex float. 1120 assert(IntTy->isComplexIntegerType()); 1121 QualType result = S.Context.getComplexType(FloatTy); 1122 1123 // _Complex int -> _Complex float 1124 if (ConvertInt) 1125 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1126 CK_IntegralComplexToFloatingComplex); 1127 1128 // float -> _Complex float 1129 if (ConvertFloat) 1130 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1131 CK_FloatingRealToComplex); 1132 1133 return result; 1134 } 1135 1136 /// Handle arithmethic conversion with floating point types. Helper 1137 /// function of UsualArithmeticConversions() 1138 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1139 ExprResult &RHS, QualType LHSType, 1140 QualType RHSType, bool IsCompAssign) { 1141 bool LHSFloat = LHSType->isRealFloatingType(); 1142 bool RHSFloat = RHSType->isRealFloatingType(); 1143 1144 // N1169 4.1.4: If one of the operands has a floating type and the other 1145 // operand has a fixed-point type, the fixed-point operand 1146 // is converted to the floating type [...] 1147 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1148 if (LHSFloat) 1149 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1150 else if (!IsCompAssign) 1151 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1152 return LHSFloat ? LHSType : RHSType; 1153 } 1154 1155 // If we have two real floating types, convert the smaller operand 1156 // to the bigger result. 1157 if (LHSFloat && RHSFloat) { 1158 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1159 if (order > 0) { 1160 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1161 return LHSType; 1162 } 1163 1164 assert(order < 0 && "illegal float comparison"); 1165 if (!IsCompAssign) 1166 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1167 return RHSType; 1168 } 1169 1170 if (LHSFloat) { 1171 // Half FP has to be promoted to float unless it is natively supported 1172 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1173 LHSType = S.Context.FloatTy; 1174 1175 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1176 /*ConvertFloat=*/!IsCompAssign, 1177 /*ConvertInt=*/ true); 1178 } 1179 assert(RHSFloat); 1180 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1181 /*ConvertFloat=*/ true, 1182 /*ConvertInt=*/!IsCompAssign); 1183 } 1184 1185 /// Diagnose attempts to convert between __float128 and long double if 1186 /// there is no support for such conversion. Helper function of 1187 /// UsualArithmeticConversions(). 1188 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1189 QualType RHSType) { 1190 /* No issue converting if at least one of the types is not a floating point 1191 type or the two types have the same rank. 1192 */ 1193 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1194 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1195 return false; 1196 1197 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1198 "The remaining types must be floating point types."); 1199 1200 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1201 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1202 1203 QualType LHSElemType = LHSComplex ? 1204 LHSComplex->getElementType() : LHSType; 1205 QualType RHSElemType = RHSComplex ? 1206 RHSComplex->getElementType() : RHSType; 1207 1208 // No issue if the two types have the same representation 1209 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1210 &S.Context.getFloatTypeSemantics(RHSElemType)) 1211 return false; 1212 1213 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1214 RHSElemType == S.Context.LongDoubleTy); 1215 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1216 RHSElemType == S.Context.Float128Ty); 1217 1218 // We've handled the situation where __float128 and long double have the same 1219 // representation. We allow all conversions for all possible long double types 1220 // except PPC's double double. 1221 return Float128AndLongDouble && 1222 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1223 &llvm::APFloat::PPCDoubleDouble()); 1224 } 1225 1226 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1227 1228 namespace { 1229 /// These helper callbacks are placed in an anonymous namespace to 1230 /// permit their use as function template parameters. 1231 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1232 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1233 } 1234 1235 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1236 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1237 CK_IntegralComplexCast); 1238 } 1239 } 1240 1241 /// Handle integer arithmetic conversions. Helper function of 1242 /// UsualArithmeticConversions() 1243 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1244 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1245 ExprResult &RHS, QualType LHSType, 1246 QualType RHSType, bool IsCompAssign) { 1247 // The rules for this case are in C99 6.3.1.8 1248 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1249 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1250 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1251 if (LHSSigned == RHSSigned) { 1252 // Same signedness; use the higher-ranked type 1253 if (order >= 0) { 1254 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1255 return LHSType; 1256 } else if (!IsCompAssign) 1257 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1258 return RHSType; 1259 } else if (order != (LHSSigned ? 1 : -1)) { 1260 // The unsigned type has greater than or equal rank to the 1261 // signed type, so use the unsigned type 1262 if (RHSSigned) { 1263 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1264 return LHSType; 1265 } else if (!IsCompAssign) 1266 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1267 return RHSType; 1268 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1269 // The two types are different widths; if we are here, that 1270 // means the signed type is larger than the unsigned type, so 1271 // use the signed type. 1272 if (LHSSigned) { 1273 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1274 return LHSType; 1275 } else if (!IsCompAssign) 1276 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1277 return RHSType; 1278 } else { 1279 // The signed type is higher-ranked than the unsigned type, 1280 // but isn't actually any bigger (like unsigned int and long 1281 // on most 32-bit systems). Use the unsigned type corresponding 1282 // to the signed type. 1283 QualType result = 1284 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1285 RHS = (*doRHSCast)(S, RHS.get(), result); 1286 if (!IsCompAssign) 1287 LHS = (*doLHSCast)(S, LHS.get(), result); 1288 return result; 1289 } 1290 } 1291 1292 /// Handle conversions with GCC complex int extension. Helper function 1293 /// of UsualArithmeticConversions() 1294 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1295 ExprResult &RHS, QualType LHSType, 1296 QualType RHSType, 1297 bool IsCompAssign) { 1298 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1299 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1300 1301 if (LHSComplexInt && RHSComplexInt) { 1302 QualType LHSEltType = LHSComplexInt->getElementType(); 1303 QualType RHSEltType = RHSComplexInt->getElementType(); 1304 QualType ScalarType = 1305 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1306 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1307 1308 return S.Context.getComplexType(ScalarType); 1309 } 1310 1311 if (LHSComplexInt) { 1312 QualType LHSEltType = LHSComplexInt->getElementType(); 1313 QualType ScalarType = 1314 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1315 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1316 QualType ComplexType = S.Context.getComplexType(ScalarType); 1317 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1318 CK_IntegralRealToComplex); 1319 1320 return ComplexType; 1321 } 1322 1323 assert(RHSComplexInt); 1324 1325 QualType RHSEltType = RHSComplexInt->getElementType(); 1326 QualType ScalarType = 1327 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1328 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1329 QualType ComplexType = S.Context.getComplexType(ScalarType); 1330 1331 if (!IsCompAssign) 1332 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1333 CK_IntegralRealToComplex); 1334 return ComplexType; 1335 } 1336 1337 /// Return the rank of a given fixed point or integer type. The value itself 1338 /// doesn't matter, but the values must be increasing with proper increasing 1339 /// rank as described in N1169 4.1.1. 1340 static unsigned GetFixedPointRank(QualType Ty) { 1341 const auto *BTy = Ty->getAs<BuiltinType>(); 1342 assert(BTy && "Expected a builtin type."); 1343 1344 switch (BTy->getKind()) { 1345 case BuiltinType::ShortFract: 1346 case BuiltinType::UShortFract: 1347 case BuiltinType::SatShortFract: 1348 case BuiltinType::SatUShortFract: 1349 return 1; 1350 case BuiltinType::Fract: 1351 case BuiltinType::UFract: 1352 case BuiltinType::SatFract: 1353 case BuiltinType::SatUFract: 1354 return 2; 1355 case BuiltinType::LongFract: 1356 case BuiltinType::ULongFract: 1357 case BuiltinType::SatLongFract: 1358 case BuiltinType::SatULongFract: 1359 return 3; 1360 case BuiltinType::ShortAccum: 1361 case BuiltinType::UShortAccum: 1362 case BuiltinType::SatShortAccum: 1363 case BuiltinType::SatUShortAccum: 1364 return 4; 1365 case BuiltinType::Accum: 1366 case BuiltinType::UAccum: 1367 case BuiltinType::SatAccum: 1368 case BuiltinType::SatUAccum: 1369 return 5; 1370 case BuiltinType::LongAccum: 1371 case BuiltinType::ULongAccum: 1372 case BuiltinType::SatLongAccum: 1373 case BuiltinType::SatULongAccum: 1374 return 6; 1375 default: 1376 if (BTy->isInteger()) 1377 return 0; 1378 llvm_unreachable("Unexpected fixed point or integer type"); 1379 } 1380 } 1381 1382 /// handleFixedPointConversion - Fixed point operations between fixed 1383 /// point types and integers or other fixed point types do not fall under 1384 /// usual arithmetic conversion since these conversions could result in loss 1385 /// of precsision (N1169 4.1.4). These operations should be calculated with 1386 /// the full precision of their result type (N1169 4.1.6.2.1). 1387 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1388 QualType RHSTy) { 1389 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1390 "Expected at least one of the operands to be a fixed point type"); 1391 assert((LHSTy->isFixedPointOrIntegerType() || 1392 RHSTy->isFixedPointOrIntegerType()) && 1393 "Special fixed point arithmetic operation conversions are only " 1394 "applied to ints or other fixed point types"); 1395 1396 // If one operand has signed fixed-point type and the other operand has 1397 // unsigned fixed-point type, then the unsigned fixed-point operand is 1398 // converted to its corresponding signed fixed-point type and the resulting 1399 // type is the type of the converted operand. 1400 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1401 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1402 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1403 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1404 1405 // The result type is the type with the highest rank, whereby a fixed-point 1406 // conversion rank is always greater than an integer conversion rank; if the 1407 // type of either of the operands is a saturating fixedpoint type, the result 1408 // type shall be the saturating fixed-point type corresponding to the type 1409 // with the highest rank; the resulting value is converted (taking into 1410 // account rounding and overflow) to the precision of the resulting type. 1411 // Same ranks between signed and unsigned types are resolved earlier, so both 1412 // types are either signed or both unsigned at this point. 1413 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1414 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1415 1416 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1417 1418 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1419 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1420 1421 return ResultTy; 1422 } 1423 1424 /// Check that the usual arithmetic conversions can be performed on this pair of 1425 /// expressions that might be of enumeration type. 1426 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1427 SourceLocation Loc, 1428 Sema::ArithConvKind ACK) { 1429 // C++2a [expr.arith.conv]p1: 1430 // If one operand is of enumeration type and the other operand is of a 1431 // different enumeration type or a floating-point type, this behavior is 1432 // deprecated ([depr.arith.conv.enum]). 1433 // 1434 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1435 // Eventually we will presumably reject these cases (in C++23 onwards?). 1436 QualType L = LHS->getType(), R = RHS->getType(); 1437 bool LEnum = L->isUnscopedEnumerationType(), 1438 REnum = R->isUnscopedEnumerationType(); 1439 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1440 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1441 (REnum && L->isFloatingType())) { 1442 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1443 ? diag::warn_arith_conv_enum_float_cxx20 1444 : diag::warn_arith_conv_enum_float) 1445 << LHS->getSourceRange() << RHS->getSourceRange() 1446 << (int)ACK << LEnum << L << R; 1447 } else if (!IsCompAssign && LEnum && REnum && 1448 !S.Context.hasSameUnqualifiedType(L, R)) { 1449 unsigned DiagID; 1450 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1451 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1452 // If either enumeration type is unnamed, it's less likely that the 1453 // user cares about this, but this situation is still deprecated in 1454 // C++2a. Use a different warning group. 1455 DiagID = S.getLangOpts().CPlusPlus20 1456 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1457 : diag::warn_arith_conv_mixed_anon_enum_types; 1458 } else if (ACK == Sema::ACK_Conditional) { 1459 // Conditional expressions are separated out because they have 1460 // historically had a different warning flag. 1461 DiagID = S.getLangOpts().CPlusPlus20 1462 ? diag::warn_conditional_mixed_enum_types_cxx20 1463 : diag::warn_conditional_mixed_enum_types; 1464 } else if (ACK == Sema::ACK_Comparison) { 1465 // Comparison expressions are separated out because they have 1466 // historically had a different warning flag. 1467 DiagID = S.getLangOpts().CPlusPlus20 1468 ? diag::warn_comparison_mixed_enum_types_cxx20 1469 : diag::warn_comparison_mixed_enum_types; 1470 } else { 1471 DiagID = S.getLangOpts().CPlusPlus20 1472 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1473 : diag::warn_arith_conv_mixed_enum_types; 1474 } 1475 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1476 << (int)ACK << L << R; 1477 } 1478 } 1479 1480 /// UsualArithmeticConversions - Performs various conversions that are common to 1481 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1482 /// routine returns the first non-arithmetic type found. The client is 1483 /// responsible for emitting appropriate error diagnostics. 1484 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1485 SourceLocation Loc, 1486 ArithConvKind ACK) { 1487 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1488 1489 if (ACK != ACK_CompAssign) { 1490 LHS = UsualUnaryConversions(LHS.get()); 1491 if (LHS.isInvalid()) 1492 return QualType(); 1493 } 1494 1495 RHS = UsualUnaryConversions(RHS.get()); 1496 if (RHS.isInvalid()) 1497 return QualType(); 1498 1499 // For conversion purposes, we ignore any qualifiers. 1500 // For example, "const float" and "float" are equivalent. 1501 QualType LHSType = 1502 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1503 QualType RHSType = 1504 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1505 1506 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1507 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1508 LHSType = AtomicLHS->getValueType(); 1509 1510 // If both types are identical, no conversion is needed. 1511 if (LHSType == RHSType) 1512 return LHSType; 1513 1514 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1515 // The caller can deal with this (e.g. pointer + int). 1516 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1517 return QualType(); 1518 1519 // Apply unary and bitfield promotions to the LHS's type. 1520 QualType LHSUnpromotedType = LHSType; 1521 if (LHSType->isPromotableIntegerType()) 1522 LHSType = Context.getPromotedIntegerType(LHSType); 1523 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1524 if (!LHSBitfieldPromoteTy.isNull()) 1525 LHSType = LHSBitfieldPromoteTy; 1526 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1527 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1528 1529 // If both types are identical, no conversion is needed. 1530 if (LHSType == RHSType) 1531 return LHSType; 1532 1533 // ExtInt types aren't subject to conversions between them or normal integers, 1534 // so this fails. 1535 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1536 return QualType(); 1537 1538 // At this point, we have two different arithmetic types. 1539 1540 // Diagnose attempts to convert between __float128 and long double where 1541 // such conversions currently can't be handled. 1542 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1543 return QualType(); 1544 1545 // Handle complex types first (C99 6.3.1.8p1). 1546 if (LHSType->isComplexType() || RHSType->isComplexType()) 1547 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1548 ACK == ACK_CompAssign); 1549 1550 // Now handle "real" floating types (i.e. float, double, long double). 1551 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1552 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1553 ACK == ACK_CompAssign); 1554 1555 // Handle GCC complex int extension. 1556 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1557 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1558 ACK == ACK_CompAssign); 1559 1560 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1561 return handleFixedPointConversion(*this, LHSType, RHSType); 1562 1563 // Finally, we have two differing integer types. 1564 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1565 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1566 } 1567 1568 //===----------------------------------------------------------------------===// 1569 // Semantic Analysis for various Expression Types 1570 //===----------------------------------------------------------------------===// 1571 1572 1573 ExprResult 1574 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1575 SourceLocation DefaultLoc, 1576 SourceLocation RParenLoc, 1577 Expr *ControllingExpr, 1578 ArrayRef<ParsedType> ArgTypes, 1579 ArrayRef<Expr *> ArgExprs) { 1580 unsigned NumAssocs = ArgTypes.size(); 1581 assert(NumAssocs == ArgExprs.size()); 1582 1583 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1584 for (unsigned i = 0; i < NumAssocs; ++i) { 1585 if (ArgTypes[i]) 1586 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1587 else 1588 Types[i] = nullptr; 1589 } 1590 1591 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1592 ControllingExpr, 1593 llvm::makeArrayRef(Types, NumAssocs), 1594 ArgExprs); 1595 delete [] Types; 1596 return ER; 1597 } 1598 1599 ExprResult 1600 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1601 SourceLocation DefaultLoc, 1602 SourceLocation RParenLoc, 1603 Expr *ControllingExpr, 1604 ArrayRef<TypeSourceInfo *> Types, 1605 ArrayRef<Expr *> Exprs) { 1606 unsigned NumAssocs = Types.size(); 1607 assert(NumAssocs == Exprs.size()); 1608 1609 // Decay and strip qualifiers for the controlling expression type, and handle 1610 // placeholder type replacement. See committee discussion from WG14 DR423. 1611 { 1612 EnterExpressionEvaluationContext Unevaluated( 1613 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1614 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1615 if (R.isInvalid()) 1616 return ExprError(); 1617 ControllingExpr = R.get(); 1618 } 1619 1620 // The controlling expression is an unevaluated operand, so side effects are 1621 // likely unintended. 1622 if (!inTemplateInstantiation() && 1623 ControllingExpr->HasSideEffects(Context, false)) 1624 Diag(ControllingExpr->getExprLoc(), 1625 diag::warn_side_effects_unevaluated_context); 1626 1627 bool TypeErrorFound = false, 1628 IsResultDependent = ControllingExpr->isTypeDependent(), 1629 ContainsUnexpandedParameterPack 1630 = ControllingExpr->containsUnexpandedParameterPack(); 1631 1632 for (unsigned i = 0; i < NumAssocs; ++i) { 1633 if (Exprs[i]->containsUnexpandedParameterPack()) 1634 ContainsUnexpandedParameterPack = true; 1635 1636 if (Types[i]) { 1637 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1638 ContainsUnexpandedParameterPack = true; 1639 1640 if (Types[i]->getType()->isDependentType()) { 1641 IsResultDependent = true; 1642 } else { 1643 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1644 // complete object type other than a variably modified type." 1645 unsigned D = 0; 1646 if (Types[i]->getType()->isIncompleteType()) 1647 D = diag::err_assoc_type_incomplete; 1648 else if (!Types[i]->getType()->isObjectType()) 1649 D = diag::err_assoc_type_nonobject; 1650 else if (Types[i]->getType()->isVariablyModifiedType()) 1651 D = diag::err_assoc_type_variably_modified; 1652 1653 if (D != 0) { 1654 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1655 << Types[i]->getTypeLoc().getSourceRange() 1656 << Types[i]->getType(); 1657 TypeErrorFound = true; 1658 } 1659 1660 // C11 6.5.1.1p2 "No two generic associations in the same generic 1661 // selection shall specify compatible types." 1662 for (unsigned j = i+1; j < NumAssocs; ++j) 1663 if (Types[j] && !Types[j]->getType()->isDependentType() && 1664 Context.typesAreCompatible(Types[i]->getType(), 1665 Types[j]->getType())) { 1666 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1667 diag::err_assoc_compatible_types) 1668 << Types[j]->getTypeLoc().getSourceRange() 1669 << Types[j]->getType() 1670 << Types[i]->getType(); 1671 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1672 diag::note_compat_assoc) 1673 << Types[i]->getTypeLoc().getSourceRange() 1674 << Types[i]->getType(); 1675 TypeErrorFound = true; 1676 } 1677 } 1678 } 1679 } 1680 if (TypeErrorFound) 1681 return ExprError(); 1682 1683 // If we determined that the generic selection is result-dependent, don't 1684 // try to compute the result expression. 1685 if (IsResultDependent) 1686 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1687 Exprs, DefaultLoc, RParenLoc, 1688 ContainsUnexpandedParameterPack); 1689 1690 SmallVector<unsigned, 1> CompatIndices; 1691 unsigned DefaultIndex = -1U; 1692 for (unsigned i = 0; i < NumAssocs; ++i) { 1693 if (!Types[i]) 1694 DefaultIndex = i; 1695 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1696 Types[i]->getType())) 1697 CompatIndices.push_back(i); 1698 } 1699 1700 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1701 // type compatible with at most one of the types named in its generic 1702 // association list." 1703 if (CompatIndices.size() > 1) { 1704 // We strip parens here because the controlling expression is typically 1705 // parenthesized in macro definitions. 1706 ControllingExpr = ControllingExpr->IgnoreParens(); 1707 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1708 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1709 << (unsigned)CompatIndices.size(); 1710 for (unsigned I : CompatIndices) { 1711 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1712 diag::note_compat_assoc) 1713 << Types[I]->getTypeLoc().getSourceRange() 1714 << Types[I]->getType(); 1715 } 1716 return ExprError(); 1717 } 1718 1719 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1720 // its controlling expression shall have type compatible with exactly one of 1721 // the types named in its generic association list." 1722 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1723 // We strip parens here because the controlling expression is typically 1724 // parenthesized in macro definitions. 1725 ControllingExpr = ControllingExpr->IgnoreParens(); 1726 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1727 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1728 return ExprError(); 1729 } 1730 1731 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1732 // type name that is compatible with the type of the controlling expression, 1733 // then the result expression of the generic selection is the expression 1734 // in that generic association. Otherwise, the result expression of the 1735 // generic selection is the expression in the default generic association." 1736 unsigned ResultIndex = 1737 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1738 1739 return GenericSelectionExpr::Create( 1740 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1741 ContainsUnexpandedParameterPack, ResultIndex); 1742 } 1743 1744 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1745 /// location of the token and the offset of the ud-suffix within it. 1746 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1747 unsigned Offset) { 1748 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1749 S.getLangOpts()); 1750 } 1751 1752 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1753 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1754 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1755 IdentifierInfo *UDSuffix, 1756 SourceLocation UDSuffixLoc, 1757 ArrayRef<Expr*> Args, 1758 SourceLocation LitEndLoc) { 1759 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1760 1761 QualType ArgTy[2]; 1762 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1763 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1764 if (ArgTy[ArgIdx]->isArrayType()) 1765 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1766 } 1767 1768 DeclarationName OpName = 1769 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1770 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1771 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1772 1773 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1774 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1775 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1776 /*AllowStringTemplatePack*/ false, 1777 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1778 return ExprError(); 1779 1780 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1781 } 1782 1783 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1784 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1785 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1786 /// multiple tokens. However, the common case is that StringToks points to one 1787 /// string. 1788 /// 1789 ExprResult 1790 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1791 assert(!StringToks.empty() && "Must have at least one string!"); 1792 1793 StringLiteralParser Literal(StringToks, PP); 1794 if (Literal.hadError) 1795 return ExprError(); 1796 1797 SmallVector<SourceLocation, 4> StringTokLocs; 1798 for (const Token &Tok : StringToks) 1799 StringTokLocs.push_back(Tok.getLocation()); 1800 1801 QualType CharTy = Context.CharTy; 1802 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1803 if (Literal.isWide()) { 1804 CharTy = Context.getWideCharType(); 1805 Kind = StringLiteral::Wide; 1806 } else if (Literal.isUTF8()) { 1807 if (getLangOpts().Char8) 1808 CharTy = Context.Char8Ty; 1809 Kind = StringLiteral::UTF8; 1810 } else if (Literal.isUTF16()) { 1811 CharTy = Context.Char16Ty; 1812 Kind = StringLiteral::UTF16; 1813 } else if (Literal.isUTF32()) { 1814 CharTy = Context.Char32Ty; 1815 Kind = StringLiteral::UTF32; 1816 } else if (Literal.isPascal()) { 1817 CharTy = Context.UnsignedCharTy; 1818 } 1819 1820 // Warn on initializing an array of char from a u8 string literal; this 1821 // becomes ill-formed in C++2a. 1822 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1823 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1824 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1825 1826 // Create removals for all 'u8' prefixes in the string literal(s). This 1827 // ensures C++2a compatibility (but may change the program behavior when 1828 // built by non-Clang compilers for which the execution character set is 1829 // not always UTF-8). 1830 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1831 SourceLocation RemovalDiagLoc; 1832 for (const Token &Tok : StringToks) { 1833 if (Tok.getKind() == tok::utf8_string_literal) { 1834 if (RemovalDiagLoc.isInvalid()) 1835 RemovalDiagLoc = Tok.getLocation(); 1836 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1837 Tok.getLocation(), 1838 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1839 getSourceManager(), getLangOpts()))); 1840 } 1841 } 1842 Diag(RemovalDiagLoc, RemovalDiag); 1843 } 1844 1845 QualType StrTy = 1846 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1847 1848 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1849 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1850 Kind, Literal.Pascal, StrTy, 1851 &StringTokLocs[0], 1852 StringTokLocs.size()); 1853 if (Literal.getUDSuffix().empty()) 1854 return Lit; 1855 1856 // We're building a user-defined literal. 1857 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1858 SourceLocation UDSuffixLoc = 1859 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1860 Literal.getUDSuffixOffset()); 1861 1862 // Make sure we're allowed user-defined literals here. 1863 if (!UDLScope) 1864 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1865 1866 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1867 // operator "" X (str, len) 1868 QualType SizeType = Context.getSizeType(); 1869 1870 DeclarationName OpName = 1871 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1872 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1873 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1874 1875 QualType ArgTy[] = { 1876 Context.getArrayDecayedType(StrTy), SizeType 1877 }; 1878 1879 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1880 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1881 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1882 /*AllowStringTemplatePack*/ true, 1883 /*DiagnoseMissing*/ true, Lit)) { 1884 1885 case LOLR_Cooked: { 1886 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1887 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1888 StringTokLocs[0]); 1889 Expr *Args[] = { Lit, LenArg }; 1890 1891 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1892 } 1893 1894 case LOLR_Template: { 1895 TemplateArgumentListInfo ExplicitArgs; 1896 TemplateArgument Arg(Lit); 1897 TemplateArgumentLocInfo ArgInfo(Lit); 1898 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1899 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1900 &ExplicitArgs); 1901 } 1902 1903 case LOLR_StringTemplatePack: { 1904 TemplateArgumentListInfo ExplicitArgs; 1905 1906 unsigned CharBits = Context.getIntWidth(CharTy); 1907 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1908 llvm::APSInt Value(CharBits, CharIsUnsigned); 1909 1910 TemplateArgument TypeArg(CharTy); 1911 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1912 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1913 1914 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1915 Value = Lit->getCodeUnit(I); 1916 TemplateArgument Arg(Context, Value, CharTy); 1917 TemplateArgumentLocInfo ArgInfo; 1918 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1919 } 1920 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1921 &ExplicitArgs); 1922 } 1923 case LOLR_Raw: 1924 case LOLR_ErrorNoDiagnostic: 1925 llvm_unreachable("unexpected literal operator lookup result"); 1926 case LOLR_Error: 1927 return ExprError(); 1928 } 1929 llvm_unreachable("unexpected literal operator lookup result"); 1930 } 1931 1932 DeclRefExpr * 1933 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1934 SourceLocation Loc, 1935 const CXXScopeSpec *SS) { 1936 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1937 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1938 } 1939 1940 DeclRefExpr * 1941 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1942 const DeclarationNameInfo &NameInfo, 1943 const CXXScopeSpec *SS, NamedDecl *FoundD, 1944 SourceLocation TemplateKWLoc, 1945 const TemplateArgumentListInfo *TemplateArgs) { 1946 NestedNameSpecifierLoc NNS = 1947 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1948 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1949 TemplateArgs); 1950 } 1951 1952 // CUDA/HIP: Check whether a captured reference variable is referencing a 1953 // host variable in a device or host device lambda. 1954 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1955 VarDecl *VD) { 1956 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1957 return false; 1958 assert(VD->getType()->isReferenceType()); 1959 1960 // Check whether the reference variable is referencing a host variable. 1961 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1962 if (!DRE) 1963 return false; 1964 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1965 if (!Referee || !Referee->hasGlobalStorage() || 1966 Referee->hasAttr<CUDADeviceAttr>()) 1967 return false; 1968 1969 // Check whether the current function is a device or host device lambda. 1970 // Check whether the reference variable is a capture by getDeclContext() 1971 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1972 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1973 if (MD && MD->getParent()->isLambda() && 1974 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1975 VD->getDeclContext() != MD) 1976 return true; 1977 1978 return false; 1979 } 1980 1981 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1982 // A declaration named in an unevaluated operand never constitutes an odr-use. 1983 if (isUnevaluatedContext()) 1984 return NOUR_Unevaluated; 1985 1986 // C++2a [basic.def.odr]p4: 1987 // A variable x whose name appears as a potentially-evaluated expression e 1988 // is odr-used by e unless [...] x is a reference that is usable in 1989 // constant expressions. 1990 // CUDA/HIP: 1991 // If a reference variable referencing a host variable is captured in a 1992 // device or host device lambda, the value of the referee must be copied 1993 // to the capture and the reference variable must be treated as odr-use 1994 // since the value of the referee is not known at compile time and must 1995 // be loaded from the captured. 1996 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1997 if (VD->getType()->isReferenceType() && 1998 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1999 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2000 VD->isUsableInConstantExpressions(Context)) 2001 return NOUR_Constant; 2002 } 2003 2004 // All remaining non-variable cases constitute an odr-use. For variables, we 2005 // need to wait and see how the expression is used. 2006 return NOUR_None; 2007 } 2008 2009 /// BuildDeclRefExpr - Build an expression that references a 2010 /// declaration that does not require a closure capture. 2011 DeclRefExpr * 2012 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2013 const DeclarationNameInfo &NameInfo, 2014 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2015 SourceLocation TemplateKWLoc, 2016 const TemplateArgumentListInfo *TemplateArgs) { 2017 bool RefersToCapturedVariable = 2018 isa<VarDecl>(D) && 2019 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2020 2021 DeclRefExpr *E = DeclRefExpr::Create( 2022 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2023 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2024 MarkDeclRefReferenced(E); 2025 2026 // C++ [except.spec]p17: 2027 // An exception-specification is considered to be needed when: 2028 // - in an expression, the function is the unique lookup result or 2029 // the selected member of a set of overloaded functions. 2030 // 2031 // We delay doing this until after we've built the function reference and 2032 // marked it as used so that: 2033 // a) if the function is defaulted, we get errors from defining it before / 2034 // instead of errors from computing its exception specification, and 2035 // b) if the function is a defaulted comparison, we can use the body we 2036 // build when defining it as input to the exception specification 2037 // computation rather than computing a new body. 2038 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2039 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2040 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2041 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2042 } 2043 } 2044 2045 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2046 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2047 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2048 getCurFunction()->recordUseOfWeak(E); 2049 2050 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2051 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2052 FD = IFD->getAnonField(); 2053 if (FD) { 2054 UnusedPrivateFields.remove(FD); 2055 // Just in case we're building an illegal pointer-to-member. 2056 if (FD->isBitField()) 2057 E->setObjectKind(OK_BitField); 2058 } 2059 2060 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2061 // designates a bit-field. 2062 if (auto *BD = dyn_cast<BindingDecl>(D)) 2063 if (auto *BE = BD->getBinding()) 2064 E->setObjectKind(BE->getObjectKind()); 2065 2066 return E; 2067 } 2068 2069 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2070 /// possibly a list of template arguments. 2071 /// 2072 /// If this produces template arguments, it is permitted to call 2073 /// DecomposeTemplateName. 2074 /// 2075 /// This actually loses a lot of source location information for 2076 /// non-standard name kinds; we should consider preserving that in 2077 /// some way. 2078 void 2079 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2080 TemplateArgumentListInfo &Buffer, 2081 DeclarationNameInfo &NameInfo, 2082 const TemplateArgumentListInfo *&TemplateArgs) { 2083 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2084 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2085 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2086 2087 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2088 Id.TemplateId->NumArgs); 2089 translateTemplateArguments(TemplateArgsPtr, Buffer); 2090 2091 TemplateName TName = Id.TemplateId->Template.get(); 2092 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2093 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2094 TemplateArgs = &Buffer; 2095 } else { 2096 NameInfo = GetNameFromUnqualifiedId(Id); 2097 TemplateArgs = nullptr; 2098 } 2099 } 2100 2101 static void emitEmptyLookupTypoDiagnostic( 2102 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2103 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2104 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2105 DeclContext *Ctx = 2106 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2107 if (!TC) { 2108 // Emit a special diagnostic for failed member lookups. 2109 // FIXME: computing the declaration context might fail here (?) 2110 if (Ctx) 2111 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2112 << SS.getRange(); 2113 else 2114 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2115 return; 2116 } 2117 2118 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2119 bool DroppedSpecifier = 2120 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2121 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2122 ? diag::note_implicit_param_decl 2123 : diag::note_previous_decl; 2124 if (!Ctx) 2125 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2126 SemaRef.PDiag(NoteID)); 2127 else 2128 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2129 << Typo << Ctx << DroppedSpecifier 2130 << SS.getRange(), 2131 SemaRef.PDiag(NoteID)); 2132 } 2133 2134 /// Diagnose a lookup that found results in an enclosing class during error 2135 /// recovery. This usually indicates that the results were found in a dependent 2136 /// base class that could not be searched as part of a template definition. 2137 /// Always issues a diagnostic (though this may be only a warning in MS 2138 /// compatibility mode). 2139 /// 2140 /// Return \c true if the error is unrecoverable, or \c false if the caller 2141 /// should attempt to recover using these lookup results. 2142 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2143 // During a default argument instantiation the CurContext points 2144 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2145 // function parameter list, hence add an explicit check. 2146 bool isDefaultArgument = 2147 !CodeSynthesisContexts.empty() && 2148 CodeSynthesisContexts.back().Kind == 2149 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2150 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2151 bool isInstance = CurMethod && CurMethod->isInstance() && 2152 R.getNamingClass() == CurMethod->getParent() && 2153 !isDefaultArgument; 2154 2155 // There are two ways we can find a class-scope declaration during template 2156 // instantiation that we did not find in the template definition: if it is a 2157 // member of a dependent base class, or if it is declared after the point of 2158 // use in the same class. Distinguish these by comparing the class in which 2159 // the member was found to the naming class of the lookup. 2160 unsigned DiagID = diag::err_found_in_dependent_base; 2161 unsigned NoteID = diag::note_member_declared_at; 2162 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2163 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2164 : diag::err_found_later_in_class; 2165 } else if (getLangOpts().MSVCCompat) { 2166 DiagID = diag::ext_found_in_dependent_base; 2167 NoteID = diag::note_dependent_member_use; 2168 } 2169 2170 if (isInstance) { 2171 // Give a code modification hint to insert 'this->'. 2172 Diag(R.getNameLoc(), DiagID) 2173 << R.getLookupName() 2174 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2175 CheckCXXThisCapture(R.getNameLoc()); 2176 } else { 2177 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2178 // they're not shadowed). 2179 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2180 } 2181 2182 for (NamedDecl *D : R) 2183 Diag(D->getLocation(), NoteID); 2184 2185 // Return true if we are inside a default argument instantiation 2186 // and the found name refers to an instance member function, otherwise 2187 // the caller will try to create an implicit member call and this is wrong 2188 // for default arguments. 2189 // 2190 // FIXME: Is this special case necessary? We could allow the caller to 2191 // diagnose this. 2192 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2193 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2194 return true; 2195 } 2196 2197 // Tell the callee to try to recover. 2198 return false; 2199 } 2200 2201 /// Diagnose an empty lookup. 2202 /// 2203 /// \return false if new lookup candidates were found 2204 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2205 CorrectionCandidateCallback &CCC, 2206 TemplateArgumentListInfo *ExplicitTemplateArgs, 2207 ArrayRef<Expr *> Args, TypoExpr **Out) { 2208 DeclarationName Name = R.getLookupName(); 2209 2210 unsigned diagnostic = diag::err_undeclared_var_use; 2211 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2212 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2213 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2214 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2215 diagnostic = diag::err_undeclared_use; 2216 diagnostic_suggest = diag::err_undeclared_use_suggest; 2217 } 2218 2219 // If the original lookup was an unqualified lookup, fake an 2220 // unqualified lookup. This is useful when (for example) the 2221 // original lookup would not have found something because it was a 2222 // dependent name. 2223 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2224 while (DC) { 2225 if (isa<CXXRecordDecl>(DC)) { 2226 LookupQualifiedName(R, DC); 2227 2228 if (!R.empty()) { 2229 // Don't give errors about ambiguities in this lookup. 2230 R.suppressDiagnostics(); 2231 2232 // If there's a best viable function among the results, only mention 2233 // that one in the notes. 2234 OverloadCandidateSet Candidates(R.getNameLoc(), 2235 OverloadCandidateSet::CSK_Normal); 2236 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2237 OverloadCandidateSet::iterator Best; 2238 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2239 OR_Success) { 2240 R.clear(); 2241 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2242 R.resolveKind(); 2243 } 2244 2245 return DiagnoseDependentMemberLookup(R); 2246 } 2247 2248 R.clear(); 2249 } 2250 2251 DC = DC->getLookupParent(); 2252 } 2253 2254 // We didn't find anything, so try to correct for a typo. 2255 TypoCorrection Corrected; 2256 if (S && Out) { 2257 SourceLocation TypoLoc = R.getNameLoc(); 2258 assert(!ExplicitTemplateArgs && 2259 "Diagnosing an empty lookup with explicit template args!"); 2260 *Out = CorrectTypoDelayed( 2261 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2262 [=](const TypoCorrection &TC) { 2263 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2264 diagnostic, diagnostic_suggest); 2265 }, 2266 nullptr, CTK_ErrorRecovery); 2267 if (*Out) 2268 return true; 2269 } else if (S && 2270 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2271 S, &SS, CCC, CTK_ErrorRecovery))) { 2272 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2273 bool DroppedSpecifier = 2274 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2275 R.setLookupName(Corrected.getCorrection()); 2276 2277 bool AcceptableWithRecovery = false; 2278 bool AcceptableWithoutRecovery = false; 2279 NamedDecl *ND = Corrected.getFoundDecl(); 2280 if (ND) { 2281 if (Corrected.isOverloaded()) { 2282 OverloadCandidateSet OCS(R.getNameLoc(), 2283 OverloadCandidateSet::CSK_Normal); 2284 OverloadCandidateSet::iterator Best; 2285 for (NamedDecl *CD : Corrected) { 2286 if (FunctionTemplateDecl *FTD = 2287 dyn_cast<FunctionTemplateDecl>(CD)) 2288 AddTemplateOverloadCandidate( 2289 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2290 Args, OCS); 2291 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2292 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2293 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2294 Args, OCS); 2295 } 2296 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2297 case OR_Success: 2298 ND = Best->FoundDecl; 2299 Corrected.setCorrectionDecl(ND); 2300 break; 2301 default: 2302 // FIXME: Arbitrarily pick the first declaration for the note. 2303 Corrected.setCorrectionDecl(ND); 2304 break; 2305 } 2306 } 2307 R.addDecl(ND); 2308 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2309 CXXRecordDecl *Record = nullptr; 2310 if (Corrected.getCorrectionSpecifier()) { 2311 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2312 Record = Ty->getAsCXXRecordDecl(); 2313 } 2314 if (!Record) 2315 Record = cast<CXXRecordDecl>( 2316 ND->getDeclContext()->getRedeclContext()); 2317 R.setNamingClass(Record); 2318 } 2319 2320 auto *UnderlyingND = ND->getUnderlyingDecl(); 2321 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2322 isa<FunctionTemplateDecl>(UnderlyingND); 2323 // FIXME: If we ended up with a typo for a type name or 2324 // Objective-C class name, we're in trouble because the parser 2325 // is in the wrong place to recover. Suggest the typo 2326 // correction, but don't make it a fix-it since we're not going 2327 // to recover well anyway. 2328 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2329 getAsTypeTemplateDecl(UnderlyingND) || 2330 isa<ObjCInterfaceDecl>(UnderlyingND); 2331 } else { 2332 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2333 // because we aren't able to recover. 2334 AcceptableWithoutRecovery = true; 2335 } 2336 2337 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2338 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2339 ? diag::note_implicit_param_decl 2340 : diag::note_previous_decl; 2341 if (SS.isEmpty()) 2342 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2343 PDiag(NoteID), AcceptableWithRecovery); 2344 else 2345 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2346 << Name << computeDeclContext(SS, false) 2347 << DroppedSpecifier << SS.getRange(), 2348 PDiag(NoteID), AcceptableWithRecovery); 2349 2350 // Tell the callee whether to try to recover. 2351 return !AcceptableWithRecovery; 2352 } 2353 } 2354 R.clear(); 2355 2356 // Emit a special diagnostic for failed member lookups. 2357 // FIXME: computing the declaration context might fail here (?) 2358 if (!SS.isEmpty()) { 2359 Diag(R.getNameLoc(), diag::err_no_member) 2360 << Name << computeDeclContext(SS, false) 2361 << SS.getRange(); 2362 return true; 2363 } 2364 2365 // Give up, we can't recover. 2366 Diag(R.getNameLoc(), diagnostic) << Name; 2367 return true; 2368 } 2369 2370 /// In Microsoft mode, if we are inside a template class whose parent class has 2371 /// dependent base classes, and we can't resolve an unqualified identifier, then 2372 /// assume the identifier is a member of a dependent base class. We can only 2373 /// recover successfully in static methods, instance methods, and other contexts 2374 /// where 'this' is available. This doesn't precisely match MSVC's 2375 /// instantiation model, but it's close enough. 2376 static Expr * 2377 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2378 DeclarationNameInfo &NameInfo, 2379 SourceLocation TemplateKWLoc, 2380 const TemplateArgumentListInfo *TemplateArgs) { 2381 // Only try to recover from lookup into dependent bases in static methods or 2382 // contexts where 'this' is available. 2383 QualType ThisType = S.getCurrentThisType(); 2384 const CXXRecordDecl *RD = nullptr; 2385 if (!ThisType.isNull()) 2386 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2387 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2388 RD = MD->getParent(); 2389 if (!RD || !RD->hasAnyDependentBases()) 2390 return nullptr; 2391 2392 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2393 // is available, suggest inserting 'this->' as a fixit. 2394 SourceLocation Loc = NameInfo.getLoc(); 2395 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2396 DB << NameInfo.getName() << RD; 2397 2398 if (!ThisType.isNull()) { 2399 DB << FixItHint::CreateInsertion(Loc, "this->"); 2400 return CXXDependentScopeMemberExpr::Create( 2401 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2402 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2403 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2404 } 2405 2406 // Synthesize a fake NNS that points to the derived class. This will 2407 // perform name lookup during template instantiation. 2408 CXXScopeSpec SS; 2409 auto *NNS = 2410 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2411 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2412 return DependentScopeDeclRefExpr::Create( 2413 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2414 TemplateArgs); 2415 } 2416 2417 ExprResult 2418 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2419 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2420 bool HasTrailingLParen, bool IsAddressOfOperand, 2421 CorrectionCandidateCallback *CCC, 2422 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2423 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2424 "cannot be direct & operand and have a trailing lparen"); 2425 if (SS.isInvalid()) 2426 return ExprError(); 2427 2428 TemplateArgumentListInfo TemplateArgsBuffer; 2429 2430 // Decompose the UnqualifiedId into the following data. 2431 DeclarationNameInfo NameInfo; 2432 const TemplateArgumentListInfo *TemplateArgs; 2433 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2434 2435 DeclarationName Name = NameInfo.getName(); 2436 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2437 SourceLocation NameLoc = NameInfo.getLoc(); 2438 2439 if (II && II->isEditorPlaceholder()) { 2440 // FIXME: When typed placeholders are supported we can create a typed 2441 // placeholder expression node. 2442 return ExprError(); 2443 } 2444 2445 // C++ [temp.dep.expr]p3: 2446 // An id-expression is type-dependent if it contains: 2447 // -- an identifier that was declared with a dependent type, 2448 // (note: handled after lookup) 2449 // -- a template-id that is dependent, 2450 // (note: handled in BuildTemplateIdExpr) 2451 // -- a conversion-function-id that specifies a dependent type, 2452 // -- a nested-name-specifier that contains a class-name that 2453 // names a dependent type. 2454 // Determine whether this is a member of an unknown specialization; 2455 // we need to handle these differently. 2456 bool DependentID = false; 2457 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2458 Name.getCXXNameType()->isDependentType()) { 2459 DependentID = true; 2460 } else if (SS.isSet()) { 2461 if (DeclContext *DC = computeDeclContext(SS, false)) { 2462 if (RequireCompleteDeclContext(SS, DC)) 2463 return ExprError(); 2464 } else { 2465 DependentID = true; 2466 } 2467 } 2468 2469 if (DependentID) 2470 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2471 IsAddressOfOperand, TemplateArgs); 2472 2473 // Perform the required lookup. 2474 LookupResult R(*this, NameInfo, 2475 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2476 ? LookupObjCImplicitSelfParam 2477 : LookupOrdinaryName); 2478 if (TemplateKWLoc.isValid() || TemplateArgs) { 2479 // Lookup the template name again to correctly establish the context in 2480 // which it was found. This is really unfortunate as we already did the 2481 // lookup to determine that it was a template name in the first place. If 2482 // this becomes a performance hit, we can work harder to preserve those 2483 // results until we get here but it's likely not worth it. 2484 bool MemberOfUnknownSpecialization; 2485 AssumedTemplateKind AssumedTemplate; 2486 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2487 MemberOfUnknownSpecialization, TemplateKWLoc, 2488 &AssumedTemplate)) 2489 return ExprError(); 2490 2491 if (MemberOfUnknownSpecialization || 2492 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2493 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2494 IsAddressOfOperand, TemplateArgs); 2495 } else { 2496 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2497 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2498 2499 // If the result might be in a dependent base class, this is a dependent 2500 // id-expression. 2501 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2502 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2503 IsAddressOfOperand, TemplateArgs); 2504 2505 // If this reference is in an Objective-C method, then we need to do 2506 // some special Objective-C lookup, too. 2507 if (IvarLookupFollowUp) { 2508 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2509 if (E.isInvalid()) 2510 return ExprError(); 2511 2512 if (Expr *Ex = E.getAs<Expr>()) 2513 return Ex; 2514 } 2515 } 2516 2517 if (R.isAmbiguous()) 2518 return ExprError(); 2519 2520 // This could be an implicitly declared function reference (legal in C90, 2521 // extension in C99, forbidden in C++). 2522 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2523 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2524 if (D) R.addDecl(D); 2525 } 2526 2527 // Determine whether this name might be a candidate for 2528 // argument-dependent lookup. 2529 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2530 2531 if (R.empty() && !ADL) { 2532 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2533 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2534 TemplateKWLoc, TemplateArgs)) 2535 return E; 2536 } 2537 2538 // Don't diagnose an empty lookup for inline assembly. 2539 if (IsInlineAsmIdentifier) 2540 return ExprError(); 2541 2542 // If this name wasn't predeclared and if this is not a function 2543 // call, diagnose the problem. 2544 TypoExpr *TE = nullptr; 2545 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2546 : nullptr); 2547 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2548 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2549 "Typo correction callback misconfigured"); 2550 if (CCC) { 2551 // Make sure the callback knows what the typo being diagnosed is. 2552 CCC->setTypoName(II); 2553 if (SS.isValid()) 2554 CCC->setTypoNNS(SS.getScopeRep()); 2555 } 2556 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2557 // a template name, but we happen to have always already looked up the name 2558 // before we get here if it must be a template name. 2559 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2560 None, &TE)) { 2561 if (TE && KeywordReplacement) { 2562 auto &State = getTypoExprState(TE); 2563 auto BestTC = State.Consumer->getNextCorrection(); 2564 if (BestTC.isKeyword()) { 2565 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2566 if (State.DiagHandler) 2567 State.DiagHandler(BestTC); 2568 KeywordReplacement->startToken(); 2569 KeywordReplacement->setKind(II->getTokenID()); 2570 KeywordReplacement->setIdentifierInfo(II); 2571 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2572 // Clean up the state associated with the TypoExpr, since it has 2573 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2574 clearDelayedTypo(TE); 2575 // Signal that a correction to a keyword was performed by returning a 2576 // valid-but-null ExprResult. 2577 return (Expr*)nullptr; 2578 } 2579 State.Consumer->resetCorrectionStream(); 2580 } 2581 return TE ? TE : ExprError(); 2582 } 2583 2584 assert(!R.empty() && 2585 "DiagnoseEmptyLookup returned false but added no results"); 2586 2587 // If we found an Objective-C instance variable, let 2588 // LookupInObjCMethod build the appropriate expression to 2589 // reference the ivar. 2590 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2591 R.clear(); 2592 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2593 // In a hopelessly buggy code, Objective-C instance variable 2594 // lookup fails and no expression will be built to reference it. 2595 if (!E.isInvalid() && !E.get()) 2596 return ExprError(); 2597 return E; 2598 } 2599 } 2600 2601 // This is guaranteed from this point on. 2602 assert(!R.empty() || ADL); 2603 2604 // Check whether this might be a C++ implicit instance member access. 2605 // C++ [class.mfct.non-static]p3: 2606 // When an id-expression that is not part of a class member access 2607 // syntax and not used to form a pointer to member is used in the 2608 // body of a non-static member function of class X, if name lookup 2609 // resolves the name in the id-expression to a non-static non-type 2610 // member of some class C, the id-expression is transformed into a 2611 // class member access expression using (*this) as the 2612 // postfix-expression to the left of the . operator. 2613 // 2614 // But we don't actually need to do this for '&' operands if R 2615 // resolved to a function or overloaded function set, because the 2616 // expression is ill-formed if it actually works out to be a 2617 // non-static member function: 2618 // 2619 // C++ [expr.ref]p4: 2620 // Otherwise, if E1.E2 refers to a non-static member function. . . 2621 // [t]he expression can be used only as the left-hand operand of a 2622 // member function call. 2623 // 2624 // There are other safeguards against such uses, but it's important 2625 // to get this right here so that we don't end up making a 2626 // spuriously dependent expression if we're inside a dependent 2627 // instance method. 2628 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2629 bool MightBeImplicitMember; 2630 if (!IsAddressOfOperand) 2631 MightBeImplicitMember = true; 2632 else if (!SS.isEmpty()) 2633 MightBeImplicitMember = false; 2634 else if (R.isOverloadedResult()) 2635 MightBeImplicitMember = false; 2636 else if (R.isUnresolvableResult()) 2637 MightBeImplicitMember = true; 2638 else 2639 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2640 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2641 isa<MSPropertyDecl>(R.getFoundDecl()); 2642 2643 if (MightBeImplicitMember) 2644 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2645 R, TemplateArgs, S); 2646 } 2647 2648 if (TemplateArgs || TemplateKWLoc.isValid()) { 2649 2650 // In C++1y, if this is a variable template id, then check it 2651 // in BuildTemplateIdExpr(). 2652 // The single lookup result must be a variable template declaration. 2653 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2654 Id.TemplateId->Kind == TNK_Var_template) { 2655 assert(R.getAsSingle<VarTemplateDecl>() && 2656 "There should only be one declaration found."); 2657 } 2658 2659 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2660 } 2661 2662 return BuildDeclarationNameExpr(SS, R, ADL); 2663 } 2664 2665 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2666 /// declaration name, generally during template instantiation. 2667 /// There's a large number of things which don't need to be done along 2668 /// this path. 2669 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2670 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2671 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2672 DeclContext *DC = computeDeclContext(SS, false); 2673 if (!DC) 2674 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2675 NameInfo, /*TemplateArgs=*/nullptr); 2676 2677 if (RequireCompleteDeclContext(SS, DC)) 2678 return ExprError(); 2679 2680 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2681 LookupQualifiedName(R, DC); 2682 2683 if (R.isAmbiguous()) 2684 return ExprError(); 2685 2686 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2687 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2688 NameInfo, /*TemplateArgs=*/nullptr); 2689 2690 if (R.empty()) { 2691 // Don't diagnose problems with invalid record decl, the secondary no_member 2692 // diagnostic during template instantiation is likely bogus, e.g. if a class 2693 // is invalid because it's derived from an invalid base class, then missing 2694 // members were likely supposed to be inherited. 2695 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2696 if (CD->isInvalidDecl()) 2697 return ExprError(); 2698 Diag(NameInfo.getLoc(), diag::err_no_member) 2699 << NameInfo.getName() << DC << SS.getRange(); 2700 return ExprError(); 2701 } 2702 2703 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2704 // Diagnose a missing typename if this resolved unambiguously to a type in 2705 // a dependent context. If we can recover with a type, downgrade this to 2706 // a warning in Microsoft compatibility mode. 2707 unsigned DiagID = diag::err_typename_missing; 2708 if (RecoveryTSI && getLangOpts().MSVCCompat) 2709 DiagID = diag::ext_typename_missing; 2710 SourceLocation Loc = SS.getBeginLoc(); 2711 auto D = Diag(Loc, DiagID); 2712 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2713 << SourceRange(Loc, NameInfo.getEndLoc()); 2714 2715 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2716 // context. 2717 if (!RecoveryTSI) 2718 return ExprError(); 2719 2720 // Only issue the fixit if we're prepared to recover. 2721 D << FixItHint::CreateInsertion(Loc, "typename "); 2722 2723 // Recover by pretending this was an elaborated type. 2724 QualType Ty = Context.getTypeDeclType(TD); 2725 TypeLocBuilder TLB; 2726 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2727 2728 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2729 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2730 QTL.setElaboratedKeywordLoc(SourceLocation()); 2731 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2732 2733 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2734 2735 return ExprEmpty(); 2736 } 2737 2738 // Defend against this resolving to an implicit member access. We usually 2739 // won't get here if this might be a legitimate a class member (we end up in 2740 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2741 // a pointer-to-member or in an unevaluated context in C++11. 2742 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2743 return BuildPossibleImplicitMemberExpr(SS, 2744 /*TemplateKWLoc=*/SourceLocation(), 2745 R, /*TemplateArgs=*/nullptr, S); 2746 2747 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2748 } 2749 2750 /// The parser has read a name in, and Sema has detected that we're currently 2751 /// inside an ObjC method. Perform some additional checks and determine if we 2752 /// should form a reference to an ivar. 2753 /// 2754 /// Ideally, most of this would be done by lookup, but there's 2755 /// actually quite a lot of extra work involved. 2756 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2757 IdentifierInfo *II) { 2758 SourceLocation Loc = Lookup.getNameLoc(); 2759 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2760 2761 // Check for error condition which is already reported. 2762 if (!CurMethod) 2763 return DeclResult(true); 2764 2765 // There are two cases to handle here. 1) scoped lookup could have failed, 2766 // in which case we should look for an ivar. 2) scoped lookup could have 2767 // found a decl, but that decl is outside the current instance method (i.e. 2768 // a global variable). In these two cases, we do a lookup for an ivar with 2769 // this name, if the lookup sucedes, we replace it our current decl. 2770 2771 // If we're in a class method, we don't normally want to look for 2772 // ivars. But if we don't find anything else, and there's an 2773 // ivar, that's an error. 2774 bool IsClassMethod = CurMethod->isClassMethod(); 2775 2776 bool LookForIvars; 2777 if (Lookup.empty()) 2778 LookForIvars = true; 2779 else if (IsClassMethod) 2780 LookForIvars = false; 2781 else 2782 LookForIvars = (Lookup.isSingleResult() && 2783 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2784 ObjCInterfaceDecl *IFace = nullptr; 2785 if (LookForIvars) { 2786 IFace = CurMethod->getClassInterface(); 2787 ObjCInterfaceDecl *ClassDeclared; 2788 ObjCIvarDecl *IV = nullptr; 2789 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2790 // Diagnose using an ivar in a class method. 2791 if (IsClassMethod) { 2792 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2793 return DeclResult(true); 2794 } 2795 2796 // Diagnose the use of an ivar outside of the declaring class. 2797 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2798 !declaresSameEntity(ClassDeclared, IFace) && 2799 !getLangOpts().DebuggerSupport) 2800 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2801 2802 // Success. 2803 return IV; 2804 } 2805 } else if (CurMethod->isInstanceMethod()) { 2806 // We should warn if a local variable hides an ivar. 2807 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2808 ObjCInterfaceDecl *ClassDeclared; 2809 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2810 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2811 declaresSameEntity(IFace, ClassDeclared)) 2812 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2813 } 2814 } 2815 } else if (Lookup.isSingleResult() && 2816 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2817 // If accessing a stand-alone ivar in a class method, this is an error. 2818 if (const ObjCIvarDecl *IV = 2819 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2820 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2821 return DeclResult(true); 2822 } 2823 } 2824 2825 // Didn't encounter an error, didn't find an ivar. 2826 return DeclResult(false); 2827 } 2828 2829 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2830 ObjCIvarDecl *IV) { 2831 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2832 assert(CurMethod && CurMethod->isInstanceMethod() && 2833 "should not reference ivar from this context"); 2834 2835 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2836 assert(IFace && "should not reference ivar from this context"); 2837 2838 // If we're referencing an invalid decl, just return this as a silent 2839 // error node. The error diagnostic was already emitted on the decl. 2840 if (IV->isInvalidDecl()) 2841 return ExprError(); 2842 2843 // Check if referencing a field with __attribute__((deprecated)). 2844 if (DiagnoseUseOfDecl(IV, Loc)) 2845 return ExprError(); 2846 2847 // FIXME: This should use a new expr for a direct reference, don't 2848 // turn this into Self->ivar, just return a BareIVarExpr or something. 2849 IdentifierInfo &II = Context.Idents.get("self"); 2850 UnqualifiedId SelfName; 2851 SelfName.setImplicitSelfParam(&II); 2852 CXXScopeSpec SelfScopeSpec; 2853 SourceLocation TemplateKWLoc; 2854 ExprResult SelfExpr = 2855 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2856 /*HasTrailingLParen=*/false, 2857 /*IsAddressOfOperand=*/false); 2858 if (SelfExpr.isInvalid()) 2859 return ExprError(); 2860 2861 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2862 if (SelfExpr.isInvalid()) 2863 return ExprError(); 2864 2865 MarkAnyDeclReferenced(Loc, IV, true); 2866 2867 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2868 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2869 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2870 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2871 2872 ObjCIvarRefExpr *Result = new (Context) 2873 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2874 IV->getLocation(), SelfExpr.get(), true, true); 2875 2876 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2877 if (!isUnevaluatedContext() && 2878 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2879 getCurFunction()->recordUseOfWeak(Result); 2880 } 2881 if (getLangOpts().ObjCAutoRefCount) 2882 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2883 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2884 2885 return Result; 2886 } 2887 2888 /// The parser has read a name in, and Sema has detected that we're currently 2889 /// inside an ObjC method. Perform some additional checks and determine if we 2890 /// should form a reference to an ivar. If so, build an expression referencing 2891 /// that ivar. 2892 ExprResult 2893 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2894 IdentifierInfo *II, bool AllowBuiltinCreation) { 2895 // FIXME: Integrate this lookup step into LookupParsedName. 2896 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2897 if (Ivar.isInvalid()) 2898 return ExprError(); 2899 if (Ivar.isUsable()) 2900 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2901 cast<ObjCIvarDecl>(Ivar.get())); 2902 2903 if (Lookup.empty() && II && AllowBuiltinCreation) 2904 LookupBuiltin(Lookup); 2905 2906 // Sentinel value saying that we didn't do anything special. 2907 return ExprResult(false); 2908 } 2909 2910 /// Cast a base object to a member's actual type. 2911 /// 2912 /// There are two relevant checks: 2913 /// 2914 /// C++ [class.access.base]p7: 2915 /// 2916 /// If a class member access operator [...] is used to access a non-static 2917 /// data member or non-static member function, the reference is ill-formed if 2918 /// the left operand [...] cannot be implicitly converted to a pointer to the 2919 /// naming class of the right operand. 2920 /// 2921 /// C++ [expr.ref]p7: 2922 /// 2923 /// If E2 is a non-static data member or a non-static member function, the 2924 /// program is ill-formed if the class of which E2 is directly a member is an 2925 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2926 /// 2927 /// Note that the latter check does not consider access; the access of the 2928 /// "real" base class is checked as appropriate when checking the access of the 2929 /// member name. 2930 ExprResult 2931 Sema::PerformObjectMemberConversion(Expr *From, 2932 NestedNameSpecifier *Qualifier, 2933 NamedDecl *FoundDecl, 2934 NamedDecl *Member) { 2935 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2936 if (!RD) 2937 return From; 2938 2939 QualType DestRecordType; 2940 QualType DestType; 2941 QualType FromRecordType; 2942 QualType FromType = From->getType(); 2943 bool PointerConversions = false; 2944 if (isa<FieldDecl>(Member)) { 2945 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2946 auto FromPtrType = FromType->getAs<PointerType>(); 2947 DestRecordType = Context.getAddrSpaceQualType( 2948 DestRecordType, FromPtrType 2949 ? FromType->getPointeeType().getAddressSpace() 2950 : FromType.getAddressSpace()); 2951 2952 if (FromPtrType) { 2953 DestType = Context.getPointerType(DestRecordType); 2954 FromRecordType = FromPtrType->getPointeeType(); 2955 PointerConversions = true; 2956 } else { 2957 DestType = DestRecordType; 2958 FromRecordType = FromType; 2959 } 2960 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2961 if (Method->isStatic()) 2962 return From; 2963 2964 DestType = Method->getThisType(); 2965 DestRecordType = DestType->getPointeeType(); 2966 2967 if (FromType->getAs<PointerType>()) { 2968 FromRecordType = FromType->getPointeeType(); 2969 PointerConversions = true; 2970 } else { 2971 FromRecordType = FromType; 2972 DestType = DestRecordType; 2973 } 2974 2975 LangAS FromAS = FromRecordType.getAddressSpace(); 2976 LangAS DestAS = DestRecordType.getAddressSpace(); 2977 if (FromAS != DestAS) { 2978 QualType FromRecordTypeWithoutAS = 2979 Context.removeAddrSpaceQualType(FromRecordType); 2980 QualType FromTypeWithDestAS = 2981 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2982 if (PointerConversions) 2983 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2984 From = ImpCastExprToType(From, FromTypeWithDestAS, 2985 CK_AddressSpaceConversion, From->getValueKind()) 2986 .get(); 2987 } 2988 } else { 2989 // No conversion necessary. 2990 return From; 2991 } 2992 2993 if (DestType->isDependentType() || FromType->isDependentType()) 2994 return From; 2995 2996 // If the unqualified types are the same, no conversion is necessary. 2997 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2998 return From; 2999 3000 SourceRange FromRange = From->getSourceRange(); 3001 SourceLocation FromLoc = FromRange.getBegin(); 3002 3003 ExprValueKind VK = From->getValueKind(); 3004 3005 // C++ [class.member.lookup]p8: 3006 // [...] Ambiguities can often be resolved by qualifying a name with its 3007 // class name. 3008 // 3009 // If the member was a qualified name and the qualified referred to a 3010 // specific base subobject type, we'll cast to that intermediate type 3011 // first and then to the object in which the member is declared. That allows 3012 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3013 // 3014 // class Base { public: int x; }; 3015 // class Derived1 : public Base { }; 3016 // class Derived2 : public Base { }; 3017 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3018 // 3019 // void VeryDerived::f() { 3020 // x = 17; // error: ambiguous base subobjects 3021 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3022 // } 3023 if (Qualifier && Qualifier->getAsType()) { 3024 QualType QType = QualType(Qualifier->getAsType(), 0); 3025 assert(QType->isRecordType() && "lookup done with non-record type"); 3026 3027 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3028 3029 // In C++98, the qualifier type doesn't actually have to be a base 3030 // type of the object type, in which case we just ignore it. 3031 // Otherwise build the appropriate casts. 3032 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3033 CXXCastPath BasePath; 3034 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3035 FromLoc, FromRange, &BasePath)) 3036 return ExprError(); 3037 3038 if (PointerConversions) 3039 QType = Context.getPointerType(QType); 3040 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3041 VK, &BasePath).get(); 3042 3043 FromType = QType; 3044 FromRecordType = QRecordType; 3045 3046 // If the qualifier type was the same as the destination type, 3047 // we're done. 3048 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3049 return From; 3050 } 3051 } 3052 3053 CXXCastPath BasePath; 3054 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3055 FromLoc, FromRange, &BasePath, 3056 /*IgnoreAccess=*/true)) 3057 return ExprError(); 3058 3059 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3060 VK, &BasePath); 3061 } 3062 3063 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3064 const LookupResult &R, 3065 bool HasTrailingLParen) { 3066 // Only when used directly as the postfix-expression of a call. 3067 if (!HasTrailingLParen) 3068 return false; 3069 3070 // Never if a scope specifier was provided. 3071 if (SS.isSet()) 3072 return false; 3073 3074 // Only in C++ or ObjC++. 3075 if (!getLangOpts().CPlusPlus) 3076 return false; 3077 3078 // Turn off ADL when we find certain kinds of declarations during 3079 // normal lookup: 3080 for (NamedDecl *D : R) { 3081 // C++0x [basic.lookup.argdep]p3: 3082 // -- a declaration of a class member 3083 // Since using decls preserve this property, we check this on the 3084 // original decl. 3085 if (D->isCXXClassMember()) 3086 return false; 3087 3088 // C++0x [basic.lookup.argdep]p3: 3089 // -- a block-scope function declaration that is not a 3090 // using-declaration 3091 // NOTE: we also trigger this for function templates (in fact, we 3092 // don't check the decl type at all, since all other decl types 3093 // turn off ADL anyway). 3094 if (isa<UsingShadowDecl>(D)) 3095 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3096 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3097 return false; 3098 3099 // C++0x [basic.lookup.argdep]p3: 3100 // -- a declaration that is neither a function or a function 3101 // template 3102 // And also for builtin functions. 3103 if (isa<FunctionDecl>(D)) { 3104 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3105 3106 // But also builtin functions. 3107 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3108 return false; 3109 } else if (!isa<FunctionTemplateDecl>(D)) 3110 return false; 3111 } 3112 3113 return true; 3114 } 3115 3116 3117 /// Diagnoses obvious problems with the use of the given declaration 3118 /// as an expression. This is only actually called for lookups that 3119 /// were not overloaded, and it doesn't promise that the declaration 3120 /// will in fact be used. 3121 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3122 if (D->isInvalidDecl()) 3123 return true; 3124 3125 if (isa<TypedefNameDecl>(D)) { 3126 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3127 return true; 3128 } 3129 3130 if (isa<ObjCInterfaceDecl>(D)) { 3131 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3132 return true; 3133 } 3134 3135 if (isa<NamespaceDecl>(D)) { 3136 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3137 return true; 3138 } 3139 3140 return false; 3141 } 3142 3143 // Certain multiversion types should be treated as overloaded even when there is 3144 // only one result. 3145 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3146 assert(R.isSingleResult() && "Expected only a single result"); 3147 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3148 return FD && 3149 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3150 } 3151 3152 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3153 LookupResult &R, bool NeedsADL, 3154 bool AcceptInvalidDecl) { 3155 // If this is a single, fully-resolved result and we don't need ADL, 3156 // just build an ordinary singleton decl ref. 3157 if (!NeedsADL && R.isSingleResult() && 3158 !R.getAsSingle<FunctionTemplateDecl>() && 3159 !ShouldLookupResultBeMultiVersionOverload(R)) 3160 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3161 R.getRepresentativeDecl(), nullptr, 3162 AcceptInvalidDecl); 3163 3164 // We only need to check the declaration if there's exactly one 3165 // result, because in the overloaded case the results can only be 3166 // functions and function templates. 3167 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3168 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3169 return ExprError(); 3170 3171 // Otherwise, just build an unresolved lookup expression. Suppress 3172 // any lookup-related diagnostics; we'll hash these out later, when 3173 // we've picked a target. 3174 R.suppressDiagnostics(); 3175 3176 UnresolvedLookupExpr *ULE 3177 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3178 SS.getWithLocInContext(Context), 3179 R.getLookupNameInfo(), 3180 NeedsADL, R.isOverloadedResult(), 3181 R.begin(), R.end()); 3182 3183 return ULE; 3184 } 3185 3186 static void 3187 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3188 ValueDecl *var, DeclContext *DC); 3189 3190 /// Complete semantic analysis for a reference to the given declaration. 3191 ExprResult Sema::BuildDeclarationNameExpr( 3192 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3193 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3194 bool AcceptInvalidDecl) { 3195 assert(D && "Cannot refer to a NULL declaration"); 3196 assert(!isa<FunctionTemplateDecl>(D) && 3197 "Cannot refer unambiguously to a function template"); 3198 3199 SourceLocation Loc = NameInfo.getLoc(); 3200 if (CheckDeclInExpr(*this, Loc, D)) 3201 return ExprError(); 3202 3203 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3204 // Specifically diagnose references to class templates that are missing 3205 // a template argument list. 3206 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3207 return ExprError(); 3208 } 3209 3210 // Make sure that we're referring to a value. 3211 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3212 if (!VD) { 3213 Diag(Loc, diag::err_ref_non_value) 3214 << D << SS.getRange(); 3215 Diag(D->getLocation(), diag::note_declared_at); 3216 return ExprError(); 3217 } 3218 3219 // Check whether this declaration can be used. Note that we suppress 3220 // this check when we're going to perform argument-dependent lookup 3221 // on this function name, because this might not be the function 3222 // that overload resolution actually selects. 3223 if (DiagnoseUseOfDecl(VD, Loc)) 3224 return ExprError(); 3225 3226 // Only create DeclRefExpr's for valid Decl's. 3227 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3228 return ExprError(); 3229 3230 // Handle members of anonymous structs and unions. If we got here, 3231 // and the reference is to a class member indirect field, then this 3232 // must be the subject of a pointer-to-member expression. 3233 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3234 if (!indirectField->isCXXClassMember()) 3235 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3236 indirectField); 3237 3238 { 3239 QualType type = VD->getType(); 3240 if (type.isNull()) 3241 return ExprError(); 3242 ExprValueKind valueKind = VK_RValue; 3243 3244 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3245 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3246 // is expanded by some outer '...' in the context of the use. 3247 type = type.getNonPackExpansionType(); 3248 3249 switch (D->getKind()) { 3250 // Ignore all the non-ValueDecl kinds. 3251 #define ABSTRACT_DECL(kind) 3252 #define VALUE(type, base) 3253 #define DECL(type, base) \ 3254 case Decl::type: 3255 #include "clang/AST/DeclNodes.inc" 3256 llvm_unreachable("invalid value decl kind"); 3257 3258 // These shouldn't make it here. 3259 case Decl::ObjCAtDefsField: 3260 llvm_unreachable("forming non-member reference to ivar?"); 3261 3262 // Enum constants are always r-values and never references. 3263 // Unresolved using declarations are dependent. 3264 case Decl::EnumConstant: 3265 case Decl::UnresolvedUsingValue: 3266 case Decl::OMPDeclareReduction: 3267 case Decl::OMPDeclareMapper: 3268 valueKind = VK_RValue; 3269 break; 3270 3271 // Fields and indirect fields that got here must be for 3272 // pointer-to-member expressions; we just call them l-values for 3273 // internal consistency, because this subexpression doesn't really 3274 // exist in the high-level semantics. 3275 case Decl::Field: 3276 case Decl::IndirectField: 3277 case Decl::ObjCIvar: 3278 assert(getLangOpts().CPlusPlus && 3279 "building reference to field in C?"); 3280 3281 // These can't have reference type in well-formed programs, but 3282 // for internal consistency we do this anyway. 3283 type = type.getNonReferenceType(); 3284 valueKind = VK_LValue; 3285 break; 3286 3287 // Non-type template parameters are either l-values or r-values 3288 // depending on the type. 3289 case Decl::NonTypeTemplateParm: { 3290 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3291 type = reftype->getPointeeType(); 3292 valueKind = VK_LValue; // even if the parameter is an r-value reference 3293 break; 3294 } 3295 3296 // [expr.prim.id.unqual]p2: 3297 // If the entity is a template parameter object for a template 3298 // parameter of type T, the type of the expression is const T. 3299 // [...] The expression is an lvalue if the entity is a [...] template 3300 // parameter object. 3301 if (type->isRecordType()) { 3302 type = type.getUnqualifiedType().withConst(); 3303 valueKind = VK_LValue; 3304 break; 3305 } 3306 3307 // For non-references, we need to strip qualifiers just in case 3308 // the template parameter was declared as 'const int' or whatever. 3309 valueKind = VK_RValue; 3310 type = type.getUnqualifiedType(); 3311 break; 3312 } 3313 3314 case Decl::Var: 3315 case Decl::VarTemplateSpecialization: 3316 case Decl::VarTemplatePartialSpecialization: 3317 case Decl::Decomposition: 3318 case Decl::OMPCapturedExpr: 3319 // In C, "extern void blah;" is valid and is an r-value. 3320 if (!getLangOpts().CPlusPlus && 3321 !type.hasQualifiers() && 3322 type->isVoidType()) { 3323 valueKind = VK_RValue; 3324 break; 3325 } 3326 LLVM_FALLTHROUGH; 3327 3328 case Decl::ImplicitParam: 3329 case Decl::ParmVar: { 3330 // These are always l-values. 3331 valueKind = VK_LValue; 3332 type = type.getNonReferenceType(); 3333 3334 // FIXME: Does the addition of const really only apply in 3335 // potentially-evaluated contexts? Since the variable isn't actually 3336 // captured in an unevaluated context, it seems that the answer is no. 3337 if (!isUnevaluatedContext()) { 3338 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3339 if (!CapturedType.isNull()) 3340 type = CapturedType; 3341 } 3342 3343 break; 3344 } 3345 3346 case Decl::Binding: { 3347 // These are always lvalues. 3348 valueKind = VK_LValue; 3349 type = type.getNonReferenceType(); 3350 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3351 // decides how that's supposed to work. 3352 auto *BD = cast<BindingDecl>(VD); 3353 if (BD->getDeclContext() != CurContext) { 3354 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3355 if (DD && DD->hasLocalStorage()) 3356 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3357 } 3358 break; 3359 } 3360 3361 case Decl::Function: { 3362 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3363 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3364 type = Context.BuiltinFnTy; 3365 valueKind = VK_RValue; 3366 break; 3367 } 3368 } 3369 3370 const FunctionType *fty = type->castAs<FunctionType>(); 3371 3372 // If we're referring to a function with an __unknown_anytype 3373 // result type, make the entire expression __unknown_anytype. 3374 if (fty->getReturnType() == Context.UnknownAnyTy) { 3375 type = Context.UnknownAnyTy; 3376 valueKind = VK_RValue; 3377 break; 3378 } 3379 3380 // Functions are l-values in C++. 3381 if (getLangOpts().CPlusPlus) { 3382 valueKind = VK_LValue; 3383 break; 3384 } 3385 3386 // C99 DR 316 says that, if a function type comes from a 3387 // function definition (without a prototype), that type is only 3388 // used for checking compatibility. Therefore, when referencing 3389 // the function, we pretend that we don't have the full function 3390 // type. 3391 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3392 isa<FunctionProtoType>(fty)) 3393 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3394 fty->getExtInfo()); 3395 3396 // Functions are r-values in C. 3397 valueKind = VK_RValue; 3398 break; 3399 } 3400 3401 case Decl::CXXDeductionGuide: 3402 llvm_unreachable("building reference to deduction guide"); 3403 3404 case Decl::MSProperty: 3405 case Decl::MSGuid: 3406 case Decl::TemplateParamObject: 3407 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3408 // capture in OpenMP, or duplicated between host and device? 3409 valueKind = VK_LValue; 3410 break; 3411 3412 case Decl::CXXMethod: 3413 // If we're referring to a method with an __unknown_anytype 3414 // result type, make the entire expression __unknown_anytype. 3415 // This should only be possible with a type written directly. 3416 if (const FunctionProtoType *proto 3417 = dyn_cast<FunctionProtoType>(VD->getType())) 3418 if (proto->getReturnType() == Context.UnknownAnyTy) { 3419 type = Context.UnknownAnyTy; 3420 valueKind = VK_RValue; 3421 break; 3422 } 3423 3424 // C++ methods are l-values if static, r-values if non-static. 3425 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3426 valueKind = VK_LValue; 3427 break; 3428 } 3429 LLVM_FALLTHROUGH; 3430 3431 case Decl::CXXConversion: 3432 case Decl::CXXDestructor: 3433 case Decl::CXXConstructor: 3434 valueKind = VK_RValue; 3435 break; 3436 } 3437 3438 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3439 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3440 TemplateArgs); 3441 } 3442 } 3443 3444 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3445 SmallString<32> &Target) { 3446 Target.resize(CharByteWidth * (Source.size() + 1)); 3447 char *ResultPtr = &Target[0]; 3448 const llvm::UTF8 *ErrorPtr; 3449 bool success = 3450 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3451 (void)success; 3452 assert(success); 3453 Target.resize(ResultPtr - &Target[0]); 3454 } 3455 3456 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3457 PredefinedExpr::IdentKind IK) { 3458 // Pick the current block, lambda, captured statement or function. 3459 Decl *currentDecl = nullptr; 3460 if (const BlockScopeInfo *BSI = getCurBlock()) 3461 currentDecl = BSI->TheDecl; 3462 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3463 currentDecl = LSI->CallOperator; 3464 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3465 currentDecl = CSI->TheCapturedDecl; 3466 else 3467 currentDecl = getCurFunctionOrMethodDecl(); 3468 3469 if (!currentDecl) { 3470 Diag(Loc, diag::ext_predef_outside_function); 3471 currentDecl = Context.getTranslationUnitDecl(); 3472 } 3473 3474 QualType ResTy; 3475 StringLiteral *SL = nullptr; 3476 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3477 ResTy = Context.DependentTy; 3478 else { 3479 // Pre-defined identifiers are of type char[x], where x is the length of 3480 // the string. 3481 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3482 unsigned Length = Str.length(); 3483 3484 llvm::APInt LengthI(32, Length + 1); 3485 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3486 ResTy = 3487 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3488 SmallString<32> RawChars; 3489 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3490 Str, RawChars); 3491 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3492 ArrayType::Normal, 3493 /*IndexTypeQuals*/ 0); 3494 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3495 /*Pascal*/ false, ResTy, Loc); 3496 } else { 3497 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3498 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3499 ArrayType::Normal, 3500 /*IndexTypeQuals*/ 0); 3501 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3502 /*Pascal*/ false, ResTy, Loc); 3503 } 3504 } 3505 3506 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3507 } 3508 3509 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3510 SourceLocation LParen, 3511 SourceLocation RParen, 3512 TypeSourceInfo *TSI) { 3513 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3514 } 3515 3516 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3517 SourceLocation LParen, 3518 SourceLocation RParen, 3519 ParsedType ParsedTy) { 3520 TypeSourceInfo *TSI = nullptr; 3521 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3522 3523 if (Ty.isNull()) 3524 return ExprError(); 3525 if (!TSI) 3526 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3527 3528 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3529 } 3530 3531 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3532 PredefinedExpr::IdentKind IK; 3533 3534 switch (Kind) { 3535 default: llvm_unreachable("Unknown simple primary expr!"); 3536 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3537 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3538 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3539 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3540 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3541 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3542 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3543 } 3544 3545 return BuildPredefinedExpr(Loc, IK); 3546 } 3547 3548 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3549 SmallString<16> CharBuffer; 3550 bool Invalid = false; 3551 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3552 if (Invalid) 3553 return ExprError(); 3554 3555 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3556 PP, Tok.getKind()); 3557 if (Literal.hadError()) 3558 return ExprError(); 3559 3560 QualType Ty; 3561 if (Literal.isWide()) 3562 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3563 else if (Literal.isUTF8() && getLangOpts().Char8) 3564 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3565 else if (Literal.isUTF16()) 3566 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3567 else if (Literal.isUTF32()) 3568 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3569 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3570 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3571 else 3572 Ty = Context.CharTy; // 'x' -> char in C++ 3573 3574 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3575 if (Literal.isWide()) 3576 Kind = CharacterLiteral::Wide; 3577 else if (Literal.isUTF16()) 3578 Kind = CharacterLiteral::UTF16; 3579 else if (Literal.isUTF32()) 3580 Kind = CharacterLiteral::UTF32; 3581 else if (Literal.isUTF8()) 3582 Kind = CharacterLiteral::UTF8; 3583 3584 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3585 Tok.getLocation()); 3586 3587 if (Literal.getUDSuffix().empty()) 3588 return Lit; 3589 3590 // We're building a user-defined literal. 3591 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3592 SourceLocation UDSuffixLoc = 3593 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3594 3595 // Make sure we're allowed user-defined literals here. 3596 if (!UDLScope) 3597 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3598 3599 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3600 // operator "" X (ch) 3601 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3602 Lit, Tok.getLocation()); 3603 } 3604 3605 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3606 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3607 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3608 Context.IntTy, Loc); 3609 } 3610 3611 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3612 QualType Ty, SourceLocation Loc) { 3613 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3614 3615 using llvm::APFloat; 3616 APFloat Val(Format); 3617 3618 APFloat::opStatus result = Literal.GetFloatValue(Val); 3619 3620 // Overflow is always an error, but underflow is only an error if 3621 // we underflowed to zero (APFloat reports denormals as underflow). 3622 if ((result & APFloat::opOverflow) || 3623 ((result & APFloat::opUnderflow) && Val.isZero())) { 3624 unsigned diagnostic; 3625 SmallString<20> buffer; 3626 if (result & APFloat::opOverflow) { 3627 diagnostic = diag::warn_float_overflow; 3628 APFloat::getLargest(Format).toString(buffer); 3629 } else { 3630 diagnostic = diag::warn_float_underflow; 3631 APFloat::getSmallest(Format).toString(buffer); 3632 } 3633 3634 S.Diag(Loc, diagnostic) 3635 << Ty 3636 << StringRef(buffer.data(), buffer.size()); 3637 } 3638 3639 bool isExact = (result == APFloat::opOK); 3640 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3641 } 3642 3643 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3644 assert(E && "Invalid expression"); 3645 3646 if (E->isValueDependent()) 3647 return false; 3648 3649 QualType QT = E->getType(); 3650 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3651 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3652 return true; 3653 } 3654 3655 llvm::APSInt ValueAPS; 3656 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3657 3658 if (R.isInvalid()) 3659 return true; 3660 3661 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3662 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3663 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3664 << ValueAPS.toString(10) << ValueIsPositive; 3665 return true; 3666 } 3667 3668 return false; 3669 } 3670 3671 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3672 // Fast path for a single digit (which is quite common). A single digit 3673 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3674 if (Tok.getLength() == 1) { 3675 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3676 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3677 } 3678 3679 SmallString<128> SpellingBuffer; 3680 // NumericLiteralParser wants to overread by one character. Add padding to 3681 // the buffer in case the token is copied to the buffer. If getSpelling() 3682 // returns a StringRef to the memory buffer, it should have a null char at 3683 // the EOF, so it is also safe. 3684 SpellingBuffer.resize(Tok.getLength() + 1); 3685 3686 // Get the spelling of the token, which eliminates trigraphs, etc. 3687 bool Invalid = false; 3688 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3689 if (Invalid) 3690 return ExprError(); 3691 3692 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3693 PP.getSourceManager(), PP.getLangOpts(), 3694 PP.getTargetInfo(), PP.getDiagnostics()); 3695 if (Literal.hadError) 3696 return ExprError(); 3697 3698 if (Literal.hasUDSuffix()) { 3699 // We're building a user-defined literal. 3700 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3701 SourceLocation UDSuffixLoc = 3702 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3703 3704 // Make sure we're allowed user-defined literals here. 3705 if (!UDLScope) 3706 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3707 3708 QualType CookedTy; 3709 if (Literal.isFloatingLiteral()) { 3710 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3711 // long double, the literal is treated as a call of the form 3712 // operator "" X (f L) 3713 CookedTy = Context.LongDoubleTy; 3714 } else { 3715 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3716 // unsigned long long, the literal is treated as a call of the form 3717 // operator "" X (n ULL) 3718 CookedTy = Context.UnsignedLongLongTy; 3719 } 3720 3721 DeclarationName OpName = 3722 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3723 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3724 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3725 3726 SourceLocation TokLoc = Tok.getLocation(); 3727 3728 // Perform literal operator lookup to determine if we're building a raw 3729 // literal or a cooked one. 3730 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3731 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3732 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3733 /*AllowStringTemplatePack*/ false, 3734 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3735 case LOLR_ErrorNoDiagnostic: 3736 // Lookup failure for imaginary constants isn't fatal, there's still the 3737 // GNU extension producing _Complex types. 3738 break; 3739 case LOLR_Error: 3740 return ExprError(); 3741 case LOLR_Cooked: { 3742 Expr *Lit; 3743 if (Literal.isFloatingLiteral()) { 3744 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3745 } else { 3746 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3747 if (Literal.GetIntegerValue(ResultVal)) 3748 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3749 << /* Unsigned */ 1; 3750 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3751 Tok.getLocation()); 3752 } 3753 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3754 } 3755 3756 case LOLR_Raw: { 3757 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3758 // literal is treated as a call of the form 3759 // operator "" X ("n") 3760 unsigned Length = Literal.getUDSuffixOffset(); 3761 QualType StrTy = Context.getConstantArrayType( 3762 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3763 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3764 Expr *Lit = StringLiteral::Create( 3765 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3766 /*Pascal*/false, StrTy, &TokLoc, 1); 3767 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3768 } 3769 3770 case LOLR_Template: { 3771 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3772 // template), L is treated as a call fo the form 3773 // operator "" X <'c1', 'c2', ... 'ck'>() 3774 // where n is the source character sequence c1 c2 ... ck. 3775 TemplateArgumentListInfo ExplicitArgs; 3776 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3777 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3778 llvm::APSInt Value(CharBits, CharIsUnsigned); 3779 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3780 Value = TokSpelling[I]; 3781 TemplateArgument Arg(Context, Value, Context.CharTy); 3782 TemplateArgumentLocInfo ArgInfo; 3783 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3784 } 3785 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3786 &ExplicitArgs); 3787 } 3788 case LOLR_StringTemplatePack: 3789 llvm_unreachable("unexpected literal operator lookup result"); 3790 } 3791 } 3792 3793 Expr *Res; 3794 3795 if (Literal.isFixedPointLiteral()) { 3796 QualType Ty; 3797 3798 if (Literal.isAccum) { 3799 if (Literal.isHalf) { 3800 Ty = Context.ShortAccumTy; 3801 } else if (Literal.isLong) { 3802 Ty = Context.LongAccumTy; 3803 } else { 3804 Ty = Context.AccumTy; 3805 } 3806 } else if (Literal.isFract) { 3807 if (Literal.isHalf) { 3808 Ty = Context.ShortFractTy; 3809 } else if (Literal.isLong) { 3810 Ty = Context.LongFractTy; 3811 } else { 3812 Ty = Context.FractTy; 3813 } 3814 } 3815 3816 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3817 3818 bool isSigned = !Literal.isUnsigned; 3819 unsigned scale = Context.getFixedPointScale(Ty); 3820 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3821 3822 llvm::APInt Val(bit_width, 0, isSigned); 3823 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3824 bool ValIsZero = Val.isNullValue() && !Overflowed; 3825 3826 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3827 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3828 // Clause 6.4.4 - The value of a constant shall be in the range of 3829 // representable values for its type, with exception for constants of a 3830 // fract type with a value of exactly 1; such a constant shall denote 3831 // the maximal value for the type. 3832 --Val; 3833 else if (Val.ugt(MaxVal) || Overflowed) 3834 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3835 3836 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3837 Tok.getLocation(), scale); 3838 } else if (Literal.isFloatingLiteral()) { 3839 QualType Ty; 3840 if (Literal.isHalf){ 3841 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3842 Ty = Context.HalfTy; 3843 else { 3844 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3845 return ExprError(); 3846 } 3847 } else if (Literal.isFloat) 3848 Ty = Context.FloatTy; 3849 else if (Literal.isLong) 3850 Ty = Context.LongDoubleTy; 3851 else if (Literal.isFloat16) 3852 Ty = Context.Float16Ty; 3853 else if (Literal.isFloat128) 3854 Ty = Context.Float128Ty; 3855 else 3856 Ty = Context.DoubleTy; 3857 3858 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3859 3860 if (Ty == Context.DoubleTy) { 3861 if (getLangOpts().SinglePrecisionConstants) { 3862 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3863 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3864 } 3865 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3866 "cl_khr_fp64", getLangOpts())) { 3867 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3868 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3869 << (getLangOpts().OpenCLVersion >= 300); 3870 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3871 } 3872 } 3873 } else if (!Literal.isIntegerLiteral()) { 3874 return ExprError(); 3875 } else { 3876 QualType Ty; 3877 3878 // 'long long' is a C99 or C++11 feature. 3879 if (!getLangOpts().C99 && Literal.isLongLong) { 3880 if (getLangOpts().CPlusPlus) 3881 Diag(Tok.getLocation(), 3882 getLangOpts().CPlusPlus11 ? 3883 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3884 else 3885 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3886 } 3887 3888 // 'z/uz' literals are a C++2b feature. 3889 if (Literal.isSizeT) 3890 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3891 ? getLangOpts().CPlusPlus2b 3892 ? diag::warn_cxx20_compat_size_t_suffix 3893 : diag::ext_cxx2b_size_t_suffix 3894 : diag::err_cxx2b_size_t_suffix); 3895 3896 // Get the value in the widest-possible width. 3897 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3898 llvm::APInt ResultVal(MaxWidth, 0); 3899 3900 if (Literal.GetIntegerValue(ResultVal)) { 3901 // If this value didn't fit into uintmax_t, error and force to ull. 3902 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3903 << /* Unsigned */ 1; 3904 Ty = Context.UnsignedLongLongTy; 3905 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3906 "long long is not intmax_t?"); 3907 } else { 3908 // If this value fits into a ULL, try to figure out what else it fits into 3909 // according to the rules of C99 6.4.4.1p5. 3910 3911 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3912 // be an unsigned int. 3913 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3914 3915 // Check from smallest to largest, picking the smallest type we can. 3916 unsigned Width = 0; 3917 3918 // Microsoft specific integer suffixes are explicitly sized. 3919 if (Literal.MicrosoftInteger) { 3920 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3921 Width = 8; 3922 Ty = Context.CharTy; 3923 } else { 3924 Width = Literal.MicrosoftInteger; 3925 Ty = Context.getIntTypeForBitwidth(Width, 3926 /*Signed=*/!Literal.isUnsigned); 3927 } 3928 } 3929 3930 // Check C++2b size_t literals. 3931 if (Literal.isSizeT) { 3932 assert(!Literal.MicrosoftInteger && 3933 "size_t literals can't be Microsoft literals"); 3934 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3935 Context.getTargetInfo().getSizeType()); 3936 3937 // Does it fit in size_t? 3938 if (ResultVal.isIntN(SizeTSize)) { 3939 // Does it fit in ssize_t? 3940 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3941 Ty = Context.getSignedSizeType(); 3942 else if (AllowUnsigned) 3943 Ty = Context.getSizeType(); 3944 Width = SizeTSize; 3945 } 3946 } 3947 3948 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3949 !Literal.isSizeT) { 3950 // Are int/unsigned possibilities? 3951 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3952 3953 // Does it fit in a unsigned int? 3954 if (ResultVal.isIntN(IntSize)) { 3955 // Does it fit in a signed int? 3956 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3957 Ty = Context.IntTy; 3958 else if (AllowUnsigned) 3959 Ty = Context.UnsignedIntTy; 3960 Width = IntSize; 3961 } 3962 } 3963 3964 // Are long/unsigned long possibilities? 3965 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3966 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3967 3968 // Does it fit in a unsigned long? 3969 if (ResultVal.isIntN(LongSize)) { 3970 // Does it fit in a signed long? 3971 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3972 Ty = Context.LongTy; 3973 else if (AllowUnsigned) 3974 Ty = Context.UnsignedLongTy; 3975 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3976 // is compatible. 3977 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3978 const unsigned LongLongSize = 3979 Context.getTargetInfo().getLongLongWidth(); 3980 Diag(Tok.getLocation(), 3981 getLangOpts().CPlusPlus 3982 ? Literal.isLong 3983 ? diag::warn_old_implicitly_unsigned_long_cxx 3984 : /*C++98 UB*/ diag:: 3985 ext_old_implicitly_unsigned_long_cxx 3986 : diag::warn_old_implicitly_unsigned_long) 3987 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3988 : /*will be ill-formed*/ 1); 3989 Ty = Context.UnsignedLongTy; 3990 } 3991 Width = LongSize; 3992 } 3993 } 3994 3995 // Check long long if needed. 3996 if (Ty.isNull() && !Literal.isSizeT) { 3997 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3998 3999 // Does it fit in a unsigned long long? 4000 if (ResultVal.isIntN(LongLongSize)) { 4001 // Does it fit in a signed long long? 4002 // To be compatible with MSVC, hex integer literals ending with the 4003 // LL or i64 suffix are always signed in Microsoft mode. 4004 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4005 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4006 Ty = Context.LongLongTy; 4007 else if (AllowUnsigned) 4008 Ty = Context.UnsignedLongLongTy; 4009 Width = LongLongSize; 4010 } 4011 } 4012 4013 // If we still couldn't decide a type, we either have 'size_t' literal 4014 // that is out of range, or a decimal literal that does not fit in a 4015 // signed long long and has no U suffix. 4016 if (Ty.isNull()) { 4017 if (Literal.isSizeT) 4018 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4019 << Literal.isUnsigned; 4020 else 4021 Diag(Tok.getLocation(), 4022 diag::ext_integer_literal_too_large_for_signed); 4023 Ty = Context.UnsignedLongLongTy; 4024 Width = Context.getTargetInfo().getLongLongWidth(); 4025 } 4026 4027 if (ResultVal.getBitWidth() != Width) 4028 ResultVal = ResultVal.trunc(Width); 4029 } 4030 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4031 } 4032 4033 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4034 if (Literal.isImaginary) { 4035 Res = new (Context) ImaginaryLiteral(Res, 4036 Context.getComplexType(Res->getType())); 4037 4038 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4039 } 4040 return Res; 4041 } 4042 4043 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4044 assert(E && "ActOnParenExpr() missing expr"); 4045 return new (Context) ParenExpr(L, R, E); 4046 } 4047 4048 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4049 SourceLocation Loc, 4050 SourceRange ArgRange) { 4051 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4052 // scalar or vector data type argument..." 4053 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4054 // type (C99 6.2.5p18) or void. 4055 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4056 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4057 << T << ArgRange; 4058 return true; 4059 } 4060 4061 assert((T->isVoidType() || !T->isIncompleteType()) && 4062 "Scalar types should always be complete"); 4063 return false; 4064 } 4065 4066 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4067 SourceLocation Loc, 4068 SourceRange ArgRange, 4069 UnaryExprOrTypeTrait TraitKind) { 4070 // Invalid types must be hard errors for SFINAE in C++. 4071 if (S.LangOpts.CPlusPlus) 4072 return true; 4073 4074 // C99 6.5.3.4p1: 4075 if (T->isFunctionType() && 4076 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4077 TraitKind == UETT_PreferredAlignOf)) { 4078 // sizeof(function)/alignof(function) is allowed as an extension. 4079 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4080 << getTraitSpelling(TraitKind) << ArgRange; 4081 return false; 4082 } 4083 4084 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4085 // this is an error (OpenCL v1.1 s6.3.k) 4086 if (T->isVoidType()) { 4087 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4088 : diag::ext_sizeof_alignof_void_type; 4089 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4090 return false; 4091 } 4092 4093 return true; 4094 } 4095 4096 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4097 SourceLocation Loc, 4098 SourceRange ArgRange, 4099 UnaryExprOrTypeTrait TraitKind) { 4100 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4101 // runtime doesn't allow it. 4102 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4103 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4104 << T << (TraitKind == UETT_SizeOf) 4105 << ArgRange; 4106 return true; 4107 } 4108 4109 return false; 4110 } 4111 4112 /// Check whether E is a pointer from a decayed array type (the decayed 4113 /// pointer type is equal to T) and emit a warning if it is. 4114 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4115 Expr *E) { 4116 // Don't warn if the operation changed the type. 4117 if (T != E->getType()) 4118 return; 4119 4120 // Now look for array decays. 4121 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4122 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4123 return; 4124 4125 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4126 << ICE->getType() 4127 << ICE->getSubExpr()->getType(); 4128 } 4129 4130 /// Check the constraints on expression operands to unary type expression 4131 /// and type traits. 4132 /// 4133 /// Completes any types necessary and validates the constraints on the operand 4134 /// expression. The logic mostly mirrors the type-based overload, but may modify 4135 /// the expression as it completes the type for that expression through template 4136 /// instantiation, etc. 4137 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4138 UnaryExprOrTypeTrait ExprKind) { 4139 QualType ExprTy = E->getType(); 4140 assert(!ExprTy->isReferenceType()); 4141 4142 bool IsUnevaluatedOperand = 4143 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4144 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4145 if (IsUnevaluatedOperand) { 4146 ExprResult Result = CheckUnevaluatedOperand(E); 4147 if (Result.isInvalid()) 4148 return true; 4149 E = Result.get(); 4150 } 4151 4152 // The operand for sizeof and alignof is in an unevaluated expression context, 4153 // so side effects could result in unintended consequences. 4154 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4155 // used to build SFINAE gadgets. 4156 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4157 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4158 !E->isInstantiationDependent() && 4159 E->HasSideEffects(Context, false)) 4160 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4161 4162 if (ExprKind == UETT_VecStep) 4163 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4164 E->getSourceRange()); 4165 4166 // Explicitly list some types as extensions. 4167 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4168 E->getSourceRange(), ExprKind)) 4169 return false; 4170 4171 // 'alignof' applied to an expression only requires the base element type of 4172 // the expression to be complete. 'sizeof' requires the expression's type to 4173 // be complete (and will attempt to complete it if it's an array of unknown 4174 // bound). 4175 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4176 if (RequireCompleteSizedType( 4177 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4178 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4179 getTraitSpelling(ExprKind), E->getSourceRange())) 4180 return true; 4181 } else { 4182 if (RequireCompleteSizedExprType( 4183 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4184 getTraitSpelling(ExprKind), E->getSourceRange())) 4185 return true; 4186 } 4187 4188 // Completing the expression's type may have changed it. 4189 ExprTy = E->getType(); 4190 assert(!ExprTy->isReferenceType()); 4191 4192 if (ExprTy->isFunctionType()) { 4193 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4194 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4195 return true; 4196 } 4197 4198 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4199 E->getSourceRange(), ExprKind)) 4200 return true; 4201 4202 if (ExprKind == UETT_SizeOf) { 4203 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4204 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4205 QualType OType = PVD->getOriginalType(); 4206 QualType Type = PVD->getType(); 4207 if (Type->isPointerType() && OType->isArrayType()) { 4208 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4209 << Type << OType; 4210 Diag(PVD->getLocation(), diag::note_declared_at); 4211 } 4212 } 4213 } 4214 4215 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4216 // decays into a pointer and returns an unintended result. This is most 4217 // likely a typo for "sizeof(array) op x". 4218 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4219 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4220 BO->getLHS()); 4221 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4222 BO->getRHS()); 4223 } 4224 } 4225 4226 return false; 4227 } 4228 4229 /// Check the constraints on operands to unary expression and type 4230 /// traits. 4231 /// 4232 /// This will complete any types necessary, and validate the various constraints 4233 /// on those operands. 4234 /// 4235 /// The UsualUnaryConversions() function is *not* called by this routine. 4236 /// C99 6.3.2.1p[2-4] all state: 4237 /// Except when it is the operand of the sizeof operator ... 4238 /// 4239 /// C++ [expr.sizeof]p4 4240 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4241 /// standard conversions are not applied to the operand of sizeof. 4242 /// 4243 /// This policy is followed for all of the unary trait expressions. 4244 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4245 SourceLocation OpLoc, 4246 SourceRange ExprRange, 4247 UnaryExprOrTypeTrait ExprKind) { 4248 if (ExprType->isDependentType()) 4249 return false; 4250 4251 // C++ [expr.sizeof]p2: 4252 // When applied to a reference or a reference type, the result 4253 // is the size of the referenced type. 4254 // C++11 [expr.alignof]p3: 4255 // When alignof is applied to a reference type, the result 4256 // shall be the alignment of the referenced type. 4257 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4258 ExprType = Ref->getPointeeType(); 4259 4260 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4261 // When alignof or _Alignof is applied to an array type, the result 4262 // is the alignment of the element type. 4263 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4264 ExprKind == UETT_OpenMPRequiredSimdAlign) 4265 ExprType = Context.getBaseElementType(ExprType); 4266 4267 if (ExprKind == UETT_VecStep) 4268 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4269 4270 // Explicitly list some types as extensions. 4271 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4272 ExprKind)) 4273 return false; 4274 4275 if (RequireCompleteSizedType( 4276 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4277 getTraitSpelling(ExprKind), ExprRange)) 4278 return true; 4279 4280 if (ExprType->isFunctionType()) { 4281 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4282 << getTraitSpelling(ExprKind) << ExprRange; 4283 return true; 4284 } 4285 4286 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4287 ExprKind)) 4288 return true; 4289 4290 return false; 4291 } 4292 4293 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4294 // Cannot know anything else if the expression is dependent. 4295 if (E->isTypeDependent()) 4296 return false; 4297 4298 if (E->getObjectKind() == OK_BitField) { 4299 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4300 << 1 << E->getSourceRange(); 4301 return true; 4302 } 4303 4304 ValueDecl *D = nullptr; 4305 Expr *Inner = E->IgnoreParens(); 4306 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4307 D = DRE->getDecl(); 4308 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4309 D = ME->getMemberDecl(); 4310 } 4311 4312 // If it's a field, require the containing struct to have a 4313 // complete definition so that we can compute the layout. 4314 // 4315 // This can happen in C++11 onwards, either by naming the member 4316 // in a way that is not transformed into a member access expression 4317 // (in an unevaluated operand, for instance), or by naming the member 4318 // in a trailing-return-type. 4319 // 4320 // For the record, since __alignof__ on expressions is a GCC 4321 // extension, GCC seems to permit this but always gives the 4322 // nonsensical answer 0. 4323 // 4324 // We don't really need the layout here --- we could instead just 4325 // directly check for all the appropriate alignment-lowing 4326 // attributes --- but that would require duplicating a lot of 4327 // logic that just isn't worth duplicating for such a marginal 4328 // use-case. 4329 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4330 // Fast path this check, since we at least know the record has a 4331 // definition if we can find a member of it. 4332 if (!FD->getParent()->isCompleteDefinition()) { 4333 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4334 << E->getSourceRange(); 4335 return true; 4336 } 4337 4338 // Otherwise, if it's a field, and the field doesn't have 4339 // reference type, then it must have a complete type (or be a 4340 // flexible array member, which we explicitly want to 4341 // white-list anyway), which makes the following checks trivial. 4342 if (!FD->getType()->isReferenceType()) 4343 return false; 4344 } 4345 4346 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4347 } 4348 4349 bool Sema::CheckVecStepExpr(Expr *E) { 4350 E = E->IgnoreParens(); 4351 4352 // Cannot know anything else if the expression is dependent. 4353 if (E->isTypeDependent()) 4354 return false; 4355 4356 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4357 } 4358 4359 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4360 CapturingScopeInfo *CSI) { 4361 assert(T->isVariablyModifiedType()); 4362 assert(CSI != nullptr); 4363 4364 // We're going to walk down into the type and look for VLA expressions. 4365 do { 4366 const Type *Ty = T.getTypePtr(); 4367 switch (Ty->getTypeClass()) { 4368 #define TYPE(Class, Base) 4369 #define ABSTRACT_TYPE(Class, Base) 4370 #define NON_CANONICAL_TYPE(Class, Base) 4371 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4372 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4373 #include "clang/AST/TypeNodes.inc" 4374 T = QualType(); 4375 break; 4376 // These types are never variably-modified. 4377 case Type::Builtin: 4378 case Type::Complex: 4379 case Type::Vector: 4380 case Type::ExtVector: 4381 case Type::ConstantMatrix: 4382 case Type::Record: 4383 case Type::Enum: 4384 case Type::Elaborated: 4385 case Type::TemplateSpecialization: 4386 case Type::ObjCObject: 4387 case Type::ObjCInterface: 4388 case Type::ObjCObjectPointer: 4389 case Type::ObjCTypeParam: 4390 case Type::Pipe: 4391 case Type::ExtInt: 4392 llvm_unreachable("type class is never variably-modified!"); 4393 case Type::Adjusted: 4394 T = cast<AdjustedType>(Ty)->getOriginalType(); 4395 break; 4396 case Type::Decayed: 4397 T = cast<DecayedType>(Ty)->getPointeeType(); 4398 break; 4399 case Type::Pointer: 4400 T = cast<PointerType>(Ty)->getPointeeType(); 4401 break; 4402 case Type::BlockPointer: 4403 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4404 break; 4405 case Type::LValueReference: 4406 case Type::RValueReference: 4407 T = cast<ReferenceType>(Ty)->getPointeeType(); 4408 break; 4409 case Type::MemberPointer: 4410 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4411 break; 4412 case Type::ConstantArray: 4413 case Type::IncompleteArray: 4414 // Losing element qualification here is fine. 4415 T = cast<ArrayType>(Ty)->getElementType(); 4416 break; 4417 case Type::VariableArray: { 4418 // Losing element qualification here is fine. 4419 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4420 4421 // Unknown size indication requires no size computation. 4422 // Otherwise, evaluate and record it. 4423 auto Size = VAT->getSizeExpr(); 4424 if (Size && !CSI->isVLATypeCaptured(VAT) && 4425 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4426 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4427 4428 T = VAT->getElementType(); 4429 break; 4430 } 4431 case Type::FunctionProto: 4432 case Type::FunctionNoProto: 4433 T = cast<FunctionType>(Ty)->getReturnType(); 4434 break; 4435 case Type::Paren: 4436 case Type::TypeOf: 4437 case Type::UnaryTransform: 4438 case Type::Attributed: 4439 case Type::SubstTemplateTypeParm: 4440 case Type::MacroQualified: 4441 // Keep walking after single level desugaring. 4442 T = T.getSingleStepDesugaredType(Context); 4443 break; 4444 case Type::Typedef: 4445 T = cast<TypedefType>(Ty)->desugar(); 4446 break; 4447 case Type::Decltype: 4448 T = cast<DecltypeType>(Ty)->desugar(); 4449 break; 4450 case Type::Auto: 4451 case Type::DeducedTemplateSpecialization: 4452 T = cast<DeducedType>(Ty)->getDeducedType(); 4453 break; 4454 case Type::TypeOfExpr: 4455 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4456 break; 4457 case Type::Atomic: 4458 T = cast<AtomicType>(Ty)->getValueType(); 4459 break; 4460 } 4461 } while (!T.isNull() && T->isVariablyModifiedType()); 4462 } 4463 4464 /// Build a sizeof or alignof expression given a type operand. 4465 ExprResult 4466 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4467 SourceLocation OpLoc, 4468 UnaryExprOrTypeTrait ExprKind, 4469 SourceRange R) { 4470 if (!TInfo) 4471 return ExprError(); 4472 4473 QualType T = TInfo->getType(); 4474 4475 if (!T->isDependentType() && 4476 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4477 return ExprError(); 4478 4479 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4480 if (auto *TT = T->getAs<TypedefType>()) { 4481 for (auto I = FunctionScopes.rbegin(), 4482 E = std::prev(FunctionScopes.rend()); 4483 I != E; ++I) { 4484 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4485 if (CSI == nullptr) 4486 break; 4487 DeclContext *DC = nullptr; 4488 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4489 DC = LSI->CallOperator; 4490 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4491 DC = CRSI->TheCapturedDecl; 4492 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4493 DC = BSI->TheDecl; 4494 if (DC) { 4495 if (DC->containsDecl(TT->getDecl())) 4496 break; 4497 captureVariablyModifiedType(Context, T, CSI); 4498 } 4499 } 4500 } 4501 } 4502 4503 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4504 return new (Context) UnaryExprOrTypeTraitExpr( 4505 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4506 } 4507 4508 /// Build a sizeof or alignof expression given an expression 4509 /// operand. 4510 ExprResult 4511 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4512 UnaryExprOrTypeTrait ExprKind) { 4513 ExprResult PE = CheckPlaceholderExpr(E); 4514 if (PE.isInvalid()) 4515 return ExprError(); 4516 4517 E = PE.get(); 4518 4519 // Verify that the operand is valid. 4520 bool isInvalid = false; 4521 if (E->isTypeDependent()) { 4522 // Delay type-checking for type-dependent expressions. 4523 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4524 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4525 } else if (ExprKind == UETT_VecStep) { 4526 isInvalid = CheckVecStepExpr(E); 4527 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4528 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4529 isInvalid = true; 4530 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4531 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4532 isInvalid = true; 4533 } else { 4534 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4535 } 4536 4537 if (isInvalid) 4538 return ExprError(); 4539 4540 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4541 PE = TransformToPotentiallyEvaluated(E); 4542 if (PE.isInvalid()) return ExprError(); 4543 E = PE.get(); 4544 } 4545 4546 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4547 return new (Context) UnaryExprOrTypeTraitExpr( 4548 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4549 } 4550 4551 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4552 /// expr and the same for @c alignof and @c __alignof 4553 /// Note that the ArgRange is invalid if isType is false. 4554 ExprResult 4555 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4556 UnaryExprOrTypeTrait ExprKind, bool IsType, 4557 void *TyOrEx, SourceRange ArgRange) { 4558 // If error parsing type, ignore. 4559 if (!TyOrEx) return ExprError(); 4560 4561 if (IsType) { 4562 TypeSourceInfo *TInfo; 4563 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4564 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4565 } 4566 4567 Expr *ArgEx = (Expr *)TyOrEx; 4568 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4569 return Result; 4570 } 4571 4572 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4573 bool IsReal) { 4574 if (V.get()->isTypeDependent()) 4575 return S.Context.DependentTy; 4576 4577 // _Real and _Imag are only l-values for normal l-values. 4578 if (V.get()->getObjectKind() != OK_Ordinary) { 4579 V = S.DefaultLvalueConversion(V.get()); 4580 if (V.isInvalid()) 4581 return QualType(); 4582 } 4583 4584 // These operators return the element type of a complex type. 4585 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4586 return CT->getElementType(); 4587 4588 // Otherwise they pass through real integer and floating point types here. 4589 if (V.get()->getType()->isArithmeticType()) 4590 return V.get()->getType(); 4591 4592 // Test for placeholders. 4593 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4594 if (PR.isInvalid()) return QualType(); 4595 if (PR.get() != V.get()) { 4596 V = PR; 4597 return CheckRealImagOperand(S, V, Loc, IsReal); 4598 } 4599 4600 // Reject anything else. 4601 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4602 << (IsReal ? "__real" : "__imag"); 4603 return QualType(); 4604 } 4605 4606 4607 4608 ExprResult 4609 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4610 tok::TokenKind Kind, Expr *Input) { 4611 UnaryOperatorKind Opc; 4612 switch (Kind) { 4613 default: llvm_unreachable("Unknown unary op!"); 4614 case tok::plusplus: Opc = UO_PostInc; break; 4615 case tok::minusminus: Opc = UO_PostDec; break; 4616 } 4617 4618 // Since this might is a postfix expression, get rid of ParenListExprs. 4619 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4620 if (Result.isInvalid()) return ExprError(); 4621 Input = Result.get(); 4622 4623 return BuildUnaryOp(S, OpLoc, Opc, Input); 4624 } 4625 4626 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4627 /// 4628 /// \return true on error 4629 static bool checkArithmeticOnObjCPointer(Sema &S, 4630 SourceLocation opLoc, 4631 Expr *op) { 4632 assert(op->getType()->isObjCObjectPointerType()); 4633 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4634 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4635 return false; 4636 4637 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4638 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4639 << op->getSourceRange(); 4640 return true; 4641 } 4642 4643 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4644 auto *BaseNoParens = Base->IgnoreParens(); 4645 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4646 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4647 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4648 } 4649 4650 ExprResult 4651 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4652 Expr *idx, SourceLocation rbLoc) { 4653 if (base && !base->getType().isNull() && 4654 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4655 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4656 SourceLocation(), /*Length*/ nullptr, 4657 /*Stride=*/nullptr, rbLoc); 4658 4659 // Since this might be a postfix expression, get rid of ParenListExprs. 4660 if (isa<ParenListExpr>(base)) { 4661 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4662 if (result.isInvalid()) return ExprError(); 4663 base = result.get(); 4664 } 4665 4666 // Check if base and idx form a MatrixSubscriptExpr. 4667 // 4668 // Helper to check for comma expressions, which are not allowed as indices for 4669 // matrix subscript expressions. 4670 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4671 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4672 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4673 << SourceRange(base->getBeginLoc(), rbLoc); 4674 return true; 4675 } 4676 return false; 4677 }; 4678 // The matrix subscript operator ([][])is considered a single operator. 4679 // Separating the index expressions by parenthesis is not allowed. 4680 if (base->getType()->isSpecificPlaceholderType( 4681 BuiltinType::IncompleteMatrixIdx) && 4682 !isa<MatrixSubscriptExpr>(base)) { 4683 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4684 << SourceRange(base->getBeginLoc(), rbLoc); 4685 return ExprError(); 4686 } 4687 // If the base is a MatrixSubscriptExpr, try to create a new 4688 // MatrixSubscriptExpr. 4689 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4690 if (matSubscriptE) { 4691 if (CheckAndReportCommaError(idx)) 4692 return ExprError(); 4693 4694 assert(matSubscriptE->isIncomplete() && 4695 "base has to be an incomplete matrix subscript"); 4696 return CreateBuiltinMatrixSubscriptExpr( 4697 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4698 } 4699 4700 // Handle any non-overload placeholder types in the base and index 4701 // expressions. We can't handle overloads here because the other 4702 // operand might be an overloadable type, in which case the overload 4703 // resolution for the operator overload should get the first crack 4704 // at the overload. 4705 bool IsMSPropertySubscript = false; 4706 if (base->getType()->isNonOverloadPlaceholderType()) { 4707 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4708 if (!IsMSPropertySubscript) { 4709 ExprResult result = CheckPlaceholderExpr(base); 4710 if (result.isInvalid()) 4711 return ExprError(); 4712 base = result.get(); 4713 } 4714 } 4715 4716 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4717 if (base->getType()->isMatrixType()) { 4718 if (CheckAndReportCommaError(idx)) 4719 return ExprError(); 4720 4721 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4722 } 4723 4724 // A comma-expression as the index is deprecated in C++2a onwards. 4725 if (getLangOpts().CPlusPlus20 && 4726 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4727 (isa<CXXOperatorCallExpr>(idx) && 4728 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4729 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4730 << SourceRange(base->getBeginLoc(), rbLoc); 4731 } 4732 4733 if (idx->getType()->isNonOverloadPlaceholderType()) { 4734 ExprResult result = CheckPlaceholderExpr(idx); 4735 if (result.isInvalid()) return ExprError(); 4736 idx = result.get(); 4737 } 4738 4739 // Build an unanalyzed expression if either operand is type-dependent. 4740 if (getLangOpts().CPlusPlus && 4741 (base->isTypeDependent() || idx->isTypeDependent())) { 4742 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4743 VK_LValue, OK_Ordinary, rbLoc); 4744 } 4745 4746 // MSDN, property (C++) 4747 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4748 // This attribute can also be used in the declaration of an empty array in a 4749 // class or structure definition. For example: 4750 // __declspec(property(get=GetX, put=PutX)) int x[]; 4751 // The above statement indicates that x[] can be used with one or more array 4752 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4753 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4754 if (IsMSPropertySubscript) { 4755 // Build MS property subscript expression if base is MS property reference 4756 // or MS property subscript. 4757 return new (Context) MSPropertySubscriptExpr( 4758 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4759 } 4760 4761 // Use C++ overloaded-operator rules if either operand has record 4762 // type. The spec says to do this if either type is *overloadable*, 4763 // but enum types can't declare subscript operators or conversion 4764 // operators, so there's nothing interesting for overload resolution 4765 // to do if there aren't any record types involved. 4766 // 4767 // ObjC pointers have their own subscripting logic that is not tied 4768 // to overload resolution and so should not take this path. 4769 if (getLangOpts().CPlusPlus && 4770 (base->getType()->isRecordType() || 4771 (!base->getType()->isObjCObjectPointerType() && 4772 idx->getType()->isRecordType()))) { 4773 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4774 } 4775 4776 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4777 4778 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4779 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4780 4781 return Res; 4782 } 4783 4784 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4785 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4786 InitializationKind Kind = 4787 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4788 InitializationSequence InitSeq(*this, Entity, Kind, E); 4789 return InitSeq.Perform(*this, Entity, Kind, E); 4790 } 4791 4792 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4793 Expr *ColumnIdx, 4794 SourceLocation RBLoc) { 4795 ExprResult BaseR = CheckPlaceholderExpr(Base); 4796 if (BaseR.isInvalid()) 4797 return BaseR; 4798 Base = BaseR.get(); 4799 4800 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4801 if (RowR.isInvalid()) 4802 return RowR; 4803 RowIdx = RowR.get(); 4804 4805 if (!ColumnIdx) 4806 return new (Context) MatrixSubscriptExpr( 4807 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4808 4809 // Build an unanalyzed expression if any of the operands is type-dependent. 4810 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4811 ColumnIdx->isTypeDependent()) 4812 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4813 Context.DependentTy, RBLoc); 4814 4815 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4816 if (ColumnR.isInvalid()) 4817 return ColumnR; 4818 ColumnIdx = ColumnR.get(); 4819 4820 // Check that IndexExpr is an integer expression. If it is a constant 4821 // expression, check that it is less than Dim (= the number of elements in the 4822 // corresponding dimension). 4823 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4824 bool IsColumnIdx) -> Expr * { 4825 if (!IndexExpr->getType()->isIntegerType() && 4826 !IndexExpr->isTypeDependent()) { 4827 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4828 << IsColumnIdx; 4829 return nullptr; 4830 } 4831 4832 if (Optional<llvm::APSInt> Idx = 4833 IndexExpr->getIntegerConstantExpr(Context)) { 4834 if ((*Idx < 0 || *Idx >= Dim)) { 4835 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4836 << IsColumnIdx << Dim; 4837 return nullptr; 4838 } 4839 } 4840 4841 ExprResult ConvExpr = 4842 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4843 assert(!ConvExpr.isInvalid() && 4844 "should be able to convert any integer type to size type"); 4845 return ConvExpr.get(); 4846 }; 4847 4848 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4849 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4850 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4851 if (!RowIdx || !ColumnIdx) 4852 return ExprError(); 4853 4854 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4855 MTy->getElementType(), RBLoc); 4856 } 4857 4858 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4859 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4860 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4861 4862 // For expressions like `&(*s).b`, the base is recorded and what should be 4863 // checked. 4864 const MemberExpr *Member = nullptr; 4865 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4866 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4867 4868 LastRecord.PossibleDerefs.erase(StrippedExpr); 4869 } 4870 4871 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4872 if (isUnevaluatedContext()) 4873 return; 4874 4875 QualType ResultTy = E->getType(); 4876 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4877 4878 // Bail if the element is an array since it is not memory access. 4879 if (isa<ArrayType>(ResultTy)) 4880 return; 4881 4882 if (ResultTy->hasAttr(attr::NoDeref)) { 4883 LastRecord.PossibleDerefs.insert(E); 4884 return; 4885 } 4886 4887 // Check if the base type is a pointer to a member access of a struct 4888 // marked with noderef. 4889 const Expr *Base = E->getBase(); 4890 QualType BaseTy = Base->getType(); 4891 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4892 // Not a pointer access 4893 return; 4894 4895 const MemberExpr *Member = nullptr; 4896 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4897 Member->isArrow()) 4898 Base = Member->getBase(); 4899 4900 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4901 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4902 LastRecord.PossibleDerefs.insert(E); 4903 } 4904 } 4905 4906 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4907 Expr *LowerBound, 4908 SourceLocation ColonLocFirst, 4909 SourceLocation ColonLocSecond, 4910 Expr *Length, Expr *Stride, 4911 SourceLocation RBLoc) { 4912 if (Base->getType()->isPlaceholderType() && 4913 !Base->getType()->isSpecificPlaceholderType( 4914 BuiltinType::OMPArraySection)) { 4915 ExprResult Result = CheckPlaceholderExpr(Base); 4916 if (Result.isInvalid()) 4917 return ExprError(); 4918 Base = Result.get(); 4919 } 4920 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4921 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4922 if (Result.isInvalid()) 4923 return ExprError(); 4924 Result = DefaultLvalueConversion(Result.get()); 4925 if (Result.isInvalid()) 4926 return ExprError(); 4927 LowerBound = Result.get(); 4928 } 4929 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4930 ExprResult Result = CheckPlaceholderExpr(Length); 4931 if (Result.isInvalid()) 4932 return ExprError(); 4933 Result = DefaultLvalueConversion(Result.get()); 4934 if (Result.isInvalid()) 4935 return ExprError(); 4936 Length = Result.get(); 4937 } 4938 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4939 ExprResult Result = CheckPlaceholderExpr(Stride); 4940 if (Result.isInvalid()) 4941 return ExprError(); 4942 Result = DefaultLvalueConversion(Result.get()); 4943 if (Result.isInvalid()) 4944 return ExprError(); 4945 Stride = Result.get(); 4946 } 4947 4948 // Build an unanalyzed expression if either operand is type-dependent. 4949 if (Base->isTypeDependent() || 4950 (LowerBound && 4951 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4952 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4953 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4954 return new (Context) OMPArraySectionExpr( 4955 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4956 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4957 } 4958 4959 // Perform default conversions. 4960 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4961 QualType ResultTy; 4962 if (OriginalTy->isAnyPointerType()) { 4963 ResultTy = OriginalTy->getPointeeType(); 4964 } else if (OriginalTy->isArrayType()) { 4965 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4966 } else { 4967 return ExprError( 4968 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4969 << Base->getSourceRange()); 4970 } 4971 // C99 6.5.2.1p1 4972 if (LowerBound) { 4973 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4974 LowerBound); 4975 if (Res.isInvalid()) 4976 return ExprError(Diag(LowerBound->getExprLoc(), 4977 diag::err_omp_typecheck_section_not_integer) 4978 << 0 << LowerBound->getSourceRange()); 4979 LowerBound = Res.get(); 4980 4981 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4982 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4983 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4984 << 0 << LowerBound->getSourceRange(); 4985 } 4986 if (Length) { 4987 auto Res = 4988 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4989 if (Res.isInvalid()) 4990 return ExprError(Diag(Length->getExprLoc(), 4991 diag::err_omp_typecheck_section_not_integer) 4992 << 1 << Length->getSourceRange()); 4993 Length = Res.get(); 4994 4995 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4996 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4997 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4998 << 1 << Length->getSourceRange(); 4999 } 5000 if (Stride) { 5001 ExprResult Res = 5002 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5003 if (Res.isInvalid()) 5004 return ExprError(Diag(Stride->getExprLoc(), 5005 diag::err_omp_typecheck_section_not_integer) 5006 << 1 << Stride->getSourceRange()); 5007 Stride = Res.get(); 5008 5009 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5010 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5011 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5012 << 1 << Stride->getSourceRange(); 5013 } 5014 5015 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5016 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5017 // type. Note that functions are not objects, and that (in C99 parlance) 5018 // incomplete types are not object types. 5019 if (ResultTy->isFunctionType()) { 5020 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5021 << ResultTy << Base->getSourceRange(); 5022 return ExprError(); 5023 } 5024 5025 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5026 diag::err_omp_section_incomplete_type, Base)) 5027 return ExprError(); 5028 5029 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5030 Expr::EvalResult Result; 5031 if (LowerBound->EvaluateAsInt(Result, Context)) { 5032 // OpenMP 5.0, [2.1.5 Array Sections] 5033 // The array section must be a subset of the original array. 5034 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5035 if (LowerBoundValue.isNegative()) { 5036 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5037 << LowerBound->getSourceRange(); 5038 return ExprError(); 5039 } 5040 } 5041 } 5042 5043 if (Length) { 5044 Expr::EvalResult Result; 5045 if (Length->EvaluateAsInt(Result, Context)) { 5046 // OpenMP 5.0, [2.1.5 Array Sections] 5047 // The length must evaluate to non-negative integers. 5048 llvm::APSInt LengthValue = Result.Val.getInt(); 5049 if (LengthValue.isNegative()) { 5050 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5051 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 5052 << Length->getSourceRange(); 5053 return ExprError(); 5054 } 5055 } 5056 } else if (ColonLocFirst.isValid() && 5057 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5058 !OriginalTy->isVariableArrayType()))) { 5059 // OpenMP 5.0, [2.1.5 Array Sections] 5060 // When the size of the array dimension is not known, the length must be 5061 // specified explicitly. 5062 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5063 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5064 return ExprError(); 5065 } 5066 5067 if (Stride) { 5068 Expr::EvalResult Result; 5069 if (Stride->EvaluateAsInt(Result, Context)) { 5070 // OpenMP 5.0, [2.1.5 Array Sections] 5071 // The stride must evaluate to a positive integer. 5072 llvm::APSInt StrideValue = Result.Val.getInt(); 5073 if (!StrideValue.isStrictlyPositive()) { 5074 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5075 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 5076 << Stride->getSourceRange(); 5077 return ExprError(); 5078 } 5079 } 5080 } 5081 5082 if (!Base->getType()->isSpecificPlaceholderType( 5083 BuiltinType::OMPArraySection)) { 5084 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5085 if (Result.isInvalid()) 5086 return ExprError(); 5087 Base = Result.get(); 5088 } 5089 return new (Context) OMPArraySectionExpr( 5090 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5091 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5092 } 5093 5094 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5095 SourceLocation RParenLoc, 5096 ArrayRef<Expr *> Dims, 5097 ArrayRef<SourceRange> Brackets) { 5098 if (Base->getType()->isPlaceholderType()) { 5099 ExprResult Result = CheckPlaceholderExpr(Base); 5100 if (Result.isInvalid()) 5101 return ExprError(); 5102 Result = DefaultLvalueConversion(Result.get()); 5103 if (Result.isInvalid()) 5104 return ExprError(); 5105 Base = Result.get(); 5106 } 5107 QualType BaseTy = Base->getType(); 5108 // Delay analysis of the types/expressions if instantiation/specialization is 5109 // required. 5110 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5111 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5112 LParenLoc, RParenLoc, Dims, Brackets); 5113 if (!BaseTy->isPointerType() || 5114 (!Base->isTypeDependent() && 5115 BaseTy->getPointeeType()->isIncompleteType())) 5116 return ExprError(Diag(Base->getExprLoc(), 5117 diag::err_omp_non_pointer_type_array_shaping_base) 5118 << Base->getSourceRange()); 5119 5120 SmallVector<Expr *, 4> NewDims; 5121 bool ErrorFound = false; 5122 for (Expr *Dim : Dims) { 5123 if (Dim->getType()->isPlaceholderType()) { 5124 ExprResult Result = CheckPlaceholderExpr(Dim); 5125 if (Result.isInvalid()) { 5126 ErrorFound = true; 5127 continue; 5128 } 5129 Result = DefaultLvalueConversion(Result.get()); 5130 if (Result.isInvalid()) { 5131 ErrorFound = true; 5132 continue; 5133 } 5134 Dim = Result.get(); 5135 } 5136 if (!Dim->isTypeDependent()) { 5137 ExprResult Result = 5138 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5139 if (Result.isInvalid()) { 5140 ErrorFound = true; 5141 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5142 << Dim->getSourceRange(); 5143 continue; 5144 } 5145 Dim = Result.get(); 5146 Expr::EvalResult EvResult; 5147 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5148 // OpenMP 5.0, [2.1.4 Array Shaping] 5149 // Each si is an integral type expression that must evaluate to a 5150 // positive integer. 5151 llvm::APSInt Value = EvResult.Val.getInt(); 5152 if (!Value.isStrictlyPositive()) { 5153 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5154 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5155 << Dim->getSourceRange(); 5156 ErrorFound = true; 5157 continue; 5158 } 5159 } 5160 } 5161 NewDims.push_back(Dim); 5162 } 5163 if (ErrorFound) 5164 return ExprError(); 5165 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5166 LParenLoc, RParenLoc, NewDims, Brackets); 5167 } 5168 5169 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5170 SourceLocation LLoc, SourceLocation RLoc, 5171 ArrayRef<OMPIteratorData> Data) { 5172 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5173 bool IsCorrect = true; 5174 for (const OMPIteratorData &D : Data) { 5175 TypeSourceInfo *TInfo = nullptr; 5176 SourceLocation StartLoc; 5177 QualType DeclTy; 5178 if (!D.Type.getAsOpaquePtr()) { 5179 // OpenMP 5.0, 2.1.6 Iterators 5180 // In an iterator-specifier, if the iterator-type is not specified then 5181 // the type of that iterator is of int type. 5182 DeclTy = Context.IntTy; 5183 StartLoc = D.DeclIdentLoc; 5184 } else { 5185 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5186 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5187 } 5188 5189 bool IsDeclTyDependent = DeclTy->isDependentType() || 5190 DeclTy->containsUnexpandedParameterPack() || 5191 DeclTy->isInstantiationDependentType(); 5192 if (!IsDeclTyDependent) { 5193 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5194 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5195 // The iterator-type must be an integral or pointer type. 5196 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5197 << DeclTy; 5198 IsCorrect = false; 5199 continue; 5200 } 5201 if (DeclTy.isConstant(Context)) { 5202 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5203 // The iterator-type must not be const qualified. 5204 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5205 << DeclTy; 5206 IsCorrect = false; 5207 continue; 5208 } 5209 } 5210 5211 // Iterator declaration. 5212 assert(D.DeclIdent && "Identifier expected."); 5213 // Always try to create iterator declarator to avoid extra error messages 5214 // about unknown declarations use. 5215 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5216 D.DeclIdent, DeclTy, TInfo, SC_None); 5217 VD->setImplicit(); 5218 if (S) { 5219 // Check for conflicting previous declaration. 5220 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5221 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5222 ForVisibleRedeclaration); 5223 Previous.suppressDiagnostics(); 5224 LookupName(Previous, S); 5225 5226 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5227 /*AllowInlineNamespace=*/false); 5228 if (!Previous.empty()) { 5229 NamedDecl *Old = Previous.getRepresentativeDecl(); 5230 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5231 Diag(Old->getLocation(), diag::note_previous_definition); 5232 } else { 5233 PushOnScopeChains(VD, S); 5234 } 5235 } else { 5236 CurContext->addDecl(VD); 5237 } 5238 Expr *Begin = D.Range.Begin; 5239 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5240 ExprResult BeginRes = 5241 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5242 Begin = BeginRes.get(); 5243 } 5244 Expr *End = D.Range.End; 5245 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5246 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5247 End = EndRes.get(); 5248 } 5249 Expr *Step = D.Range.Step; 5250 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5251 if (!Step->getType()->isIntegralType(Context)) { 5252 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5253 << Step << Step->getSourceRange(); 5254 IsCorrect = false; 5255 continue; 5256 } 5257 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5258 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5259 // If the step expression of a range-specification equals zero, the 5260 // behavior is unspecified. 5261 if (Result && Result->isNullValue()) { 5262 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5263 << Step << Step->getSourceRange(); 5264 IsCorrect = false; 5265 continue; 5266 } 5267 } 5268 if (!Begin || !End || !IsCorrect) { 5269 IsCorrect = false; 5270 continue; 5271 } 5272 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5273 IDElem.IteratorDecl = VD; 5274 IDElem.AssignmentLoc = D.AssignLoc; 5275 IDElem.Range.Begin = Begin; 5276 IDElem.Range.End = End; 5277 IDElem.Range.Step = Step; 5278 IDElem.ColonLoc = D.ColonLoc; 5279 IDElem.SecondColonLoc = D.SecColonLoc; 5280 } 5281 if (!IsCorrect) { 5282 // Invalidate all created iterator declarations if error is found. 5283 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5284 if (Decl *ID = D.IteratorDecl) 5285 ID->setInvalidDecl(); 5286 } 5287 return ExprError(); 5288 } 5289 SmallVector<OMPIteratorHelperData, 4> Helpers; 5290 if (!CurContext->isDependentContext()) { 5291 // Build number of ityeration for each iteration range. 5292 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5293 // ((Begini-Stepi-1-Endi) / -Stepi); 5294 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5295 // (Endi - Begini) 5296 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5297 D.Range.Begin); 5298 if(!Res.isUsable()) { 5299 IsCorrect = false; 5300 continue; 5301 } 5302 ExprResult St, St1; 5303 if (D.Range.Step) { 5304 St = D.Range.Step; 5305 // (Endi - Begini) + Stepi 5306 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5307 if (!Res.isUsable()) { 5308 IsCorrect = false; 5309 continue; 5310 } 5311 // (Endi - Begini) + Stepi - 1 5312 Res = 5313 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5314 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5315 if (!Res.isUsable()) { 5316 IsCorrect = false; 5317 continue; 5318 } 5319 // ((Endi - Begini) + Stepi - 1) / Stepi 5320 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5321 if (!Res.isUsable()) { 5322 IsCorrect = false; 5323 continue; 5324 } 5325 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5326 // (Begini - Endi) 5327 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5328 D.Range.Begin, D.Range.End); 5329 if (!Res1.isUsable()) { 5330 IsCorrect = false; 5331 continue; 5332 } 5333 // (Begini - Endi) - Stepi 5334 Res1 = 5335 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5336 if (!Res1.isUsable()) { 5337 IsCorrect = false; 5338 continue; 5339 } 5340 // (Begini - Endi) - Stepi - 1 5341 Res1 = 5342 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5343 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5344 if (!Res1.isUsable()) { 5345 IsCorrect = false; 5346 continue; 5347 } 5348 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5349 Res1 = 5350 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5351 if (!Res1.isUsable()) { 5352 IsCorrect = false; 5353 continue; 5354 } 5355 // Stepi > 0. 5356 ExprResult CmpRes = 5357 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5358 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5359 if (!CmpRes.isUsable()) { 5360 IsCorrect = false; 5361 continue; 5362 } 5363 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5364 Res.get(), Res1.get()); 5365 if (!Res.isUsable()) { 5366 IsCorrect = false; 5367 continue; 5368 } 5369 } 5370 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5371 if (!Res.isUsable()) { 5372 IsCorrect = false; 5373 continue; 5374 } 5375 5376 // Build counter update. 5377 // Build counter. 5378 auto *CounterVD = 5379 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5380 D.IteratorDecl->getBeginLoc(), nullptr, 5381 Res.get()->getType(), nullptr, SC_None); 5382 CounterVD->setImplicit(); 5383 ExprResult RefRes = 5384 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5385 D.IteratorDecl->getBeginLoc()); 5386 // Build counter update. 5387 // I = Begini + counter * Stepi; 5388 ExprResult UpdateRes; 5389 if (D.Range.Step) { 5390 UpdateRes = CreateBuiltinBinOp( 5391 D.AssignmentLoc, BO_Mul, 5392 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5393 } else { 5394 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5395 } 5396 if (!UpdateRes.isUsable()) { 5397 IsCorrect = false; 5398 continue; 5399 } 5400 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5401 UpdateRes.get()); 5402 if (!UpdateRes.isUsable()) { 5403 IsCorrect = false; 5404 continue; 5405 } 5406 ExprResult VDRes = 5407 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5408 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5409 D.IteratorDecl->getBeginLoc()); 5410 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5411 UpdateRes.get()); 5412 if (!UpdateRes.isUsable()) { 5413 IsCorrect = false; 5414 continue; 5415 } 5416 UpdateRes = 5417 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5418 if (!UpdateRes.isUsable()) { 5419 IsCorrect = false; 5420 continue; 5421 } 5422 ExprResult CounterUpdateRes = 5423 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5424 if (!CounterUpdateRes.isUsable()) { 5425 IsCorrect = false; 5426 continue; 5427 } 5428 CounterUpdateRes = 5429 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5430 if (!CounterUpdateRes.isUsable()) { 5431 IsCorrect = false; 5432 continue; 5433 } 5434 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5435 HD.CounterVD = CounterVD; 5436 HD.Upper = Res.get(); 5437 HD.Update = UpdateRes.get(); 5438 HD.CounterUpdate = CounterUpdateRes.get(); 5439 } 5440 } else { 5441 Helpers.assign(ID.size(), {}); 5442 } 5443 if (!IsCorrect) { 5444 // Invalidate all created iterator declarations if error is found. 5445 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5446 if (Decl *ID = D.IteratorDecl) 5447 ID->setInvalidDecl(); 5448 } 5449 return ExprError(); 5450 } 5451 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5452 LLoc, RLoc, ID, Helpers); 5453 } 5454 5455 ExprResult 5456 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5457 Expr *Idx, SourceLocation RLoc) { 5458 Expr *LHSExp = Base; 5459 Expr *RHSExp = Idx; 5460 5461 ExprValueKind VK = VK_LValue; 5462 ExprObjectKind OK = OK_Ordinary; 5463 5464 // Per C++ core issue 1213, the result is an xvalue if either operand is 5465 // a non-lvalue array, and an lvalue otherwise. 5466 if (getLangOpts().CPlusPlus11) { 5467 for (auto *Op : {LHSExp, RHSExp}) { 5468 Op = Op->IgnoreImplicit(); 5469 if (Op->getType()->isArrayType() && !Op->isLValue()) 5470 VK = VK_XValue; 5471 } 5472 } 5473 5474 // Perform default conversions. 5475 if (!LHSExp->getType()->getAs<VectorType>()) { 5476 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5477 if (Result.isInvalid()) 5478 return ExprError(); 5479 LHSExp = Result.get(); 5480 } 5481 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5482 if (Result.isInvalid()) 5483 return ExprError(); 5484 RHSExp = Result.get(); 5485 5486 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5487 5488 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5489 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5490 // in the subscript position. As a result, we need to derive the array base 5491 // and index from the expression types. 5492 Expr *BaseExpr, *IndexExpr; 5493 QualType ResultType; 5494 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5495 BaseExpr = LHSExp; 5496 IndexExpr = RHSExp; 5497 ResultType = Context.DependentTy; 5498 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5499 BaseExpr = LHSExp; 5500 IndexExpr = RHSExp; 5501 ResultType = PTy->getPointeeType(); 5502 } else if (const ObjCObjectPointerType *PTy = 5503 LHSTy->getAs<ObjCObjectPointerType>()) { 5504 BaseExpr = LHSExp; 5505 IndexExpr = RHSExp; 5506 5507 // Use custom logic if this should be the pseudo-object subscript 5508 // expression. 5509 if (!LangOpts.isSubscriptPointerArithmetic()) 5510 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5511 nullptr); 5512 5513 ResultType = PTy->getPointeeType(); 5514 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5515 // Handle the uncommon case of "123[Ptr]". 5516 BaseExpr = RHSExp; 5517 IndexExpr = LHSExp; 5518 ResultType = PTy->getPointeeType(); 5519 } else if (const ObjCObjectPointerType *PTy = 5520 RHSTy->getAs<ObjCObjectPointerType>()) { 5521 // Handle the uncommon case of "123[Ptr]". 5522 BaseExpr = RHSExp; 5523 IndexExpr = LHSExp; 5524 ResultType = PTy->getPointeeType(); 5525 if (!LangOpts.isSubscriptPointerArithmetic()) { 5526 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5527 << ResultType << BaseExpr->getSourceRange(); 5528 return ExprError(); 5529 } 5530 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5531 BaseExpr = LHSExp; // vectors: V[123] 5532 IndexExpr = RHSExp; 5533 // We apply C++ DR1213 to vector subscripting too. 5534 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5535 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5536 if (Materialized.isInvalid()) 5537 return ExprError(); 5538 LHSExp = Materialized.get(); 5539 } 5540 VK = LHSExp->getValueKind(); 5541 if (VK != VK_RValue) 5542 OK = OK_VectorComponent; 5543 5544 ResultType = VTy->getElementType(); 5545 QualType BaseType = BaseExpr->getType(); 5546 Qualifiers BaseQuals = BaseType.getQualifiers(); 5547 Qualifiers MemberQuals = ResultType.getQualifiers(); 5548 Qualifiers Combined = BaseQuals + MemberQuals; 5549 if (Combined != MemberQuals) 5550 ResultType = Context.getQualifiedType(ResultType, Combined); 5551 } else if (LHSTy->isArrayType()) { 5552 // If we see an array that wasn't promoted by 5553 // DefaultFunctionArrayLvalueConversion, it must be an array that 5554 // wasn't promoted because of the C90 rule that doesn't 5555 // allow promoting non-lvalue arrays. Warn, then 5556 // force the promotion here. 5557 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5558 << LHSExp->getSourceRange(); 5559 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5560 CK_ArrayToPointerDecay).get(); 5561 LHSTy = LHSExp->getType(); 5562 5563 BaseExpr = LHSExp; 5564 IndexExpr = RHSExp; 5565 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5566 } else if (RHSTy->isArrayType()) { 5567 // Same as previous, except for 123[f().a] case 5568 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5569 << RHSExp->getSourceRange(); 5570 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5571 CK_ArrayToPointerDecay).get(); 5572 RHSTy = RHSExp->getType(); 5573 5574 BaseExpr = RHSExp; 5575 IndexExpr = LHSExp; 5576 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5577 } else { 5578 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5579 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5580 } 5581 // C99 6.5.2.1p1 5582 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5583 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5584 << IndexExpr->getSourceRange()); 5585 5586 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5587 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5588 && !IndexExpr->isTypeDependent()) 5589 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5590 5591 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5592 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5593 // type. Note that Functions are not objects, and that (in C99 parlance) 5594 // incomplete types are not object types. 5595 if (ResultType->isFunctionType()) { 5596 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5597 << ResultType << BaseExpr->getSourceRange(); 5598 return ExprError(); 5599 } 5600 5601 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5602 // GNU extension: subscripting on pointer to void 5603 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5604 << BaseExpr->getSourceRange(); 5605 5606 // C forbids expressions of unqualified void type from being l-values. 5607 // See IsCForbiddenLValueType. 5608 if (!ResultType.hasQualifiers()) VK = VK_RValue; 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_RValue || 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 (dyn_cast_or_null<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 return false; 5915 } 5916 5917 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5918 const FunctionProtoType *Proto, 5919 unsigned FirstParam, ArrayRef<Expr *> Args, 5920 SmallVectorImpl<Expr *> &AllArgs, 5921 VariadicCallType CallType, bool AllowExplicit, 5922 bool IsListInitialization) { 5923 unsigned NumParams = Proto->getNumParams(); 5924 bool Invalid = false; 5925 size_t ArgIx = 0; 5926 // Continue to check argument types (even if we have too few/many args). 5927 for (unsigned i = FirstParam; i < NumParams; i++) { 5928 QualType ProtoArgType = Proto->getParamType(i); 5929 5930 Expr *Arg; 5931 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5932 if (ArgIx < Args.size()) { 5933 Arg = Args[ArgIx++]; 5934 5935 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5936 diag::err_call_incomplete_argument, Arg)) 5937 return true; 5938 5939 // Strip the unbridged-cast placeholder expression off, if applicable. 5940 bool CFAudited = false; 5941 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5942 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5943 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5944 Arg = stripARCUnbridgedCast(Arg); 5945 else if (getLangOpts().ObjCAutoRefCount && 5946 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5947 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5948 CFAudited = true; 5949 5950 if (Proto->getExtParameterInfo(i).isNoEscape() && 5951 ProtoArgType->isBlockPointerType()) 5952 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5953 BE->getBlockDecl()->setDoesNotEscape(); 5954 5955 InitializedEntity Entity = 5956 Param ? InitializedEntity::InitializeParameter(Context, Param, 5957 ProtoArgType) 5958 : InitializedEntity::InitializeParameter( 5959 Context, ProtoArgType, Proto->isParamConsumed(i)); 5960 5961 // Remember that parameter belongs to a CF audited API. 5962 if (CFAudited) 5963 Entity.setParameterCFAudited(); 5964 5965 ExprResult ArgE = PerformCopyInitialization( 5966 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5967 if (ArgE.isInvalid()) 5968 return true; 5969 5970 Arg = ArgE.getAs<Expr>(); 5971 } else { 5972 assert(Param && "can't use default arguments without a known callee"); 5973 5974 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5975 if (ArgExpr.isInvalid()) 5976 return true; 5977 5978 Arg = ArgExpr.getAs<Expr>(); 5979 } 5980 5981 // Check for array bounds violations for each argument to the call. This 5982 // check only triggers warnings when the argument isn't a more complex Expr 5983 // with its own checking, such as a BinaryOperator. 5984 CheckArrayAccess(Arg); 5985 5986 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5987 CheckStaticArrayArgument(CallLoc, Param, Arg); 5988 5989 AllArgs.push_back(Arg); 5990 } 5991 5992 // If this is a variadic call, handle args passed through "...". 5993 if (CallType != VariadicDoesNotApply) { 5994 // Assume that extern "C" functions with variadic arguments that 5995 // return __unknown_anytype aren't *really* variadic. 5996 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5997 FDecl->isExternC()) { 5998 for (Expr *A : Args.slice(ArgIx)) { 5999 QualType paramType; // ignored 6000 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6001 Invalid |= arg.isInvalid(); 6002 AllArgs.push_back(arg.get()); 6003 } 6004 6005 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6006 } else { 6007 for (Expr *A : Args.slice(ArgIx)) { 6008 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6009 Invalid |= Arg.isInvalid(); 6010 AllArgs.push_back(Arg.get()); 6011 } 6012 } 6013 6014 // Check for array bounds violations. 6015 for (Expr *A : Args.slice(ArgIx)) 6016 CheckArrayAccess(A); 6017 } 6018 return Invalid; 6019 } 6020 6021 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6022 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6023 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6024 TL = DTL.getOriginalLoc(); 6025 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6026 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6027 << ATL.getLocalSourceRange(); 6028 } 6029 6030 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6031 /// array parameter, check that it is non-null, and that if it is formed by 6032 /// array-to-pointer decay, the underlying array is sufficiently large. 6033 /// 6034 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6035 /// array type derivation, then for each call to the function, the value of the 6036 /// corresponding actual argument shall provide access to the first element of 6037 /// an array with at least as many elements as specified by the size expression. 6038 void 6039 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6040 ParmVarDecl *Param, 6041 const Expr *ArgExpr) { 6042 // Static array parameters are not supported in C++. 6043 if (!Param || getLangOpts().CPlusPlus) 6044 return; 6045 6046 QualType OrigTy = Param->getOriginalType(); 6047 6048 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6049 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6050 return; 6051 6052 if (ArgExpr->isNullPointerConstant(Context, 6053 Expr::NPC_NeverValueDependent)) { 6054 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6055 DiagnoseCalleeStaticArrayParam(*this, Param); 6056 return; 6057 } 6058 6059 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6060 if (!CAT) 6061 return; 6062 6063 const ConstantArrayType *ArgCAT = 6064 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6065 if (!ArgCAT) 6066 return; 6067 6068 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6069 ArgCAT->getElementType())) { 6070 if (ArgCAT->getSize().ult(CAT->getSize())) { 6071 Diag(CallLoc, diag::warn_static_array_too_small) 6072 << ArgExpr->getSourceRange() 6073 << (unsigned)ArgCAT->getSize().getZExtValue() 6074 << (unsigned)CAT->getSize().getZExtValue() << 0; 6075 DiagnoseCalleeStaticArrayParam(*this, Param); 6076 } 6077 return; 6078 } 6079 6080 Optional<CharUnits> ArgSize = 6081 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6082 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6083 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6084 Diag(CallLoc, diag::warn_static_array_too_small) 6085 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6086 << (unsigned)ParmSize->getQuantity() << 1; 6087 DiagnoseCalleeStaticArrayParam(*this, Param); 6088 } 6089 } 6090 6091 /// Given a function expression of unknown-any type, try to rebuild it 6092 /// to have a function type. 6093 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6094 6095 /// Is the given type a placeholder that we need to lower out 6096 /// immediately during argument processing? 6097 static bool isPlaceholderToRemoveAsArg(QualType type) { 6098 // Placeholders are never sugared. 6099 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6100 if (!placeholder) return false; 6101 6102 switch (placeholder->getKind()) { 6103 // Ignore all the non-placeholder types. 6104 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6105 case BuiltinType::Id: 6106 #include "clang/Basic/OpenCLImageTypes.def" 6107 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6108 case BuiltinType::Id: 6109 #include "clang/Basic/OpenCLExtensionTypes.def" 6110 // In practice we'll never use this, since all SVE types are sugared 6111 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6112 #define SVE_TYPE(Name, Id, SingletonId) \ 6113 case BuiltinType::Id: 6114 #include "clang/Basic/AArch64SVEACLETypes.def" 6115 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6116 case BuiltinType::Id: 6117 #include "clang/Basic/PPCTypes.def" 6118 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6119 #include "clang/Basic/RISCVVTypes.def" 6120 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6121 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6122 #include "clang/AST/BuiltinTypes.def" 6123 return false; 6124 6125 // We cannot lower out overload sets; they might validly be resolved 6126 // by the call machinery. 6127 case BuiltinType::Overload: 6128 return false; 6129 6130 // Unbridged casts in ARC can be handled in some call positions and 6131 // should be left in place. 6132 case BuiltinType::ARCUnbridgedCast: 6133 return false; 6134 6135 // Pseudo-objects should be converted as soon as possible. 6136 case BuiltinType::PseudoObject: 6137 return true; 6138 6139 // The debugger mode could theoretically but currently does not try 6140 // to resolve unknown-typed arguments based on known parameter types. 6141 case BuiltinType::UnknownAny: 6142 return true; 6143 6144 // These are always invalid as call arguments and should be reported. 6145 case BuiltinType::BoundMember: 6146 case BuiltinType::BuiltinFn: 6147 case BuiltinType::IncompleteMatrixIdx: 6148 case BuiltinType::OMPArraySection: 6149 case BuiltinType::OMPArrayShaping: 6150 case BuiltinType::OMPIterator: 6151 return true; 6152 6153 } 6154 llvm_unreachable("bad builtin type kind"); 6155 } 6156 6157 /// Check an argument list for placeholders that we won't try to 6158 /// handle later. 6159 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6160 // Apply this processing to all the arguments at once instead of 6161 // dying at the first failure. 6162 bool hasInvalid = false; 6163 for (size_t i = 0, e = args.size(); i != e; i++) { 6164 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6165 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6166 if (result.isInvalid()) hasInvalid = true; 6167 else args[i] = result.get(); 6168 } 6169 } 6170 return hasInvalid; 6171 } 6172 6173 /// If a builtin function has a pointer argument with no explicit address 6174 /// space, then it should be able to accept a pointer to any address 6175 /// space as input. In order to do this, we need to replace the 6176 /// standard builtin declaration with one that uses the same address space 6177 /// as the call. 6178 /// 6179 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6180 /// it does not contain any pointer arguments without 6181 /// an address space qualifer. Otherwise the rewritten 6182 /// FunctionDecl is returned. 6183 /// TODO: Handle pointer return types. 6184 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6185 FunctionDecl *FDecl, 6186 MultiExprArg ArgExprs) { 6187 6188 QualType DeclType = FDecl->getType(); 6189 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6190 6191 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6192 ArgExprs.size() < FT->getNumParams()) 6193 return nullptr; 6194 6195 bool NeedsNewDecl = false; 6196 unsigned i = 0; 6197 SmallVector<QualType, 8> OverloadParams; 6198 6199 for (QualType ParamType : FT->param_types()) { 6200 6201 // Convert array arguments to pointer to simplify type lookup. 6202 ExprResult ArgRes = 6203 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6204 if (ArgRes.isInvalid()) 6205 return nullptr; 6206 Expr *Arg = ArgRes.get(); 6207 QualType ArgType = Arg->getType(); 6208 if (!ParamType->isPointerType() || 6209 ParamType.hasAddressSpace() || 6210 !ArgType->isPointerType() || 6211 !ArgType->getPointeeType().hasAddressSpace()) { 6212 OverloadParams.push_back(ParamType); 6213 continue; 6214 } 6215 6216 QualType PointeeType = ParamType->getPointeeType(); 6217 if (PointeeType.hasAddressSpace()) 6218 continue; 6219 6220 NeedsNewDecl = true; 6221 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6222 6223 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6224 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6225 } 6226 6227 if (!NeedsNewDecl) 6228 return nullptr; 6229 6230 FunctionProtoType::ExtProtoInfo EPI; 6231 EPI.Variadic = FT->isVariadic(); 6232 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6233 OverloadParams, EPI); 6234 DeclContext *Parent = FDecl->getParent(); 6235 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6236 FDecl->getLocation(), 6237 FDecl->getLocation(), 6238 FDecl->getIdentifier(), 6239 OverloadTy, 6240 /*TInfo=*/nullptr, 6241 SC_Extern, false, 6242 /*hasPrototype=*/true); 6243 SmallVector<ParmVarDecl*, 16> Params; 6244 FT = cast<FunctionProtoType>(OverloadTy); 6245 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6246 QualType ParamType = FT->getParamType(i); 6247 ParmVarDecl *Parm = 6248 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6249 SourceLocation(), nullptr, ParamType, 6250 /*TInfo=*/nullptr, SC_None, nullptr); 6251 Parm->setScopeInfo(0, i); 6252 Params.push_back(Parm); 6253 } 6254 OverloadDecl->setParams(Params); 6255 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6256 return OverloadDecl; 6257 } 6258 6259 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6260 FunctionDecl *Callee, 6261 MultiExprArg ArgExprs) { 6262 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6263 // similar attributes) really don't like it when functions are called with an 6264 // invalid number of args. 6265 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6266 /*PartialOverloading=*/false) && 6267 !Callee->isVariadic()) 6268 return; 6269 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6270 return; 6271 6272 if (const EnableIfAttr *Attr = 6273 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6274 S.Diag(Fn->getBeginLoc(), 6275 isa<CXXMethodDecl>(Callee) 6276 ? diag::err_ovl_no_viable_member_function_in_call 6277 : diag::err_ovl_no_viable_function_in_call) 6278 << Callee << Callee->getSourceRange(); 6279 S.Diag(Callee->getLocation(), 6280 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6281 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6282 return; 6283 } 6284 } 6285 6286 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6287 const UnresolvedMemberExpr *const UME, Sema &S) { 6288 6289 const auto GetFunctionLevelDCIfCXXClass = 6290 [](Sema &S) -> const CXXRecordDecl * { 6291 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6292 if (!DC || !DC->getParent()) 6293 return nullptr; 6294 6295 // If the call to some member function was made from within a member 6296 // function body 'M' return return 'M's parent. 6297 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6298 return MD->getParent()->getCanonicalDecl(); 6299 // else the call was made from within a default member initializer of a 6300 // class, so return the class. 6301 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6302 return RD->getCanonicalDecl(); 6303 return nullptr; 6304 }; 6305 // If our DeclContext is neither a member function nor a class (in the 6306 // case of a lambda in a default member initializer), we can't have an 6307 // enclosing 'this'. 6308 6309 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6310 if (!CurParentClass) 6311 return false; 6312 6313 // The naming class for implicit member functions call is the class in which 6314 // name lookup starts. 6315 const CXXRecordDecl *const NamingClass = 6316 UME->getNamingClass()->getCanonicalDecl(); 6317 assert(NamingClass && "Must have naming class even for implicit access"); 6318 6319 // If the unresolved member functions were found in a 'naming class' that is 6320 // related (either the same or derived from) to the class that contains the 6321 // member function that itself contained the implicit member access. 6322 6323 return CurParentClass == NamingClass || 6324 CurParentClass->isDerivedFrom(NamingClass); 6325 } 6326 6327 static void 6328 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6329 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6330 6331 if (!UME) 6332 return; 6333 6334 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6335 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6336 // already been captured, or if this is an implicit member function call (if 6337 // it isn't, an attempt to capture 'this' should already have been made). 6338 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6339 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6340 return; 6341 6342 // Check if the naming class in which the unresolved members were found is 6343 // related (same as or is a base of) to the enclosing class. 6344 6345 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6346 return; 6347 6348 6349 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6350 // If the enclosing function is not dependent, then this lambda is 6351 // capture ready, so if we can capture this, do so. 6352 if (!EnclosingFunctionCtx->isDependentContext()) { 6353 // If the current lambda and all enclosing lambdas can capture 'this' - 6354 // then go ahead and capture 'this' (since our unresolved overload set 6355 // contains at least one non-static member function). 6356 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6357 S.CheckCXXThisCapture(CallLoc); 6358 } else if (S.CurContext->isDependentContext()) { 6359 // ... since this is an implicit member reference, that might potentially 6360 // involve a 'this' capture, mark 'this' for potential capture in 6361 // enclosing lambdas. 6362 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6363 CurLSI->addPotentialThisCapture(CallLoc); 6364 } 6365 } 6366 6367 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6368 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6369 Expr *ExecConfig) { 6370 ExprResult Call = 6371 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6372 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6373 if (Call.isInvalid()) 6374 return Call; 6375 6376 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6377 // language modes. 6378 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6379 if (ULE->hasExplicitTemplateArgs() && 6380 ULE->decls_begin() == ULE->decls_end()) { 6381 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6382 ? diag::warn_cxx17_compat_adl_only_template_id 6383 : diag::ext_adl_only_template_id) 6384 << ULE->getName(); 6385 } 6386 } 6387 6388 if (LangOpts.OpenMP) 6389 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6390 ExecConfig); 6391 6392 return Call; 6393 } 6394 6395 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6396 /// This provides the location of the left/right parens and a list of comma 6397 /// locations. 6398 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6399 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6400 Expr *ExecConfig, bool IsExecConfig, 6401 bool AllowRecovery) { 6402 // Since this might be a postfix expression, get rid of ParenListExprs. 6403 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6404 if (Result.isInvalid()) return ExprError(); 6405 Fn = Result.get(); 6406 6407 if (checkArgsForPlaceholders(*this, ArgExprs)) 6408 return ExprError(); 6409 6410 if (getLangOpts().CPlusPlus) { 6411 // If this is a pseudo-destructor expression, build the call immediately. 6412 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6413 if (!ArgExprs.empty()) { 6414 // Pseudo-destructor calls should not have any arguments. 6415 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6416 << FixItHint::CreateRemoval( 6417 SourceRange(ArgExprs.front()->getBeginLoc(), 6418 ArgExprs.back()->getEndLoc())); 6419 } 6420 6421 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6422 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6423 } 6424 if (Fn->getType() == Context.PseudoObjectTy) { 6425 ExprResult result = CheckPlaceholderExpr(Fn); 6426 if (result.isInvalid()) return ExprError(); 6427 Fn = result.get(); 6428 } 6429 6430 // Determine whether this is a dependent call inside a C++ template, 6431 // in which case we won't do any semantic analysis now. 6432 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6433 if (ExecConfig) { 6434 return CUDAKernelCallExpr::Create( 6435 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6436 Context.DependentTy, VK_RValue, 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_RValue, 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, AllowRecovery); 6462 } 6463 } 6464 6465 // Check for overloaded calls. This can happen even in C due to extensions. 6466 if (Fn->getType() == Context.OverloadTy) { 6467 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6468 6469 // We aren't supposed to apply this logic if there's an '&' involved. 6470 if (!find.HasFormOfMemberPointer) { 6471 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6472 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6473 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6474 OverloadExpr *ovl = find.Expression; 6475 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6476 return BuildOverloadedCallExpr( 6477 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6478 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6479 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6480 RParenLoc, AllowRecovery); 6481 } 6482 } 6483 6484 // If we're directly calling a function, get the appropriate declaration. 6485 if (Fn->getType() == Context.UnknownAnyTy) { 6486 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6487 if (result.isInvalid()) return ExprError(); 6488 Fn = result.get(); 6489 } 6490 6491 Expr *NakedFn = Fn->IgnoreParens(); 6492 6493 bool CallingNDeclIndirectly = false; 6494 NamedDecl *NDecl = nullptr; 6495 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6496 if (UnOp->getOpcode() == UO_AddrOf) { 6497 CallingNDeclIndirectly = true; 6498 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6499 } 6500 } 6501 6502 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6503 NDecl = DRE->getDecl(); 6504 6505 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6506 if (FDecl && FDecl->getBuiltinID()) { 6507 // Rewrite the function decl for this builtin by replacing parameters 6508 // with no explicit address space with the address space of the arguments 6509 // in ArgExprs. 6510 if ((FDecl = 6511 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6512 NDecl = FDecl; 6513 Fn = DeclRefExpr::Create( 6514 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6515 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6516 nullptr, DRE->isNonOdrUse()); 6517 } 6518 } 6519 } else if (isa<MemberExpr>(NakedFn)) 6520 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6521 6522 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6523 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6524 FD, /*Complain=*/true, Fn->getBeginLoc())) 6525 return ExprError(); 6526 6527 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6528 } 6529 6530 if (Context.isDependenceAllowed() && 6531 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6532 assert(!getLangOpts().CPlusPlus); 6533 assert((Fn->containsErrors() || 6534 llvm::any_of(ArgExprs, 6535 [](clang::Expr *E) { return E->containsErrors(); })) && 6536 "should only occur in error-recovery path."); 6537 QualType ReturnType = 6538 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6539 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6540 : Context.DependentTy; 6541 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6542 Expr::getValueKindForType(ReturnType), RParenLoc, 6543 CurFPFeatureOverrides()); 6544 } 6545 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6546 ExecConfig, IsExecConfig); 6547 } 6548 6549 /// Parse a __builtin_astype expression. 6550 /// 6551 /// __builtin_astype( value, dst type ) 6552 /// 6553 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6554 SourceLocation BuiltinLoc, 6555 SourceLocation RParenLoc) { 6556 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6557 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6558 } 6559 6560 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6561 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6562 SourceLocation BuiltinLoc, 6563 SourceLocation RParenLoc) { 6564 ExprValueKind VK = VK_RValue; 6565 ExprObjectKind OK = OK_Ordinary; 6566 QualType SrcTy = E->getType(); 6567 if (!SrcTy->isDependentType() && 6568 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6569 return ExprError( 6570 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6571 << DestTy << SrcTy << E->getSourceRange()); 6572 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6573 } 6574 6575 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6576 /// provided arguments. 6577 /// 6578 /// __builtin_convertvector( value, dst type ) 6579 /// 6580 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6581 SourceLocation BuiltinLoc, 6582 SourceLocation RParenLoc) { 6583 TypeSourceInfo *TInfo; 6584 GetTypeFromParser(ParsedDestTy, &TInfo); 6585 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6586 } 6587 6588 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6589 /// i.e. an expression not of \p OverloadTy. The expression should 6590 /// unary-convert to an expression of function-pointer or 6591 /// block-pointer type. 6592 /// 6593 /// \param NDecl the declaration being called, if available 6594 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6595 SourceLocation LParenLoc, 6596 ArrayRef<Expr *> Args, 6597 SourceLocation RParenLoc, Expr *Config, 6598 bool IsExecConfig, ADLCallKind UsesADL) { 6599 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6600 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6601 6602 // Functions with 'interrupt' attribute cannot be called directly. 6603 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6604 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6605 return ExprError(); 6606 } 6607 6608 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6609 // so there's some risk when calling out to non-interrupt handler functions 6610 // that the callee might not preserve them. This is easy to diagnose here, 6611 // but can be very challenging to debug. 6612 // Likewise, X86 interrupt handlers may only call routines with attribute 6613 // no_caller_saved_registers since there is no efficient way to 6614 // save and restore the non-GPR state. 6615 if (auto *Caller = getCurFunctionDecl()) { 6616 if (Caller->hasAttr<ARMInterruptAttr>()) { 6617 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6618 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6619 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6620 if (FDecl) 6621 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6622 } 6623 } 6624 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6625 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6626 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6627 if (FDecl) 6628 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6629 } 6630 } 6631 6632 // Promote the function operand. 6633 // We special-case function promotion here because we only allow promoting 6634 // builtin functions to function pointers in the callee of a call. 6635 ExprResult Result; 6636 QualType ResultTy; 6637 if (BuiltinID && 6638 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6639 // Extract the return type from the (builtin) function pointer type. 6640 // FIXME Several builtins still have setType in 6641 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6642 // Builtins.def to ensure they are correct before removing setType calls. 6643 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6644 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6645 ResultTy = FDecl->getCallResultType(); 6646 } else { 6647 Result = CallExprUnaryConversions(Fn); 6648 ResultTy = Context.BoolTy; 6649 } 6650 if (Result.isInvalid()) 6651 return ExprError(); 6652 Fn = Result.get(); 6653 6654 // Check for a valid function type, but only if it is not a builtin which 6655 // requires custom type checking. These will be handled by 6656 // CheckBuiltinFunctionCall below just after creation of the call expression. 6657 const FunctionType *FuncT = nullptr; 6658 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6659 retry: 6660 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6661 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6662 // have type pointer to function". 6663 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6664 if (!FuncT) 6665 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6666 << Fn->getType() << Fn->getSourceRange()); 6667 } else if (const BlockPointerType *BPT = 6668 Fn->getType()->getAs<BlockPointerType>()) { 6669 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6670 } else { 6671 // Handle calls to expressions of unknown-any type. 6672 if (Fn->getType() == Context.UnknownAnyTy) { 6673 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6674 if (rewrite.isInvalid()) 6675 return ExprError(); 6676 Fn = rewrite.get(); 6677 goto retry; 6678 } 6679 6680 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6681 << Fn->getType() << Fn->getSourceRange()); 6682 } 6683 } 6684 6685 // Get the number of parameters in the function prototype, if any. 6686 // We will allocate space for max(Args.size(), NumParams) arguments 6687 // in the call expression. 6688 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6689 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6690 6691 CallExpr *TheCall; 6692 if (Config) { 6693 assert(UsesADL == ADLCallKind::NotADL && 6694 "CUDAKernelCallExpr should not use ADL"); 6695 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6696 Args, ResultTy, VK_RValue, RParenLoc, 6697 CurFPFeatureOverrides(), NumParams); 6698 } else { 6699 TheCall = 6700 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6701 CurFPFeatureOverrides(), NumParams, UsesADL); 6702 } 6703 6704 if (!Context.isDependenceAllowed()) { 6705 // Forget about the nulled arguments since typo correction 6706 // do not handle them well. 6707 TheCall->shrinkNumArgs(Args.size()); 6708 // C cannot always handle TypoExpr nodes in builtin calls and direct 6709 // function calls as their argument checking don't necessarily handle 6710 // dependent types properly, so make sure any TypoExprs have been 6711 // dealt with. 6712 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6713 if (!Result.isUsable()) return ExprError(); 6714 CallExpr *TheOldCall = TheCall; 6715 TheCall = dyn_cast<CallExpr>(Result.get()); 6716 bool CorrectedTypos = TheCall != TheOldCall; 6717 if (!TheCall) return Result; 6718 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6719 6720 // A new call expression node was created if some typos were corrected. 6721 // However it may not have been constructed with enough storage. In this 6722 // case, rebuild the node with enough storage. The waste of space is 6723 // immaterial since this only happens when some typos were corrected. 6724 if (CorrectedTypos && Args.size() < NumParams) { 6725 if (Config) 6726 TheCall = CUDAKernelCallExpr::Create( 6727 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6728 RParenLoc, CurFPFeatureOverrides(), NumParams); 6729 else 6730 TheCall = 6731 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6732 CurFPFeatureOverrides(), NumParams, UsesADL); 6733 } 6734 // We can now handle the nulled arguments for the default arguments. 6735 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6736 } 6737 6738 // Bail out early if calling a builtin with custom type checking. 6739 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6740 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6741 6742 if (getLangOpts().CUDA) { 6743 if (Config) { 6744 // CUDA: Kernel calls must be to global functions 6745 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6746 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6747 << FDecl << Fn->getSourceRange()); 6748 6749 // CUDA: Kernel function must have 'void' return type 6750 if (!FuncT->getReturnType()->isVoidType() && 6751 !FuncT->getReturnType()->getAs<AutoType>() && 6752 !FuncT->getReturnType()->isInstantiationDependentType()) 6753 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6754 << Fn->getType() << Fn->getSourceRange()); 6755 } else { 6756 // CUDA: Calls to global functions must be configured 6757 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6758 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6759 << FDecl << Fn->getSourceRange()); 6760 } 6761 } 6762 6763 // Check for a valid return type 6764 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6765 FDecl)) 6766 return ExprError(); 6767 6768 // We know the result type of the call, set it. 6769 TheCall->setType(FuncT->getCallResultType(Context)); 6770 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6771 6772 if (Proto) { 6773 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6774 IsExecConfig)) 6775 return ExprError(); 6776 } else { 6777 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6778 6779 if (FDecl) { 6780 // Check if we have too few/too many template arguments, based 6781 // on our knowledge of the function definition. 6782 const FunctionDecl *Def = nullptr; 6783 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6784 Proto = Def->getType()->getAs<FunctionProtoType>(); 6785 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6786 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6787 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6788 } 6789 6790 // If the function we're calling isn't a function prototype, but we have 6791 // a function prototype from a prior declaratiom, use that prototype. 6792 if (!FDecl->hasPrototype()) 6793 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6794 } 6795 6796 // Promote the arguments (C99 6.5.2.2p6). 6797 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6798 Expr *Arg = Args[i]; 6799 6800 if (Proto && i < Proto->getNumParams()) { 6801 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6802 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6803 ExprResult ArgE = 6804 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6805 if (ArgE.isInvalid()) 6806 return true; 6807 6808 Arg = ArgE.getAs<Expr>(); 6809 6810 } else { 6811 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6812 6813 if (ArgE.isInvalid()) 6814 return true; 6815 6816 Arg = ArgE.getAs<Expr>(); 6817 } 6818 6819 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6820 diag::err_call_incomplete_argument, Arg)) 6821 return ExprError(); 6822 6823 TheCall->setArg(i, Arg); 6824 } 6825 } 6826 6827 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6828 if (!Method->isStatic()) 6829 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6830 << Fn->getSourceRange()); 6831 6832 // Check for sentinels 6833 if (NDecl) 6834 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6835 6836 // Warn for unions passing across security boundary (CMSE). 6837 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6838 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6839 if (const auto *RT = 6840 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6841 if (RT->getDecl()->isOrContainsUnion()) 6842 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6843 << 0 << i; 6844 } 6845 } 6846 } 6847 6848 // Do special checking on direct calls to functions. 6849 if (FDecl) { 6850 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6851 return ExprError(); 6852 6853 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6854 6855 if (BuiltinID) 6856 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6857 } else if (NDecl) { 6858 if (CheckPointerCall(NDecl, TheCall, Proto)) 6859 return ExprError(); 6860 } else { 6861 if (CheckOtherCall(TheCall, Proto)) 6862 return ExprError(); 6863 } 6864 6865 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6866 } 6867 6868 ExprResult 6869 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6870 SourceLocation RParenLoc, Expr *InitExpr) { 6871 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6872 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6873 6874 TypeSourceInfo *TInfo; 6875 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6876 if (!TInfo) 6877 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6878 6879 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6880 } 6881 6882 ExprResult 6883 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6884 SourceLocation RParenLoc, Expr *LiteralExpr) { 6885 QualType literalType = TInfo->getType(); 6886 6887 if (literalType->isArrayType()) { 6888 if (RequireCompleteSizedType( 6889 LParenLoc, Context.getBaseElementType(literalType), 6890 diag::err_array_incomplete_or_sizeless_type, 6891 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6892 return ExprError(); 6893 if (literalType->isVariableArrayType()) { 6894 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6895 diag::err_variable_object_no_init)) { 6896 return ExprError(); 6897 } 6898 } 6899 } else if (!literalType->isDependentType() && 6900 RequireCompleteType(LParenLoc, literalType, 6901 diag::err_typecheck_decl_incomplete_type, 6902 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6903 return ExprError(); 6904 6905 InitializedEntity Entity 6906 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6907 InitializationKind Kind 6908 = InitializationKind::CreateCStyleCast(LParenLoc, 6909 SourceRange(LParenLoc, RParenLoc), 6910 /*InitList=*/true); 6911 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6912 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6913 &literalType); 6914 if (Result.isInvalid()) 6915 return ExprError(); 6916 LiteralExpr = Result.get(); 6917 6918 bool isFileScope = !CurContext->isFunctionOrMethod(); 6919 6920 // In C, compound literals are l-values for some reason. 6921 // For GCC compatibility, in C++, file-scope array compound literals with 6922 // constant initializers are also l-values, and compound literals are 6923 // otherwise prvalues. 6924 // 6925 // (GCC also treats C++ list-initialized file-scope array prvalues with 6926 // constant initializers as l-values, but that's non-conforming, so we don't 6927 // follow it there.) 6928 // 6929 // FIXME: It would be better to handle the lvalue cases as materializing and 6930 // lifetime-extending a temporary object, but our materialized temporaries 6931 // representation only supports lifetime extension from a variable, not "out 6932 // of thin air". 6933 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6934 // is bound to the result of applying array-to-pointer decay to the compound 6935 // literal. 6936 // FIXME: GCC supports compound literals of reference type, which should 6937 // obviously have a value kind derived from the kind of reference involved. 6938 ExprValueKind VK = 6939 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6940 ? VK_RValue 6941 : VK_LValue; 6942 6943 if (isFileScope) 6944 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6945 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6946 Expr *Init = ILE->getInit(i); 6947 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6948 } 6949 6950 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6951 VK, LiteralExpr, isFileScope); 6952 if (isFileScope) { 6953 if (!LiteralExpr->isTypeDependent() && 6954 !LiteralExpr->isValueDependent() && 6955 !literalType->isDependentType()) // C99 6.5.2.5p3 6956 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6957 return ExprError(); 6958 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6959 literalType.getAddressSpace() != LangAS::Default) { 6960 // Embedded-C extensions to C99 6.5.2.5: 6961 // "If the compound literal occurs inside the body of a function, the 6962 // type name shall not be qualified by an address-space qualifier." 6963 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6964 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6965 return ExprError(); 6966 } 6967 6968 if (!isFileScope && !getLangOpts().CPlusPlus) { 6969 // Compound literals that have automatic storage duration are destroyed at 6970 // the end of the scope in C; in C++, they're just temporaries. 6971 6972 // Emit diagnostics if it is or contains a C union type that is non-trivial 6973 // to destruct. 6974 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6975 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6976 NTCUC_CompoundLiteral, NTCUK_Destruct); 6977 6978 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6979 if (literalType.isDestructedType()) { 6980 Cleanup.setExprNeedsCleanups(true); 6981 ExprCleanupObjects.push_back(E); 6982 getCurFunction()->setHasBranchProtectedScope(); 6983 } 6984 } 6985 6986 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6987 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6988 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6989 E->getInitializer()->getExprLoc()); 6990 6991 return MaybeBindToTemporary(E); 6992 } 6993 6994 ExprResult 6995 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6996 SourceLocation RBraceLoc) { 6997 // Only produce each kind of designated initialization diagnostic once. 6998 SourceLocation FirstDesignator; 6999 bool DiagnosedArrayDesignator = false; 7000 bool DiagnosedNestedDesignator = false; 7001 bool DiagnosedMixedDesignator = false; 7002 7003 // Check that any designated initializers are syntactically valid in the 7004 // current language mode. 7005 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7006 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7007 if (FirstDesignator.isInvalid()) 7008 FirstDesignator = DIE->getBeginLoc(); 7009 7010 if (!getLangOpts().CPlusPlus) 7011 break; 7012 7013 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7014 DiagnosedNestedDesignator = true; 7015 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7016 << DIE->getDesignatorsSourceRange(); 7017 } 7018 7019 for (auto &Desig : DIE->designators()) { 7020 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7021 DiagnosedArrayDesignator = true; 7022 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7023 << Desig.getSourceRange(); 7024 } 7025 } 7026 7027 if (!DiagnosedMixedDesignator && 7028 !isa<DesignatedInitExpr>(InitArgList[0])) { 7029 DiagnosedMixedDesignator = true; 7030 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7031 << DIE->getSourceRange(); 7032 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7033 << InitArgList[0]->getSourceRange(); 7034 } 7035 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7036 isa<DesignatedInitExpr>(InitArgList[0])) { 7037 DiagnosedMixedDesignator = true; 7038 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7039 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7040 << DIE->getSourceRange(); 7041 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7042 << InitArgList[I]->getSourceRange(); 7043 } 7044 } 7045 7046 if (FirstDesignator.isValid()) { 7047 // Only diagnose designated initiaization as a C++20 extension if we didn't 7048 // already diagnose use of (non-C++20) C99 designator syntax. 7049 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7050 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7051 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7052 ? diag::warn_cxx17_compat_designated_init 7053 : diag::ext_cxx_designated_init); 7054 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7055 Diag(FirstDesignator, diag::ext_designated_init); 7056 } 7057 } 7058 7059 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7060 } 7061 7062 ExprResult 7063 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7064 SourceLocation RBraceLoc) { 7065 // Semantic analysis for initializers is done by ActOnDeclarator() and 7066 // CheckInitializer() - it requires knowledge of the object being initialized. 7067 7068 // Immediately handle non-overload placeholders. Overloads can be 7069 // resolved contextually, but everything else here can't. 7070 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7071 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7072 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7073 7074 // Ignore failures; dropping the entire initializer list because 7075 // of one failure would be terrible for indexing/etc. 7076 if (result.isInvalid()) continue; 7077 7078 InitArgList[I] = result.get(); 7079 } 7080 } 7081 7082 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7083 RBraceLoc); 7084 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7085 return E; 7086 } 7087 7088 /// Do an explicit extend of the given block pointer if we're in ARC. 7089 void Sema::maybeExtendBlockObject(ExprResult &E) { 7090 assert(E.get()->getType()->isBlockPointerType()); 7091 assert(E.get()->isRValue()); 7092 7093 // Only do this in an r-value context. 7094 if (!getLangOpts().ObjCAutoRefCount) return; 7095 7096 E = ImplicitCastExpr::Create( 7097 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7098 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 7099 Cleanup.setExprNeedsCleanups(true); 7100 } 7101 7102 /// Prepare a conversion of the given expression to an ObjC object 7103 /// pointer type. 7104 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7105 QualType type = E.get()->getType(); 7106 if (type->isObjCObjectPointerType()) { 7107 return CK_BitCast; 7108 } else if (type->isBlockPointerType()) { 7109 maybeExtendBlockObject(E); 7110 return CK_BlockPointerToObjCPointerCast; 7111 } else { 7112 assert(type->isPointerType()); 7113 return CK_CPointerToObjCPointerCast; 7114 } 7115 } 7116 7117 /// Prepares for a scalar cast, performing all the necessary stages 7118 /// except the final cast and returning the kind required. 7119 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7120 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7121 // Also, callers should have filtered out the invalid cases with 7122 // pointers. Everything else should be possible. 7123 7124 QualType SrcTy = Src.get()->getType(); 7125 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7126 return CK_NoOp; 7127 7128 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7129 case Type::STK_MemberPointer: 7130 llvm_unreachable("member pointer type in C"); 7131 7132 case Type::STK_CPointer: 7133 case Type::STK_BlockPointer: 7134 case Type::STK_ObjCObjectPointer: 7135 switch (DestTy->getScalarTypeKind()) { 7136 case Type::STK_CPointer: { 7137 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7138 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7139 if (SrcAS != DestAS) 7140 return CK_AddressSpaceConversion; 7141 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7142 return CK_NoOp; 7143 return CK_BitCast; 7144 } 7145 case Type::STK_BlockPointer: 7146 return (SrcKind == Type::STK_BlockPointer 7147 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7148 case Type::STK_ObjCObjectPointer: 7149 if (SrcKind == Type::STK_ObjCObjectPointer) 7150 return CK_BitCast; 7151 if (SrcKind == Type::STK_CPointer) 7152 return CK_CPointerToObjCPointerCast; 7153 maybeExtendBlockObject(Src); 7154 return CK_BlockPointerToObjCPointerCast; 7155 case Type::STK_Bool: 7156 return CK_PointerToBoolean; 7157 case Type::STK_Integral: 7158 return CK_PointerToIntegral; 7159 case Type::STK_Floating: 7160 case Type::STK_FloatingComplex: 7161 case Type::STK_IntegralComplex: 7162 case Type::STK_MemberPointer: 7163 case Type::STK_FixedPoint: 7164 llvm_unreachable("illegal cast from pointer"); 7165 } 7166 llvm_unreachable("Should have returned before this"); 7167 7168 case Type::STK_FixedPoint: 7169 switch (DestTy->getScalarTypeKind()) { 7170 case Type::STK_FixedPoint: 7171 return CK_FixedPointCast; 7172 case Type::STK_Bool: 7173 return CK_FixedPointToBoolean; 7174 case Type::STK_Integral: 7175 return CK_FixedPointToIntegral; 7176 case Type::STK_Floating: 7177 return CK_FixedPointToFloating; 7178 case Type::STK_IntegralComplex: 7179 case Type::STK_FloatingComplex: 7180 Diag(Src.get()->getExprLoc(), 7181 diag::err_unimplemented_conversion_with_fixed_point_type) 7182 << DestTy; 7183 return CK_IntegralCast; 7184 case Type::STK_CPointer: 7185 case Type::STK_ObjCObjectPointer: 7186 case Type::STK_BlockPointer: 7187 case Type::STK_MemberPointer: 7188 llvm_unreachable("illegal cast to pointer type"); 7189 } 7190 llvm_unreachable("Should have returned before this"); 7191 7192 case Type::STK_Bool: // casting from bool is like casting from an integer 7193 case Type::STK_Integral: 7194 switch (DestTy->getScalarTypeKind()) { 7195 case Type::STK_CPointer: 7196 case Type::STK_ObjCObjectPointer: 7197 case Type::STK_BlockPointer: 7198 if (Src.get()->isNullPointerConstant(Context, 7199 Expr::NPC_ValueDependentIsNull)) 7200 return CK_NullToPointer; 7201 return CK_IntegralToPointer; 7202 case Type::STK_Bool: 7203 return CK_IntegralToBoolean; 7204 case Type::STK_Integral: 7205 return CK_IntegralCast; 7206 case Type::STK_Floating: 7207 return CK_IntegralToFloating; 7208 case Type::STK_IntegralComplex: 7209 Src = ImpCastExprToType(Src.get(), 7210 DestTy->castAs<ComplexType>()->getElementType(), 7211 CK_IntegralCast); 7212 return CK_IntegralRealToComplex; 7213 case Type::STK_FloatingComplex: 7214 Src = ImpCastExprToType(Src.get(), 7215 DestTy->castAs<ComplexType>()->getElementType(), 7216 CK_IntegralToFloating); 7217 return CK_FloatingRealToComplex; 7218 case Type::STK_MemberPointer: 7219 llvm_unreachable("member pointer type in C"); 7220 case Type::STK_FixedPoint: 7221 return CK_IntegralToFixedPoint; 7222 } 7223 llvm_unreachable("Should have returned before this"); 7224 7225 case Type::STK_Floating: 7226 switch (DestTy->getScalarTypeKind()) { 7227 case Type::STK_Floating: 7228 return CK_FloatingCast; 7229 case Type::STK_Bool: 7230 return CK_FloatingToBoolean; 7231 case Type::STK_Integral: 7232 return CK_FloatingToIntegral; 7233 case Type::STK_FloatingComplex: 7234 Src = ImpCastExprToType(Src.get(), 7235 DestTy->castAs<ComplexType>()->getElementType(), 7236 CK_FloatingCast); 7237 return CK_FloatingRealToComplex; 7238 case Type::STK_IntegralComplex: 7239 Src = ImpCastExprToType(Src.get(), 7240 DestTy->castAs<ComplexType>()->getElementType(), 7241 CK_FloatingToIntegral); 7242 return CK_IntegralRealToComplex; 7243 case Type::STK_CPointer: 7244 case Type::STK_ObjCObjectPointer: 7245 case Type::STK_BlockPointer: 7246 llvm_unreachable("valid float->pointer cast?"); 7247 case Type::STK_MemberPointer: 7248 llvm_unreachable("member pointer type in C"); 7249 case Type::STK_FixedPoint: 7250 return CK_FloatingToFixedPoint; 7251 } 7252 llvm_unreachable("Should have returned before this"); 7253 7254 case Type::STK_FloatingComplex: 7255 switch (DestTy->getScalarTypeKind()) { 7256 case Type::STK_FloatingComplex: 7257 return CK_FloatingComplexCast; 7258 case Type::STK_IntegralComplex: 7259 return CK_FloatingComplexToIntegralComplex; 7260 case Type::STK_Floating: { 7261 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7262 if (Context.hasSameType(ET, DestTy)) 7263 return CK_FloatingComplexToReal; 7264 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7265 return CK_FloatingCast; 7266 } 7267 case Type::STK_Bool: 7268 return CK_FloatingComplexToBoolean; 7269 case Type::STK_Integral: 7270 Src = ImpCastExprToType(Src.get(), 7271 SrcTy->castAs<ComplexType>()->getElementType(), 7272 CK_FloatingComplexToReal); 7273 return CK_FloatingToIntegral; 7274 case Type::STK_CPointer: 7275 case Type::STK_ObjCObjectPointer: 7276 case Type::STK_BlockPointer: 7277 llvm_unreachable("valid complex float->pointer cast?"); 7278 case Type::STK_MemberPointer: 7279 llvm_unreachable("member pointer type in C"); 7280 case Type::STK_FixedPoint: 7281 Diag(Src.get()->getExprLoc(), 7282 diag::err_unimplemented_conversion_with_fixed_point_type) 7283 << SrcTy; 7284 return CK_IntegralCast; 7285 } 7286 llvm_unreachable("Should have returned before this"); 7287 7288 case Type::STK_IntegralComplex: 7289 switch (DestTy->getScalarTypeKind()) { 7290 case Type::STK_FloatingComplex: 7291 return CK_IntegralComplexToFloatingComplex; 7292 case Type::STK_IntegralComplex: 7293 return CK_IntegralComplexCast; 7294 case Type::STK_Integral: { 7295 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7296 if (Context.hasSameType(ET, DestTy)) 7297 return CK_IntegralComplexToReal; 7298 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7299 return CK_IntegralCast; 7300 } 7301 case Type::STK_Bool: 7302 return CK_IntegralComplexToBoolean; 7303 case Type::STK_Floating: 7304 Src = ImpCastExprToType(Src.get(), 7305 SrcTy->castAs<ComplexType>()->getElementType(), 7306 CK_IntegralComplexToReal); 7307 return CK_IntegralToFloating; 7308 case Type::STK_CPointer: 7309 case Type::STK_ObjCObjectPointer: 7310 case Type::STK_BlockPointer: 7311 llvm_unreachable("valid complex int->pointer cast?"); 7312 case Type::STK_MemberPointer: 7313 llvm_unreachable("member pointer type in C"); 7314 case Type::STK_FixedPoint: 7315 Diag(Src.get()->getExprLoc(), 7316 diag::err_unimplemented_conversion_with_fixed_point_type) 7317 << SrcTy; 7318 return CK_IntegralCast; 7319 } 7320 llvm_unreachable("Should have returned before this"); 7321 } 7322 7323 llvm_unreachable("Unhandled scalar cast"); 7324 } 7325 7326 static bool breakDownVectorType(QualType type, uint64_t &len, 7327 QualType &eltType) { 7328 // Vectors are simple. 7329 if (const VectorType *vecType = type->getAs<VectorType>()) { 7330 len = vecType->getNumElements(); 7331 eltType = vecType->getElementType(); 7332 assert(eltType->isScalarType()); 7333 return true; 7334 } 7335 7336 // We allow lax conversion to and from non-vector types, but only if 7337 // they're real types (i.e. non-complex, non-pointer scalar types). 7338 if (!type->isRealType()) return false; 7339 7340 len = 1; 7341 eltType = type; 7342 return true; 7343 } 7344 7345 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7346 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7347 /// allowed? 7348 /// 7349 /// This will also return false if the two given types do not make sense from 7350 /// the perspective of SVE bitcasts. 7351 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7352 assert(srcTy->isVectorType() || destTy->isVectorType()); 7353 7354 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7355 if (!FirstType->isSizelessBuiltinType()) 7356 return false; 7357 7358 const auto *VecTy = SecondType->getAs<VectorType>(); 7359 return VecTy && 7360 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7361 }; 7362 7363 return ValidScalableConversion(srcTy, destTy) || 7364 ValidScalableConversion(destTy, srcTy); 7365 } 7366 7367 /// Are the two types matrix types and do they have the same dimensions i.e. 7368 /// do they have the same number of rows and the same number of columns? 7369 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7370 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7371 return false; 7372 7373 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7374 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7375 7376 return matSrcType->getNumRows() == matDestType->getNumRows() && 7377 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7378 } 7379 7380 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7381 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7382 7383 uint64_t SrcLen, DestLen; 7384 QualType SrcEltTy, DestEltTy; 7385 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7386 return false; 7387 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7388 return false; 7389 7390 // ASTContext::getTypeSize will return the size rounded up to a 7391 // power of 2, so instead of using that, we need to use the raw 7392 // element size multiplied by the element count. 7393 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7394 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7395 7396 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7397 } 7398 7399 /// Are the two types lax-compatible vector types? That is, given 7400 /// that one of them is a vector, do they have equal storage sizes, 7401 /// where the storage size is the number of elements times the element 7402 /// size? 7403 /// 7404 /// This will also return false if either of the types is neither a 7405 /// vector nor a real type. 7406 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7407 assert(destTy->isVectorType() || srcTy->isVectorType()); 7408 7409 // Disallow lax conversions between scalars and ExtVectors (these 7410 // conversions are allowed for other vector types because common headers 7411 // depend on them). Most scalar OP ExtVector cases are handled by the 7412 // splat path anyway, which does what we want (convert, not bitcast). 7413 // What this rules out for ExtVectors is crazy things like char4*float. 7414 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7415 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7416 7417 return areVectorTypesSameSize(srcTy, destTy); 7418 } 7419 7420 /// Is this a legal conversion between two types, one of which is 7421 /// known to be a vector type? 7422 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7423 assert(destTy->isVectorType() || srcTy->isVectorType()); 7424 7425 switch (Context.getLangOpts().getLaxVectorConversions()) { 7426 case LangOptions::LaxVectorConversionKind::None: 7427 return false; 7428 7429 case LangOptions::LaxVectorConversionKind::Integer: 7430 if (!srcTy->isIntegralOrEnumerationType()) { 7431 auto *Vec = srcTy->getAs<VectorType>(); 7432 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7433 return false; 7434 } 7435 if (!destTy->isIntegralOrEnumerationType()) { 7436 auto *Vec = destTy->getAs<VectorType>(); 7437 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7438 return false; 7439 } 7440 // OK, integer (vector) -> integer (vector) bitcast. 7441 break; 7442 7443 case LangOptions::LaxVectorConversionKind::All: 7444 break; 7445 } 7446 7447 return areLaxCompatibleVectorTypes(srcTy, destTy); 7448 } 7449 7450 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7451 CastKind &Kind) { 7452 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7453 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7454 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7455 << DestTy << SrcTy << R; 7456 } 7457 } else if (SrcTy->isMatrixType()) { 7458 return Diag(R.getBegin(), 7459 diag::err_invalid_conversion_between_matrix_and_type) 7460 << SrcTy << DestTy << R; 7461 } else if (DestTy->isMatrixType()) { 7462 return Diag(R.getBegin(), 7463 diag::err_invalid_conversion_between_matrix_and_type) 7464 << DestTy << SrcTy << R; 7465 } 7466 7467 Kind = CK_MatrixCast; 7468 return false; 7469 } 7470 7471 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7472 CastKind &Kind) { 7473 assert(VectorTy->isVectorType() && "Not a vector type!"); 7474 7475 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7476 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7477 return Diag(R.getBegin(), 7478 Ty->isVectorType() ? 7479 diag::err_invalid_conversion_between_vectors : 7480 diag::err_invalid_conversion_between_vector_and_integer) 7481 << VectorTy << Ty << R; 7482 } else 7483 return Diag(R.getBegin(), 7484 diag::err_invalid_conversion_between_vector_and_scalar) 7485 << VectorTy << Ty << R; 7486 7487 Kind = CK_BitCast; 7488 return false; 7489 } 7490 7491 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7492 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7493 7494 if (DestElemTy == SplattedExpr->getType()) 7495 return SplattedExpr; 7496 7497 assert(DestElemTy->isFloatingType() || 7498 DestElemTy->isIntegralOrEnumerationType()); 7499 7500 CastKind CK; 7501 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7502 // OpenCL requires that we convert `true` boolean expressions to -1, but 7503 // only when splatting vectors. 7504 if (DestElemTy->isFloatingType()) { 7505 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7506 // in two steps: boolean to signed integral, then to floating. 7507 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7508 CK_BooleanToSignedIntegral); 7509 SplattedExpr = CastExprRes.get(); 7510 CK = CK_IntegralToFloating; 7511 } else { 7512 CK = CK_BooleanToSignedIntegral; 7513 } 7514 } else { 7515 ExprResult CastExprRes = SplattedExpr; 7516 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7517 if (CastExprRes.isInvalid()) 7518 return ExprError(); 7519 SplattedExpr = CastExprRes.get(); 7520 } 7521 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7522 } 7523 7524 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7525 Expr *CastExpr, CastKind &Kind) { 7526 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7527 7528 QualType SrcTy = CastExpr->getType(); 7529 7530 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7531 // an ExtVectorType. 7532 // In OpenCL, casts between vectors of different types are not allowed. 7533 // (See OpenCL 6.2). 7534 if (SrcTy->isVectorType()) { 7535 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7536 (getLangOpts().OpenCL && 7537 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7538 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7539 << DestTy << SrcTy << R; 7540 return ExprError(); 7541 } 7542 Kind = CK_BitCast; 7543 return CastExpr; 7544 } 7545 7546 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7547 // conversion will take place first from scalar to elt type, and then 7548 // splat from elt type to vector. 7549 if (SrcTy->isPointerType()) 7550 return Diag(R.getBegin(), 7551 diag::err_invalid_conversion_between_vector_and_scalar) 7552 << DestTy << SrcTy << R; 7553 7554 Kind = CK_VectorSplat; 7555 return prepareVectorSplat(DestTy, CastExpr); 7556 } 7557 7558 ExprResult 7559 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7560 Declarator &D, ParsedType &Ty, 7561 SourceLocation RParenLoc, Expr *CastExpr) { 7562 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7563 "ActOnCastExpr(): missing type or expr"); 7564 7565 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7566 if (D.isInvalidType()) 7567 return ExprError(); 7568 7569 if (getLangOpts().CPlusPlus) { 7570 // Check that there are no default arguments (C++ only). 7571 CheckExtraCXXDefaultArguments(D); 7572 } else { 7573 // Make sure any TypoExprs have been dealt with. 7574 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7575 if (!Res.isUsable()) 7576 return ExprError(); 7577 CastExpr = Res.get(); 7578 } 7579 7580 checkUnusedDeclAttributes(D); 7581 7582 QualType castType = castTInfo->getType(); 7583 Ty = CreateParsedType(castType, castTInfo); 7584 7585 bool isVectorLiteral = false; 7586 7587 // Check for an altivec or OpenCL literal, 7588 // i.e. all the elements are integer constants. 7589 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7590 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7591 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7592 && castType->isVectorType() && (PE || PLE)) { 7593 if (PLE && PLE->getNumExprs() == 0) { 7594 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7595 return ExprError(); 7596 } 7597 if (PE || PLE->getNumExprs() == 1) { 7598 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7599 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7600 isVectorLiteral = true; 7601 } 7602 else 7603 isVectorLiteral = true; 7604 } 7605 7606 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7607 // then handle it as such. 7608 if (isVectorLiteral) 7609 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7610 7611 // If the Expr being casted is a ParenListExpr, handle it specially. 7612 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7613 // sequence of BinOp comma operators. 7614 if (isa<ParenListExpr>(CastExpr)) { 7615 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7616 if (Result.isInvalid()) return ExprError(); 7617 CastExpr = Result.get(); 7618 } 7619 7620 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7621 !getSourceManager().isInSystemMacro(LParenLoc)) 7622 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7623 7624 CheckTollFreeBridgeCast(castType, CastExpr); 7625 7626 CheckObjCBridgeRelatedCast(castType, CastExpr); 7627 7628 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7629 7630 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7631 } 7632 7633 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7634 SourceLocation RParenLoc, Expr *E, 7635 TypeSourceInfo *TInfo) { 7636 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7637 "Expected paren or paren list expression"); 7638 7639 Expr **exprs; 7640 unsigned numExprs; 7641 Expr *subExpr; 7642 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7643 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7644 LiteralLParenLoc = PE->getLParenLoc(); 7645 LiteralRParenLoc = PE->getRParenLoc(); 7646 exprs = PE->getExprs(); 7647 numExprs = PE->getNumExprs(); 7648 } else { // isa<ParenExpr> by assertion at function entrance 7649 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7650 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7651 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7652 exprs = &subExpr; 7653 numExprs = 1; 7654 } 7655 7656 QualType Ty = TInfo->getType(); 7657 assert(Ty->isVectorType() && "Expected vector type"); 7658 7659 SmallVector<Expr *, 8> initExprs; 7660 const VectorType *VTy = Ty->castAs<VectorType>(); 7661 unsigned numElems = VTy->getNumElements(); 7662 7663 // '(...)' form of vector initialization in AltiVec: the number of 7664 // initializers must be one or must match the size of the vector. 7665 // If a single value is specified in the initializer then it will be 7666 // replicated to all the components of the vector 7667 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7668 // The number of initializers must be one or must match the size of the 7669 // vector. If a single value is specified in the initializer then it will 7670 // be replicated to all the components of the vector 7671 if (numExprs == 1) { 7672 QualType ElemTy = VTy->getElementType(); 7673 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7674 if (Literal.isInvalid()) 7675 return ExprError(); 7676 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7677 PrepareScalarCast(Literal, ElemTy)); 7678 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7679 } 7680 else if (numExprs < numElems) { 7681 Diag(E->getExprLoc(), 7682 diag::err_incorrect_number_of_vector_initializers); 7683 return ExprError(); 7684 } 7685 else 7686 initExprs.append(exprs, exprs + numExprs); 7687 } 7688 else { 7689 // For OpenCL, when the number of initializers is a single value, 7690 // it will be replicated to all components of the vector. 7691 if (getLangOpts().OpenCL && 7692 VTy->getVectorKind() == VectorType::GenericVector && 7693 numExprs == 1) { 7694 QualType ElemTy = VTy->getElementType(); 7695 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7696 if (Literal.isInvalid()) 7697 return ExprError(); 7698 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7699 PrepareScalarCast(Literal, ElemTy)); 7700 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7701 } 7702 7703 initExprs.append(exprs, exprs + numExprs); 7704 } 7705 // FIXME: This means that pretty-printing the final AST will produce curly 7706 // braces instead of the original commas. 7707 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7708 initExprs, LiteralRParenLoc); 7709 initE->setType(Ty); 7710 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7711 } 7712 7713 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7714 /// the ParenListExpr into a sequence of comma binary operators. 7715 ExprResult 7716 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7717 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7718 if (!E) 7719 return OrigExpr; 7720 7721 ExprResult Result(E->getExpr(0)); 7722 7723 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7724 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7725 E->getExpr(i)); 7726 7727 if (Result.isInvalid()) return ExprError(); 7728 7729 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7730 } 7731 7732 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7733 SourceLocation R, 7734 MultiExprArg Val) { 7735 return ParenListExpr::Create(Context, L, Val, R); 7736 } 7737 7738 /// Emit a specialized diagnostic when one expression is a null pointer 7739 /// constant and the other is not a pointer. Returns true if a diagnostic is 7740 /// emitted. 7741 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7742 SourceLocation QuestionLoc) { 7743 Expr *NullExpr = LHSExpr; 7744 Expr *NonPointerExpr = RHSExpr; 7745 Expr::NullPointerConstantKind NullKind = 7746 NullExpr->isNullPointerConstant(Context, 7747 Expr::NPC_ValueDependentIsNotNull); 7748 7749 if (NullKind == Expr::NPCK_NotNull) { 7750 NullExpr = RHSExpr; 7751 NonPointerExpr = LHSExpr; 7752 NullKind = 7753 NullExpr->isNullPointerConstant(Context, 7754 Expr::NPC_ValueDependentIsNotNull); 7755 } 7756 7757 if (NullKind == Expr::NPCK_NotNull) 7758 return false; 7759 7760 if (NullKind == Expr::NPCK_ZeroExpression) 7761 return false; 7762 7763 if (NullKind == Expr::NPCK_ZeroLiteral) { 7764 // In this case, check to make sure that we got here from a "NULL" 7765 // string in the source code. 7766 NullExpr = NullExpr->IgnoreParenImpCasts(); 7767 SourceLocation loc = NullExpr->getExprLoc(); 7768 if (!findMacroSpelling(loc, "NULL")) 7769 return false; 7770 } 7771 7772 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7773 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7774 << NonPointerExpr->getType() << DiagType 7775 << NonPointerExpr->getSourceRange(); 7776 return true; 7777 } 7778 7779 /// Return false if the condition expression is valid, true otherwise. 7780 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7781 QualType CondTy = Cond->getType(); 7782 7783 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7784 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7785 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7786 << CondTy << Cond->getSourceRange(); 7787 return true; 7788 } 7789 7790 // C99 6.5.15p2 7791 if (CondTy->isScalarType()) return false; 7792 7793 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7794 << CondTy << Cond->getSourceRange(); 7795 return true; 7796 } 7797 7798 /// Handle when one or both operands are void type. 7799 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7800 ExprResult &RHS) { 7801 Expr *LHSExpr = LHS.get(); 7802 Expr *RHSExpr = RHS.get(); 7803 7804 if (!LHSExpr->getType()->isVoidType()) 7805 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7806 << RHSExpr->getSourceRange(); 7807 if (!RHSExpr->getType()->isVoidType()) 7808 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7809 << LHSExpr->getSourceRange(); 7810 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7811 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7812 return S.Context.VoidTy; 7813 } 7814 7815 /// Return false if the NullExpr can be promoted to PointerTy, 7816 /// true otherwise. 7817 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7818 QualType PointerTy) { 7819 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7820 !NullExpr.get()->isNullPointerConstant(S.Context, 7821 Expr::NPC_ValueDependentIsNull)) 7822 return true; 7823 7824 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7825 return false; 7826 } 7827 7828 /// Checks compatibility between two pointers and return the resulting 7829 /// type. 7830 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7831 ExprResult &RHS, 7832 SourceLocation Loc) { 7833 QualType LHSTy = LHS.get()->getType(); 7834 QualType RHSTy = RHS.get()->getType(); 7835 7836 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7837 // Two identical pointers types are always compatible. 7838 return LHSTy; 7839 } 7840 7841 QualType lhptee, rhptee; 7842 7843 // Get the pointee types. 7844 bool IsBlockPointer = false; 7845 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7846 lhptee = LHSBTy->getPointeeType(); 7847 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7848 IsBlockPointer = true; 7849 } else { 7850 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7851 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7852 } 7853 7854 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7855 // differently qualified versions of compatible types, the result type is 7856 // a pointer to an appropriately qualified version of the composite 7857 // type. 7858 7859 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7860 // clause doesn't make sense for our extensions. E.g. address space 2 should 7861 // be incompatible with address space 3: they may live on different devices or 7862 // anything. 7863 Qualifiers lhQual = lhptee.getQualifiers(); 7864 Qualifiers rhQual = rhptee.getQualifiers(); 7865 7866 LangAS ResultAddrSpace = LangAS::Default; 7867 LangAS LAddrSpace = lhQual.getAddressSpace(); 7868 LangAS RAddrSpace = rhQual.getAddressSpace(); 7869 7870 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7871 // spaces is disallowed. 7872 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7873 ResultAddrSpace = LAddrSpace; 7874 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7875 ResultAddrSpace = RAddrSpace; 7876 else { 7877 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7878 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7879 << RHS.get()->getSourceRange(); 7880 return QualType(); 7881 } 7882 7883 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7884 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7885 lhQual.removeCVRQualifiers(); 7886 rhQual.removeCVRQualifiers(); 7887 7888 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7889 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7890 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7891 // qual types are compatible iff 7892 // * corresponded types are compatible 7893 // * CVR qualifiers are equal 7894 // * address spaces are equal 7895 // Thus for conditional operator we merge CVR and address space unqualified 7896 // pointees and if there is a composite type we return a pointer to it with 7897 // merged qualifiers. 7898 LHSCastKind = 7899 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7900 RHSCastKind = 7901 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7902 lhQual.removeAddressSpace(); 7903 rhQual.removeAddressSpace(); 7904 7905 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7906 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7907 7908 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7909 7910 if (CompositeTy.isNull()) { 7911 // In this situation, we assume void* type. No especially good 7912 // reason, but this is what gcc does, and we do have to pick 7913 // to get a consistent AST. 7914 QualType incompatTy; 7915 incompatTy = S.Context.getPointerType( 7916 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7917 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7918 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7919 7920 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7921 // for casts between types with incompatible address space qualifiers. 7922 // For the following code the compiler produces casts between global and 7923 // local address spaces of the corresponded innermost pointees: 7924 // local int *global *a; 7925 // global int *global *b; 7926 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7927 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7928 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7929 << RHS.get()->getSourceRange(); 7930 7931 return incompatTy; 7932 } 7933 7934 // The pointer types are compatible. 7935 // In case of OpenCL ResultTy should have the address space qualifier 7936 // which is a superset of address spaces of both the 2nd and the 3rd 7937 // operands of the conditional operator. 7938 QualType ResultTy = [&, ResultAddrSpace]() { 7939 if (S.getLangOpts().OpenCL) { 7940 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7941 CompositeQuals.setAddressSpace(ResultAddrSpace); 7942 return S.Context 7943 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7944 .withCVRQualifiers(MergedCVRQual); 7945 } 7946 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7947 }(); 7948 if (IsBlockPointer) 7949 ResultTy = S.Context.getBlockPointerType(ResultTy); 7950 else 7951 ResultTy = S.Context.getPointerType(ResultTy); 7952 7953 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7954 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7955 return ResultTy; 7956 } 7957 7958 /// Return the resulting type when the operands are both block pointers. 7959 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7960 ExprResult &LHS, 7961 ExprResult &RHS, 7962 SourceLocation Loc) { 7963 QualType LHSTy = LHS.get()->getType(); 7964 QualType RHSTy = RHS.get()->getType(); 7965 7966 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7967 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7968 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7969 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7970 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7971 return destType; 7972 } 7973 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7974 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7975 << RHS.get()->getSourceRange(); 7976 return QualType(); 7977 } 7978 7979 // We have 2 block pointer types. 7980 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7981 } 7982 7983 /// Return the resulting type when the operands are both pointers. 7984 static QualType 7985 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7986 ExprResult &RHS, 7987 SourceLocation Loc) { 7988 // get the pointer types 7989 QualType LHSTy = LHS.get()->getType(); 7990 QualType RHSTy = RHS.get()->getType(); 7991 7992 // get the "pointed to" types 7993 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7994 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7995 7996 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7997 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7998 // Figure out necessary qualifiers (C99 6.5.15p6) 7999 QualType destPointee 8000 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8001 QualType destType = S.Context.getPointerType(destPointee); 8002 // Add qualifiers if necessary. 8003 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8004 // Promote to void*. 8005 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8006 return destType; 8007 } 8008 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8009 QualType destPointee 8010 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8011 QualType destType = S.Context.getPointerType(destPointee); 8012 // Add qualifiers if necessary. 8013 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8014 // Promote to void*. 8015 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8016 return destType; 8017 } 8018 8019 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8020 } 8021 8022 /// Return false if the first expression is not an integer and the second 8023 /// expression is not a pointer, true otherwise. 8024 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8025 Expr* PointerExpr, SourceLocation Loc, 8026 bool IsIntFirstExpr) { 8027 if (!PointerExpr->getType()->isPointerType() || 8028 !Int.get()->getType()->isIntegerType()) 8029 return false; 8030 8031 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8032 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8033 8034 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8035 << Expr1->getType() << Expr2->getType() 8036 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8037 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8038 CK_IntegralToPointer); 8039 return true; 8040 } 8041 8042 /// Simple conversion between integer and floating point types. 8043 /// 8044 /// Used when handling the OpenCL conditional operator where the 8045 /// condition is a vector while the other operands are scalar. 8046 /// 8047 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8048 /// types are either integer or floating type. Between the two 8049 /// operands, the type with the higher rank is defined as the "result 8050 /// type". The other operand needs to be promoted to the same type. No 8051 /// other type promotion is allowed. We cannot use 8052 /// UsualArithmeticConversions() for this purpose, since it always 8053 /// promotes promotable types. 8054 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8055 ExprResult &RHS, 8056 SourceLocation QuestionLoc) { 8057 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8058 if (LHS.isInvalid()) 8059 return QualType(); 8060 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8061 if (RHS.isInvalid()) 8062 return QualType(); 8063 8064 // For conversion purposes, we ignore any qualifiers. 8065 // For example, "const float" and "float" are equivalent. 8066 QualType LHSType = 8067 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8068 QualType RHSType = 8069 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8070 8071 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8072 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8073 << LHSType << LHS.get()->getSourceRange(); 8074 return QualType(); 8075 } 8076 8077 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8078 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8079 << RHSType << RHS.get()->getSourceRange(); 8080 return QualType(); 8081 } 8082 8083 // If both types are identical, no conversion is needed. 8084 if (LHSType == RHSType) 8085 return LHSType; 8086 8087 // Now handle "real" floating types (i.e. float, double, long double). 8088 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8089 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8090 /*IsCompAssign = */ false); 8091 8092 // Finally, we have two differing integer types. 8093 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8094 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8095 } 8096 8097 /// Convert scalar operands to a vector that matches the 8098 /// condition in length. 8099 /// 8100 /// Used when handling the OpenCL conditional operator where the 8101 /// condition is a vector while the other operands are scalar. 8102 /// 8103 /// We first compute the "result type" for the scalar operands 8104 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8105 /// into a vector of that type where the length matches the condition 8106 /// vector type. s6.11.6 requires that the element types of the result 8107 /// and the condition must have the same number of bits. 8108 static QualType 8109 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8110 QualType CondTy, SourceLocation QuestionLoc) { 8111 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8112 if (ResTy.isNull()) return QualType(); 8113 8114 const VectorType *CV = CondTy->getAs<VectorType>(); 8115 assert(CV); 8116 8117 // Determine the vector result type 8118 unsigned NumElements = CV->getNumElements(); 8119 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8120 8121 // Ensure that all types have the same number of bits 8122 if (S.Context.getTypeSize(CV->getElementType()) 8123 != S.Context.getTypeSize(ResTy)) { 8124 // Since VectorTy is created internally, it does not pretty print 8125 // with an OpenCL name. Instead, we just print a description. 8126 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8127 SmallString<64> Str; 8128 llvm::raw_svector_ostream OS(Str); 8129 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8130 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8131 << CondTy << OS.str(); 8132 return QualType(); 8133 } 8134 8135 // Convert operands to the vector result type 8136 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8137 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8138 8139 return VectorTy; 8140 } 8141 8142 /// Return false if this is a valid OpenCL condition vector 8143 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8144 SourceLocation QuestionLoc) { 8145 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8146 // integral type. 8147 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8148 assert(CondTy); 8149 QualType EleTy = CondTy->getElementType(); 8150 if (EleTy->isIntegerType()) return false; 8151 8152 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8153 << Cond->getType() << Cond->getSourceRange(); 8154 return true; 8155 } 8156 8157 /// Return false if the vector condition type and the vector 8158 /// result type are compatible. 8159 /// 8160 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8161 /// number of elements, and their element types have the same number 8162 /// of bits. 8163 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8164 SourceLocation QuestionLoc) { 8165 const VectorType *CV = CondTy->getAs<VectorType>(); 8166 const VectorType *RV = VecResTy->getAs<VectorType>(); 8167 assert(CV && RV); 8168 8169 if (CV->getNumElements() != RV->getNumElements()) { 8170 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8171 << CondTy << VecResTy; 8172 return true; 8173 } 8174 8175 QualType CVE = CV->getElementType(); 8176 QualType RVE = RV->getElementType(); 8177 8178 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8179 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8180 << CondTy << VecResTy; 8181 return true; 8182 } 8183 8184 return false; 8185 } 8186 8187 /// Return the resulting type for the conditional operator in 8188 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8189 /// s6.3.i) when the condition is a vector type. 8190 static QualType 8191 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8192 ExprResult &LHS, ExprResult &RHS, 8193 SourceLocation QuestionLoc) { 8194 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8195 if (Cond.isInvalid()) 8196 return QualType(); 8197 QualType CondTy = Cond.get()->getType(); 8198 8199 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8200 return QualType(); 8201 8202 // If either operand is a vector then find the vector type of the 8203 // result as specified in OpenCL v1.1 s6.3.i. 8204 if (LHS.get()->getType()->isVectorType() || 8205 RHS.get()->getType()->isVectorType()) { 8206 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8207 /*isCompAssign*/false, 8208 /*AllowBothBool*/true, 8209 /*AllowBoolConversions*/false); 8210 if (VecResTy.isNull()) return QualType(); 8211 // The result type must match the condition type as specified in 8212 // OpenCL v1.1 s6.11.6. 8213 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8214 return QualType(); 8215 return VecResTy; 8216 } 8217 8218 // Both operands are scalar. 8219 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8220 } 8221 8222 /// Return true if the Expr is block type 8223 static bool checkBlockType(Sema &S, const Expr *E) { 8224 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8225 QualType Ty = CE->getCallee()->getType(); 8226 if (Ty->isBlockPointerType()) { 8227 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8228 return true; 8229 } 8230 } 8231 return false; 8232 } 8233 8234 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8235 /// In that case, LHS = cond. 8236 /// C99 6.5.15 8237 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8238 ExprResult &RHS, ExprValueKind &VK, 8239 ExprObjectKind &OK, 8240 SourceLocation QuestionLoc) { 8241 8242 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8243 if (!LHSResult.isUsable()) return QualType(); 8244 LHS = LHSResult; 8245 8246 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8247 if (!RHSResult.isUsable()) return QualType(); 8248 RHS = RHSResult; 8249 8250 // C++ is sufficiently different to merit its own checker. 8251 if (getLangOpts().CPlusPlus) 8252 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8253 8254 VK = VK_RValue; 8255 OK = OK_Ordinary; 8256 8257 if (Context.isDependenceAllowed() && 8258 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8259 RHS.get()->isTypeDependent())) { 8260 assert(!getLangOpts().CPlusPlus); 8261 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8262 RHS.get()->containsErrors()) && 8263 "should only occur in error-recovery path."); 8264 return Context.DependentTy; 8265 } 8266 8267 // The OpenCL operator with a vector condition is sufficiently 8268 // different to merit its own checker. 8269 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8270 Cond.get()->getType()->isExtVectorType()) 8271 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8272 8273 // First, check the condition. 8274 Cond = UsualUnaryConversions(Cond.get()); 8275 if (Cond.isInvalid()) 8276 return QualType(); 8277 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8278 return QualType(); 8279 8280 // Now check the two expressions. 8281 if (LHS.get()->getType()->isVectorType() || 8282 RHS.get()->getType()->isVectorType()) 8283 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8284 /*AllowBothBool*/true, 8285 /*AllowBoolConversions*/false); 8286 8287 QualType ResTy = 8288 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8289 if (LHS.isInvalid() || RHS.isInvalid()) 8290 return QualType(); 8291 8292 QualType LHSTy = LHS.get()->getType(); 8293 QualType RHSTy = RHS.get()->getType(); 8294 8295 // Diagnose attempts to convert between __float128 and long double where 8296 // such conversions currently can't be handled. 8297 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8298 Diag(QuestionLoc, 8299 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8300 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8301 return QualType(); 8302 } 8303 8304 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8305 // selection operator (?:). 8306 if (getLangOpts().OpenCL && 8307 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8308 return QualType(); 8309 } 8310 8311 // If both operands have arithmetic type, do the usual arithmetic conversions 8312 // to find a common type: C99 6.5.15p3,5. 8313 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8314 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8315 // different sizes, or between ExtInts and other types. 8316 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8317 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8318 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8319 << RHS.get()->getSourceRange(); 8320 return QualType(); 8321 } 8322 8323 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8324 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8325 8326 return ResTy; 8327 } 8328 8329 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8330 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8331 return LHSTy; 8332 } 8333 8334 // If both operands are the same structure or union type, the result is that 8335 // type. 8336 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8337 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8338 if (LHSRT->getDecl() == RHSRT->getDecl()) 8339 // "If both the operands have structure or union type, the result has 8340 // that type." This implies that CV qualifiers are dropped. 8341 return LHSTy.getUnqualifiedType(); 8342 // FIXME: Type of conditional expression must be complete in C mode. 8343 } 8344 8345 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8346 // The following || allows only one side to be void (a GCC-ism). 8347 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8348 return checkConditionalVoidType(*this, LHS, RHS); 8349 } 8350 8351 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8352 // the type of the other operand." 8353 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8354 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8355 8356 // All objective-c pointer type analysis is done here. 8357 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8358 QuestionLoc); 8359 if (LHS.isInvalid() || RHS.isInvalid()) 8360 return QualType(); 8361 if (!compositeType.isNull()) 8362 return compositeType; 8363 8364 8365 // Handle block pointer types. 8366 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8367 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8368 QuestionLoc); 8369 8370 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8371 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8372 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8373 QuestionLoc); 8374 8375 // GCC compatibility: soften pointer/integer mismatch. Note that 8376 // null pointers have been filtered out by this point. 8377 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8378 /*IsIntFirstExpr=*/true)) 8379 return RHSTy; 8380 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8381 /*IsIntFirstExpr=*/false)) 8382 return LHSTy; 8383 8384 // Allow ?: operations in which both operands have the same 8385 // built-in sizeless type. 8386 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8387 return LHSTy; 8388 8389 // Emit a better diagnostic if one of the expressions is a null pointer 8390 // constant and the other is not a pointer type. In this case, the user most 8391 // likely forgot to take the address of the other expression. 8392 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8393 return QualType(); 8394 8395 // Otherwise, the operands are not compatible. 8396 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8397 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8398 << RHS.get()->getSourceRange(); 8399 return QualType(); 8400 } 8401 8402 /// FindCompositeObjCPointerType - Helper method to find composite type of 8403 /// two objective-c pointer types of the two input expressions. 8404 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8405 SourceLocation QuestionLoc) { 8406 QualType LHSTy = LHS.get()->getType(); 8407 QualType RHSTy = RHS.get()->getType(); 8408 8409 // Handle things like Class and struct objc_class*. Here we case the result 8410 // to the pseudo-builtin, because that will be implicitly cast back to the 8411 // redefinition type if an attempt is made to access its fields. 8412 if (LHSTy->isObjCClassType() && 8413 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8414 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8415 return LHSTy; 8416 } 8417 if (RHSTy->isObjCClassType() && 8418 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8419 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8420 return RHSTy; 8421 } 8422 // And the same for struct objc_object* / id 8423 if (LHSTy->isObjCIdType() && 8424 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8425 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8426 return LHSTy; 8427 } 8428 if (RHSTy->isObjCIdType() && 8429 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8430 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8431 return RHSTy; 8432 } 8433 // And the same for struct objc_selector* / SEL 8434 if (Context.isObjCSelType(LHSTy) && 8435 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8436 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8437 return LHSTy; 8438 } 8439 if (Context.isObjCSelType(RHSTy) && 8440 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8441 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8442 return RHSTy; 8443 } 8444 // Check constraints for Objective-C object pointers types. 8445 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8446 8447 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8448 // Two identical object pointer types are always compatible. 8449 return LHSTy; 8450 } 8451 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8452 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8453 QualType compositeType = LHSTy; 8454 8455 // If both operands are interfaces and either operand can be 8456 // assigned to the other, use that type as the composite 8457 // type. This allows 8458 // xxx ? (A*) a : (B*) b 8459 // where B is a subclass of A. 8460 // 8461 // Additionally, as for assignment, if either type is 'id' 8462 // allow silent coercion. Finally, if the types are 8463 // incompatible then make sure to use 'id' as the composite 8464 // type so the result is acceptable for sending messages to. 8465 8466 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8467 // It could return the composite type. 8468 if (!(compositeType = 8469 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8470 // Nothing more to do. 8471 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8472 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8473 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8474 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8475 } else if ((LHSOPT->isObjCQualifiedIdType() || 8476 RHSOPT->isObjCQualifiedIdType()) && 8477 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8478 true)) { 8479 // Need to handle "id<xx>" explicitly. 8480 // GCC allows qualified id and any Objective-C type to devolve to 8481 // id. Currently localizing to here until clear this should be 8482 // part of ObjCQualifiedIdTypesAreCompatible. 8483 compositeType = Context.getObjCIdType(); 8484 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8485 compositeType = Context.getObjCIdType(); 8486 } else { 8487 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8488 << LHSTy << RHSTy 8489 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8490 QualType incompatTy = Context.getObjCIdType(); 8491 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8492 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8493 return incompatTy; 8494 } 8495 // The object pointer types are compatible. 8496 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8497 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8498 return compositeType; 8499 } 8500 // Check Objective-C object pointer types and 'void *' 8501 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8502 if (getLangOpts().ObjCAutoRefCount) { 8503 // ARC forbids the implicit conversion of object pointers to 'void *', 8504 // so these types are not compatible. 8505 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8506 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8507 LHS = RHS = true; 8508 return QualType(); 8509 } 8510 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8511 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8512 QualType destPointee 8513 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8514 QualType destType = Context.getPointerType(destPointee); 8515 // Add qualifiers if necessary. 8516 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8517 // Promote to void*. 8518 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8519 return destType; 8520 } 8521 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8522 if (getLangOpts().ObjCAutoRefCount) { 8523 // ARC forbids the implicit conversion of object pointers to 'void *', 8524 // so these types are not compatible. 8525 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8526 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8527 LHS = RHS = true; 8528 return QualType(); 8529 } 8530 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8531 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8532 QualType destPointee 8533 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8534 QualType destType = Context.getPointerType(destPointee); 8535 // Add qualifiers if necessary. 8536 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8537 // Promote to void*. 8538 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8539 return destType; 8540 } 8541 return QualType(); 8542 } 8543 8544 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8545 /// ParenRange in parentheses. 8546 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8547 const PartialDiagnostic &Note, 8548 SourceRange ParenRange) { 8549 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8550 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8551 EndLoc.isValid()) { 8552 Self.Diag(Loc, Note) 8553 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8554 << FixItHint::CreateInsertion(EndLoc, ")"); 8555 } else { 8556 // We can't display the parentheses, so just show the bare note. 8557 Self.Diag(Loc, Note) << ParenRange; 8558 } 8559 } 8560 8561 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8562 return BinaryOperator::isAdditiveOp(Opc) || 8563 BinaryOperator::isMultiplicativeOp(Opc) || 8564 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8565 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8566 // not any of the logical operators. Bitwise-xor is commonly used as a 8567 // logical-xor because there is no logical-xor operator. The logical 8568 // operators, including uses of xor, have a high false positive rate for 8569 // precedence warnings. 8570 } 8571 8572 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8573 /// expression, either using a built-in or overloaded operator, 8574 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8575 /// expression. 8576 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8577 Expr **RHSExprs) { 8578 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8579 E = E->IgnoreImpCasts(); 8580 E = E->IgnoreConversionOperatorSingleStep(); 8581 E = E->IgnoreImpCasts(); 8582 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8583 E = MTE->getSubExpr(); 8584 E = E->IgnoreImpCasts(); 8585 } 8586 8587 // Built-in binary operator. 8588 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8589 if (IsArithmeticOp(OP->getOpcode())) { 8590 *Opcode = OP->getOpcode(); 8591 *RHSExprs = OP->getRHS(); 8592 return true; 8593 } 8594 } 8595 8596 // Overloaded operator. 8597 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8598 if (Call->getNumArgs() != 2) 8599 return false; 8600 8601 // Make sure this is really a binary operator that is safe to pass into 8602 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8603 OverloadedOperatorKind OO = Call->getOperator(); 8604 if (OO < OO_Plus || OO > OO_Arrow || 8605 OO == OO_PlusPlus || OO == OO_MinusMinus) 8606 return false; 8607 8608 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8609 if (IsArithmeticOp(OpKind)) { 8610 *Opcode = OpKind; 8611 *RHSExprs = Call->getArg(1); 8612 return true; 8613 } 8614 } 8615 8616 return false; 8617 } 8618 8619 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8620 /// or is a logical expression such as (x==y) which has int type, but is 8621 /// commonly interpreted as boolean. 8622 static bool ExprLooksBoolean(Expr *E) { 8623 E = E->IgnoreParenImpCasts(); 8624 8625 if (E->getType()->isBooleanType()) 8626 return true; 8627 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8628 return OP->isComparisonOp() || OP->isLogicalOp(); 8629 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8630 return OP->getOpcode() == UO_LNot; 8631 if (E->getType()->isPointerType()) 8632 return true; 8633 // FIXME: What about overloaded operator calls returning "unspecified boolean 8634 // type"s (commonly pointer-to-members)? 8635 8636 return false; 8637 } 8638 8639 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8640 /// and binary operator are mixed in a way that suggests the programmer assumed 8641 /// the conditional operator has higher precedence, for example: 8642 /// "int x = a + someBinaryCondition ? 1 : 2". 8643 static void DiagnoseConditionalPrecedence(Sema &Self, 8644 SourceLocation OpLoc, 8645 Expr *Condition, 8646 Expr *LHSExpr, 8647 Expr *RHSExpr) { 8648 BinaryOperatorKind CondOpcode; 8649 Expr *CondRHS; 8650 8651 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8652 return; 8653 if (!ExprLooksBoolean(CondRHS)) 8654 return; 8655 8656 // The condition is an arithmetic binary expression, with a right- 8657 // hand side that looks boolean, so warn. 8658 8659 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8660 ? diag::warn_precedence_bitwise_conditional 8661 : diag::warn_precedence_conditional; 8662 8663 Self.Diag(OpLoc, DiagID) 8664 << Condition->getSourceRange() 8665 << BinaryOperator::getOpcodeStr(CondOpcode); 8666 8667 SuggestParentheses( 8668 Self, OpLoc, 8669 Self.PDiag(diag::note_precedence_silence) 8670 << BinaryOperator::getOpcodeStr(CondOpcode), 8671 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8672 8673 SuggestParentheses(Self, OpLoc, 8674 Self.PDiag(diag::note_precedence_conditional_first), 8675 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8676 } 8677 8678 /// Compute the nullability of a conditional expression. 8679 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8680 QualType LHSTy, QualType RHSTy, 8681 ASTContext &Ctx) { 8682 if (!ResTy->isAnyPointerType()) 8683 return ResTy; 8684 8685 auto GetNullability = [&Ctx](QualType Ty) { 8686 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8687 if (Kind) { 8688 // For our purposes, treat _Nullable_result as _Nullable. 8689 if (*Kind == NullabilityKind::NullableResult) 8690 return NullabilityKind::Nullable; 8691 return *Kind; 8692 } 8693 return NullabilityKind::Unspecified; 8694 }; 8695 8696 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8697 NullabilityKind MergedKind; 8698 8699 // Compute nullability of a binary conditional expression. 8700 if (IsBin) { 8701 if (LHSKind == NullabilityKind::NonNull) 8702 MergedKind = NullabilityKind::NonNull; 8703 else 8704 MergedKind = RHSKind; 8705 // Compute nullability of a normal conditional expression. 8706 } else { 8707 if (LHSKind == NullabilityKind::Nullable || 8708 RHSKind == NullabilityKind::Nullable) 8709 MergedKind = NullabilityKind::Nullable; 8710 else if (LHSKind == NullabilityKind::NonNull) 8711 MergedKind = RHSKind; 8712 else if (RHSKind == NullabilityKind::NonNull) 8713 MergedKind = LHSKind; 8714 else 8715 MergedKind = NullabilityKind::Unspecified; 8716 } 8717 8718 // Return if ResTy already has the correct nullability. 8719 if (GetNullability(ResTy) == MergedKind) 8720 return ResTy; 8721 8722 // Strip all nullability from ResTy. 8723 while (ResTy->getNullability(Ctx)) 8724 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8725 8726 // Create a new AttributedType with the new nullability kind. 8727 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8728 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8729 } 8730 8731 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8732 /// in the case of a the GNU conditional expr extension. 8733 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8734 SourceLocation ColonLoc, 8735 Expr *CondExpr, Expr *LHSExpr, 8736 Expr *RHSExpr) { 8737 if (!Context.isDependenceAllowed()) { 8738 // C cannot handle TypoExpr nodes in the condition because it 8739 // doesn't handle dependent types properly, so make sure any TypoExprs have 8740 // been dealt with before checking the operands. 8741 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8742 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8743 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8744 8745 if (!CondResult.isUsable()) 8746 return ExprError(); 8747 8748 if (LHSExpr) { 8749 if (!LHSResult.isUsable()) 8750 return ExprError(); 8751 } 8752 8753 if (!RHSResult.isUsable()) 8754 return ExprError(); 8755 8756 CondExpr = CondResult.get(); 8757 LHSExpr = LHSResult.get(); 8758 RHSExpr = RHSResult.get(); 8759 } 8760 8761 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8762 // was the condition. 8763 OpaqueValueExpr *opaqueValue = nullptr; 8764 Expr *commonExpr = nullptr; 8765 if (!LHSExpr) { 8766 commonExpr = CondExpr; 8767 // Lower out placeholder types first. This is important so that we don't 8768 // try to capture a placeholder. This happens in few cases in C++; such 8769 // as Objective-C++'s dictionary subscripting syntax. 8770 if (commonExpr->hasPlaceholderType()) { 8771 ExprResult result = CheckPlaceholderExpr(commonExpr); 8772 if (!result.isUsable()) return ExprError(); 8773 commonExpr = result.get(); 8774 } 8775 // We usually want to apply unary conversions *before* saving, except 8776 // in the special case of a C++ l-value conditional. 8777 if (!(getLangOpts().CPlusPlus 8778 && !commonExpr->isTypeDependent() 8779 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8780 && commonExpr->isGLValue() 8781 && commonExpr->isOrdinaryOrBitFieldObject() 8782 && RHSExpr->isOrdinaryOrBitFieldObject() 8783 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8784 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8785 if (commonRes.isInvalid()) 8786 return ExprError(); 8787 commonExpr = commonRes.get(); 8788 } 8789 8790 // If the common expression is a class or array prvalue, materialize it 8791 // so that we can safely refer to it multiple times. 8792 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8793 commonExpr->getType()->isArrayType())) { 8794 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8795 if (MatExpr.isInvalid()) 8796 return ExprError(); 8797 commonExpr = MatExpr.get(); 8798 } 8799 8800 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8801 commonExpr->getType(), 8802 commonExpr->getValueKind(), 8803 commonExpr->getObjectKind(), 8804 commonExpr); 8805 LHSExpr = CondExpr = opaqueValue; 8806 } 8807 8808 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8809 ExprValueKind VK = VK_RValue; 8810 ExprObjectKind OK = OK_Ordinary; 8811 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8812 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8813 VK, OK, QuestionLoc); 8814 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8815 RHS.isInvalid()) 8816 return ExprError(); 8817 8818 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8819 RHS.get()); 8820 8821 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8822 8823 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8824 Context); 8825 8826 if (!commonExpr) 8827 return new (Context) 8828 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8829 RHS.get(), result, VK, OK); 8830 8831 return new (Context) BinaryConditionalOperator( 8832 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8833 ColonLoc, result, VK, OK); 8834 } 8835 8836 // Check if we have a conversion between incompatible cmse function pointer 8837 // types, that is, a conversion between a function pointer with the 8838 // cmse_nonsecure_call attribute and one without. 8839 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8840 QualType ToType) { 8841 if (const auto *ToFn = 8842 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8843 if (const auto *FromFn = 8844 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8845 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8846 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8847 8848 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8849 } 8850 } 8851 return false; 8852 } 8853 8854 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8855 // being closely modeled after the C99 spec:-). The odd characteristic of this 8856 // routine is it effectively iqnores the qualifiers on the top level pointee. 8857 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8858 // FIXME: add a couple examples in this comment. 8859 static Sema::AssignConvertType 8860 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8861 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8862 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8863 8864 // get the "pointed to" type (ignoring qualifiers at the top level) 8865 const Type *lhptee, *rhptee; 8866 Qualifiers lhq, rhq; 8867 std::tie(lhptee, lhq) = 8868 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8869 std::tie(rhptee, rhq) = 8870 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8871 8872 Sema::AssignConvertType ConvTy = Sema::Compatible; 8873 8874 // C99 6.5.16.1p1: This following citation is common to constraints 8875 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8876 // qualifiers of the type *pointed to* by the right; 8877 8878 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8879 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8880 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8881 // Ignore lifetime for further calculation. 8882 lhq.removeObjCLifetime(); 8883 rhq.removeObjCLifetime(); 8884 } 8885 8886 if (!lhq.compatiblyIncludes(rhq)) { 8887 // Treat address-space mismatches as fatal. 8888 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8889 return Sema::IncompatiblePointerDiscardsQualifiers; 8890 8891 // It's okay to add or remove GC or lifetime qualifiers when converting to 8892 // and from void*. 8893 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8894 .compatiblyIncludes( 8895 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8896 && (lhptee->isVoidType() || rhptee->isVoidType())) 8897 ; // keep old 8898 8899 // Treat lifetime mismatches as fatal. 8900 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8901 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8902 8903 // For GCC/MS compatibility, other qualifier mismatches are treated 8904 // as still compatible in C. 8905 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8906 } 8907 8908 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8909 // incomplete type and the other is a pointer to a qualified or unqualified 8910 // version of void... 8911 if (lhptee->isVoidType()) { 8912 if (rhptee->isIncompleteOrObjectType()) 8913 return ConvTy; 8914 8915 // As an extension, we allow cast to/from void* to function pointer. 8916 assert(rhptee->isFunctionType()); 8917 return Sema::FunctionVoidPointer; 8918 } 8919 8920 if (rhptee->isVoidType()) { 8921 if (lhptee->isIncompleteOrObjectType()) 8922 return ConvTy; 8923 8924 // As an extension, we allow cast to/from void* to function pointer. 8925 assert(lhptee->isFunctionType()); 8926 return Sema::FunctionVoidPointer; 8927 } 8928 8929 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8930 // unqualified versions of compatible types, ... 8931 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8932 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8933 // Check if the pointee types are compatible ignoring the sign. 8934 // We explicitly check for char so that we catch "char" vs 8935 // "unsigned char" on systems where "char" is unsigned. 8936 if (lhptee->isCharType()) 8937 ltrans = S.Context.UnsignedCharTy; 8938 else if (lhptee->hasSignedIntegerRepresentation()) 8939 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8940 8941 if (rhptee->isCharType()) 8942 rtrans = S.Context.UnsignedCharTy; 8943 else if (rhptee->hasSignedIntegerRepresentation()) 8944 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8945 8946 if (ltrans == rtrans) { 8947 // Types are compatible ignoring the sign. Qualifier incompatibility 8948 // takes priority over sign incompatibility because the sign 8949 // warning can be disabled. 8950 if (ConvTy != Sema::Compatible) 8951 return ConvTy; 8952 8953 return Sema::IncompatiblePointerSign; 8954 } 8955 8956 // If we are a multi-level pointer, it's possible that our issue is simply 8957 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8958 // the eventual target type is the same and the pointers have the same 8959 // level of indirection, this must be the issue. 8960 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8961 do { 8962 std::tie(lhptee, lhq) = 8963 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8964 std::tie(rhptee, rhq) = 8965 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8966 8967 // Inconsistent address spaces at this point is invalid, even if the 8968 // address spaces would be compatible. 8969 // FIXME: This doesn't catch address space mismatches for pointers of 8970 // different nesting levels, like: 8971 // __local int *** a; 8972 // int ** b = a; 8973 // It's not clear how to actually determine when such pointers are 8974 // invalidly incompatible. 8975 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8976 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8977 8978 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8979 8980 if (lhptee == rhptee) 8981 return Sema::IncompatibleNestedPointerQualifiers; 8982 } 8983 8984 // General pointer incompatibility takes priority over qualifiers. 8985 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8986 return Sema::IncompatibleFunctionPointer; 8987 return Sema::IncompatiblePointer; 8988 } 8989 if (!S.getLangOpts().CPlusPlus && 8990 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8991 return Sema::IncompatibleFunctionPointer; 8992 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8993 return Sema::IncompatibleFunctionPointer; 8994 return ConvTy; 8995 } 8996 8997 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8998 /// block pointer types are compatible or whether a block and normal pointer 8999 /// are compatible. It is more restrict than comparing two function pointer 9000 // types. 9001 static Sema::AssignConvertType 9002 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9003 QualType RHSType) { 9004 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9005 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9006 9007 QualType lhptee, rhptee; 9008 9009 // get the "pointed to" type (ignoring qualifiers at the top level) 9010 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9011 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9012 9013 // In C++, the types have to match exactly. 9014 if (S.getLangOpts().CPlusPlus) 9015 return Sema::IncompatibleBlockPointer; 9016 9017 Sema::AssignConvertType ConvTy = Sema::Compatible; 9018 9019 // For blocks we enforce that qualifiers are identical. 9020 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9021 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9022 if (S.getLangOpts().OpenCL) { 9023 LQuals.removeAddressSpace(); 9024 RQuals.removeAddressSpace(); 9025 } 9026 if (LQuals != RQuals) 9027 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9028 9029 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9030 // assignment. 9031 // The current behavior is similar to C++ lambdas. A block might be 9032 // assigned to a variable iff its return type and parameters are compatible 9033 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9034 // an assignment. Presumably it should behave in way that a function pointer 9035 // assignment does in C, so for each parameter and return type: 9036 // * CVR and address space of LHS should be a superset of CVR and address 9037 // space of RHS. 9038 // * unqualified types should be compatible. 9039 if (S.getLangOpts().OpenCL) { 9040 if (!S.Context.typesAreBlockPointerCompatible( 9041 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9042 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9043 return Sema::IncompatibleBlockPointer; 9044 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9045 return Sema::IncompatibleBlockPointer; 9046 9047 return ConvTy; 9048 } 9049 9050 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9051 /// for assignment compatibility. 9052 static Sema::AssignConvertType 9053 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9054 QualType RHSType) { 9055 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9056 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9057 9058 if (LHSType->isObjCBuiltinType()) { 9059 // Class is not compatible with ObjC object pointers. 9060 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9061 !RHSType->isObjCQualifiedClassType()) 9062 return Sema::IncompatiblePointer; 9063 return Sema::Compatible; 9064 } 9065 if (RHSType->isObjCBuiltinType()) { 9066 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9067 !LHSType->isObjCQualifiedClassType()) 9068 return Sema::IncompatiblePointer; 9069 return Sema::Compatible; 9070 } 9071 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9072 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9073 9074 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9075 // make an exception for id<P> 9076 !LHSType->isObjCQualifiedIdType()) 9077 return Sema::CompatiblePointerDiscardsQualifiers; 9078 9079 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9080 return Sema::Compatible; 9081 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9082 return Sema::IncompatibleObjCQualifiedId; 9083 return Sema::IncompatiblePointer; 9084 } 9085 9086 Sema::AssignConvertType 9087 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9088 QualType LHSType, QualType RHSType) { 9089 // Fake up an opaque expression. We don't actually care about what 9090 // cast operations are required, so if CheckAssignmentConstraints 9091 // adds casts to this they'll be wasted, but fortunately that doesn't 9092 // usually happen on valid code. 9093 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 9094 ExprResult RHSPtr = &RHSExpr; 9095 CastKind K; 9096 9097 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9098 } 9099 9100 /// This helper function returns true if QT is a vector type that has element 9101 /// type ElementType. 9102 static bool isVector(QualType QT, QualType ElementType) { 9103 if (const VectorType *VT = QT->getAs<VectorType>()) 9104 return VT->getElementType().getCanonicalType() == ElementType; 9105 return false; 9106 } 9107 9108 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9109 /// has code to accommodate several GCC extensions when type checking 9110 /// pointers. Here are some objectionable examples that GCC considers warnings: 9111 /// 9112 /// int a, *pint; 9113 /// short *pshort; 9114 /// struct foo *pfoo; 9115 /// 9116 /// pint = pshort; // warning: assignment from incompatible pointer type 9117 /// a = pint; // warning: assignment makes integer from pointer without a cast 9118 /// pint = a; // warning: assignment makes pointer from integer without a cast 9119 /// pint = pfoo; // warning: assignment from incompatible pointer type 9120 /// 9121 /// As a result, the code for dealing with pointers is more complex than the 9122 /// C99 spec dictates. 9123 /// 9124 /// Sets 'Kind' for any result kind except Incompatible. 9125 Sema::AssignConvertType 9126 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9127 CastKind &Kind, bool ConvertRHS) { 9128 QualType RHSType = RHS.get()->getType(); 9129 QualType OrigLHSType = LHSType; 9130 9131 // Get canonical types. We're not formatting these types, just comparing 9132 // them. 9133 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9134 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9135 9136 // Common case: no conversion required. 9137 if (LHSType == RHSType) { 9138 Kind = CK_NoOp; 9139 return Compatible; 9140 } 9141 9142 // If we have an atomic type, try a non-atomic assignment, then just add an 9143 // atomic qualification step. 9144 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9145 Sema::AssignConvertType result = 9146 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9147 if (result != Compatible) 9148 return result; 9149 if (Kind != CK_NoOp && ConvertRHS) 9150 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9151 Kind = CK_NonAtomicToAtomic; 9152 return Compatible; 9153 } 9154 9155 // If the left-hand side is a reference type, then we are in a 9156 // (rare!) case where we've allowed the use of references in C, 9157 // e.g., as a parameter type in a built-in function. In this case, 9158 // just make sure that the type referenced is compatible with the 9159 // right-hand side type. The caller is responsible for adjusting 9160 // LHSType so that the resulting expression does not have reference 9161 // type. 9162 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9163 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9164 Kind = CK_LValueBitCast; 9165 return Compatible; 9166 } 9167 return Incompatible; 9168 } 9169 9170 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9171 // to the same ExtVector type. 9172 if (LHSType->isExtVectorType()) { 9173 if (RHSType->isExtVectorType()) 9174 return Incompatible; 9175 if (RHSType->isArithmeticType()) { 9176 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9177 if (ConvertRHS) 9178 RHS = prepareVectorSplat(LHSType, RHS.get()); 9179 Kind = CK_VectorSplat; 9180 return Compatible; 9181 } 9182 } 9183 9184 // Conversions to or from vector type. 9185 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9186 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9187 // Allow assignments of an AltiVec vector type to an equivalent GCC 9188 // vector type and vice versa 9189 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9190 Kind = CK_BitCast; 9191 return Compatible; 9192 } 9193 9194 // If we are allowing lax vector conversions, and LHS and RHS are both 9195 // vectors, the total size only needs to be the same. This is a bitcast; 9196 // no bits are changed but the result type is different. 9197 if (isLaxVectorConversion(RHSType, LHSType)) { 9198 Kind = CK_BitCast; 9199 return IncompatibleVectors; 9200 } 9201 } 9202 9203 // When the RHS comes from another lax conversion (e.g. binops between 9204 // scalars and vectors) the result is canonicalized as a vector. When the 9205 // LHS is also a vector, the lax is allowed by the condition above. Handle 9206 // the case where LHS is a scalar. 9207 if (LHSType->isScalarType()) { 9208 const VectorType *VecType = RHSType->getAs<VectorType>(); 9209 if (VecType && VecType->getNumElements() == 1 && 9210 isLaxVectorConversion(RHSType, LHSType)) { 9211 ExprResult *VecExpr = &RHS; 9212 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9213 Kind = CK_BitCast; 9214 return Compatible; 9215 } 9216 } 9217 9218 // Allow assignments between fixed-length and sizeless SVE vectors. 9219 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9220 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9221 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9222 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9223 Kind = CK_BitCast; 9224 return Compatible; 9225 } 9226 9227 return Incompatible; 9228 } 9229 9230 // Diagnose attempts to convert between __float128 and long double where 9231 // such conversions currently can't be handled. 9232 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9233 return Incompatible; 9234 9235 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9236 // discards the imaginary part. 9237 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9238 !LHSType->getAs<ComplexType>()) 9239 return Incompatible; 9240 9241 // Arithmetic conversions. 9242 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9243 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9244 if (ConvertRHS) 9245 Kind = PrepareScalarCast(RHS, LHSType); 9246 return Compatible; 9247 } 9248 9249 // Conversions to normal pointers. 9250 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9251 // U* -> T* 9252 if (isa<PointerType>(RHSType)) { 9253 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9254 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9255 if (AddrSpaceL != AddrSpaceR) 9256 Kind = CK_AddressSpaceConversion; 9257 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9258 Kind = CK_NoOp; 9259 else 9260 Kind = CK_BitCast; 9261 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9262 } 9263 9264 // int -> T* 9265 if (RHSType->isIntegerType()) { 9266 Kind = CK_IntegralToPointer; // FIXME: null? 9267 return IntToPointer; 9268 } 9269 9270 // C pointers are not compatible with ObjC object pointers, 9271 // with two exceptions: 9272 if (isa<ObjCObjectPointerType>(RHSType)) { 9273 // - conversions to void* 9274 if (LHSPointer->getPointeeType()->isVoidType()) { 9275 Kind = CK_BitCast; 9276 return Compatible; 9277 } 9278 9279 // - conversions from 'Class' to the redefinition type 9280 if (RHSType->isObjCClassType() && 9281 Context.hasSameType(LHSType, 9282 Context.getObjCClassRedefinitionType())) { 9283 Kind = CK_BitCast; 9284 return Compatible; 9285 } 9286 9287 Kind = CK_BitCast; 9288 return IncompatiblePointer; 9289 } 9290 9291 // U^ -> void* 9292 if (RHSType->getAs<BlockPointerType>()) { 9293 if (LHSPointer->getPointeeType()->isVoidType()) { 9294 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9295 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9296 ->getPointeeType() 9297 .getAddressSpace(); 9298 Kind = 9299 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9300 return Compatible; 9301 } 9302 } 9303 9304 return Incompatible; 9305 } 9306 9307 // Conversions to block pointers. 9308 if (isa<BlockPointerType>(LHSType)) { 9309 // U^ -> T^ 9310 if (RHSType->isBlockPointerType()) { 9311 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9312 ->getPointeeType() 9313 .getAddressSpace(); 9314 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9315 ->getPointeeType() 9316 .getAddressSpace(); 9317 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9318 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9319 } 9320 9321 // int or null -> T^ 9322 if (RHSType->isIntegerType()) { 9323 Kind = CK_IntegralToPointer; // FIXME: null 9324 return IntToBlockPointer; 9325 } 9326 9327 // id -> T^ 9328 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9329 Kind = CK_AnyPointerToBlockPointerCast; 9330 return Compatible; 9331 } 9332 9333 // void* -> T^ 9334 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9335 if (RHSPT->getPointeeType()->isVoidType()) { 9336 Kind = CK_AnyPointerToBlockPointerCast; 9337 return Compatible; 9338 } 9339 9340 return Incompatible; 9341 } 9342 9343 // Conversions to Objective-C pointers. 9344 if (isa<ObjCObjectPointerType>(LHSType)) { 9345 // A* -> B* 9346 if (RHSType->isObjCObjectPointerType()) { 9347 Kind = CK_BitCast; 9348 Sema::AssignConvertType result = 9349 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9350 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9351 result == Compatible && 9352 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9353 result = IncompatibleObjCWeakRef; 9354 return result; 9355 } 9356 9357 // int or null -> A* 9358 if (RHSType->isIntegerType()) { 9359 Kind = CK_IntegralToPointer; // FIXME: null 9360 return IntToPointer; 9361 } 9362 9363 // In general, C pointers are not compatible with ObjC object pointers, 9364 // with two exceptions: 9365 if (isa<PointerType>(RHSType)) { 9366 Kind = CK_CPointerToObjCPointerCast; 9367 9368 // - conversions from 'void*' 9369 if (RHSType->isVoidPointerType()) { 9370 return Compatible; 9371 } 9372 9373 // - conversions to 'Class' from its redefinition type 9374 if (LHSType->isObjCClassType() && 9375 Context.hasSameType(RHSType, 9376 Context.getObjCClassRedefinitionType())) { 9377 return Compatible; 9378 } 9379 9380 return IncompatiblePointer; 9381 } 9382 9383 // Only under strict condition T^ is compatible with an Objective-C pointer. 9384 if (RHSType->isBlockPointerType() && 9385 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9386 if (ConvertRHS) 9387 maybeExtendBlockObject(RHS); 9388 Kind = CK_BlockPointerToObjCPointerCast; 9389 return Compatible; 9390 } 9391 9392 return Incompatible; 9393 } 9394 9395 // Conversions from pointers that are not covered by the above. 9396 if (isa<PointerType>(RHSType)) { 9397 // T* -> _Bool 9398 if (LHSType == Context.BoolTy) { 9399 Kind = CK_PointerToBoolean; 9400 return Compatible; 9401 } 9402 9403 // T* -> int 9404 if (LHSType->isIntegerType()) { 9405 Kind = CK_PointerToIntegral; 9406 return PointerToInt; 9407 } 9408 9409 return Incompatible; 9410 } 9411 9412 // Conversions from Objective-C pointers that are not covered by the above. 9413 if (isa<ObjCObjectPointerType>(RHSType)) { 9414 // T* -> _Bool 9415 if (LHSType == Context.BoolTy) { 9416 Kind = CK_PointerToBoolean; 9417 return Compatible; 9418 } 9419 9420 // T* -> int 9421 if (LHSType->isIntegerType()) { 9422 Kind = CK_PointerToIntegral; 9423 return PointerToInt; 9424 } 9425 9426 return Incompatible; 9427 } 9428 9429 // struct A -> struct B 9430 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9431 if (Context.typesAreCompatible(LHSType, RHSType)) { 9432 Kind = CK_NoOp; 9433 return Compatible; 9434 } 9435 } 9436 9437 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9438 Kind = CK_IntToOCLSampler; 9439 return Compatible; 9440 } 9441 9442 return Incompatible; 9443 } 9444 9445 /// Constructs a transparent union from an expression that is 9446 /// used to initialize the transparent union. 9447 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9448 ExprResult &EResult, QualType UnionType, 9449 FieldDecl *Field) { 9450 // Build an initializer list that designates the appropriate member 9451 // of the transparent union. 9452 Expr *E = EResult.get(); 9453 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9454 E, SourceLocation()); 9455 Initializer->setType(UnionType); 9456 Initializer->setInitializedFieldInUnion(Field); 9457 9458 // Build a compound literal constructing a value of the transparent 9459 // union type from this initializer list. 9460 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9461 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9462 VK_RValue, Initializer, false); 9463 } 9464 9465 Sema::AssignConvertType 9466 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9467 ExprResult &RHS) { 9468 QualType RHSType = RHS.get()->getType(); 9469 9470 // If the ArgType is a Union type, we want to handle a potential 9471 // transparent_union GCC extension. 9472 const RecordType *UT = ArgType->getAsUnionType(); 9473 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9474 return Incompatible; 9475 9476 // The field to initialize within the transparent union. 9477 RecordDecl *UD = UT->getDecl(); 9478 FieldDecl *InitField = nullptr; 9479 // It's compatible if the expression matches any of the fields. 9480 for (auto *it : UD->fields()) { 9481 if (it->getType()->isPointerType()) { 9482 // If the transparent union contains a pointer type, we allow: 9483 // 1) void pointer 9484 // 2) null pointer constant 9485 if (RHSType->isPointerType()) 9486 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9487 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9488 InitField = it; 9489 break; 9490 } 9491 9492 if (RHS.get()->isNullPointerConstant(Context, 9493 Expr::NPC_ValueDependentIsNull)) { 9494 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9495 CK_NullToPointer); 9496 InitField = it; 9497 break; 9498 } 9499 } 9500 9501 CastKind Kind; 9502 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9503 == Compatible) { 9504 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9505 InitField = it; 9506 break; 9507 } 9508 } 9509 9510 if (!InitField) 9511 return Incompatible; 9512 9513 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9514 return Compatible; 9515 } 9516 9517 Sema::AssignConvertType 9518 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9519 bool Diagnose, 9520 bool DiagnoseCFAudited, 9521 bool ConvertRHS) { 9522 // We need to be able to tell the caller whether we diagnosed a problem, if 9523 // they ask us to issue diagnostics. 9524 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9525 9526 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9527 // we can't avoid *all* modifications at the moment, so we need some somewhere 9528 // to put the updated value. 9529 ExprResult LocalRHS = CallerRHS; 9530 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9531 9532 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9533 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9534 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9535 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9536 Diag(RHS.get()->getExprLoc(), 9537 diag::warn_noderef_to_dereferenceable_pointer) 9538 << RHS.get()->getSourceRange(); 9539 } 9540 } 9541 } 9542 9543 if (getLangOpts().CPlusPlus) { 9544 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9545 // C++ 5.17p3: If the left operand is not of class type, the 9546 // expression is implicitly converted (C++ 4) to the 9547 // cv-unqualified type of the left operand. 9548 QualType RHSType = RHS.get()->getType(); 9549 if (Diagnose) { 9550 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9551 AA_Assigning); 9552 } else { 9553 ImplicitConversionSequence ICS = 9554 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9555 /*SuppressUserConversions=*/false, 9556 AllowedExplicit::None, 9557 /*InOverloadResolution=*/false, 9558 /*CStyle=*/false, 9559 /*AllowObjCWritebackConversion=*/false); 9560 if (ICS.isFailure()) 9561 return Incompatible; 9562 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9563 ICS, AA_Assigning); 9564 } 9565 if (RHS.isInvalid()) 9566 return Incompatible; 9567 Sema::AssignConvertType result = Compatible; 9568 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9569 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9570 result = IncompatibleObjCWeakRef; 9571 return result; 9572 } 9573 9574 // FIXME: Currently, we fall through and treat C++ classes like C 9575 // structures. 9576 // FIXME: We also fall through for atomics; not sure what should 9577 // happen there, though. 9578 } else if (RHS.get()->getType() == Context.OverloadTy) { 9579 // As a set of extensions to C, we support overloading on functions. These 9580 // functions need to be resolved here. 9581 DeclAccessPair DAP; 9582 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9583 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9584 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9585 else 9586 return Incompatible; 9587 } 9588 9589 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9590 // a null pointer constant. 9591 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9592 LHSType->isBlockPointerType()) && 9593 RHS.get()->isNullPointerConstant(Context, 9594 Expr::NPC_ValueDependentIsNull)) { 9595 if (Diagnose || ConvertRHS) { 9596 CastKind Kind; 9597 CXXCastPath Path; 9598 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9599 /*IgnoreBaseAccess=*/false, Diagnose); 9600 if (ConvertRHS) 9601 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9602 } 9603 return Compatible; 9604 } 9605 9606 // OpenCL queue_t type assignment. 9607 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9608 Context, Expr::NPC_ValueDependentIsNull)) { 9609 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9610 return Compatible; 9611 } 9612 9613 // This check seems unnatural, however it is necessary to ensure the proper 9614 // conversion of functions/arrays. If the conversion were done for all 9615 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9616 // expressions that suppress this implicit conversion (&, sizeof). 9617 // 9618 // Suppress this for references: C++ 8.5.3p5. 9619 if (!LHSType->isReferenceType()) { 9620 // FIXME: We potentially allocate here even if ConvertRHS is false. 9621 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9622 if (RHS.isInvalid()) 9623 return Incompatible; 9624 } 9625 CastKind Kind; 9626 Sema::AssignConvertType result = 9627 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9628 9629 // C99 6.5.16.1p2: The value of the right operand is converted to the 9630 // type of the assignment expression. 9631 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9632 // so that we can use references in built-in functions even in C. 9633 // The getNonReferenceType() call makes sure that the resulting expression 9634 // does not have reference type. 9635 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9636 QualType Ty = LHSType.getNonLValueExprType(Context); 9637 Expr *E = RHS.get(); 9638 9639 // Check for various Objective-C errors. If we are not reporting 9640 // diagnostics and just checking for errors, e.g., during overload 9641 // resolution, return Incompatible to indicate the failure. 9642 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9643 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9644 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9645 if (!Diagnose) 9646 return Incompatible; 9647 } 9648 if (getLangOpts().ObjC && 9649 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9650 E->getType(), E, Diagnose) || 9651 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9652 if (!Diagnose) 9653 return Incompatible; 9654 // Replace the expression with a corrected version and continue so we 9655 // can find further errors. 9656 RHS = E; 9657 return Compatible; 9658 } 9659 9660 if (ConvertRHS) 9661 RHS = ImpCastExprToType(E, Ty, Kind); 9662 } 9663 9664 return result; 9665 } 9666 9667 namespace { 9668 /// The original operand to an operator, prior to the application of the usual 9669 /// arithmetic conversions and converting the arguments of a builtin operator 9670 /// candidate. 9671 struct OriginalOperand { 9672 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9673 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9674 Op = MTE->getSubExpr(); 9675 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9676 Op = BTE->getSubExpr(); 9677 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9678 Orig = ICE->getSubExprAsWritten(); 9679 Conversion = ICE->getConversionFunction(); 9680 } 9681 } 9682 9683 QualType getType() const { return Orig->getType(); } 9684 9685 Expr *Orig; 9686 NamedDecl *Conversion; 9687 }; 9688 } 9689 9690 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9691 ExprResult &RHS) { 9692 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9693 9694 Diag(Loc, diag::err_typecheck_invalid_operands) 9695 << OrigLHS.getType() << OrigRHS.getType() 9696 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9697 9698 // If a user-defined conversion was applied to either of the operands prior 9699 // to applying the built-in operator rules, tell the user about it. 9700 if (OrigLHS.Conversion) { 9701 Diag(OrigLHS.Conversion->getLocation(), 9702 diag::note_typecheck_invalid_operands_converted) 9703 << 0 << LHS.get()->getType(); 9704 } 9705 if (OrigRHS.Conversion) { 9706 Diag(OrigRHS.Conversion->getLocation(), 9707 diag::note_typecheck_invalid_operands_converted) 9708 << 1 << RHS.get()->getType(); 9709 } 9710 9711 return QualType(); 9712 } 9713 9714 // Diagnose cases where a scalar was implicitly converted to a vector and 9715 // diagnose the underlying types. Otherwise, diagnose the error 9716 // as invalid vector logical operands for non-C++ cases. 9717 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9718 ExprResult &RHS) { 9719 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9720 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9721 9722 bool LHSNatVec = LHSType->isVectorType(); 9723 bool RHSNatVec = RHSType->isVectorType(); 9724 9725 if (!(LHSNatVec && RHSNatVec)) { 9726 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9727 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9728 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9729 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9730 << Vector->getSourceRange(); 9731 return QualType(); 9732 } 9733 9734 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9735 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9736 << RHS.get()->getSourceRange(); 9737 9738 return QualType(); 9739 } 9740 9741 /// Try to convert a value of non-vector type to a vector type by converting 9742 /// the type to the element type of the vector and then performing a splat. 9743 /// If the language is OpenCL, we only use conversions that promote scalar 9744 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9745 /// for float->int. 9746 /// 9747 /// OpenCL V2.0 6.2.6.p2: 9748 /// An error shall occur if any scalar operand type has greater rank 9749 /// than the type of the vector element. 9750 /// 9751 /// \param scalar - if non-null, actually perform the conversions 9752 /// \return true if the operation fails (but without diagnosing the failure) 9753 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9754 QualType scalarTy, 9755 QualType vectorEltTy, 9756 QualType vectorTy, 9757 unsigned &DiagID) { 9758 // The conversion to apply to the scalar before splatting it, 9759 // if necessary. 9760 CastKind scalarCast = CK_NoOp; 9761 9762 if (vectorEltTy->isIntegralType(S.Context)) { 9763 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9764 (scalarTy->isIntegerType() && 9765 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9766 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9767 return true; 9768 } 9769 if (!scalarTy->isIntegralType(S.Context)) 9770 return true; 9771 scalarCast = CK_IntegralCast; 9772 } else if (vectorEltTy->isRealFloatingType()) { 9773 if (scalarTy->isRealFloatingType()) { 9774 if (S.getLangOpts().OpenCL && 9775 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9776 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9777 return true; 9778 } 9779 scalarCast = CK_FloatingCast; 9780 } 9781 else if (scalarTy->isIntegralType(S.Context)) 9782 scalarCast = CK_IntegralToFloating; 9783 else 9784 return true; 9785 } else { 9786 return true; 9787 } 9788 9789 // Adjust scalar if desired. 9790 if (scalar) { 9791 if (scalarCast != CK_NoOp) 9792 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9793 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9794 } 9795 return false; 9796 } 9797 9798 /// Convert vector E to a vector with the same number of elements but different 9799 /// element type. 9800 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9801 const auto *VecTy = E->getType()->getAs<VectorType>(); 9802 assert(VecTy && "Expression E must be a vector"); 9803 QualType NewVecTy = S.Context.getVectorType(ElementType, 9804 VecTy->getNumElements(), 9805 VecTy->getVectorKind()); 9806 9807 // Look through the implicit cast. Return the subexpression if its type is 9808 // NewVecTy. 9809 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9810 if (ICE->getSubExpr()->getType() == NewVecTy) 9811 return ICE->getSubExpr(); 9812 9813 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9814 return S.ImpCastExprToType(E, NewVecTy, Cast); 9815 } 9816 9817 /// Test if a (constant) integer Int can be casted to another integer type 9818 /// IntTy without losing precision. 9819 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9820 QualType OtherIntTy) { 9821 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9822 9823 // Reject cases where the value of the Int is unknown as that would 9824 // possibly cause truncation, but accept cases where the scalar can be 9825 // demoted without loss of precision. 9826 Expr::EvalResult EVResult; 9827 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9828 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9829 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9830 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9831 9832 if (CstInt) { 9833 // If the scalar is constant and is of a higher order and has more active 9834 // bits that the vector element type, reject it. 9835 llvm::APSInt Result = EVResult.Val.getInt(); 9836 unsigned NumBits = IntSigned 9837 ? (Result.isNegative() ? Result.getMinSignedBits() 9838 : Result.getActiveBits()) 9839 : Result.getActiveBits(); 9840 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9841 return true; 9842 9843 // If the signedness of the scalar type and the vector element type 9844 // differs and the number of bits is greater than that of the vector 9845 // element reject it. 9846 return (IntSigned != OtherIntSigned && 9847 NumBits > S.Context.getIntWidth(OtherIntTy)); 9848 } 9849 9850 // Reject cases where the value of the scalar is not constant and it's 9851 // order is greater than that of the vector element type. 9852 return (Order < 0); 9853 } 9854 9855 /// Test if a (constant) integer Int can be casted to floating point type 9856 /// FloatTy without losing precision. 9857 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9858 QualType FloatTy) { 9859 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9860 9861 // Determine if the integer constant can be expressed as a floating point 9862 // number of the appropriate type. 9863 Expr::EvalResult EVResult; 9864 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9865 9866 uint64_t Bits = 0; 9867 if (CstInt) { 9868 // Reject constants that would be truncated if they were converted to 9869 // the floating point type. Test by simple to/from conversion. 9870 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9871 // could be avoided if there was a convertFromAPInt method 9872 // which could signal back if implicit truncation occurred. 9873 llvm::APSInt Result = EVResult.Val.getInt(); 9874 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9875 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9876 llvm::APFloat::rmTowardZero); 9877 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9878 !IntTy->hasSignedIntegerRepresentation()); 9879 bool Ignored = false; 9880 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9881 &Ignored); 9882 if (Result != ConvertBack) 9883 return true; 9884 } else { 9885 // Reject types that cannot be fully encoded into the mantissa of 9886 // the float. 9887 Bits = S.Context.getTypeSize(IntTy); 9888 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9889 S.Context.getFloatTypeSemantics(FloatTy)); 9890 if (Bits > FloatPrec) 9891 return true; 9892 } 9893 9894 return false; 9895 } 9896 9897 /// Attempt to convert and splat Scalar into a vector whose types matches 9898 /// Vector following GCC conversion rules. The rule is that implicit 9899 /// conversion can occur when Scalar can be casted to match Vector's element 9900 /// type without causing truncation of Scalar. 9901 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9902 ExprResult *Vector) { 9903 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9904 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9905 const VectorType *VT = VectorTy->getAs<VectorType>(); 9906 9907 assert(!isa<ExtVectorType>(VT) && 9908 "ExtVectorTypes should not be handled here!"); 9909 9910 QualType VectorEltTy = VT->getElementType(); 9911 9912 // Reject cases where the vector element type or the scalar element type are 9913 // not integral or floating point types. 9914 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9915 return true; 9916 9917 // The conversion to apply to the scalar before splatting it, 9918 // if necessary. 9919 CastKind ScalarCast = CK_NoOp; 9920 9921 // Accept cases where the vector elements are integers and the scalar is 9922 // an integer. 9923 // FIXME: Notionally if the scalar was a floating point value with a precise 9924 // integral representation, we could cast it to an appropriate integer 9925 // type and then perform the rest of the checks here. GCC will perform 9926 // this conversion in some cases as determined by the input language. 9927 // We should accept it on a language independent basis. 9928 if (VectorEltTy->isIntegralType(S.Context) && 9929 ScalarTy->isIntegralType(S.Context) && 9930 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9931 9932 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9933 return true; 9934 9935 ScalarCast = CK_IntegralCast; 9936 } else if (VectorEltTy->isIntegralType(S.Context) && 9937 ScalarTy->isRealFloatingType()) { 9938 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9939 ScalarCast = CK_FloatingToIntegral; 9940 else 9941 return true; 9942 } else if (VectorEltTy->isRealFloatingType()) { 9943 if (ScalarTy->isRealFloatingType()) { 9944 9945 // Reject cases where the scalar type is not a constant and has a higher 9946 // Order than the vector element type. 9947 llvm::APFloat Result(0.0); 9948 9949 // Determine whether this is a constant scalar. In the event that the 9950 // value is dependent (and thus cannot be evaluated by the constant 9951 // evaluator), skip the evaluation. This will then diagnose once the 9952 // expression is instantiated. 9953 bool CstScalar = Scalar->get()->isValueDependent() || 9954 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9955 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9956 if (!CstScalar && Order < 0) 9957 return true; 9958 9959 // If the scalar cannot be safely casted to the vector element type, 9960 // reject it. 9961 if (CstScalar) { 9962 bool Truncated = false; 9963 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9964 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9965 if (Truncated) 9966 return true; 9967 } 9968 9969 ScalarCast = CK_FloatingCast; 9970 } else if (ScalarTy->isIntegralType(S.Context)) { 9971 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9972 return true; 9973 9974 ScalarCast = CK_IntegralToFloating; 9975 } else 9976 return true; 9977 } else if (ScalarTy->isEnumeralType()) 9978 return true; 9979 9980 // Adjust scalar if desired. 9981 if (Scalar) { 9982 if (ScalarCast != CK_NoOp) 9983 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9984 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9985 } 9986 return false; 9987 } 9988 9989 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9990 SourceLocation Loc, bool IsCompAssign, 9991 bool AllowBothBool, 9992 bool AllowBoolConversions) { 9993 if (!IsCompAssign) { 9994 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9995 if (LHS.isInvalid()) 9996 return QualType(); 9997 } 9998 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9999 if (RHS.isInvalid()) 10000 return QualType(); 10001 10002 // For conversion purposes, we ignore any qualifiers. 10003 // For example, "const float" and "float" are equivalent. 10004 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10005 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10006 10007 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10008 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10009 assert(LHSVecType || RHSVecType); 10010 10011 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10012 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10013 return InvalidOperands(Loc, LHS, RHS); 10014 10015 // AltiVec-style "vector bool op vector bool" combinations are allowed 10016 // for some operators but not others. 10017 if (!AllowBothBool && 10018 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10019 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10020 return InvalidOperands(Loc, LHS, RHS); 10021 10022 // If the vector types are identical, return. 10023 if (Context.hasSameType(LHSType, RHSType)) 10024 return LHSType; 10025 10026 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10027 if (LHSVecType && RHSVecType && 10028 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10029 if (isa<ExtVectorType>(LHSVecType)) { 10030 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10031 return LHSType; 10032 } 10033 10034 if (!IsCompAssign) 10035 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10036 return RHSType; 10037 } 10038 10039 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10040 // can be mixed, with the result being the non-bool type. The non-bool 10041 // operand must have integer element type. 10042 if (AllowBoolConversions && LHSVecType && RHSVecType && 10043 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10044 (Context.getTypeSize(LHSVecType->getElementType()) == 10045 Context.getTypeSize(RHSVecType->getElementType()))) { 10046 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10047 LHSVecType->getElementType()->isIntegerType() && 10048 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10049 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10050 return LHSType; 10051 } 10052 if (!IsCompAssign && 10053 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10054 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10055 RHSVecType->getElementType()->isIntegerType()) { 10056 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10057 return RHSType; 10058 } 10059 } 10060 10061 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10062 // since the ambiguity can affect the ABI. 10063 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10064 const VectorType *VecType = SecondType->getAs<VectorType>(); 10065 return FirstType->isSizelessBuiltinType() && VecType && 10066 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10067 VecType->getVectorKind() == 10068 VectorType::SveFixedLengthPredicateVector); 10069 }; 10070 10071 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10072 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10073 return QualType(); 10074 } 10075 10076 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10077 // since the ambiguity can affect the ABI. 10078 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10079 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10080 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10081 10082 if (FirstVecType && SecondVecType) 10083 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10084 (SecondVecType->getVectorKind() == 10085 VectorType::SveFixedLengthDataVector || 10086 SecondVecType->getVectorKind() == 10087 VectorType::SveFixedLengthPredicateVector); 10088 10089 return FirstType->isSizelessBuiltinType() && SecondVecType && 10090 SecondVecType->getVectorKind() == VectorType::GenericVector; 10091 }; 10092 10093 if (IsSveGnuConversion(LHSType, RHSType) || 10094 IsSveGnuConversion(RHSType, LHSType)) { 10095 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10096 return QualType(); 10097 } 10098 10099 // If there's a vector type and a scalar, try to convert the scalar to 10100 // the vector element type and splat. 10101 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10102 if (!RHSVecType) { 10103 if (isa<ExtVectorType>(LHSVecType)) { 10104 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10105 LHSVecType->getElementType(), LHSType, 10106 DiagID)) 10107 return LHSType; 10108 } else { 10109 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10110 return LHSType; 10111 } 10112 } 10113 if (!LHSVecType) { 10114 if (isa<ExtVectorType>(RHSVecType)) { 10115 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10116 LHSType, RHSVecType->getElementType(), 10117 RHSType, DiagID)) 10118 return RHSType; 10119 } else { 10120 if (LHS.get()->getValueKind() == VK_LValue || 10121 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10122 return RHSType; 10123 } 10124 } 10125 10126 // FIXME: The code below also handles conversion between vectors and 10127 // non-scalars, we should break this down into fine grained specific checks 10128 // and emit proper diagnostics. 10129 QualType VecType = LHSVecType ? LHSType : RHSType; 10130 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10131 QualType OtherType = LHSVecType ? RHSType : LHSType; 10132 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10133 if (isLaxVectorConversion(OtherType, VecType)) { 10134 // If we're allowing lax vector conversions, only the total (data) size 10135 // needs to be the same. For non compound assignment, if one of the types is 10136 // scalar, the result is always the vector type. 10137 if (!IsCompAssign) { 10138 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10139 return VecType; 10140 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10141 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10142 // type. Note that this is already done by non-compound assignments in 10143 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10144 // <1 x T> -> T. The result is also a vector type. 10145 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10146 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10147 ExprResult *RHSExpr = &RHS; 10148 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10149 return VecType; 10150 } 10151 } 10152 10153 // Okay, the expression is invalid. 10154 10155 // If there's a non-vector, non-real operand, diagnose that. 10156 if ((!RHSVecType && !RHSType->isRealType()) || 10157 (!LHSVecType && !LHSType->isRealType())) { 10158 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10159 << LHSType << RHSType 10160 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10161 return QualType(); 10162 } 10163 10164 // OpenCL V1.1 6.2.6.p1: 10165 // If the operands are of more than one vector type, then an error shall 10166 // occur. Implicit conversions between vector types are not permitted, per 10167 // section 6.2.1. 10168 if (getLangOpts().OpenCL && 10169 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10170 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10171 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10172 << RHSType; 10173 return QualType(); 10174 } 10175 10176 10177 // If there is a vector type that is not a ExtVector and a scalar, we reach 10178 // this point if scalar could not be converted to the vector's element type 10179 // without truncation. 10180 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10181 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10182 QualType Scalar = LHSVecType ? RHSType : LHSType; 10183 QualType Vector = LHSVecType ? LHSType : RHSType; 10184 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10185 Diag(Loc, 10186 diag::err_typecheck_vector_not_convertable_implict_truncation) 10187 << ScalarOrVector << Scalar << Vector; 10188 10189 return QualType(); 10190 } 10191 10192 // Otherwise, use the generic diagnostic. 10193 Diag(Loc, DiagID) 10194 << LHSType << RHSType 10195 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10196 return QualType(); 10197 } 10198 10199 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10200 // expression. These are mainly cases where the null pointer is used as an 10201 // integer instead of a pointer. 10202 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10203 SourceLocation Loc, bool IsCompare) { 10204 // The canonical way to check for a GNU null is with isNullPointerConstant, 10205 // but we use a bit of a hack here for speed; this is a relatively 10206 // hot path, and isNullPointerConstant is slow. 10207 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10208 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10209 10210 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10211 10212 // Avoid analyzing cases where the result will either be invalid (and 10213 // diagnosed as such) or entirely valid and not something to warn about. 10214 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10215 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10216 return; 10217 10218 // Comparison operations would not make sense with a null pointer no matter 10219 // what the other expression is. 10220 if (!IsCompare) { 10221 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10222 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10223 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10224 return; 10225 } 10226 10227 // The rest of the operations only make sense with a null pointer 10228 // if the other expression is a pointer. 10229 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10230 NonNullType->canDecayToPointerType()) 10231 return; 10232 10233 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10234 << LHSNull /* LHS is NULL */ << NonNullType 10235 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10236 } 10237 10238 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10239 SourceLocation Loc) { 10240 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10241 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10242 if (!LUE || !RUE) 10243 return; 10244 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10245 RUE->getKind() != UETT_SizeOf) 10246 return; 10247 10248 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10249 QualType LHSTy = LHSArg->getType(); 10250 QualType RHSTy; 10251 10252 if (RUE->isArgumentType()) 10253 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10254 else 10255 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10256 10257 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10258 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10259 return; 10260 10261 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10262 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10263 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10264 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10265 << LHSArgDecl; 10266 } 10267 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10268 QualType ArrayElemTy = ArrayTy->getElementType(); 10269 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10270 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10271 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10272 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10273 return; 10274 S.Diag(Loc, diag::warn_division_sizeof_array) 10275 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10276 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10277 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10278 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10279 << LHSArgDecl; 10280 } 10281 10282 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10283 } 10284 } 10285 10286 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10287 ExprResult &RHS, 10288 SourceLocation Loc, bool IsDiv) { 10289 // Check for division/remainder by zero. 10290 Expr::EvalResult RHSValue; 10291 if (!RHS.get()->isValueDependent() && 10292 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10293 RHSValue.Val.getInt() == 0) 10294 S.DiagRuntimeBehavior(Loc, RHS.get(), 10295 S.PDiag(diag::warn_remainder_division_by_zero) 10296 << IsDiv << RHS.get()->getSourceRange()); 10297 } 10298 10299 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10300 SourceLocation Loc, 10301 bool IsCompAssign, bool IsDiv) { 10302 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10303 10304 QualType LHSTy = LHS.get()->getType(); 10305 QualType RHSTy = RHS.get()->getType(); 10306 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10307 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10308 /*AllowBothBool*/getLangOpts().AltiVec, 10309 /*AllowBoolConversions*/false); 10310 if (!IsDiv && 10311 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10312 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10313 // For division, only matrix-by-scalar is supported. Other combinations with 10314 // matrix types are invalid. 10315 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10316 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10317 10318 QualType compType = UsualArithmeticConversions( 10319 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10320 if (LHS.isInvalid() || RHS.isInvalid()) 10321 return QualType(); 10322 10323 10324 if (compType.isNull() || !compType->isArithmeticType()) 10325 return InvalidOperands(Loc, LHS, RHS); 10326 if (IsDiv) { 10327 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10328 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10329 } 10330 return compType; 10331 } 10332 10333 QualType Sema::CheckRemainderOperands( 10334 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10335 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10336 10337 if (LHS.get()->getType()->isVectorType() || 10338 RHS.get()->getType()->isVectorType()) { 10339 if (LHS.get()->getType()->hasIntegerRepresentation() && 10340 RHS.get()->getType()->hasIntegerRepresentation()) 10341 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10342 /*AllowBothBool*/getLangOpts().AltiVec, 10343 /*AllowBoolConversions*/false); 10344 return InvalidOperands(Loc, LHS, RHS); 10345 } 10346 10347 QualType compType = UsualArithmeticConversions( 10348 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10349 if (LHS.isInvalid() || RHS.isInvalid()) 10350 return QualType(); 10351 10352 if (compType.isNull() || !compType->isIntegerType()) 10353 return InvalidOperands(Loc, LHS, RHS); 10354 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10355 return compType; 10356 } 10357 10358 /// Diagnose invalid arithmetic on two void pointers. 10359 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10360 Expr *LHSExpr, Expr *RHSExpr) { 10361 S.Diag(Loc, S.getLangOpts().CPlusPlus 10362 ? diag::err_typecheck_pointer_arith_void_type 10363 : diag::ext_gnu_void_ptr) 10364 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10365 << RHSExpr->getSourceRange(); 10366 } 10367 10368 /// Diagnose invalid arithmetic on a void pointer. 10369 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10370 Expr *Pointer) { 10371 S.Diag(Loc, S.getLangOpts().CPlusPlus 10372 ? diag::err_typecheck_pointer_arith_void_type 10373 : diag::ext_gnu_void_ptr) 10374 << 0 /* one pointer */ << Pointer->getSourceRange(); 10375 } 10376 10377 /// Diagnose invalid arithmetic on a null pointer. 10378 /// 10379 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10380 /// idiom, which we recognize as a GNU extension. 10381 /// 10382 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10383 Expr *Pointer, bool IsGNUIdiom) { 10384 if (IsGNUIdiom) 10385 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10386 << Pointer->getSourceRange(); 10387 else 10388 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10389 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10390 } 10391 10392 /// Diagnose invalid arithmetic on two function pointers. 10393 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10394 Expr *LHS, Expr *RHS) { 10395 assert(LHS->getType()->isAnyPointerType()); 10396 assert(RHS->getType()->isAnyPointerType()); 10397 S.Diag(Loc, S.getLangOpts().CPlusPlus 10398 ? diag::err_typecheck_pointer_arith_function_type 10399 : diag::ext_gnu_ptr_func_arith) 10400 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10401 // We only show the second type if it differs from the first. 10402 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10403 RHS->getType()) 10404 << RHS->getType()->getPointeeType() 10405 << LHS->getSourceRange() << RHS->getSourceRange(); 10406 } 10407 10408 /// Diagnose invalid arithmetic on a function pointer. 10409 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10410 Expr *Pointer) { 10411 assert(Pointer->getType()->isAnyPointerType()); 10412 S.Diag(Loc, S.getLangOpts().CPlusPlus 10413 ? diag::err_typecheck_pointer_arith_function_type 10414 : diag::ext_gnu_ptr_func_arith) 10415 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10416 << 0 /* one pointer, so only one type */ 10417 << Pointer->getSourceRange(); 10418 } 10419 10420 /// Emit error if Operand is incomplete pointer type 10421 /// 10422 /// \returns True if pointer has incomplete type 10423 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10424 Expr *Operand) { 10425 QualType ResType = Operand->getType(); 10426 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10427 ResType = ResAtomicType->getValueType(); 10428 10429 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10430 QualType PointeeTy = ResType->getPointeeType(); 10431 return S.RequireCompleteSizedType( 10432 Loc, PointeeTy, 10433 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10434 Operand->getSourceRange()); 10435 } 10436 10437 /// Check the validity of an arithmetic pointer operand. 10438 /// 10439 /// If the operand has pointer type, this code will check for pointer types 10440 /// which are invalid in arithmetic operations. These will be diagnosed 10441 /// appropriately, including whether or not the use is supported as an 10442 /// extension. 10443 /// 10444 /// \returns True when the operand is valid to use (even if as an extension). 10445 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10446 Expr *Operand) { 10447 QualType ResType = Operand->getType(); 10448 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10449 ResType = ResAtomicType->getValueType(); 10450 10451 if (!ResType->isAnyPointerType()) return true; 10452 10453 QualType PointeeTy = ResType->getPointeeType(); 10454 if (PointeeTy->isVoidType()) { 10455 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10456 return !S.getLangOpts().CPlusPlus; 10457 } 10458 if (PointeeTy->isFunctionType()) { 10459 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10460 return !S.getLangOpts().CPlusPlus; 10461 } 10462 10463 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10464 10465 return true; 10466 } 10467 10468 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10469 /// operands. 10470 /// 10471 /// This routine will diagnose any invalid arithmetic on pointer operands much 10472 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10473 /// for emitting a single diagnostic even for operations where both LHS and RHS 10474 /// are (potentially problematic) pointers. 10475 /// 10476 /// \returns True when the operand is valid to use (even if as an extension). 10477 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10478 Expr *LHSExpr, Expr *RHSExpr) { 10479 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10480 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10481 if (!isLHSPointer && !isRHSPointer) return true; 10482 10483 QualType LHSPointeeTy, RHSPointeeTy; 10484 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10485 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10486 10487 // if both are pointers check if operation is valid wrt address spaces 10488 if (isLHSPointer && isRHSPointer) { 10489 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10490 S.Diag(Loc, 10491 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10492 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10493 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10494 return false; 10495 } 10496 } 10497 10498 // Check for arithmetic on pointers to incomplete types. 10499 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10500 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10501 if (isLHSVoidPtr || isRHSVoidPtr) { 10502 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10503 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10504 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10505 10506 return !S.getLangOpts().CPlusPlus; 10507 } 10508 10509 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10510 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10511 if (isLHSFuncPtr || isRHSFuncPtr) { 10512 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10513 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10514 RHSExpr); 10515 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10516 10517 return !S.getLangOpts().CPlusPlus; 10518 } 10519 10520 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10521 return false; 10522 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10523 return false; 10524 10525 return true; 10526 } 10527 10528 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10529 /// literal. 10530 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10531 Expr *LHSExpr, Expr *RHSExpr) { 10532 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10533 Expr* IndexExpr = RHSExpr; 10534 if (!StrExpr) { 10535 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10536 IndexExpr = LHSExpr; 10537 } 10538 10539 bool IsStringPlusInt = StrExpr && 10540 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10541 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10542 return; 10543 10544 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10545 Self.Diag(OpLoc, diag::warn_string_plus_int) 10546 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10547 10548 // Only print a fixit for "str" + int, not for int + "str". 10549 if (IndexExpr == RHSExpr) { 10550 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10551 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10552 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10553 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10554 << FixItHint::CreateInsertion(EndLoc, "]"); 10555 } else 10556 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10557 } 10558 10559 /// Emit a warning when adding a char literal to a string. 10560 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10561 Expr *LHSExpr, Expr *RHSExpr) { 10562 const Expr *StringRefExpr = LHSExpr; 10563 const CharacterLiteral *CharExpr = 10564 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10565 10566 if (!CharExpr) { 10567 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10568 StringRefExpr = RHSExpr; 10569 } 10570 10571 if (!CharExpr || !StringRefExpr) 10572 return; 10573 10574 const QualType StringType = StringRefExpr->getType(); 10575 10576 // Return if not a PointerType. 10577 if (!StringType->isAnyPointerType()) 10578 return; 10579 10580 // Return if not a CharacterType. 10581 if (!StringType->getPointeeType()->isAnyCharacterType()) 10582 return; 10583 10584 ASTContext &Ctx = Self.getASTContext(); 10585 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10586 10587 const QualType CharType = CharExpr->getType(); 10588 if (!CharType->isAnyCharacterType() && 10589 CharType->isIntegerType() && 10590 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10591 Self.Diag(OpLoc, diag::warn_string_plus_char) 10592 << DiagRange << Ctx.CharTy; 10593 } else { 10594 Self.Diag(OpLoc, diag::warn_string_plus_char) 10595 << DiagRange << CharExpr->getType(); 10596 } 10597 10598 // Only print a fixit for str + char, not for char + str. 10599 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10600 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10601 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10602 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10603 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10604 << FixItHint::CreateInsertion(EndLoc, "]"); 10605 } else { 10606 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10607 } 10608 } 10609 10610 /// Emit error when two pointers are incompatible. 10611 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10612 Expr *LHSExpr, Expr *RHSExpr) { 10613 assert(LHSExpr->getType()->isAnyPointerType()); 10614 assert(RHSExpr->getType()->isAnyPointerType()); 10615 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10616 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10617 << RHSExpr->getSourceRange(); 10618 } 10619 10620 // C99 6.5.6 10621 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10622 SourceLocation Loc, BinaryOperatorKind Opc, 10623 QualType* CompLHSTy) { 10624 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10625 10626 if (LHS.get()->getType()->isVectorType() || 10627 RHS.get()->getType()->isVectorType()) { 10628 QualType compType = CheckVectorOperands( 10629 LHS, RHS, Loc, CompLHSTy, 10630 /*AllowBothBool*/getLangOpts().AltiVec, 10631 /*AllowBoolConversions*/getLangOpts().ZVector); 10632 if (CompLHSTy) *CompLHSTy = compType; 10633 return compType; 10634 } 10635 10636 if (LHS.get()->getType()->isConstantMatrixType() || 10637 RHS.get()->getType()->isConstantMatrixType()) { 10638 QualType compType = 10639 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10640 if (CompLHSTy) 10641 *CompLHSTy = compType; 10642 return compType; 10643 } 10644 10645 QualType compType = UsualArithmeticConversions( 10646 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10647 if (LHS.isInvalid() || RHS.isInvalid()) 10648 return QualType(); 10649 10650 // Diagnose "string literal" '+' int and string '+' "char literal". 10651 if (Opc == BO_Add) { 10652 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10653 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10654 } 10655 10656 // handle the common case first (both operands are arithmetic). 10657 if (!compType.isNull() && compType->isArithmeticType()) { 10658 if (CompLHSTy) *CompLHSTy = compType; 10659 return compType; 10660 } 10661 10662 // Type-checking. Ultimately the pointer's going to be in PExp; 10663 // note that we bias towards the LHS being the pointer. 10664 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10665 10666 bool isObjCPointer; 10667 if (PExp->getType()->isPointerType()) { 10668 isObjCPointer = false; 10669 } else if (PExp->getType()->isObjCObjectPointerType()) { 10670 isObjCPointer = true; 10671 } else { 10672 std::swap(PExp, IExp); 10673 if (PExp->getType()->isPointerType()) { 10674 isObjCPointer = false; 10675 } else if (PExp->getType()->isObjCObjectPointerType()) { 10676 isObjCPointer = true; 10677 } else { 10678 return InvalidOperands(Loc, LHS, RHS); 10679 } 10680 } 10681 assert(PExp->getType()->isAnyPointerType()); 10682 10683 if (!IExp->getType()->isIntegerType()) 10684 return InvalidOperands(Loc, LHS, RHS); 10685 10686 // Adding to a null pointer results in undefined behavior. 10687 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10688 Context, Expr::NPC_ValueDependentIsNotNull)) { 10689 // In C++ adding zero to a null pointer is defined. 10690 Expr::EvalResult KnownVal; 10691 if (!getLangOpts().CPlusPlus || 10692 (!IExp->isValueDependent() && 10693 (!IExp->EvaluateAsInt(KnownVal, Context) || 10694 KnownVal.Val.getInt() != 0))) { 10695 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10696 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10697 Context, BO_Add, PExp, IExp); 10698 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10699 } 10700 } 10701 10702 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10703 return QualType(); 10704 10705 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10706 return QualType(); 10707 10708 // Check array bounds for pointer arithemtic 10709 CheckArrayAccess(PExp, IExp); 10710 10711 if (CompLHSTy) { 10712 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10713 if (LHSTy.isNull()) { 10714 LHSTy = LHS.get()->getType(); 10715 if (LHSTy->isPromotableIntegerType()) 10716 LHSTy = Context.getPromotedIntegerType(LHSTy); 10717 } 10718 *CompLHSTy = LHSTy; 10719 } 10720 10721 return PExp->getType(); 10722 } 10723 10724 // C99 6.5.6 10725 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10726 SourceLocation Loc, 10727 QualType* CompLHSTy) { 10728 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10729 10730 if (LHS.get()->getType()->isVectorType() || 10731 RHS.get()->getType()->isVectorType()) { 10732 QualType compType = CheckVectorOperands( 10733 LHS, RHS, Loc, CompLHSTy, 10734 /*AllowBothBool*/getLangOpts().AltiVec, 10735 /*AllowBoolConversions*/getLangOpts().ZVector); 10736 if (CompLHSTy) *CompLHSTy = compType; 10737 return compType; 10738 } 10739 10740 if (LHS.get()->getType()->isConstantMatrixType() || 10741 RHS.get()->getType()->isConstantMatrixType()) { 10742 QualType compType = 10743 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10744 if (CompLHSTy) 10745 *CompLHSTy = compType; 10746 return compType; 10747 } 10748 10749 QualType compType = UsualArithmeticConversions( 10750 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10751 if (LHS.isInvalid() || RHS.isInvalid()) 10752 return QualType(); 10753 10754 // Enforce type constraints: C99 6.5.6p3. 10755 10756 // Handle the common case first (both operands are arithmetic). 10757 if (!compType.isNull() && compType->isArithmeticType()) { 10758 if (CompLHSTy) *CompLHSTy = compType; 10759 return compType; 10760 } 10761 10762 // Either ptr - int or ptr - ptr. 10763 if (LHS.get()->getType()->isAnyPointerType()) { 10764 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10765 10766 // Diagnose bad cases where we step over interface counts. 10767 if (LHS.get()->getType()->isObjCObjectPointerType() && 10768 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10769 return QualType(); 10770 10771 // The result type of a pointer-int computation is the pointer type. 10772 if (RHS.get()->getType()->isIntegerType()) { 10773 // Subtracting from a null pointer should produce a warning. 10774 // The last argument to the diagnose call says this doesn't match the 10775 // GNU int-to-pointer idiom. 10776 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10777 Expr::NPC_ValueDependentIsNotNull)) { 10778 // In C++ adding zero to a null pointer is defined. 10779 Expr::EvalResult KnownVal; 10780 if (!getLangOpts().CPlusPlus || 10781 (!RHS.get()->isValueDependent() && 10782 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10783 KnownVal.Val.getInt() != 0))) { 10784 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10785 } 10786 } 10787 10788 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10789 return QualType(); 10790 10791 // Check array bounds for pointer arithemtic 10792 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10793 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10794 10795 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10796 return LHS.get()->getType(); 10797 } 10798 10799 // Handle pointer-pointer subtractions. 10800 if (const PointerType *RHSPTy 10801 = RHS.get()->getType()->getAs<PointerType>()) { 10802 QualType rpointee = RHSPTy->getPointeeType(); 10803 10804 if (getLangOpts().CPlusPlus) { 10805 // Pointee types must be the same: C++ [expr.add] 10806 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10807 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10808 } 10809 } else { 10810 // Pointee types must be compatible C99 6.5.6p3 10811 if (!Context.typesAreCompatible( 10812 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10813 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10814 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10815 return QualType(); 10816 } 10817 } 10818 10819 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10820 LHS.get(), RHS.get())) 10821 return QualType(); 10822 10823 // FIXME: Add warnings for nullptr - ptr. 10824 10825 // The pointee type may have zero size. As an extension, a structure or 10826 // union may have zero size or an array may have zero length. In this 10827 // case subtraction does not make sense. 10828 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10829 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10830 if (ElementSize.isZero()) { 10831 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10832 << rpointee.getUnqualifiedType() 10833 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10834 } 10835 } 10836 10837 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10838 return Context.getPointerDiffType(); 10839 } 10840 } 10841 10842 return InvalidOperands(Loc, LHS, RHS); 10843 } 10844 10845 static bool isScopedEnumerationType(QualType T) { 10846 if (const EnumType *ET = T->getAs<EnumType>()) 10847 return ET->getDecl()->isScoped(); 10848 return false; 10849 } 10850 10851 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10852 SourceLocation Loc, BinaryOperatorKind Opc, 10853 QualType LHSType) { 10854 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10855 // so skip remaining warnings as we don't want to modify values within Sema. 10856 if (S.getLangOpts().OpenCL) 10857 return; 10858 10859 // Check right/shifter operand 10860 Expr::EvalResult RHSResult; 10861 if (RHS.get()->isValueDependent() || 10862 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10863 return; 10864 llvm::APSInt Right = RHSResult.Val.getInt(); 10865 10866 if (Right.isNegative()) { 10867 S.DiagRuntimeBehavior(Loc, RHS.get(), 10868 S.PDiag(diag::warn_shift_negative) 10869 << RHS.get()->getSourceRange()); 10870 return; 10871 } 10872 10873 QualType LHSExprType = LHS.get()->getType(); 10874 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10875 if (LHSExprType->isExtIntType()) 10876 LeftSize = S.Context.getIntWidth(LHSExprType); 10877 else if (LHSExprType->isFixedPointType()) { 10878 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10879 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10880 } 10881 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10882 if (Right.uge(LeftBits)) { 10883 S.DiagRuntimeBehavior(Loc, RHS.get(), 10884 S.PDiag(diag::warn_shift_gt_typewidth) 10885 << RHS.get()->getSourceRange()); 10886 return; 10887 } 10888 10889 // FIXME: We probably need to handle fixed point types specially here. 10890 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10891 return; 10892 10893 // When left shifting an ICE which is signed, we can check for overflow which 10894 // according to C++ standards prior to C++2a has undefined behavior 10895 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10896 // more than the maximum value representable in the result type, so never 10897 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10898 // expression is still probably a bug.) 10899 Expr::EvalResult LHSResult; 10900 if (LHS.get()->isValueDependent() || 10901 LHSType->hasUnsignedIntegerRepresentation() || 10902 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10903 return; 10904 llvm::APSInt Left = LHSResult.Val.getInt(); 10905 10906 // If LHS does not have a signed type and non-negative value 10907 // then, the behavior is undefined before C++2a. Warn about it. 10908 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10909 !S.getLangOpts().CPlusPlus20) { 10910 S.DiagRuntimeBehavior(Loc, LHS.get(), 10911 S.PDiag(diag::warn_shift_lhs_negative) 10912 << LHS.get()->getSourceRange()); 10913 return; 10914 } 10915 10916 llvm::APInt ResultBits = 10917 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10918 if (LeftBits.uge(ResultBits)) 10919 return; 10920 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10921 Result = Result.shl(Right); 10922 10923 // Print the bit representation of the signed integer as an unsigned 10924 // hexadecimal number. 10925 SmallString<40> HexResult; 10926 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10927 10928 // If we are only missing a sign bit, this is less likely to result in actual 10929 // bugs -- if the result is cast back to an unsigned type, it will have the 10930 // expected value. Thus we place this behind a different warning that can be 10931 // turned off separately if needed. 10932 if (LeftBits == ResultBits - 1) { 10933 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10934 << HexResult << LHSType 10935 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10936 return; 10937 } 10938 10939 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10940 << HexResult.str() << Result.getMinSignedBits() << LHSType 10941 << Left.getBitWidth() << LHS.get()->getSourceRange() 10942 << RHS.get()->getSourceRange(); 10943 } 10944 10945 /// Return the resulting type when a vector is shifted 10946 /// by a scalar or vector shift amount. 10947 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10948 SourceLocation Loc, bool IsCompAssign) { 10949 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10950 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10951 !LHS.get()->getType()->isVectorType()) { 10952 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10953 << RHS.get()->getType() << LHS.get()->getType() 10954 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10955 return QualType(); 10956 } 10957 10958 if (!IsCompAssign) { 10959 LHS = S.UsualUnaryConversions(LHS.get()); 10960 if (LHS.isInvalid()) return QualType(); 10961 } 10962 10963 RHS = S.UsualUnaryConversions(RHS.get()); 10964 if (RHS.isInvalid()) return QualType(); 10965 10966 QualType LHSType = LHS.get()->getType(); 10967 // Note that LHS might be a scalar because the routine calls not only in 10968 // OpenCL case. 10969 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10970 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10971 10972 // Note that RHS might not be a vector. 10973 QualType RHSType = RHS.get()->getType(); 10974 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10975 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10976 10977 // The operands need to be integers. 10978 if (!LHSEleType->isIntegerType()) { 10979 S.Diag(Loc, diag::err_typecheck_expect_int) 10980 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10981 return QualType(); 10982 } 10983 10984 if (!RHSEleType->isIntegerType()) { 10985 S.Diag(Loc, diag::err_typecheck_expect_int) 10986 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10987 return QualType(); 10988 } 10989 10990 if (!LHSVecTy) { 10991 assert(RHSVecTy); 10992 if (IsCompAssign) 10993 return RHSType; 10994 if (LHSEleType != RHSEleType) { 10995 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10996 LHSEleType = RHSEleType; 10997 } 10998 QualType VecTy = 10999 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11000 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11001 LHSType = VecTy; 11002 } else if (RHSVecTy) { 11003 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11004 // are applied component-wise. So if RHS is a vector, then ensure 11005 // that the number of elements is the same as LHS... 11006 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11007 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11008 << LHS.get()->getType() << RHS.get()->getType() 11009 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11010 return QualType(); 11011 } 11012 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11013 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11014 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11015 if (LHSBT != RHSBT && 11016 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11017 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11018 << LHS.get()->getType() << RHS.get()->getType() 11019 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11020 } 11021 } 11022 } else { 11023 // ...else expand RHS to match the number of elements in LHS. 11024 QualType VecTy = 11025 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11026 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11027 } 11028 11029 return LHSType; 11030 } 11031 11032 // C99 6.5.7 11033 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11034 SourceLocation Loc, BinaryOperatorKind Opc, 11035 bool IsCompAssign) { 11036 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11037 11038 // Vector shifts promote their scalar inputs to vector type. 11039 if (LHS.get()->getType()->isVectorType() || 11040 RHS.get()->getType()->isVectorType()) { 11041 if (LangOpts.ZVector) { 11042 // The shift operators for the z vector extensions work basically 11043 // like general shifts, except that neither the LHS nor the RHS is 11044 // allowed to be a "vector bool". 11045 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11046 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11047 return InvalidOperands(Loc, LHS, RHS); 11048 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11049 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11050 return InvalidOperands(Loc, LHS, RHS); 11051 } 11052 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11053 } 11054 11055 // Shifts don't perform usual arithmetic conversions, they just do integer 11056 // promotions on each operand. C99 6.5.7p3 11057 11058 // For the LHS, do usual unary conversions, but then reset them away 11059 // if this is a compound assignment. 11060 ExprResult OldLHS = LHS; 11061 LHS = UsualUnaryConversions(LHS.get()); 11062 if (LHS.isInvalid()) 11063 return QualType(); 11064 QualType LHSType = LHS.get()->getType(); 11065 if (IsCompAssign) LHS = OldLHS; 11066 11067 // The RHS is simpler. 11068 RHS = UsualUnaryConversions(RHS.get()); 11069 if (RHS.isInvalid()) 11070 return QualType(); 11071 QualType RHSType = RHS.get()->getType(); 11072 11073 // C99 6.5.7p2: Each of the operands shall have integer type. 11074 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11075 if ((!LHSType->isFixedPointOrIntegerType() && 11076 !LHSType->hasIntegerRepresentation()) || 11077 !RHSType->hasIntegerRepresentation()) 11078 return InvalidOperands(Loc, LHS, RHS); 11079 11080 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11081 // hasIntegerRepresentation() above instead of this. 11082 if (isScopedEnumerationType(LHSType) || 11083 isScopedEnumerationType(RHSType)) { 11084 return InvalidOperands(Loc, LHS, RHS); 11085 } 11086 // Sanity-check shift operands 11087 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11088 11089 // "The type of the result is that of the promoted left operand." 11090 return LHSType; 11091 } 11092 11093 /// Diagnose bad pointer comparisons. 11094 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11095 ExprResult &LHS, ExprResult &RHS, 11096 bool IsError) { 11097 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11098 : diag::ext_typecheck_comparison_of_distinct_pointers) 11099 << LHS.get()->getType() << RHS.get()->getType() 11100 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11101 } 11102 11103 /// Returns false if the pointers are converted to a composite type, 11104 /// true otherwise. 11105 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11106 ExprResult &LHS, ExprResult &RHS) { 11107 // C++ [expr.rel]p2: 11108 // [...] Pointer conversions (4.10) and qualification 11109 // conversions (4.4) are performed on pointer operands (or on 11110 // a pointer operand and a null pointer constant) to bring 11111 // them to their composite pointer type. [...] 11112 // 11113 // C++ [expr.eq]p1 uses the same notion for (in)equality 11114 // comparisons of pointers. 11115 11116 QualType LHSType = LHS.get()->getType(); 11117 QualType RHSType = RHS.get()->getType(); 11118 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11119 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11120 11121 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11122 if (T.isNull()) { 11123 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11124 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11125 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11126 else 11127 S.InvalidOperands(Loc, LHS, RHS); 11128 return true; 11129 } 11130 11131 return false; 11132 } 11133 11134 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11135 ExprResult &LHS, 11136 ExprResult &RHS, 11137 bool IsError) { 11138 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11139 : diag::ext_typecheck_comparison_of_fptr_to_void) 11140 << LHS.get()->getType() << RHS.get()->getType() 11141 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11142 } 11143 11144 static bool isObjCObjectLiteral(ExprResult &E) { 11145 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11146 case Stmt::ObjCArrayLiteralClass: 11147 case Stmt::ObjCDictionaryLiteralClass: 11148 case Stmt::ObjCStringLiteralClass: 11149 case Stmt::ObjCBoxedExprClass: 11150 return true; 11151 default: 11152 // Note that ObjCBoolLiteral is NOT an object literal! 11153 return false; 11154 } 11155 } 11156 11157 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11158 const ObjCObjectPointerType *Type = 11159 LHS->getType()->getAs<ObjCObjectPointerType>(); 11160 11161 // If this is not actually an Objective-C object, bail out. 11162 if (!Type) 11163 return false; 11164 11165 // Get the LHS object's interface type. 11166 QualType InterfaceType = Type->getPointeeType(); 11167 11168 // If the RHS isn't an Objective-C object, bail out. 11169 if (!RHS->getType()->isObjCObjectPointerType()) 11170 return false; 11171 11172 // Try to find the -isEqual: method. 11173 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11174 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11175 InterfaceType, 11176 /*IsInstance=*/true); 11177 if (!Method) { 11178 if (Type->isObjCIdType()) { 11179 // For 'id', just check the global pool. 11180 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11181 /*receiverId=*/true); 11182 } else { 11183 // Check protocols. 11184 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11185 /*IsInstance=*/true); 11186 } 11187 } 11188 11189 if (!Method) 11190 return false; 11191 11192 QualType T = Method->parameters()[0]->getType(); 11193 if (!T->isObjCObjectPointerType()) 11194 return false; 11195 11196 QualType R = Method->getReturnType(); 11197 if (!R->isScalarType()) 11198 return false; 11199 11200 return true; 11201 } 11202 11203 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11204 FromE = FromE->IgnoreParenImpCasts(); 11205 switch (FromE->getStmtClass()) { 11206 default: 11207 break; 11208 case Stmt::ObjCStringLiteralClass: 11209 // "string literal" 11210 return LK_String; 11211 case Stmt::ObjCArrayLiteralClass: 11212 // "array literal" 11213 return LK_Array; 11214 case Stmt::ObjCDictionaryLiteralClass: 11215 // "dictionary literal" 11216 return LK_Dictionary; 11217 case Stmt::BlockExprClass: 11218 return LK_Block; 11219 case Stmt::ObjCBoxedExprClass: { 11220 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11221 switch (Inner->getStmtClass()) { 11222 case Stmt::IntegerLiteralClass: 11223 case Stmt::FloatingLiteralClass: 11224 case Stmt::CharacterLiteralClass: 11225 case Stmt::ObjCBoolLiteralExprClass: 11226 case Stmt::CXXBoolLiteralExprClass: 11227 // "numeric literal" 11228 return LK_Numeric; 11229 case Stmt::ImplicitCastExprClass: { 11230 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11231 // Boolean literals can be represented by implicit casts. 11232 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11233 return LK_Numeric; 11234 break; 11235 } 11236 default: 11237 break; 11238 } 11239 return LK_Boxed; 11240 } 11241 } 11242 return LK_None; 11243 } 11244 11245 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11246 ExprResult &LHS, ExprResult &RHS, 11247 BinaryOperator::Opcode Opc){ 11248 Expr *Literal; 11249 Expr *Other; 11250 if (isObjCObjectLiteral(LHS)) { 11251 Literal = LHS.get(); 11252 Other = RHS.get(); 11253 } else { 11254 Literal = RHS.get(); 11255 Other = LHS.get(); 11256 } 11257 11258 // Don't warn on comparisons against nil. 11259 Other = Other->IgnoreParenCasts(); 11260 if (Other->isNullPointerConstant(S.getASTContext(), 11261 Expr::NPC_ValueDependentIsNotNull)) 11262 return; 11263 11264 // This should be kept in sync with warn_objc_literal_comparison. 11265 // LK_String should always be after the other literals, since it has its own 11266 // warning flag. 11267 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11268 assert(LiteralKind != Sema::LK_Block); 11269 if (LiteralKind == Sema::LK_None) { 11270 llvm_unreachable("Unknown Objective-C object literal kind"); 11271 } 11272 11273 if (LiteralKind == Sema::LK_String) 11274 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11275 << Literal->getSourceRange(); 11276 else 11277 S.Diag(Loc, diag::warn_objc_literal_comparison) 11278 << LiteralKind << Literal->getSourceRange(); 11279 11280 if (BinaryOperator::isEqualityOp(Opc) && 11281 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11282 SourceLocation Start = LHS.get()->getBeginLoc(); 11283 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11284 CharSourceRange OpRange = 11285 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11286 11287 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11288 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11289 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11290 << FixItHint::CreateInsertion(End, "]"); 11291 } 11292 } 11293 11294 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11295 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11296 ExprResult &RHS, SourceLocation Loc, 11297 BinaryOperatorKind Opc) { 11298 // Check that left hand side is !something. 11299 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11300 if (!UO || UO->getOpcode() != UO_LNot) return; 11301 11302 // Only check if the right hand side is non-bool arithmetic type. 11303 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11304 11305 // Make sure that the something in !something is not bool. 11306 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11307 if (SubExpr->isKnownToHaveBooleanValue()) return; 11308 11309 // Emit warning. 11310 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11311 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11312 << Loc << IsBitwiseOp; 11313 11314 // First note suggest !(x < y) 11315 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11316 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11317 FirstClose = S.getLocForEndOfToken(FirstClose); 11318 if (FirstClose.isInvalid()) 11319 FirstOpen = SourceLocation(); 11320 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11321 << IsBitwiseOp 11322 << FixItHint::CreateInsertion(FirstOpen, "(") 11323 << FixItHint::CreateInsertion(FirstClose, ")"); 11324 11325 // Second note suggests (!x) < y 11326 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11327 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11328 SecondClose = S.getLocForEndOfToken(SecondClose); 11329 if (SecondClose.isInvalid()) 11330 SecondOpen = SourceLocation(); 11331 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11332 << FixItHint::CreateInsertion(SecondOpen, "(") 11333 << FixItHint::CreateInsertion(SecondClose, ")"); 11334 } 11335 11336 // Returns true if E refers to a non-weak array. 11337 static bool checkForArray(const Expr *E) { 11338 const ValueDecl *D = nullptr; 11339 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11340 D = DR->getDecl(); 11341 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11342 if (Mem->isImplicitAccess()) 11343 D = Mem->getMemberDecl(); 11344 } 11345 if (!D) 11346 return false; 11347 return D->getType()->isArrayType() && !D->isWeak(); 11348 } 11349 11350 /// Diagnose some forms of syntactically-obvious tautological comparison. 11351 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11352 Expr *LHS, Expr *RHS, 11353 BinaryOperatorKind Opc) { 11354 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11355 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11356 11357 QualType LHSType = LHS->getType(); 11358 QualType RHSType = RHS->getType(); 11359 if (LHSType->hasFloatingRepresentation() || 11360 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11361 S.inTemplateInstantiation()) 11362 return; 11363 11364 // Comparisons between two array types are ill-formed for operator<=>, so 11365 // we shouldn't emit any additional warnings about it. 11366 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11367 return; 11368 11369 // For non-floating point types, check for self-comparisons of the form 11370 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11371 // often indicate logic errors in the program. 11372 // 11373 // NOTE: Don't warn about comparison expressions resulting from macro 11374 // expansion. Also don't warn about comparisons which are only self 11375 // comparisons within a template instantiation. The warnings should catch 11376 // obvious cases in the definition of the template anyways. The idea is to 11377 // warn when the typed comparison operator will always evaluate to the same 11378 // result. 11379 11380 // Used for indexing into %select in warn_comparison_always 11381 enum { 11382 AlwaysConstant, 11383 AlwaysTrue, 11384 AlwaysFalse, 11385 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11386 }; 11387 11388 // C++2a [depr.array.comp]: 11389 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11390 // operands of array type are deprecated. 11391 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11392 RHSStripped->getType()->isArrayType()) { 11393 S.Diag(Loc, diag::warn_depr_array_comparison) 11394 << LHS->getSourceRange() << RHS->getSourceRange() 11395 << LHSStripped->getType() << RHSStripped->getType(); 11396 // Carry on to produce the tautological comparison warning, if this 11397 // expression is potentially-evaluated, we can resolve the array to a 11398 // non-weak declaration, and so on. 11399 } 11400 11401 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11402 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11403 unsigned Result; 11404 switch (Opc) { 11405 case BO_EQ: 11406 case BO_LE: 11407 case BO_GE: 11408 Result = AlwaysTrue; 11409 break; 11410 case BO_NE: 11411 case BO_LT: 11412 case BO_GT: 11413 Result = AlwaysFalse; 11414 break; 11415 case BO_Cmp: 11416 Result = AlwaysEqual; 11417 break; 11418 default: 11419 Result = AlwaysConstant; 11420 break; 11421 } 11422 S.DiagRuntimeBehavior(Loc, nullptr, 11423 S.PDiag(diag::warn_comparison_always) 11424 << 0 /*self-comparison*/ 11425 << Result); 11426 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11427 // What is it always going to evaluate to? 11428 unsigned Result; 11429 switch (Opc) { 11430 case BO_EQ: // e.g. array1 == array2 11431 Result = AlwaysFalse; 11432 break; 11433 case BO_NE: // e.g. array1 != array2 11434 Result = AlwaysTrue; 11435 break; 11436 default: // e.g. array1 <= array2 11437 // The best we can say is 'a constant' 11438 Result = AlwaysConstant; 11439 break; 11440 } 11441 S.DiagRuntimeBehavior(Loc, nullptr, 11442 S.PDiag(diag::warn_comparison_always) 11443 << 1 /*array comparison*/ 11444 << Result); 11445 } 11446 } 11447 11448 if (isa<CastExpr>(LHSStripped)) 11449 LHSStripped = LHSStripped->IgnoreParenCasts(); 11450 if (isa<CastExpr>(RHSStripped)) 11451 RHSStripped = RHSStripped->IgnoreParenCasts(); 11452 11453 // Warn about comparisons against a string constant (unless the other 11454 // operand is null); the user probably wants string comparison function. 11455 Expr *LiteralString = nullptr; 11456 Expr *LiteralStringStripped = nullptr; 11457 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11458 !RHSStripped->isNullPointerConstant(S.Context, 11459 Expr::NPC_ValueDependentIsNull)) { 11460 LiteralString = LHS; 11461 LiteralStringStripped = LHSStripped; 11462 } else if ((isa<StringLiteral>(RHSStripped) || 11463 isa<ObjCEncodeExpr>(RHSStripped)) && 11464 !LHSStripped->isNullPointerConstant(S.Context, 11465 Expr::NPC_ValueDependentIsNull)) { 11466 LiteralString = RHS; 11467 LiteralStringStripped = RHSStripped; 11468 } 11469 11470 if (LiteralString) { 11471 S.DiagRuntimeBehavior(Loc, nullptr, 11472 S.PDiag(diag::warn_stringcompare) 11473 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11474 << LiteralString->getSourceRange()); 11475 } 11476 } 11477 11478 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11479 switch (CK) { 11480 default: { 11481 #ifndef NDEBUG 11482 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11483 << "\n"; 11484 #endif 11485 llvm_unreachable("unhandled cast kind"); 11486 } 11487 case CK_UserDefinedConversion: 11488 return ICK_Identity; 11489 case CK_LValueToRValue: 11490 return ICK_Lvalue_To_Rvalue; 11491 case CK_ArrayToPointerDecay: 11492 return ICK_Array_To_Pointer; 11493 case CK_FunctionToPointerDecay: 11494 return ICK_Function_To_Pointer; 11495 case CK_IntegralCast: 11496 return ICK_Integral_Conversion; 11497 case CK_FloatingCast: 11498 return ICK_Floating_Conversion; 11499 case CK_IntegralToFloating: 11500 case CK_FloatingToIntegral: 11501 return ICK_Floating_Integral; 11502 case CK_IntegralComplexCast: 11503 case CK_FloatingComplexCast: 11504 case CK_FloatingComplexToIntegralComplex: 11505 case CK_IntegralComplexToFloatingComplex: 11506 return ICK_Complex_Conversion; 11507 case CK_FloatingComplexToReal: 11508 case CK_FloatingRealToComplex: 11509 case CK_IntegralComplexToReal: 11510 case CK_IntegralRealToComplex: 11511 return ICK_Complex_Real; 11512 } 11513 } 11514 11515 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11516 QualType FromType, 11517 SourceLocation Loc) { 11518 // Check for a narrowing implicit conversion. 11519 StandardConversionSequence SCS; 11520 SCS.setAsIdentityConversion(); 11521 SCS.setToType(0, FromType); 11522 SCS.setToType(1, ToType); 11523 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11524 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11525 11526 APValue PreNarrowingValue; 11527 QualType PreNarrowingType; 11528 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11529 PreNarrowingType, 11530 /*IgnoreFloatToIntegralConversion*/ true)) { 11531 case NK_Dependent_Narrowing: 11532 // Implicit conversion to a narrower type, but the expression is 11533 // value-dependent so we can't tell whether it's actually narrowing. 11534 case NK_Not_Narrowing: 11535 return false; 11536 11537 case NK_Constant_Narrowing: 11538 // Implicit conversion to a narrower type, and the value is not a constant 11539 // expression. 11540 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11541 << /*Constant*/ 1 11542 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11543 return true; 11544 11545 case NK_Variable_Narrowing: 11546 // Implicit conversion to a narrower type, and the value is not a constant 11547 // expression. 11548 case NK_Type_Narrowing: 11549 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11550 << /*Constant*/ 0 << FromType << ToType; 11551 // TODO: It's not a constant expression, but what if the user intended it 11552 // to be? Can we produce notes to help them figure out why it isn't? 11553 return true; 11554 } 11555 llvm_unreachable("unhandled case in switch"); 11556 } 11557 11558 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11559 ExprResult &LHS, 11560 ExprResult &RHS, 11561 SourceLocation Loc) { 11562 QualType LHSType = LHS.get()->getType(); 11563 QualType RHSType = RHS.get()->getType(); 11564 // Dig out the original argument type and expression before implicit casts 11565 // were applied. These are the types/expressions we need to check the 11566 // [expr.spaceship] requirements against. 11567 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11568 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11569 QualType LHSStrippedType = LHSStripped.get()->getType(); 11570 QualType RHSStrippedType = RHSStripped.get()->getType(); 11571 11572 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11573 // other is not, the program is ill-formed. 11574 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11575 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11576 return QualType(); 11577 } 11578 11579 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11580 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11581 RHSStrippedType->isEnumeralType(); 11582 if (NumEnumArgs == 1) { 11583 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11584 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11585 if (OtherTy->hasFloatingRepresentation()) { 11586 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11587 return QualType(); 11588 } 11589 } 11590 if (NumEnumArgs == 2) { 11591 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11592 // type E, the operator yields the result of converting the operands 11593 // to the underlying type of E and applying <=> to the converted operands. 11594 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11595 S.InvalidOperands(Loc, LHS, RHS); 11596 return QualType(); 11597 } 11598 QualType IntType = 11599 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11600 assert(IntType->isArithmeticType()); 11601 11602 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11603 // promote the boolean type, and all other promotable integer types, to 11604 // avoid this. 11605 if (IntType->isPromotableIntegerType()) 11606 IntType = S.Context.getPromotedIntegerType(IntType); 11607 11608 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11609 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11610 LHSType = RHSType = IntType; 11611 } 11612 11613 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11614 // usual arithmetic conversions are applied to the operands. 11615 QualType Type = 11616 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11617 if (LHS.isInvalid() || RHS.isInvalid()) 11618 return QualType(); 11619 if (Type.isNull()) 11620 return S.InvalidOperands(Loc, LHS, RHS); 11621 11622 Optional<ComparisonCategoryType> CCT = 11623 getComparisonCategoryForBuiltinCmp(Type); 11624 if (!CCT) 11625 return S.InvalidOperands(Loc, LHS, RHS); 11626 11627 bool HasNarrowing = checkThreeWayNarrowingConversion( 11628 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11629 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11630 RHS.get()->getBeginLoc()); 11631 if (HasNarrowing) 11632 return QualType(); 11633 11634 assert(!Type.isNull() && "composite type for <=> has not been set"); 11635 11636 return S.CheckComparisonCategoryType( 11637 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11638 } 11639 11640 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11641 ExprResult &RHS, 11642 SourceLocation Loc, 11643 BinaryOperatorKind Opc) { 11644 if (Opc == BO_Cmp) 11645 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11646 11647 // C99 6.5.8p3 / C99 6.5.9p4 11648 QualType Type = 11649 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11650 if (LHS.isInvalid() || RHS.isInvalid()) 11651 return QualType(); 11652 if (Type.isNull()) 11653 return S.InvalidOperands(Loc, LHS, RHS); 11654 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11655 11656 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11657 return S.InvalidOperands(Loc, LHS, RHS); 11658 11659 // Check for comparisons of floating point operands using != and ==. 11660 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11661 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11662 11663 // The result of comparisons is 'bool' in C++, 'int' in C. 11664 return S.Context.getLogicalOperationType(); 11665 } 11666 11667 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11668 if (!NullE.get()->getType()->isAnyPointerType()) 11669 return; 11670 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11671 if (!E.get()->getType()->isAnyPointerType() && 11672 E.get()->isNullPointerConstant(Context, 11673 Expr::NPC_ValueDependentIsNotNull) == 11674 Expr::NPCK_ZeroExpression) { 11675 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11676 if (CL->getValue() == 0) 11677 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11678 << NullValue 11679 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11680 NullValue ? "NULL" : "(void *)0"); 11681 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11682 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11683 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11684 if (T == Context.CharTy) 11685 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11686 << NullValue 11687 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11688 NullValue ? "NULL" : "(void *)0"); 11689 } 11690 } 11691 } 11692 11693 // C99 6.5.8, C++ [expr.rel] 11694 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11695 SourceLocation Loc, 11696 BinaryOperatorKind Opc) { 11697 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11698 bool IsThreeWay = Opc == BO_Cmp; 11699 bool IsOrdered = IsRelational || IsThreeWay; 11700 auto IsAnyPointerType = [](ExprResult E) { 11701 QualType Ty = E.get()->getType(); 11702 return Ty->isPointerType() || Ty->isMemberPointerType(); 11703 }; 11704 11705 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11706 // type, array-to-pointer, ..., conversions are performed on both operands to 11707 // bring them to their composite type. 11708 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11709 // any type-related checks. 11710 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11711 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11712 if (LHS.isInvalid()) 11713 return QualType(); 11714 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11715 if (RHS.isInvalid()) 11716 return QualType(); 11717 } else { 11718 LHS = DefaultLvalueConversion(LHS.get()); 11719 if (LHS.isInvalid()) 11720 return QualType(); 11721 RHS = DefaultLvalueConversion(RHS.get()); 11722 if (RHS.isInvalid()) 11723 return QualType(); 11724 } 11725 11726 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11727 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11728 CheckPtrComparisonWithNullChar(LHS, RHS); 11729 CheckPtrComparisonWithNullChar(RHS, LHS); 11730 } 11731 11732 // Handle vector comparisons separately. 11733 if (LHS.get()->getType()->isVectorType() || 11734 RHS.get()->getType()->isVectorType()) 11735 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11736 11737 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11738 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11739 11740 QualType LHSType = LHS.get()->getType(); 11741 QualType RHSType = RHS.get()->getType(); 11742 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11743 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11744 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11745 11746 const Expr::NullPointerConstantKind LHSNullKind = 11747 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11748 const Expr::NullPointerConstantKind RHSNullKind = 11749 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11750 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11751 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11752 11753 auto computeResultTy = [&]() { 11754 if (Opc != BO_Cmp) 11755 return Context.getLogicalOperationType(); 11756 assert(getLangOpts().CPlusPlus); 11757 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11758 11759 QualType CompositeTy = LHS.get()->getType(); 11760 assert(!CompositeTy->isReferenceType()); 11761 11762 Optional<ComparisonCategoryType> CCT = 11763 getComparisonCategoryForBuiltinCmp(CompositeTy); 11764 if (!CCT) 11765 return InvalidOperands(Loc, LHS, RHS); 11766 11767 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11768 // P0946R0: Comparisons between a null pointer constant and an object 11769 // pointer result in std::strong_equality, which is ill-formed under 11770 // P1959R0. 11771 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11772 << (LHSIsNull ? LHS.get()->getSourceRange() 11773 : RHS.get()->getSourceRange()); 11774 return QualType(); 11775 } 11776 11777 return CheckComparisonCategoryType( 11778 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11779 }; 11780 11781 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11782 bool IsEquality = Opc == BO_EQ; 11783 if (RHSIsNull) 11784 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11785 RHS.get()->getSourceRange()); 11786 else 11787 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11788 LHS.get()->getSourceRange()); 11789 } 11790 11791 if ((LHSType->isIntegerType() && !LHSIsNull) || 11792 (RHSType->isIntegerType() && !RHSIsNull)) { 11793 // Skip normal pointer conversion checks in this case; we have better 11794 // diagnostics for this below. 11795 } else if (getLangOpts().CPlusPlus) { 11796 // Equality comparison of a function pointer to a void pointer is invalid, 11797 // but we allow it as an extension. 11798 // FIXME: If we really want to allow this, should it be part of composite 11799 // pointer type computation so it works in conditionals too? 11800 if (!IsOrdered && 11801 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11802 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11803 // This is a gcc extension compatibility comparison. 11804 // In a SFINAE context, we treat this as a hard error to maintain 11805 // conformance with the C++ standard. 11806 diagnoseFunctionPointerToVoidComparison( 11807 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11808 11809 if (isSFINAEContext()) 11810 return QualType(); 11811 11812 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11813 return computeResultTy(); 11814 } 11815 11816 // C++ [expr.eq]p2: 11817 // If at least one operand is a pointer [...] bring them to their 11818 // composite pointer type. 11819 // C++ [expr.spaceship]p6 11820 // If at least one of the operands is of pointer type, [...] bring them 11821 // to their composite pointer type. 11822 // C++ [expr.rel]p2: 11823 // If both operands are pointers, [...] bring them to their composite 11824 // pointer type. 11825 // For <=>, the only valid non-pointer types are arrays and functions, and 11826 // we already decayed those, so this is really the same as the relational 11827 // comparison rule. 11828 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11829 (IsOrdered ? 2 : 1) && 11830 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11831 RHSType->isObjCObjectPointerType()))) { 11832 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11833 return QualType(); 11834 return computeResultTy(); 11835 } 11836 } else if (LHSType->isPointerType() && 11837 RHSType->isPointerType()) { // C99 6.5.8p2 11838 // All of the following pointer-related warnings are GCC extensions, except 11839 // when handling null pointer constants. 11840 QualType LCanPointeeTy = 11841 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11842 QualType RCanPointeeTy = 11843 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11844 11845 // C99 6.5.9p2 and C99 6.5.8p2 11846 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11847 RCanPointeeTy.getUnqualifiedType())) { 11848 if (IsRelational) { 11849 // Pointers both need to point to complete or incomplete types 11850 if ((LCanPointeeTy->isIncompleteType() != 11851 RCanPointeeTy->isIncompleteType()) && 11852 !getLangOpts().C11) { 11853 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11854 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11855 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11856 << RCanPointeeTy->isIncompleteType(); 11857 } 11858 if (LCanPointeeTy->isFunctionType()) { 11859 // Valid unless a relational comparison of function pointers 11860 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11861 << LHSType << RHSType << LHS.get()->getSourceRange() 11862 << RHS.get()->getSourceRange(); 11863 } 11864 } 11865 } else if (!IsRelational && 11866 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11867 // Valid unless comparison between non-null pointer and function pointer 11868 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11869 && !LHSIsNull && !RHSIsNull) 11870 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11871 /*isError*/false); 11872 } else { 11873 // Invalid 11874 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11875 } 11876 if (LCanPointeeTy != RCanPointeeTy) { 11877 // Treat NULL constant as a special case in OpenCL. 11878 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11879 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11880 Diag(Loc, 11881 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11882 << LHSType << RHSType << 0 /* comparison */ 11883 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11884 } 11885 } 11886 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11887 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11888 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11889 : CK_BitCast; 11890 if (LHSIsNull && !RHSIsNull) 11891 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11892 else 11893 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11894 } 11895 return computeResultTy(); 11896 } 11897 11898 if (getLangOpts().CPlusPlus) { 11899 // C++ [expr.eq]p4: 11900 // Two operands of type std::nullptr_t or one operand of type 11901 // std::nullptr_t and the other a null pointer constant compare equal. 11902 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11903 if (LHSType->isNullPtrType()) { 11904 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11905 return computeResultTy(); 11906 } 11907 if (RHSType->isNullPtrType()) { 11908 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11909 return computeResultTy(); 11910 } 11911 } 11912 11913 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11914 // These aren't covered by the composite pointer type rules. 11915 if (!IsOrdered && RHSType->isNullPtrType() && 11916 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11917 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11918 return computeResultTy(); 11919 } 11920 if (!IsOrdered && LHSType->isNullPtrType() && 11921 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11922 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11923 return computeResultTy(); 11924 } 11925 11926 if (IsRelational && 11927 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11928 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11929 // HACK: Relational comparison of nullptr_t against a pointer type is 11930 // invalid per DR583, but we allow it within std::less<> and friends, 11931 // since otherwise common uses of it break. 11932 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11933 // friends to have std::nullptr_t overload candidates. 11934 DeclContext *DC = CurContext; 11935 if (isa<FunctionDecl>(DC)) 11936 DC = DC->getParent(); 11937 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11938 if (CTSD->isInStdNamespace() && 11939 llvm::StringSwitch<bool>(CTSD->getName()) 11940 .Cases("less", "less_equal", "greater", "greater_equal", true) 11941 .Default(false)) { 11942 if (RHSType->isNullPtrType()) 11943 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11944 else 11945 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11946 return computeResultTy(); 11947 } 11948 } 11949 } 11950 11951 // C++ [expr.eq]p2: 11952 // If at least one operand is a pointer to member, [...] bring them to 11953 // their composite pointer type. 11954 if (!IsOrdered && 11955 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11956 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11957 return QualType(); 11958 else 11959 return computeResultTy(); 11960 } 11961 } 11962 11963 // Handle block pointer types. 11964 if (!IsOrdered && LHSType->isBlockPointerType() && 11965 RHSType->isBlockPointerType()) { 11966 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11967 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11968 11969 if (!LHSIsNull && !RHSIsNull && 11970 !Context.typesAreCompatible(lpointee, rpointee)) { 11971 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11972 << LHSType << RHSType << LHS.get()->getSourceRange() 11973 << RHS.get()->getSourceRange(); 11974 } 11975 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11976 return computeResultTy(); 11977 } 11978 11979 // Allow block pointers to be compared with null pointer constants. 11980 if (!IsOrdered 11981 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11982 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11983 if (!LHSIsNull && !RHSIsNull) { 11984 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11985 ->getPointeeType()->isVoidType()) 11986 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11987 ->getPointeeType()->isVoidType()))) 11988 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11989 << LHSType << RHSType << LHS.get()->getSourceRange() 11990 << RHS.get()->getSourceRange(); 11991 } 11992 if (LHSIsNull && !RHSIsNull) 11993 LHS = ImpCastExprToType(LHS.get(), RHSType, 11994 RHSType->isPointerType() ? CK_BitCast 11995 : CK_AnyPointerToBlockPointerCast); 11996 else 11997 RHS = ImpCastExprToType(RHS.get(), LHSType, 11998 LHSType->isPointerType() ? CK_BitCast 11999 : CK_AnyPointerToBlockPointerCast); 12000 return computeResultTy(); 12001 } 12002 12003 if (LHSType->isObjCObjectPointerType() || 12004 RHSType->isObjCObjectPointerType()) { 12005 const PointerType *LPT = LHSType->getAs<PointerType>(); 12006 const PointerType *RPT = RHSType->getAs<PointerType>(); 12007 if (LPT || RPT) { 12008 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12009 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12010 12011 if (!LPtrToVoid && !RPtrToVoid && 12012 !Context.typesAreCompatible(LHSType, RHSType)) { 12013 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12014 /*isError*/false); 12015 } 12016 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12017 // the RHS, but we have test coverage for this behavior. 12018 // FIXME: Consider using convertPointersToCompositeType in C++. 12019 if (LHSIsNull && !RHSIsNull) { 12020 Expr *E = LHS.get(); 12021 if (getLangOpts().ObjCAutoRefCount) 12022 CheckObjCConversion(SourceRange(), RHSType, E, 12023 CCK_ImplicitConversion); 12024 LHS = ImpCastExprToType(E, RHSType, 12025 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12026 } 12027 else { 12028 Expr *E = RHS.get(); 12029 if (getLangOpts().ObjCAutoRefCount) 12030 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12031 /*Diagnose=*/true, 12032 /*DiagnoseCFAudited=*/false, Opc); 12033 RHS = ImpCastExprToType(E, LHSType, 12034 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12035 } 12036 return computeResultTy(); 12037 } 12038 if (LHSType->isObjCObjectPointerType() && 12039 RHSType->isObjCObjectPointerType()) { 12040 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12041 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12042 /*isError*/false); 12043 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12044 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12045 12046 if (LHSIsNull && !RHSIsNull) 12047 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12048 else 12049 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12050 return computeResultTy(); 12051 } 12052 12053 if (!IsOrdered && LHSType->isBlockPointerType() && 12054 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12055 LHS = ImpCastExprToType(LHS.get(), RHSType, 12056 CK_BlockPointerToObjCPointerCast); 12057 return computeResultTy(); 12058 } else if (!IsOrdered && 12059 LHSType->isBlockCompatibleObjCPointerType(Context) && 12060 RHSType->isBlockPointerType()) { 12061 RHS = ImpCastExprToType(RHS.get(), LHSType, 12062 CK_BlockPointerToObjCPointerCast); 12063 return computeResultTy(); 12064 } 12065 } 12066 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12067 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12068 unsigned DiagID = 0; 12069 bool isError = false; 12070 if (LangOpts.DebuggerSupport) { 12071 // Under a debugger, allow the comparison of pointers to integers, 12072 // since users tend to want to compare addresses. 12073 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12074 (RHSIsNull && RHSType->isIntegerType())) { 12075 if (IsOrdered) { 12076 isError = getLangOpts().CPlusPlus; 12077 DiagID = 12078 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12079 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12080 } 12081 } else if (getLangOpts().CPlusPlus) { 12082 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12083 isError = true; 12084 } else if (IsOrdered) 12085 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12086 else 12087 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12088 12089 if (DiagID) { 12090 Diag(Loc, DiagID) 12091 << LHSType << RHSType << LHS.get()->getSourceRange() 12092 << RHS.get()->getSourceRange(); 12093 if (isError) 12094 return QualType(); 12095 } 12096 12097 if (LHSType->isIntegerType()) 12098 LHS = ImpCastExprToType(LHS.get(), RHSType, 12099 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12100 else 12101 RHS = ImpCastExprToType(RHS.get(), LHSType, 12102 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12103 return computeResultTy(); 12104 } 12105 12106 // Handle block pointers. 12107 if (!IsOrdered && RHSIsNull 12108 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12109 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12110 return computeResultTy(); 12111 } 12112 if (!IsOrdered && LHSIsNull 12113 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12114 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12115 return computeResultTy(); 12116 } 12117 12118 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12119 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12120 return computeResultTy(); 12121 } 12122 12123 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12124 return computeResultTy(); 12125 } 12126 12127 if (LHSIsNull && RHSType->isQueueT()) { 12128 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12129 return computeResultTy(); 12130 } 12131 12132 if (LHSType->isQueueT() && RHSIsNull) { 12133 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12134 return computeResultTy(); 12135 } 12136 } 12137 12138 return InvalidOperands(Loc, LHS, RHS); 12139 } 12140 12141 // Return a signed ext_vector_type that is of identical size and number of 12142 // elements. For floating point vectors, return an integer type of identical 12143 // size and number of elements. In the non ext_vector_type case, search from 12144 // the largest type to the smallest type to avoid cases where long long == long, 12145 // where long gets picked over long long. 12146 QualType Sema::GetSignedVectorType(QualType V) { 12147 const VectorType *VTy = V->castAs<VectorType>(); 12148 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12149 12150 if (isa<ExtVectorType>(VTy)) { 12151 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12152 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12153 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12154 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12155 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12156 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12157 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12158 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12159 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12160 "Unhandled vector element size in vector compare"); 12161 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12162 } 12163 12164 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12165 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12166 VectorType::GenericVector); 12167 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12168 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12169 VectorType::GenericVector); 12170 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12171 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12172 VectorType::GenericVector); 12173 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12174 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12175 VectorType::GenericVector); 12176 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12177 "Unhandled vector element size in vector compare"); 12178 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12179 VectorType::GenericVector); 12180 } 12181 12182 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12183 /// operates on extended vector types. Instead of producing an IntTy result, 12184 /// like a scalar comparison, a vector comparison produces a vector of integer 12185 /// types. 12186 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12187 SourceLocation Loc, 12188 BinaryOperatorKind Opc) { 12189 if (Opc == BO_Cmp) { 12190 Diag(Loc, diag::err_three_way_vector_comparison); 12191 return QualType(); 12192 } 12193 12194 // Check to make sure we're operating on vectors of the same type and width, 12195 // Allowing one side to be a scalar of element type. 12196 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12197 /*AllowBothBool*/true, 12198 /*AllowBoolConversions*/getLangOpts().ZVector); 12199 if (vType.isNull()) 12200 return vType; 12201 12202 QualType LHSType = LHS.get()->getType(); 12203 12204 // If AltiVec, the comparison results in a numeric type, i.e. 12205 // bool for C++, int for C 12206 if (getLangOpts().AltiVec && 12207 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 12208 return Context.getLogicalOperationType(); 12209 12210 // For non-floating point types, check for self-comparisons of the form 12211 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12212 // often indicate logic errors in the program. 12213 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12214 12215 // Check for comparisons of floating point operands using != and ==. 12216 if (BinaryOperator::isEqualityOp(Opc) && 12217 LHSType->hasFloatingRepresentation()) { 12218 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12219 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12220 } 12221 12222 // Return a signed type for the vector. 12223 return GetSignedVectorType(vType); 12224 } 12225 12226 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12227 const ExprResult &XorRHS, 12228 const SourceLocation Loc) { 12229 // Do not diagnose macros. 12230 if (Loc.isMacroID()) 12231 return; 12232 12233 // Do not diagnose if both LHS and RHS are macros. 12234 if (XorLHS.get()->getExprLoc().isMacroID() && 12235 XorRHS.get()->getExprLoc().isMacroID()) 12236 return; 12237 12238 bool Negative = false; 12239 bool ExplicitPlus = false; 12240 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12241 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12242 12243 if (!LHSInt) 12244 return; 12245 if (!RHSInt) { 12246 // Check negative literals. 12247 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12248 UnaryOperatorKind Opc = UO->getOpcode(); 12249 if (Opc != UO_Minus && Opc != UO_Plus) 12250 return; 12251 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12252 if (!RHSInt) 12253 return; 12254 Negative = (Opc == UO_Minus); 12255 ExplicitPlus = !Negative; 12256 } else { 12257 return; 12258 } 12259 } 12260 12261 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12262 llvm::APInt RightSideValue = RHSInt->getValue(); 12263 if (LeftSideValue != 2 && LeftSideValue != 10) 12264 return; 12265 12266 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12267 return; 12268 12269 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12270 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12271 llvm::StringRef ExprStr = 12272 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12273 12274 CharSourceRange XorRange = 12275 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12276 llvm::StringRef XorStr = 12277 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12278 // Do not diagnose if xor keyword/macro is used. 12279 if (XorStr == "xor") 12280 return; 12281 12282 std::string LHSStr = std::string(Lexer::getSourceText( 12283 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12284 S.getSourceManager(), S.getLangOpts())); 12285 std::string RHSStr = std::string(Lexer::getSourceText( 12286 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12287 S.getSourceManager(), S.getLangOpts())); 12288 12289 if (Negative) { 12290 RightSideValue = -RightSideValue; 12291 RHSStr = "-" + RHSStr; 12292 } else if (ExplicitPlus) { 12293 RHSStr = "+" + RHSStr; 12294 } 12295 12296 StringRef LHSStrRef = LHSStr; 12297 StringRef RHSStrRef = RHSStr; 12298 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12299 // literals. 12300 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12301 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12302 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12303 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12304 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12305 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12306 LHSStrRef.find('\'') != StringRef::npos || 12307 RHSStrRef.find('\'') != StringRef::npos) 12308 return; 12309 12310 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12311 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12312 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12313 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12314 std::string SuggestedExpr = "1 << " + RHSStr; 12315 bool Overflow = false; 12316 llvm::APInt One = (LeftSideValue - 1); 12317 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12318 if (Overflow) { 12319 if (RightSideIntValue < 64) 12320 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12321 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12322 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12323 else if (RightSideIntValue == 64) 12324 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12325 else 12326 return; 12327 } else { 12328 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12329 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12330 << PowValue.toString(10, true) 12331 << FixItHint::CreateReplacement( 12332 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12333 } 12334 12335 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12336 } else if (LeftSideValue == 10) { 12337 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12338 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12339 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12340 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12341 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12342 } 12343 } 12344 12345 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12346 SourceLocation Loc) { 12347 // Ensure that either both operands are of the same vector type, or 12348 // one operand is of a vector type and the other is of its element type. 12349 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12350 /*AllowBothBool*/true, 12351 /*AllowBoolConversions*/false); 12352 if (vType.isNull()) 12353 return InvalidOperands(Loc, LHS, RHS); 12354 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12355 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12356 return InvalidOperands(Loc, LHS, RHS); 12357 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12358 // usage of the logical operators && and || with vectors in C. This 12359 // check could be notionally dropped. 12360 if (!getLangOpts().CPlusPlus && 12361 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12362 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12363 12364 return GetSignedVectorType(LHS.get()->getType()); 12365 } 12366 12367 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12368 SourceLocation Loc, 12369 bool IsCompAssign) { 12370 if (!IsCompAssign) { 12371 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12372 if (LHS.isInvalid()) 12373 return QualType(); 12374 } 12375 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12376 if (RHS.isInvalid()) 12377 return QualType(); 12378 12379 // For conversion purposes, we ignore any qualifiers. 12380 // For example, "const float" and "float" are equivalent. 12381 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12382 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12383 12384 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12385 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12386 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12387 12388 if (Context.hasSameType(LHSType, RHSType)) 12389 return LHSType; 12390 12391 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12392 // case we have to return InvalidOperands. 12393 ExprResult OriginalLHS = LHS; 12394 ExprResult OriginalRHS = RHS; 12395 if (LHSMatType && !RHSMatType) { 12396 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12397 if (!RHS.isInvalid()) 12398 return LHSType; 12399 12400 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12401 } 12402 12403 if (!LHSMatType && RHSMatType) { 12404 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12405 if (!LHS.isInvalid()) 12406 return RHSType; 12407 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12408 } 12409 12410 return InvalidOperands(Loc, LHS, RHS); 12411 } 12412 12413 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12414 SourceLocation Loc, 12415 bool IsCompAssign) { 12416 if (!IsCompAssign) { 12417 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12418 if (LHS.isInvalid()) 12419 return QualType(); 12420 } 12421 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12422 if (RHS.isInvalid()) 12423 return QualType(); 12424 12425 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12426 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12427 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12428 12429 if (LHSMatType && RHSMatType) { 12430 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12431 return InvalidOperands(Loc, LHS, RHS); 12432 12433 if (!Context.hasSameType(LHSMatType->getElementType(), 12434 RHSMatType->getElementType())) 12435 return InvalidOperands(Loc, LHS, RHS); 12436 12437 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12438 LHSMatType->getNumRows(), 12439 RHSMatType->getNumColumns()); 12440 } 12441 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12442 } 12443 12444 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12445 SourceLocation Loc, 12446 BinaryOperatorKind Opc) { 12447 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12448 12449 bool IsCompAssign = 12450 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12451 12452 if (LHS.get()->getType()->isVectorType() || 12453 RHS.get()->getType()->isVectorType()) { 12454 if (LHS.get()->getType()->hasIntegerRepresentation() && 12455 RHS.get()->getType()->hasIntegerRepresentation()) 12456 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12457 /*AllowBothBool*/true, 12458 /*AllowBoolConversions*/getLangOpts().ZVector); 12459 return InvalidOperands(Loc, LHS, RHS); 12460 } 12461 12462 if (Opc == BO_And) 12463 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12464 12465 if (LHS.get()->getType()->hasFloatingRepresentation() || 12466 RHS.get()->getType()->hasFloatingRepresentation()) 12467 return InvalidOperands(Loc, LHS, RHS); 12468 12469 ExprResult LHSResult = LHS, RHSResult = RHS; 12470 QualType compType = UsualArithmeticConversions( 12471 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12472 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12473 return QualType(); 12474 LHS = LHSResult.get(); 12475 RHS = RHSResult.get(); 12476 12477 if (Opc == BO_Xor) 12478 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12479 12480 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12481 return compType; 12482 return InvalidOperands(Loc, LHS, RHS); 12483 } 12484 12485 // C99 6.5.[13,14] 12486 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12487 SourceLocation Loc, 12488 BinaryOperatorKind Opc) { 12489 // Check vector operands differently. 12490 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12491 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12492 12493 bool EnumConstantInBoolContext = false; 12494 for (const ExprResult &HS : {LHS, RHS}) { 12495 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12496 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12497 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12498 EnumConstantInBoolContext = true; 12499 } 12500 } 12501 12502 if (EnumConstantInBoolContext) 12503 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12504 12505 // Diagnose cases where the user write a logical and/or but probably meant a 12506 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12507 // is a constant. 12508 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12509 !LHS.get()->getType()->isBooleanType() && 12510 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12511 // Don't warn in macros or template instantiations. 12512 !Loc.isMacroID() && !inTemplateInstantiation()) { 12513 // If the RHS can be constant folded, and if it constant folds to something 12514 // that isn't 0 or 1 (which indicate a potential logical operation that 12515 // happened to fold to true/false) then warn. 12516 // Parens on the RHS are ignored. 12517 Expr::EvalResult EVResult; 12518 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12519 llvm::APSInt Result = EVResult.Val.getInt(); 12520 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12521 !RHS.get()->getExprLoc().isMacroID()) || 12522 (Result != 0 && Result != 1)) { 12523 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12524 << RHS.get()->getSourceRange() 12525 << (Opc == BO_LAnd ? "&&" : "||"); 12526 // Suggest replacing the logical operator with the bitwise version 12527 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12528 << (Opc == BO_LAnd ? "&" : "|") 12529 << FixItHint::CreateReplacement(SourceRange( 12530 Loc, getLocForEndOfToken(Loc)), 12531 Opc == BO_LAnd ? "&" : "|"); 12532 if (Opc == BO_LAnd) 12533 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12534 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12535 << FixItHint::CreateRemoval( 12536 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12537 RHS.get()->getEndLoc())); 12538 } 12539 } 12540 } 12541 12542 if (!Context.getLangOpts().CPlusPlus) { 12543 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12544 // not operate on the built-in scalar and vector float types. 12545 if (Context.getLangOpts().OpenCL && 12546 Context.getLangOpts().OpenCLVersion < 120) { 12547 if (LHS.get()->getType()->isFloatingType() || 12548 RHS.get()->getType()->isFloatingType()) 12549 return InvalidOperands(Loc, LHS, RHS); 12550 } 12551 12552 LHS = UsualUnaryConversions(LHS.get()); 12553 if (LHS.isInvalid()) 12554 return QualType(); 12555 12556 RHS = UsualUnaryConversions(RHS.get()); 12557 if (RHS.isInvalid()) 12558 return QualType(); 12559 12560 if (!LHS.get()->getType()->isScalarType() || 12561 !RHS.get()->getType()->isScalarType()) 12562 return InvalidOperands(Loc, LHS, RHS); 12563 12564 return Context.IntTy; 12565 } 12566 12567 // The following is safe because we only use this method for 12568 // non-overloadable operands. 12569 12570 // C++ [expr.log.and]p1 12571 // C++ [expr.log.or]p1 12572 // The operands are both contextually converted to type bool. 12573 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12574 if (LHSRes.isInvalid()) 12575 return InvalidOperands(Loc, LHS, RHS); 12576 LHS = LHSRes; 12577 12578 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12579 if (RHSRes.isInvalid()) 12580 return InvalidOperands(Loc, LHS, RHS); 12581 RHS = RHSRes; 12582 12583 // C++ [expr.log.and]p2 12584 // C++ [expr.log.or]p2 12585 // The result is a bool. 12586 return Context.BoolTy; 12587 } 12588 12589 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12590 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12591 if (!ME) return false; 12592 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12593 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12594 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12595 if (!Base) return false; 12596 return Base->getMethodDecl() != nullptr; 12597 } 12598 12599 /// Is the given expression (which must be 'const') a reference to a 12600 /// variable which was originally non-const, but which has become 12601 /// 'const' due to being captured within a block? 12602 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12603 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12604 assert(E->isLValue() && E->getType().isConstQualified()); 12605 E = E->IgnoreParens(); 12606 12607 // Must be a reference to a declaration from an enclosing scope. 12608 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12609 if (!DRE) return NCCK_None; 12610 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12611 12612 // The declaration must be a variable which is not declared 'const'. 12613 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12614 if (!var) return NCCK_None; 12615 if (var->getType().isConstQualified()) return NCCK_None; 12616 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12617 12618 // Decide whether the first capture was for a block or a lambda. 12619 DeclContext *DC = S.CurContext, *Prev = nullptr; 12620 // Decide whether the first capture was for a block or a lambda. 12621 while (DC) { 12622 // For init-capture, it is possible that the variable belongs to the 12623 // template pattern of the current context. 12624 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12625 if (var->isInitCapture() && 12626 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12627 break; 12628 if (DC == var->getDeclContext()) 12629 break; 12630 Prev = DC; 12631 DC = DC->getParent(); 12632 } 12633 // Unless we have an init-capture, we've gone one step too far. 12634 if (!var->isInitCapture()) 12635 DC = Prev; 12636 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12637 } 12638 12639 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12640 Ty = Ty.getNonReferenceType(); 12641 if (IsDereference && Ty->isPointerType()) 12642 Ty = Ty->getPointeeType(); 12643 return !Ty.isConstQualified(); 12644 } 12645 12646 // Update err_typecheck_assign_const and note_typecheck_assign_const 12647 // when this enum is changed. 12648 enum { 12649 ConstFunction, 12650 ConstVariable, 12651 ConstMember, 12652 ConstMethod, 12653 NestedConstMember, 12654 ConstUnknown, // Keep as last element 12655 }; 12656 12657 /// Emit the "read-only variable not assignable" error and print notes to give 12658 /// more information about why the variable is not assignable, such as pointing 12659 /// to the declaration of a const variable, showing that a method is const, or 12660 /// that the function is returning a const reference. 12661 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12662 SourceLocation Loc) { 12663 SourceRange ExprRange = E->getSourceRange(); 12664 12665 // Only emit one error on the first const found. All other consts will emit 12666 // a note to the error. 12667 bool DiagnosticEmitted = false; 12668 12669 // Track if the current expression is the result of a dereference, and if the 12670 // next checked expression is the result of a dereference. 12671 bool IsDereference = false; 12672 bool NextIsDereference = false; 12673 12674 // Loop to process MemberExpr chains. 12675 while (true) { 12676 IsDereference = NextIsDereference; 12677 12678 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12679 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12680 NextIsDereference = ME->isArrow(); 12681 const ValueDecl *VD = ME->getMemberDecl(); 12682 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12683 // Mutable fields can be modified even if the class is const. 12684 if (Field->isMutable()) { 12685 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12686 break; 12687 } 12688 12689 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12690 if (!DiagnosticEmitted) { 12691 S.Diag(Loc, diag::err_typecheck_assign_const) 12692 << ExprRange << ConstMember << false /*static*/ << Field 12693 << Field->getType(); 12694 DiagnosticEmitted = true; 12695 } 12696 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12697 << ConstMember << false /*static*/ << Field << Field->getType() 12698 << Field->getSourceRange(); 12699 } 12700 E = ME->getBase(); 12701 continue; 12702 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12703 if (VDecl->getType().isConstQualified()) { 12704 if (!DiagnosticEmitted) { 12705 S.Diag(Loc, diag::err_typecheck_assign_const) 12706 << ExprRange << ConstMember << true /*static*/ << VDecl 12707 << VDecl->getType(); 12708 DiagnosticEmitted = true; 12709 } 12710 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12711 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12712 << VDecl->getSourceRange(); 12713 } 12714 // Static fields do not inherit constness from parents. 12715 break; 12716 } 12717 break; // End MemberExpr 12718 } else if (const ArraySubscriptExpr *ASE = 12719 dyn_cast<ArraySubscriptExpr>(E)) { 12720 E = ASE->getBase()->IgnoreParenImpCasts(); 12721 continue; 12722 } else if (const ExtVectorElementExpr *EVE = 12723 dyn_cast<ExtVectorElementExpr>(E)) { 12724 E = EVE->getBase()->IgnoreParenImpCasts(); 12725 continue; 12726 } 12727 break; 12728 } 12729 12730 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12731 // Function calls 12732 const FunctionDecl *FD = CE->getDirectCallee(); 12733 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12734 if (!DiagnosticEmitted) { 12735 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12736 << ConstFunction << FD; 12737 DiagnosticEmitted = true; 12738 } 12739 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12740 diag::note_typecheck_assign_const) 12741 << ConstFunction << FD << FD->getReturnType() 12742 << FD->getReturnTypeSourceRange(); 12743 } 12744 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12745 // Point to variable declaration. 12746 if (const ValueDecl *VD = DRE->getDecl()) { 12747 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12748 if (!DiagnosticEmitted) { 12749 S.Diag(Loc, diag::err_typecheck_assign_const) 12750 << ExprRange << ConstVariable << VD << VD->getType(); 12751 DiagnosticEmitted = true; 12752 } 12753 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12754 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12755 } 12756 } 12757 } else if (isa<CXXThisExpr>(E)) { 12758 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12759 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12760 if (MD->isConst()) { 12761 if (!DiagnosticEmitted) { 12762 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12763 << ConstMethod << MD; 12764 DiagnosticEmitted = true; 12765 } 12766 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12767 << ConstMethod << MD << MD->getSourceRange(); 12768 } 12769 } 12770 } 12771 } 12772 12773 if (DiagnosticEmitted) 12774 return; 12775 12776 // Can't determine a more specific message, so display the generic error. 12777 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12778 } 12779 12780 enum OriginalExprKind { 12781 OEK_Variable, 12782 OEK_Member, 12783 OEK_LValue 12784 }; 12785 12786 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12787 const RecordType *Ty, 12788 SourceLocation Loc, SourceRange Range, 12789 OriginalExprKind OEK, 12790 bool &DiagnosticEmitted) { 12791 std::vector<const RecordType *> RecordTypeList; 12792 RecordTypeList.push_back(Ty); 12793 unsigned NextToCheckIndex = 0; 12794 // We walk the record hierarchy breadth-first to ensure that we print 12795 // diagnostics in field nesting order. 12796 while (RecordTypeList.size() > NextToCheckIndex) { 12797 bool IsNested = NextToCheckIndex > 0; 12798 for (const FieldDecl *Field : 12799 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12800 // First, check every field for constness. 12801 QualType FieldTy = Field->getType(); 12802 if (FieldTy.isConstQualified()) { 12803 if (!DiagnosticEmitted) { 12804 S.Diag(Loc, diag::err_typecheck_assign_const) 12805 << Range << NestedConstMember << OEK << VD 12806 << IsNested << Field; 12807 DiagnosticEmitted = true; 12808 } 12809 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12810 << NestedConstMember << IsNested << Field 12811 << FieldTy << Field->getSourceRange(); 12812 } 12813 12814 // Then we append it to the list to check next in order. 12815 FieldTy = FieldTy.getCanonicalType(); 12816 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12817 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12818 RecordTypeList.push_back(FieldRecTy); 12819 } 12820 } 12821 ++NextToCheckIndex; 12822 } 12823 } 12824 12825 /// Emit an error for the case where a record we are trying to assign to has a 12826 /// const-qualified field somewhere in its hierarchy. 12827 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12828 SourceLocation Loc) { 12829 QualType Ty = E->getType(); 12830 assert(Ty->isRecordType() && "lvalue was not record?"); 12831 SourceRange Range = E->getSourceRange(); 12832 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12833 bool DiagEmitted = false; 12834 12835 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12836 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12837 Range, OEK_Member, DiagEmitted); 12838 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12839 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12840 Range, OEK_Variable, DiagEmitted); 12841 else 12842 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12843 Range, OEK_LValue, DiagEmitted); 12844 if (!DiagEmitted) 12845 DiagnoseConstAssignment(S, E, Loc); 12846 } 12847 12848 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12849 /// emit an error and return true. If so, return false. 12850 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12851 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12852 12853 S.CheckShadowingDeclModification(E, Loc); 12854 12855 SourceLocation OrigLoc = Loc; 12856 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12857 &Loc); 12858 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12859 IsLV = Expr::MLV_InvalidMessageExpression; 12860 if (IsLV == Expr::MLV_Valid) 12861 return false; 12862 12863 unsigned DiagID = 0; 12864 bool NeedType = false; 12865 switch (IsLV) { // C99 6.5.16p2 12866 case Expr::MLV_ConstQualified: 12867 // Use a specialized diagnostic when we're assigning to an object 12868 // from an enclosing function or block. 12869 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12870 if (NCCK == NCCK_Block) 12871 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12872 else 12873 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12874 break; 12875 } 12876 12877 // In ARC, use some specialized diagnostics for occasions where we 12878 // infer 'const'. These are always pseudo-strong variables. 12879 if (S.getLangOpts().ObjCAutoRefCount) { 12880 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12881 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12882 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12883 12884 // Use the normal diagnostic if it's pseudo-__strong but the 12885 // user actually wrote 'const'. 12886 if (var->isARCPseudoStrong() && 12887 (!var->getTypeSourceInfo() || 12888 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12889 // There are three pseudo-strong cases: 12890 // - self 12891 ObjCMethodDecl *method = S.getCurMethodDecl(); 12892 if (method && var == method->getSelfDecl()) { 12893 DiagID = method->isClassMethod() 12894 ? diag::err_typecheck_arc_assign_self_class_method 12895 : diag::err_typecheck_arc_assign_self; 12896 12897 // - Objective-C externally_retained attribute. 12898 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12899 isa<ParmVarDecl>(var)) { 12900 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12901 12902 // - fast enumeration variables 12903 } else { 12904 DiagID = diag::err_typecheck_arr_assign_enumeration; 12905 } 12906 12907 SourceRange Assign; 12908 if (Loc != OrigLoc) 12909 Assign = SourceRange(OrigLoc, OrigLoc); 12910 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12911 // We need to preserve the AST regardless, so migration tool 12912 // can do its job. 12913 return false; 12914 } 12915 } 12916 } 12917 12918 // If none of the special cases above are triggered, then this is a 12919 // simple const assignment. 12920 if (DiagID == 0) { 12921 DiagnoseConstAssignment(S, E, Loc); 12922 return true; 12923 } 12924 12925 break; 12926 case Expr::MLV_ConstAddrSpace: 12927 DiagnoseConstAssignment(S, E, Loc); 12928 return true; 12929 case Expr::MLV_ConstQualifiedField: 12930 DiagnoseRecursiveConstFields(S, E, Loc); 12931 return true; 12932 case Expr::MLV_ArrayType: 12933 case Expr::MLV_ArrayTemporary: 12934 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12935 NeedType = true; 12936 break; 12937 case Expr::MLV_NotObjectType: 12938 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12939 NeedType = true; 12940 break; 12941 case Expr::MLV_LValueCast: 12942 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12943 break; 12944 case Expr::MLV_Valid: 12945 llvm_unreachable("did not take early return for MLV_Valid"); 12946 case Expr::MLV_InvalidExpression: 12947 case Expr::MLV_MemberFunction: 12948 case Expr::MLV_ClassTemporary: 12949 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12950 break; 12951 case Expr::MLV_IncompleteType: 12952 case Expr::MLV_IncompleteVoidType: 12953 return S.RequireCompleteType(Loc, E->getType(), 12954 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12955 case Expr::MLV_DuplicateVectorComponents: 12956 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12957 break; 12958 case Expr::MLV_NoSetterProperty: 12959 llvm_unreachable("readonly properties should be processed differently"); 12960 case Expr::MLV_InvalidMessageExpression: 12961 DiagID = diag::err_readonly_message_assignment; 12962 break; 12963 case Expr::MLV_SubObjCPropertySetting: 12964 DiagID = diag::err_no_subobject_property_setting; 12965 break; 12966 } 12967 12968 SourceRange Assign; 12969 if (Loc != OrigLoc) 12970 Assign = SourceRange(OrigLoc, OrigLoc); 12971 if (NeedType) 12972 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12973 else 12974 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12975 return true; 12976 } 12977 12978 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12979 SourceLocation Loc, 12980 Sema &Sema) { 12981 if (Sema.inTemplateInstantiation()) 12982 return; 12983 if (Sema.isUnevaluatedContext()) 12984 return; 12985 if (Loc.isInvalid() || Loc.isMacroID()) 12986 return; 12987 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12988 return; 12989 12990 // C / C++ fields 12991 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12992 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12993 if (ML && MR) { 12994 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12995 return; 12996 const ValueDecl *LHSDecl = 12997 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12998 const ValueDecl *RHSDecl = 12999 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13000 if (LHSDecl != RHSDecl) 13001 return; 13002 if (LHSDecl->getType().isVolatileQualified()) 13003 return; 13004 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13005 if (RefTy->getPointeeType().isVolatileQualified()) 13006 return; 13007 13008 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13009 } 13010 13011 // Objective-C instance variables 13012 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13013 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13014 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13015 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13016 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13017 if (RL && RR && RL->getDecl() == RR->getDecl()) 13018 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13019 } 13020 } 13021 13022 // C99 6.5.16.1 13023 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13024 SourceLocation Loc, 13025 QualType CompoundType) { 13026 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13027 13028 // Verify that LHS is a modifiable lvalue, and emit error if not. 13029 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13030 return QualType(); 13031 13032 QualType LHSType = LHSExpr->getType(); 13033 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13034 CompoundType; 13035 // OpenCL v1.2 s6.1.1.1 p2: 13036 // The half data type can only be used to declare a pointer to a buffer that 13037 // contains half values 13038 if (getLangOpts().OpenCL && 13039 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13040 LHSType->isHalfType()) { 13041 Diag(Loc, diag::err_opencl_half_load_store) << 1 13042 << LHSType.getUnqualifiedType(); 13043 return QualType(); 13044 } 13045 13046 AssignConvertType ConvTy; 13047 if (CompoundType.isNull()) { 13048 Expr *RHSCheck = RHS.get(); 13049 13050 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13051 13052 QualType LHSTy(LHSType); 13053 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13054 if (RHS.isInvalid()) 13055 return QualType(); 13056 // Special case of NSObject attributes on c-style pointer types. 13057 if (ConvTy == IncompatiblePointer && 13058 ((Context.isObjCNSObjectType(LHSType) && 13059 RHSType->isObjCObjectPointerType()) || 13060 (Context.isObjCNSObjectType(RHSType) && 13061 LHSType->isObjCObjectPointerType()))) 13062 ConvTy = Compatible; 13063 13064 if (ConvTy == Compatible && 13065 LHSType->isObjCObjectType()) 13066 Diag(Loc, diag::err_objc_object_assignment) 13067 << LHSType; 13068 13069 // If the RHS is a unary plus or minus, check to see if they = and + are 13070 // right next to each other. If so, the user may have typo'd "x =+ 4" 13071 // instead of "x += 4". 13072 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13073 RHSCheck = ICE->getSubExpr(); 13074 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13075 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13076 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13077 // Only if the two operators are exactly adjacent. 13078 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13079 // And there is a space or other character before the subexpr of the 13080 // unary +/-. We don't want to warn on "x=-1". 13081 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13082 UO->getSubExpr()->getBeginLoc().isFileID()) { 13083 Diag(Loc, diag::warn_not_compound_assign) 13084 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13085 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13086 } 13087 } 13088 13089 if (ConvTy == Compatible) { 13090 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13091 // Warn about retain cycles where a block captures the LHS, but 13092 // not if the LHS is a simple variable into which the block is 13093 // being stored...unless that variable can be captured by reference! 13094 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13095 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13096 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13097 checkRetainCycles(LHSExpr, RHS.get()); 13098 } 13099 13100 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13101 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13102 // It is safe to assign a weak reference into a strong variable. 13103 // Although this code can still have problems: 13104 // id x = self.weakProp; 13105 // id y = self.weakProp; 13106 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13107 // paths through the function. This should be revisited if 13108 // -Wrepeated-use-of-weak is made flow-sensitive. 13109 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13110 // variable, which will be valid for the current autorelease scope. 13111 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13112 RHS.get()->getBeginLoc())) 13113 getCurFunction()->markSafeWeakUse(RHS.get()); 13114 13115 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13116 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13117 } 13118 } 13119 } else { 13120 // Compound assignment "x += y" 13121 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13122 } 13123 13124 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13125 RHS.get(), AA_Assigning)) 13126 return QualType(); 13127 13128 CheckForNullPointerDereference(*this, LHSExpr); 13129 13130 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13131 if (CompoundType.isNull()) { 13132 // C++2a [expr.ass]p5: 13133 // A simple-assignment whose left operand is of a volatile-qualified 13134 // type is deprecated unless the assignment is either a discarded-value 13135 // expression or an unevaluated operand 13136 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13137 } else { 13138 // C++2a [expr.ass]p6: 13139 // [Compound-assignment] expressions are deprecated if E1 has 13140 // volatile-qualified type 13141 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13142 } 13143 } 13144 13145 // C99 6.5.16p3: The type of an assignment expression is the type of the 13146 // left operand unless the left operand has qualified type, in which case 13147 // it is the unqualified version of the type of the left operand. 13148 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13149 // is converted to the type of the assignment expression (above). 13150 // C++ 5.17p1: the type of the assignment expression is that of its left 13151 // operand. 13152 return (getLangOpts().CPlusPlus 13153 ? LHSType : LHSType.getUnqualifiedType()); 13154 } 13155 13156 // Only ignore explicit casts to void. 13157 static bool IgnoreCommaOperand(const Expr *E) { 13158 E = E->IgnoreParens(); 13159 13160 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13161 if (CE->getCastKind() == CK_ToVoid) { 13162 return true; 13163 } 13164 13165 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13166 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13167 CE->getSubExpr()->getType()->isDependentType()) { 13168 return true; 13169 } 13170 } 13171 13172 return false; 13173 } 13174 13175 // Look for instances where it is likely the comma operator is confused with 13176 // another operator. There is an explicit list of acceptable expressions for 13177 // the left hand side of the comma operator, otherwise emit a warning. 13178 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13179 // No warnings in macros 13180 if (Loc.isMacroID()) 13181 return; 13182 13183 // Don't warn in template instantiations. 13184 if (inTemplateInstantiation()) 13185 return; 13186 13187 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13188 // instead, skip more than needed, then call back into here with the 13189 // CommaVisitor in SemaStmt.cpp. 13190 // The listed locations are the initialization and increment portions 13191 // of a for loop. The additional checks are on the condition of 13192 // if statements, do/while loops, and for loops. 13193 // Differences in scope flags for C89 mode requires the extra logic. 13194 const unsigned ForIncrementFlags = 13195 getLangOpts().C99 || getLangOpts().CPlusPlus 13196 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13197 : Scope::ContinueScope | Scope::BreakScope; 13198 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13199 const unsigned ScopeFlags = getCurScope()->getFlags(); 13200 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13201 (ScopeFlags & ForInitFlags) == ForInitFlags) 13202 return; 13203 13204 // If there are multiple comma operators used together, get the RHS of the 13205 // of the comma operator as the LHS. 13206 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13207 if (BO->getOpcode() != BO_Comma) 13208 break; 13209 LHS = BO->getRHS(); 13210 } 13211 13212 // Only allow some expressions on LHS to not warn. 13213 if (IgnoreCommaOperand(LHS)) 13214 return; 13215 13216 Diag(Loc, diag::warn_comma_operator); 13217 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13218 << LHS->getSourceRange() 13219 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13220 LangOpts.CPlusPlus ? "static_cast<void>(" 13221 : "(void)(") 13222 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13223 ")"); 13224 } 13225 13226 // C99 6.5.17 13227 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13228 SourceLocation Loc) { 13229 LHS = S.CheckPlaceholderExpr(LHS.get()); 13230 RHS = S.CheckPlaceholderExpr(RHS.get()); 13231 if (LHS.isInvalid() || RHS.isInvalid()) 13232 return QualType(); 13233 13234 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13235 // operands, but not unary promotions. 13236 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13237 13238 // So we treat the LHS as a ignored value, and in C++ we allow the 13239 // containing site to determine what should be done with the RHS. 13240 LHS = S.IgnoredValueConversions(LHS.get()); 13241 if (LHS.isInvalid()) 13242 return QualType(); 13243 13244 S.DiagnoseUnusedExprResult(LHS.get()); 13245 13246 if (!S.getLangOpts().CPlusPlus) { 13247 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13248 if (RHS.isInvalid()) 13249 return QualType(); 13250 if (!RHS.get()->getType()->isVoidType()) 13251 S.RequireCompleteType(Loc, RHS.get()->getType(), 13252 diag::err_incomplete_type); 13253 } 13254 13255 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13256 S.DiagnoseCommaOperator(LHS.get(), Loc); 13257 13258 return RHS.get()->getType(); 13259 } 13260 13261 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13262 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13263 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13264 ExprValueKind &VK, 13265 ExprObjectKind &OK, 13266 SourceLocation OpLoc, 13267 bool IsInc, bool IsPrefix) { 13268 if (Op->isTypeDependent()) 13269 return S.Context.DependentTy; 13270 13271 QualType ResType = Op->getType(); 13272 // Atomic types can be used for increment / decrement where the non-atomic 13273 // versions can, so ignore the _Atomic() specifier for the purpose of 13274 // checking. 13275 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13276 ResType = ResAtomicType->getValueType(); 13277 13278 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13279 13280 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13281 // Decrement of bool is not allowed. 13282 if (!IsInc) { 13283 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13284 return QualType(); 13285 } 13286 // Increment of bool sets it to true, but is deprecated. 13287 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13288 : diag::warn_increment_bool) 13289 << Op->getSourceRange(); 13290 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13291 // Error on enum increments and decrements in C++ mode 13292 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13293 return QualType(); 13294 } else if (ResType->isRealType()) { 13295 // OK! 13296 } else if (ResType->isPointerType()) { 13297 // C99 6.5.2.4p2, 6.5.6p2 13298 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13299 return QualType(); 13300 } else if (ResType->isObjCObjectPointerType()) { 13301 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13302 // Otherwise, we just need a complete type. 13303 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13304 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13305 return QualType(); 13306 } else if (ResType->isAnyComplexType()) { 13307 // C99 does not support ++/-- on complex types, we allow as an extension. 13308 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13309 << ResType << Op->getSourceRange(); 13310 } else if (ResType->isPlaceholderType()) { 13311 ExprResult PR = S.CheckPlaceholderExpr(Op); 13312 if (PR.isInvalid()) return QualType(); 13313 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13314 IsInc, IsPrefix); 13315 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13316 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13317 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13318 (ResType->castAs<VectorType>()->getVectorKind() != 13319 VectorType::AltiVecBool)) { 13320 // The z vector extensions allow ++ and -- for non-bool vectors. 13321 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13322 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13323 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13324 } else { 13325 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13326 << ResType << int(IsInc) << Op->getSourceRange(); 13327 return QualType(); 13328 } 13329 // At this point, we know we have a real, complex or pointer type. 13330 // Now make sure the operand is a modifiable lvalue. 13331 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13332 return QualType(); 13333 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13334 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13335 // An operand with volatile-qualified type is deprecated 13336 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13337 << IsInc << ResType; 13338 } 13339 // In C++, a prefix increment is the same type as the operand. Otherwise 13340 // (in C or with postfix), the increment is the unqualified type of the 13341 // operand. 13342 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13343 VK = VK_LValue; 13344 OK = Op->getObjectKind(); 13345 return ResType; 13346 } else { 13347 VK = VK_RValue; 13348 return ResType.getUnqualifiedType(); 13349 } 13350 } 13351 13352 13353 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13354 /// This routine allows us to typecheck complex/recursive expressions 13355 /// where the declaration is needed for type checking. We only need to 13356 /// handle cases when the expression references a function designator 13357 /// or is an lvalue. Here are some examples: 13358 /// - &(x) => x 13359 /// - &*****f => f for f a function designator. 13360 /// - &s.xx => s 13361 /// - &s.zz[1].yy -> s, if zz is an array 13362 /// - *(x + 1) -> x, if x is an array 13363 /// - &"123"[2] -> 0 13364 /// - & __real__ x -> x 13365 /// 13366 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13367 /// members. 13368 static ValueDecl *getPrimaryDecl(Expr *E) { 13369 switch (E->getStmtClass()) { 13370 case Stmt::DeclRefExprClass: 13371 return cast<DeclRefExpr>(E)->getDecl(); 13372 case Stmt::MemberExprClass: 13373 // If this is an arrow operator, the address is an offset from 13374 // the base's value, so the object the base refers to is 13375 // irrelevant. 13376 if (cast<MemberExpr>(E)->isArrow()) 13377 return nullptr; 13378 // Otherwise, the expression refers to a part of the base 13379 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13380 case Stmt::ArraySubscriptExprClass: { 13381 // FIXME: This code shouldn't be necessary! We should catch the implicit 13382 // promotion of register arrays earlier. 13383 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13384 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13385 if (ICE->getSubExpr()->getType()->isArrayType()) 13386 return getPrimaryDecl(ICE->getSubExpr()); 13387 } 13388 return nullptr; 13389 } 13390 case Stmt::UnaryOperatorClass: { 13391 UnaryOperator *UO = cast<UnaryOperator>(E); 13392 13393 switch(UO->getOpcode()) { 13394 case UO_Real: 13395 case UO_Imag: 13396 case UO_Extension: 13397 return getPrimaryDecl(UO->getSubExpr()); 13398 default: 13399 return nullptr; 13400 } 13401 } 13402 case Stmt::ParenExprClass: 13403 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13404 case Stmt::ImplicitCastExprClass: 13405 // If the result of an implicit cast is an l-value, we care about 13406 // the sub-expression; otherwise, the result here doesn't matter. 13407 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13408 case Stmt::CXXUuidofExprClass: 13409 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13410 default: 13411 return nullptr; 13412 } 13413 } 13414 13415 namespace { 13416 enum { 13417 AO_Bit_Field = 0, 13418 AO_Vector_Element = 1, 13419 AO_Property_Expansion = 2, 13420 AO_Register_Variable = 3, 13421 AO_Matrix_Element = 4, 13422 AO_No_Error = 5 13423 }; 13424 } 13425 /// Diagnose invalid operand for address of operations. 13426 /// 13427 /// \param Type The type of operand which cannot have its address taken. 13428 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13429 Expr *E, unsigned Type) { 13430 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13431 } 13432 13433 /// CheckAddressOfOperand - The operand of & must be either a function 13434 /// designator or an lvalue designating an object. If it is an lvalue, the 13435 /// object cannot be declared with storage class register or be a bit field. 13436 /// Note: The usual conversions are *not* applied to the operand of the & 13437 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13438 /// In C++, the operand might be an overloaded function name, in which case 13439 /// we allow the '&' but retain the overloaded-function type. 13440 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13441 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13442 if (PTy->getKind() == BuiltinType::Overload) { 13443 Expr *E = OrigOp.get()->IgnoreParens(); 13444 if (!isa<OverloadExpr>(E)) { 13445 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13446 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13447 << OrigOp.get()->getSourceRange(); 13448 return QualType(); 13449 } 13450 13451 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13452 if (isa<UnresolvedMemberExpr>(Ovl)) 13453 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13454 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13455 << OrigOp.get()->getSourceRange(); 13456 return QualType(); 13457 } 13458 13459 return Context.OverloadTy; 13460 } 13461 13462 if (PTy->getKind() == BuiltinType::UnknownAny) 13463 return Context.UnknownAnyTy; 13464 13465 if (PTy->getKind() == BuiltinType::BoundMember) { 13466 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13467 << OrigOp.get()->getSourceRange(); 13468 return QualType(); 13469 } 13470 13471 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13472 if (OrigOp.isInvalid()) return QualType(); 13473 } 13474 13475 if (OrigOp.get()->isTypeDependent()) 13476 return Context.DependentTy; 13477 13478 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13479 13480 // Make sure to ignore parentheses in subsequent checks 13481 Expr *op = OrigOp.get()->IgnoreParens(); 13482 13483 // In OpenCL captures for blocks called as lambda functions 13484 // are located in the private address space. Blocks used in 13485 // enqueue_kernel can be located in a different address space 13486 // depending on a vendor implementation. Thus preventing 13487 // taking an address of the capture to avoid invalid AS casts. 13488 if (LangOpts.OpenCL) { 13489 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13490 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13491 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13492 return QualType(); 13493 } 13494 } 13495 13496 if (getLangOpts().C99) { 13497 // Implement C99-only parts of addressof rules. 13498 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13499 if (uOp->getOpcode() == UO_Deref) 13500 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13501 // (assuming the deref expression is valid). 13502 return uOp->getSubExpr()->getType(); 13503 } 13504 // Technically, there should be a check for array subscript 13505 // expressions here, but the result of one is always an lvalue anyway. 13506 } 13507 ValueDecl *dcl = getPrimaryDecl(op); 13508 13509 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13510 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13511 op->getBeginLoc())) 13512 return QualType(); 13513 13514 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13515 unsigned AddressOfError = AO_No_Error; 13516 13517 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13518 bool sfinae = (bool)isSFINAEContext(); 13519 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13520 : diag::ext_typecheck_addrof_temporary) 13521 << op->getType() << op->getSourceRange(); 13522 if (sfinae) 13523 return QualType(); 13524 // Materialize the temporary as an lvalue so that we can take its address. 13525 OrigOp = op = 13526 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13527 } else if (isa<ObjCSelectorExpr>(op)) { 13528 return Context.getPointerType(op->getType()); 13529 } else if (lval == Expr::LV_MemberFunction) { 13530 // If it's an instance method, make a member pointer. 13531 // The expression must have exactly the form &A::foo. 13532 13533 // If the underlying expression isn't a decl ref, give up. 13534 if (!isa<DeclRefExpr>(op)) { 13535 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13536 << OrigOp.get()->getSourceRange(); 13537 return QualType(); 13538 } 13539 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13540 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13541 13542 // The id-expression was parenthesized. 13543 if (OrigOp.get() != DRE) { 13544 Diag(OpLoc, diag::err_parens_pointer_member_function) 13545 << OrigOp.get()->getSourceRange(); 13546 13547 // The method was named without a qualifier. 13548 } else if (!DRE->getQualifier()) { 13549 if (MD->getParent()->getName().empty()) 13550 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13551 << op->getSourceRange(); 13552 else { 13553 SmallString<32> Str; 13554 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13555 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13556 << op->getSourceRange() 13557 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13558 } 13559 } 13560 13561 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13562 if (isa<CXXDestructorDecl>(MD)) 13563 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13564 13565 QualType MPTy = Context.getMemberPointerType( 13566 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13567 // Under the MS ABI, lock down the inheritance model now. 13568 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13569 (void)isCompleteType(OpLoc, MPTy); 13570 return MPTy; 13571 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13572 // C99 6.5.3.2p1 13573 // The operand must be either an l-value or a function designator 13574 if (!op->getType()->isFunctionType()) { 13575 // Use a special diagnostic for loads from property references. 13576 if (isa<PseudoObjectExpr>(op)) { 13577 AddressOfError = AO_Property_Expansion; 13578 } else { 13579 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13580 << op->getType() << op->getSourceRange(); 13581 return QualType(); 13582 } 13583 } 13584 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13585 // The operand cannot be a bit-field 13586 AddressOfError = AO_Bit_Field; 13587 } else if (op->getObjectKind() == OK_VectorComponent) { 13588 // The operand cannot be an element of a vector 13589 AddressOfError = AO_Vector_Element; 13590 } else if (op->getObjectKind() == OK_MatrixComponent) { 13591 // The operand cannot be an element of a matrix. 13592 AddressOfError = AO_Matrix_Element; 13593 } else if (dcl) { // C99 6.5.3.2p1 13594 // We have an lvalue with a decl. Make sure the decl is not declared 13595 // with the register storage-class specifier. 13596 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13597 // in C++ it is not error to take address of a register 13598 // variable (c++03 7.1.1P3) 13599 if (vd->getStorageClass() == SC_Register && 13600 !getLangOpts().CPlusPlus) { 13601 AddressOfError = AO_Register_Variable; 13602 } 13603 } else if (isa<MSPropertyDecl>(dcl)) { 13604 AddressOfError = AO_Property_Expansion; 13605 } else if (isa<FunctionTemplateDecl>(dcl)) { 13606 return Context.OverloadTy; 13607 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13608 // Okay: we can take the address of a field. 13609 // Could be a pointer to member, though, if there is an explicit 13610 // scope qualifier for the class. 13611 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13612 DeclContext *Ctx = dcl->getDeclContext(); 13613 if (Ctx && Ctx->isRecord()) { 13614 if (dcl->getType()->isReferenceType()) { 13615 Diag(OpLoc, 13616 diag::err_cannot_form_pointer_to_member_of_reference_type) 13617 << dcl->getDeclName() << dcl->getType(); 13618 return QualType(); 13619 } 13620 13621 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13622 Ctx = Ctx->getParent(); 13623 13624 QualType MPTy = Context.getMemberPointerType( 13625 op->getType(), 13626 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13627 // Under the MS ABI, lock down the inheritance model now. 13628 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13629 (void)isCompleteType(OpLoc, MPTy); 13630 return MPTy; 13631 } 13632 } 13633 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13634 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13635 llvm_unreachable("Unknown/unexpected decl type"); 13636 } 13637 13638 if (AddressOfError != AO_No_Error) { 13639 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13640 return QualType(); 13641 } 13642 13643 if (lval == Expr::LV_IncompleteVoidType) { 13644 // Taking the address of a void variable is technically illegal, but we 13645 // allow it in cases which are otherwise valid. 13646 // Example: "extern void x; void* y = &x;". 13647 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13648 } 13649 13650 // If the operand has type "type", the result has type "pointer to type". 13651 if (op->getType()->isObjCObjectType()) 13652 return Context.getObjCObjectPointerType(op->getType()); 13653 13654 CheckAddressOfPackedMember(op); 13655 13656 return Context.getPointerType(op->getType()); 13657 } 13658 13659 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13660 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13661 if (!DRE) 13662 return; 13663 const Decl *D = DRE->getDecl(); 13664 if (!D) 13665 return; 13666 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13667 if (!Param) 13668 return; 13669 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13670 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13671 return; 13672 if (FunctionScopeInfo *FD = S.getCurFunction()) 13673 if (!FD->ModifiedNonNullParams.count(Param)) 13674 FD->ModifiedNonNullParams.insert(Param); 13675 } 13676 13677 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13678 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13679 SourceLocation OpLoc) { 13680 if (Op->isTypeDependent()) 13681 return S.Context.DependentTy; 13682 13683 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13684 if (ConvResult.isInvalid()) 13685 return QualType(); 13686 Op = ConvResult.get(); 13687 QualType OpTy = Op->getType(); 13688 QualType Result; 13689 13690 if (isa<CXXReinterpretCastExpr>(Op)) { 13691 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13692 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13693 Op->getSourceRange()); 13694 } 13695 13696 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13697 { 13698 Result = PT->getPointeeType(); 13699 } 13700 else if (const ObjCObjectPointerType *OPT = 13701 OpTy->getAs<ObjCObjectPointerType>()) 13702 Result = OPT->getPointeeType(); 13703 else { 13704 ExprResult PR = S.CheckPlaceholderExpr(Op); 13705 if (PR.isInvalid()) return QualType(); 13706 if (PR.get() != Op) 13707 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13708 } 13709 13710 if (Result.isNull()) { 13711 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13712 << OpTy << Op->getSourceRange(); 13713 return QualType(); 13714 } 13715 13716 // Note that per both C89 and C99, indirection is always legal, even if Result 13717 // is an incomplete type or void. It would be possible to warn about 13718 // dereferencing a void pointer, but it's completely well-defined, and such a 13719 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13720 // for pointers to 'void' but is fine for any other pointer type: 13721 // 13722 // C++ [expr.unary.op]p1: 13723 // [...] the expression to which [the unary * operator] is applied shall 13724 // be a pointer to an object type, or a pointer to a function type 13725 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13726 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13727 << OpTy << Op->getSourceRange(); 13728 13729 // Dereferences are usually l-values... 13730 VK = VK_LValue; 13731 13732 // ...except that certain expressions are never l-values in C. 13733 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13734 VK = VK_RValue; 13735 13736 return Result; 13737 } 13738 13739 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13740 BinaryOperatorKind Opc; 13741 switch (Kind) { 13742 default: llvm_unreachable("Unknown binop!"); 13743 case tok::periodstar: Opc = BO_PtrMemD; break; 13744 case tok::arrowstar: Opc = BO_PtrMemI; break; 13745 case tok::star: Opc = BO_Mul; break; 13746 case tok::slash: Opc = BO_Div; break; 13747 case tok::percent: Opc = BO_Rem; break; 13748 case tok::plus: Opc = BO_Add; break; 13749 case tok::minus: Opc = BO_Sub; break; 13750 case tok::lessless: Opc = BO_Shl; break; 13751 case tok::greatergreater: Opc = BO_Shr; break; 13752 case tok::lessequal: Opc = BO_LE; break; 13753 case tok::less: Opc = BO_LT; break; 13754 case tok::greaterequal: Opc = BO_GE; break; 13755 case tok::greater: Opc = BO_GT; break; 13756 case tok::exclaimequal: Opc = BO_NE; break; 13757 case tok::equalequal: Opc = BO_EQ; break; 13758 case tok::spaceship: Opc = BO_Cmp; break; 13759 case tok::amp: Opc = BO_And; break; 13760 case tok::caret: Opc = BO_Xor; break; 13761 case tok::pipe: Opc = BO_Or; break; 13762 case tok::ampamp: Opc = BO_LAnd; break; 13763 case tok::pipepipe: Opc = BO_LOr; break; 13764 case tok::equal: Opc = BO_Assign; break; 13765 case tok::starequal: Opc = BO_MulAssign; break; 13766 case tok::slashequal: Opc = BO_DivAssign; break; 13767 case tok::percentequal: Opc = BO_RemAssign; break; 13768 case tok::plusequal: Opc = BO_AddAssign; break; 13769 case tok::minusequal: Opc = BO_SubAssign; break; 13770 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13771 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13772 case tok::ampequal: Opc = BO_AndAssign; break; 13773 case tok::caretequal: Opc = BO_XorAssign; break; 13774 case tok::pipeequal: Opc = BO_OrAssign; break; 13775 case tok::comma: Opc = BO_Comma; break; 13776 } 13777 return Opc; 13778 } 13779 13780 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13781 tok::TokenKind Kind) { 13782 UnaryOperatorKind Opc; 13783 switch (Kind) { 13784 default: llvm_unreachable("Unknown unary op!"); 13785 case tok::plusplus: Opc = UO_PreInc; break; 13786 case tok::minusminus: Opc = UO_PreDec; break; 13787 case tok::amp: Opc = UO_AddrOf; break; 13788 case tok::star: Opc = UO_Deref; break; 13789 case tok::plus: Opc = UO_Plus; break; 13790 case tok::minus: Opc = UO_Minus; break; 13791 case tok::tilde: Opc = UO_Not; break; 13792 case tok::exclaim: Opc = UO_LNot; break; 13793 case tok::kw___real: Opc = UO_Real; break; 13794 case tok::kw___imag: Opc = UO_Imag; break; 13795 case tok::kw___extension__: Opc = UO_Extension; break; 13796 } 13797 return Opc; 13798 } 13799 13800 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13801 /// This warning suppressed in the event of macro expansions. 13802 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13803 SourceLocation OpLoc, bool IsBuiltin) { 13804 if (S.inTemplateInstantiation()) 13805 return; 13806 if (S.isUnevaluatedContext()) 13807 return; 13808 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13809 return; 13810 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13811 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13812 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13813 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13814 if (!LHSDeclRef || !RHSDeclRef || 13815 LHSDeclRef->getLocation().isMacroID() || 13816 RHSDeclRef->getLocation().isMacroID()) 13817 return; 13818 const ValueDecl *LHSDecl = 13819 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13820 const ValueDecl *RHSDecl = 13821 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13822 if (LHSDecl != RHSDecl) 13823 return; 13824 if (LHSDecl->getType().isVolatileQualified()) 13825 return; 13826 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13827 if (RefTy->getPointeeType().isVolatileQualified()) 13828 return; 13829 13830 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13831 : diag::warn_self_assignment_overloaded) 13832 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13833 << RHSExpr->getSourceRange(); 13834 } 13835 13836 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13837 /// is usually indicative of introspection within the Objective-C pointer. 13838 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13839 SourceLocation OpLoc) { 13840 if (!S.getLangOpts().ObjC) 13841 return; 13842 13843 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13844 const Expr *LHS = L.get(); 13845 const Expr *RHS = R.get(); 13846 13847 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13848 ObjCPointerExpr = LHS; 13849 OtherExpr = RHS; 13850 } 13851 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13852 ObjCPointerExpr = RHS; 13853 OtherExpr = LHS; 13854 } 13855 13856 // This warning is deliberately made very specific to reduce false 13857 // positives with logic that uses '&' for hashing. This logic mainly 13858 // looks for code trying to introspect into tagged pointers, which 13859 // code should generally never do. 13860 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13861 unsigned Diag = diag::warn_objc_pointer_masking; 13862 // Determine if we are introspecting the result of performSelectorXXX. 13863 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13864 // Special case messages to -performSelector and friends, which 13865 // can return non-pointer values boxed in a pointer value. 13866 // Some clients may wish to silence warnings in this subcase. 13867 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13868 Selector S = ME->getSelector(); 13869 StringRef SelArg0 = S.getNameForSlot(0); 13870 if (SelArg0.startswith("performSelector")) 13871 Diag = diag::warn_objc_pointer_masking_performSelector; 13872 } 13873 13874 S.Diag(OpLoc, Diag) 13875 << ObjCPointerExpr->getSourceRange(); 13876 } 13877 } 13878 13879 static NamedDecl *getDeclFromExpr(Expr *E) { 13880 if (!E) 13881 return nullptr; 13882 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13883 return DRE->getDecl(); 13884 if (auto *ME = dyn_cast<MemberExpr>(E)) 13885 return ME->getMemberDecl(); 13886 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13887 return IRE->getDecl(); 13888 return nullptr; 13889 } 13890 13891 // This helper function promotes a binary operator's operands (which are of a 13892 // half vector type) to a vector of floats and then truncates the result to 13893 // a vector of either half or short. 13894 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13895 BinaryOperatorKind Opc, QualType ResultTy, 13896 ExprValueKind VK, ExprObjectKind OK, 13897 bool IsCompAssign, SourceLocation OpLoc, 13898 FPOptionsOverride FPFeatures) { 13899 auto &Context = S.getASTContext(); 13900 assert((isVector(ResultTy, Context.HalfTy) || 13901 isVector(ResultTy, Context.ShortTy)) && 13902 "Result must be a vector of half or short"); 13903 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13904 isVector(RHS.get()->getType(), Context.HalfTy) && 13905 "both operands expected to be a half vector"); 13906 13907 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13908 QualType BinOpResTy = RHS.get()->getType(); 13909 13910 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13911 // change BinOpResTy to a vector of ints. 13912 if (isVector(ResultTy, Context.ShortTy)) 13913 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13914 13915 if (IsCompAssign) 13916 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13917 ResultTy, VK, OK, OpLoc, FPFeatures, 13918 BinOpResTy, BinOpResTy); 13919 13920 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13921 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13922 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13923 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13924 } 13925 13926 static std::pair<ExprResult, ExprResult> 13927 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13928 Expr *RHSExpr) { 13929 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13930 if (!S.Context.isDependenceAllowed()) { 13931 // C cannot handle TypoExpr nodes on either side of a binop because it 13932 // doesn't handle dependent types properly, so make sure any TypoExprs have 13933 // been dealt with before checking the operands. 13934 LHS = S.CorrectDelayedTyposInExpr(LHS); 13935 RHS = S.CorrectDelayedTyposInExpr( 13936 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13937 [Opc, LHS](Expr *E) { 13938 if (Opc != BO_Assign) 13939 return ExprResult(E); 13940 // Avoid correcting the RHS to the same Expr as the LHS. 13941 Decl *D = getDeclFromExpr(E); 13942 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13943 }); 13944 } 13945 return std::make_pair(LHS, RHS); 13946 } 13947 13948 /// Returns true if conversion between vectors of halfs and vectors of floats 13949 /// is needed. 13950 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13951 Expr *E0, Expr *E1 = nullptr) { 13952 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13953 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13954 return false; 13955 13956 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13957 QualType Ty = E->IgnoreImplicit()->getType(); 13958 13959 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13960 // to vectors of floats. Although the element type of the vectors is __fp16, 13961 // the vectors shouldn't be treated as storage-only types. See the 13962 // discussion here: https://reviews.llvm.org/rG825235c140e7 13963 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13964 if (VT->getVectorKind() == VectorType::NeonVector) 13965 return false; 13966 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13967 } 13968 return false; 13969 }; 13970 13971 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13972 } 13973 13974 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13975 /// operator @p Opc at location @c TokLoc. This routine only supports 13976 /// built-in operations; ActOnBinOp handles overloaded operators. 13977 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13978 BinaryOperatorKind Opc, 13979 Expr *LHSExpr, Expr *RHSExpr) { 13980 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13981 // The syntax only allows initializer lists on the RHS of assignment, 13982 // so we don't need to worry about accepting invalid code for 13983 // non-assignment operators. 13984 // C++11 5.17p9: 13985 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13986 // of x = {} is x = T(). 13987 InitializationKind Kind = InitializationKind::CreateDirectList( 13988 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13989 InitializedEntity Entity = 13990 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13991 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13992 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13993 if (Init.isInvalid()) 13994 return Init; 13995 RHSExpr = Init.get(); 13996 } 13997 13998 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13999 QualType ResultTy; // Result type of the binary operator. 14000 // The following two variables are used for compound assignment operators 14001 QualType CompLHSTy; // Type of LHS after promotions for computation 14002 QualType CompResultTy; // Type of computation result 14003 ExprValueKind VK = VK_RValue; 14004 ExprObjectKind OK = OK_Ordinary; 14005 bool ConvertHalfVec = false; 14006 14007 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14008 if (!LHS.isUsable() || !RHS.isUsable()) 14009 return ExprError(); 14010 14011 if (getLangOpts().OpenCL) { 14012 QualType LHSTy = LHSExpr->getType(); 14013 QualType RHSTy = RHSExpr->getType(); 14014 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14015 // the ATOMIC_VAR_INIT macro. 14016 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14017 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14018 if (BO_Assign == Opc) 14019 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14020 else 14021 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14022 return ExprError(); 14023 } 14024 14025 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14026 // only with a builtin functions and therefore should be disallowed here. 14027 if (LHSTy->isImageType() || RHSTy->isImageType() || 14028 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14029 LHSTy->isPipeType() || RHSTy->isPipeType() || 14030 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14031 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14032 return ExprError(); 14033 } 14034 } 14035 14036 switch (Opc) { 14037 case BO_Assign: 14038 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14039 if (getLangOpts().CPlusPlus && 14040 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14041 VK = LHS.get()->getValueKind(); 14042 OK = LHS.get()->getObjectKind(); 14043 } 14044 if (!ResultTy.isNull()) { 14045 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14046 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14047 14048 // Avoid copying a block to the heap if the block is assigned to a local 14049 // auto variable that is declared in the same scope as the block. This 14050 // optimization is unsafe if the local variable is declared in an outer 14051 // scope. For example: 14052 // 14053 // BlockTy b; 14054 // { 14055 // b = ^{...}; 14056 // } 14057 // // It is unsafe to invoke the block here if it wasn't copied to the 14058 // // heap. 14059 // b(); 14060 14061 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14062 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14063 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14064 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14065 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14066 14067 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14068 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14069 NTCUC_Assignment, NTCUK_Copy); 14070 } 14071 RecordModifiableNonNullParam(*this, LHS.get()); 14072 break; 14073 case BO_PtrMemD: 14074 case BO_PtrMemI: 14075 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14076 Opc == BO_PtrMemI); 14077 break; 14078 case BO_Mul: 14079 case BO_Div: 14080 ConvertHalfVec = true; 14081 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14082 Opc == BO_Div); 14083 break; 14084 case BO_Rem: 14085 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14086 break; 14087 case BO_Add: 14088 ConvertHalfVec = true; 14089 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14090 break; 14091 case BO_Sub: 14092 ConvertHalfVec = true; 14093 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14094 break; 14095 case BO_Shl: 14096 case BO_Shr: 14097 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14098 break; 14099 case BO_LE: 14100 case BO_LT: 14101 case BO_GE: 14102 case BO_GT: 14103 ConvertHalfVec = true; 14104 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14105 break; 14106 case BO_EQ: 14107 case BO_NE: 14108 ConvertHalfVec = true; 14109 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14110 break; 14111 case BO_Cmp: 14112 ConvertHalfVec = true; 14113 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14114 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14115 break; 14116 case BO_And: 14117 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14118 LLVM_FALLTHROUGH; 14119 case BO_Xor: 14120 case BO_Or: 14121 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14122 break; 14123 case BO_LAnd: 14124 case BO_LOr: 14125 ConvertHalfVec = true; 14126 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14127 break; 14128 case BO_MulAssign: 14129 case BO_DivAssign: 14130 ConvertHalfVec = true; 14131 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14132 Opc == BO_DivAssign); 14133 CompLHSTy = CompResultTy; 14134 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14135 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14136 break; 14137 case BO_RemAssign: 14138 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14139 CompLHSTy = CompResultTy; 14140 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14141 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14142 break; 14143 case BO_AddAssign: 14144 ConvertHalfVec = true; 14145 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14146 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14147 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14148 break; 14149 case BO_SubAssign: 14150 ConvertHalfVec = true; 14151 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14152 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14153 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14154 break; 14155 case BO_ShlAssign: 14156 case BO_ShrAssign: 14157 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14158 CompLHSTy = CompResultTy; 14159 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14160 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14161 break; 14162 case BO_AndAssign: 14163 case BO_OrAssign: // fallthrough 14164 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14165 LLVM_FALLTHROUGH; 14166 case BO_XorAssign: 14167 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14168 CompLHSTy = CompResultTy; 14169 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14170 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14171 break; 14172 case BO_Comma: 14173 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14174 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14175 VK = RHS.get()->getValueKind(); 14176 OK = RHS.get()->getObjectKind(); 14177 } 14178 break; 14179 } 14180 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14181 return ExprError(); 14182 14183 // Some of the binary operations require promoting operands of half vector to 14184 // float vectors and truncating the result back to half vector. For now, we do 14185 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14186 // arm64). 14187 assert( 14188 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14189 isVector(LHS.get()->getType(), Context.HalfTy)) && 14190 "both sides are half vectors or neither sides are"); 14191 ConvertHalfVec = 14192 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14193 14194 // Check for array bounds violations for both sides of the BinaryOperator 14195 CheckArrayAccess(LHS.get()); 14196 CheckArrayAccess(RHS.get()); 14197 14198 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14199 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14200 &Context.Idents.get("object_setClass"), 14201 SourceLocation(), LookupOrdinaryName); 14202 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14203 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14204 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14205 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14206 "object_setClass(") 14207 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14208 ",") 14209 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14210 } 14211 else 14212 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14213 } 14214 else if (const ObjCIvarRefExpr *OIRE = 14215 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14216 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14217 14218 // Opc is not a compound assignment if CompResultTy is null. 14219 if (CompResultTy.isNull()) { 14220 if (ConvertHalfVec) 14221 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14222 OpLoc, CurFPFeatureOverrides()); 14223 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14224 VK, OK, OpLoc, CurFPFeatureOverrides()); 14225 } 14226 14227 // Handle compound assignments. 14228 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14229 OK_ObjCProperty) { 14230 VK = VK_LValue; 14231 OK = LHS.get()->getObjectKind(); 14232 } 14233 14234 // The LHS is not converted to the result type for fixed-point compound 14235 // assignment as the common type is computed on demand. Reset the CompLHSTy 14236 // to the LHS type we would have gotten after unary conversions. 14237 if (CompResultTy->isFixedPointType()) 14238 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14239 14240 if (ConvertHalfVec) 14241 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14242 OpLoc, CurFPFeatureOverrides()); 14243 14244 return CompoundAssignOperator::Create( 14245 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14246 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14247 } 14248 14249 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14250 /// operators are mixed in a way that suggests that the programmer forgot that 14251 /// comparison operators have higher precedence. The most typical example of 14252 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14253 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14254 SourceLocation OpLoc, Expr *LHSExpr, 14255 Expr *RHSExpr) { 14256 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14257 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14258 14259 // Check that one of the sides is a comparison operator and the other isn't. 14260 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14261 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14262 if (isLeftComp == isRightComp) 14263 return; 14264 14265 // Bitwise operations are sometimes used as eager logical ops. 14266 // Don't diagnose this. 14267 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14268 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14269 if (isLeftBitwise || isRightBitwise) 14270 return; 14271 14272 SourceRange DiagRange = isLeftComp 14273 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14274 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14275 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14276 SourceRange ParensRange = 14277 isLeftComp 14278 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14279 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14280 14281 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14282 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14283 SuggestParentheses(Self, OpLoc, 14284 Self.PDiag(diag::note_precedence_silence) << OpStr, 14285 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14286 SuggestParentheses(Self, OpLoc, 14287 Self.PDiag(diag::note_precedence_bitwise_first) 14288 << BinaryOperator::getOpcodeStr(Opc), 14289 ParensRange); 14290 } 14291 14292 /// It accepts a '&&' expr that is inside a '||' one. 14293 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14294 /// in parentheses. 14295 static void 14296 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14297 BinaryOperator *Bop) { 14298 assert(Bop->getOpcode() == BO_LAnd); 14299 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14300 << Bop->getSourceRange() << OpLoc; 14301 SuggestParentheses(Self, Bop->getOperatorLoc(), 14302 Self.PDiag(diag::note_precedence_silence) 14303 << Bop->getOpcodeStr(), 14304 Bop->getSourceRange()); 14305 } 14306 14307 /// Returns true if the given expression can be evaluated as a constant 14308 /// 'true'. 14309 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14310 bool Res; 14311 return !E->isValueDependent() && 14312 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14313 } 14314 14315 /// Returns true if the given expression can be evaluated as a constant 14316 /// 'false'. 14317 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14318 bool Res; 14319 return !E->isValueDependent() && 14320 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14321 } 14322 14323 /// Look for '&&' in the left hand of a '||' expr. 14324 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14325 Expr *LHSExpr, Expr *RHSExpr) { 14326 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14327 if (Bop->getOpcode() == BO_LAnd) { 14328 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14329 if (EvaluatesAsFalse(S, RHSExpr)) 14330 return; 14331 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14332 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14333 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14334 } else if (Bop->getOpcode() == BO_LOr) { 14335 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14336 // If it's "a || b && 1 || c" we didn't warn earlier for 14337 // "a || b && 1", but warn now. 14338 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14339 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14340 } 14341 } 14342 } 14343 } 14344 14345 /// Look for '&&' in the right hand of a '||' expr. 14346 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14347 Expr *LHSExpr, Expr *RHSExpr) { 14348 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14349 if (Bop->getOpcode() == BO_LAnd) { 14350 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14351 if (EvaluatesAsFalse(S, LHSExpr)) 14352 return; 14353 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14354 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14355 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14356 } 14357 } 14358 } 14359 14360 /// Look for bitwise op in the left or right hand of a bitwise op with 14361 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14362 /// the '&' expression in parentheses. 14363 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14364 SourceLocation OpLoc, Expr *SubExpr) { 14365 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14366 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14367 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14368 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14369 << Bop->getSourceRange() << OpLoc; 14370 SuggestParentheses(S, Bop->getOperatorLoc(), 14371 S.PDiag(diag::note_precedence_silence) 14372 << Bop->getOpcodeStr(), 14373 Bop->getSourceRange()); 14374 } 14375 } 14376 } 14377 14378 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14379 Expr *SubExpr, StringRef Shift) { 14380 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14381 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14382 StringRef Op = Bop->getOpcodeStr(); 14383 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14384 << Bop->getSourceRange() << OpLoc << Shift << Op; 14385 SuggestParentheses(S, Bop->getOperatorLoc(), 14386 S.PDiag(diag::note_precedence_silence) << Op, 14387 Bop->getSourceRange()); 14388 } 14389 } 14390 } 14391 14392 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14393 Expr *LHSExpr, Expr *RHSExpr) { 14394 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14395 if (!OCE) 14396 return; 14397 14398 FunctionDecl *FD = OCE->getDirectCallee(); 14399 if (!FD || !FD->isOverloadedOperator()) 14400 return; 14401 14402 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14403 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14404 return; 14405 14406 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14407 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14408 << (Kind == OO_LessLess); 14409 SuggestParentheses(S, OCE->getOperatorLoc(), 14410 S.PDiag(diag::note_precedence_silence) 14411 << (Kind == OO_LessLess ? "<<" : ">>"), 14412 OCE->getSourceRange()); 14413 SuggestParentheses( 14414 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14415 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14416 } 14417 14418 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14419 /// precedence. 14420 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14421 SourceLocation OpLoc, Expr *LHSExpr, 14422 Expr *RHSExpr){ 14423 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14424 if (BinaryOperator::isBitwiseOp(Opc)) 14425 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14426 14427 // Diagnose "arg1 & arg2 | arg3" 14428 if ((Opc == BO_Or || Opc == BO_Xor) && 14429 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14430 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14431 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14432 } 14433 14434 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14435 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14436 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14437 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14438 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14439 } 14440 14441 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14442 || Opc == BO_Shr) { 14443 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14444 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14445 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14446 } 14447 14448 // Warn on overloaded shift operators and comparisons, such as: 14449 // cout << 5 == 4; 14450 if (BinaryOperator::isComparisonOp(Opc)) 14451 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14452 } 14453 14454 // Binary Operators. 'Tok' is the token for the operator. 14455 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14456 tok::TokenKind Kind, 14457 Expr *LHSExpr, Expr *RHSExpr) { 14458 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14459 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14460 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14461 14462 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14463 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14464 14465 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14466 } 14467 14468 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14469 UnresolvedSetImpl &Functions) { 14470 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14471 if (OverOp != OO_None && OverOp != OO_Equal) 14472 LookupOverloadedOperatorName(OverOp, S, Functions); 14473 14474 // In C++20 onwards, we may have a second operator to look up. 14475 if (getLangOpts().CPlusPlus20) { 14476 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14477 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14478 } 14479 } 14480 14481 /// Build an overloaded binary operator expression in the given scope. 14482 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14483 BinaryOperatorKind Opc, 14484 Expr *LHS, Expr *RHS) { 14485 switch (Opc) { 14486 case BO_Assign: 14487 case BO_DivAssign: 14488 case BO_RemAssign: 14489 case BO_SubAssign: 14490 case BO_AndAssign: 14491 case BO_OrAssign: 14492 case BO_XorAssign: 14493 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14494 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14495 break; 14496 default: 14497 break; 14498 } 14499 14500 // Find all of the overloaded operators visible from this point. 14501 UnresolvedSet<16> Functions; 14502 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14503 14504 // Build the (potentially-overloaded, potentially-dependent) 14505 // binary operation. 14506 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14507 } 14508 14509 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14510 BinaryOperatorKind Opc, 14511 Expr *LHSExpr, Expr *RHSExpr) { 14512 ExprResult LHS, RHS; 14513 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14514 if (!LHS.isUsable() || !RHS.isUsable()) 14515 return ExprError(); 14516 LHSExpr = LHS.get(); 14517 RHSExpr = RHS.get(); 14518 14519 // We want to end up calling one of checkPseudoObjectAssignment 14520 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14521 // both expressions are overloadable or either is type-dependent), 14522 // or CreateBuiltinBinOp (in any other case). We also want to get 14523 // any placeholder types out of the way. 14524 14525 // Handle pseudo-objects in the LHS. 14526 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14527 // Assignments with a pseudo-object l-value need special analysis. 14528 if (pty->getKind() == BuiltinType::PseudoObject && 14529 BinaryOperator::isAssignmentOp(Opc)) 14530 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14531 14532 // Don't resolve overloads if the other type is overloadable. 14533 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14534 // We can't actually test that if we still have a placeholder, 14535 // though. Fortunately, none of the exceptions we see in that 14536 // code below are valid when the LHS is an overload set. Note 14537 // that an overload set can be dependently-typed, but it never 14538 // instantiates to having an overloadable type. 14539 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14540 if (resolvedRHS.isInvalid()) return ExprError(); 14541 RHSExpr = resolvedRHS.get(); 14542 14543 if (RHSExpr->isTypeDependent() || 14544 RHSExpr->getType()->isOverloadableType()) 14545 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14546 } 14547 14548 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14549 // template, diagnose the missing 'template' keyword instead of diagnosing 14550 // an invalid use of a bound member function. 14551 // 14552 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14553 // to C++1z [over.over]/1.4, but we already checked for that case above. 14554 if (Opc == BO_LT && inTemplateInstantiation() && 14555 (pty->getKind() == BuiltinType::BoundMember || 14556 pty->getKind() == BuiltinType::Overload)) { 14557 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14558 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14559 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14560 return isa<FunctionTemplateDecl>(ND); 14561 })) { 14562 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14563 : OE->getNameLoc(), 14564 diag::err_template_kw_missing) 14565 << OE->getName().getAsString() << ""; 14566 return ExprError(); 14567 } 14568 } 14569 14570 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14571 if (LHS.isInvalid()) return ExprError(); 14572 LHSExpr = LHS.get(); 14573 } 14574 14575 // Handle pseudo-objects in the RHS. 14576 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14577 // An overload in the RHS can potentially be resolved by the type 14578 // being assigned to. 14579 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14580 if (getLangOpts().CPlusPlus && 14581 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14582 LHSExpr->getType()->isOverloadableType())) 14583 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14584 14585 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14586 } 14587 14588 // Don't resolve overloads if the other type is overloadable. 14589 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14590 LHSExpr->getType()->isOverloadableType()) 14591 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14592 14593 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14594 if (!resolvedRHS.isUsable()) return ExprError(); 14595 RHSExpr = resolvedRHS.get(); 14596 } 14597 14598 if (getLangOpts().CPlusPlus) { 14599 // If either expression is type-dependent, always build an 14600 // overloaded op. 14601 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14602 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14603 14604 // Otherwise, build an overloaded op if either expression has an 14605 // overloadable type. 14606 if (LHSExpr->getType()->isOverloadableType() || 14607 RHSExpr->getType()->isOverloadableType()) 14608 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14609 } 14610 14611 if (getLangOpts().RecoveryAST && 14612 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14613 assert(!getLangOpts().CPlusPlus); 14614 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14615 "Should only occur in error-recovery path."); 14616 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14617 // C [6.15.16] p3: 14618 // An assignment expression has the value of the left operand after the 14619 // assignment, but is not an lvalue. 14620 return CompoundAssignOperator::Create( 14621 Context, LHSExpr, RHSExpr, Opc, 14622 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, 14623 OpLoc, CurFPFeatureOverrides()); 14624 QualType ResultType; 14625 switch (Opc) { 14626 case BO_Assign: 14627 ResultType = LHSExpr->getType().getUnqualifiedType(); 14628 break; 14629 case BO_LT: 14630 case BO_GT: 14631 case BO_LE: 14632 case BO_GE: 14633 case BO_EQ: 14634 case BO_NE: 14635 case BO_LAnd: 14636 case BO_LOr: 14637 // These operators have a fixed result type regardless of operands. 14638 ResultType = Context.IntTy; 14639 break; 14640 case BO_Comma: 14641 ResultType = RHSExpr->getType(); 14642 break; 14643 default: 14644 ResultType = Context.DependentTy; 14645 break; 14646 } 14647 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14648 VK_RValue, OK_Ordinary, OpLoc, 14649 CurFPFeatureOverrides()); 14650 } 14651 14652 // Build a built-in binary operation. 14653 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14654 } 14655 14656 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14657 if (T.isNull() || T->isDependentType()) 14658 return false; 14659 14660 if (!T->isPromotableIntegerType()) 14661 return true; 14662 14663 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14664 } 14665 14666 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14667 UnaryOperatorKind Opc, 14668 Expr *InputExpr) { 14669 ExprResult Input = InputExpr; 14670 ExprValueKind VK = VK_RValue; 14671 ExprObjectKind OK = OK_Ordinary; 14672 QualType resultType; 14673 bool CanOverflow = false; 14674 14675 bool ConvertHalfVec = false; 14676 if (getLangOpts().OpenCL) { 14677 QualType Ty = InputExpr->getType(); 14678 // The only legal unary operation for atomics is '&'. 14679 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14680 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14681 // only with a builtin functions and therefore should be disallowed here. 14682 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14683 || Ty->isBlockPointerType())) { 14684 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14685 << InputExpr->getType() 14686 << Input.get()->getSourceRange()); 14687 } 14688 } 14689 14690 switch (Opc) { 14691 case UO_PreInc: 14692 case UO_PreDec: 14693 case UO_PostInc: 14694 case UO_PostDec: 14695 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14696 OpLoc, 14697 Opc == UO_PreInc || 14698 Opc == UO_PostInc, 14699 Opc == UO_PreInc || 14700 Opc == UO_PreDec); 14701 CanOverflow = isOverflowingIntegerType(Context, resultType); 14702 break; 14703 case UO_AddrOf: 14704 resultType = CheckAddressOfOperand(Input, OpLoc); 14705 CheckAddressOfNoDeref(InputExpr); 14706 RecordModifiableNonNullParam(*this, InputExpr); 14707 break; 14708 case UO_Deref: { 14709 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14710 if (Input.isInvalid()) return ExprError(); 14711 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14712 break; 14713 } 14714 case UO_Plus: 14715 case UO_Minus: 14716 CanOverflow = Opc == UO_Minus && 14717 isOverflowingIntegerType(Context, Input.get()->getType()); 14718 Input = UsualUnaryConversions(Input.get()); 14719 if (Input.isInvalid()) return ExprError(); 14720 // Unary plus and minus require promoting an operand of half vector to a 14721 // float vector and truncating the result back to a half vector. For now, we 14722 // do this only when HalfArgsAndReturns is set (that is, when the target is 14723 // arm or arm64). 14724 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14725 14726 // If the operand is a half vector, promote it to a float vector. 14727 if (ConvertHalfVec) 14728 Input = convertVector(Input.get(), Context.FloatTy, *this); 14729 resultType = Input.get()->getType(); 14730 if (resultType->isDependentType()) 14731 break; 14732 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14733 break; 14734 else if (resultType->isVectorType() && 14735 // The z vector extensions don't allow + or - with bool vectors. 14736 (!Context.getLangOpts().ZVector || 14737 resultType->castAs<VectorType>()->getVectorKind() != 14738 VectorType::AltiVecBool)) 14739 break; 14740 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14741 Opc == UO_Plus && 14742 resultType->isPointerType()) 14743 break; 14744 14745 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14746 << resultType << Input.get()->getSourceRange()); 14747 14748 case UO_Not: // bitwise complement 14749 Input = UsualUnaryConversions(Input.get()); 14750 if (Input.isInvalid()) 14751 return ExprError(); 14752 resultType = Input.get()->getType(); 14753 if (resultType->isDependentType()) 14754 break; 14755 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14756 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14757 // C99 does not support '~' for complex conjugation. 14758 Diag(OpLoc, diag::ext_integer_complement_complex) 14759 << resultType << Input.get()->getSourceRange(); 14760 else if (resultType->hasIntegerRepresentation()) 14761 break; 14762 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14763 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14764 // on vector float types. 14765 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14766 if (!T->isIntegerType()) 14767 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14768 << resultType << Input.get()->getSourceRange()); 14769 } else { 14770 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14771 << resultType << Input.get()->getSourceRange()); 14772 } 14773 break; 14774 14775 case UO_LNot: // logical negation 14776 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14777 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14778 if (Input.isInvalid()) return ExprError(); 14779 resultType = Input.get()->getType(); 14780 14781 // Though we still have to promote half FP to float... 14782 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14783 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14784 resultType = Context.FloatTy; 14785 } 14786 14787 if (resultType->isDependentType()) 14788 break; 14789 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14790 // C99 6.5.3.3p1: ok, fallthrough; 14791 if (Context.getLangOpts().CPlusPlus) { 14792 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14793 // operand contextually converted to bool. 14794 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14795 ScalarTypeToBooleanCastKind(resultType)); 14796 } else if (Context.getLangOpts().OpenCL && 14797 Context.getLangOpts().OpenCLVersion < 120) { 14798 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14799 // operate on scalar float types. 14800 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14801 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14802 << resultType << Input.get()->getSourceRange()); 14803 } 14804 } else if (resultType->isExtVectorType()) { 14805 if (Context.getLangOpts().OpenCL && 14806 Context.getLangOpts().OpenCLVersion < 120 && 14807 !Context.getLangOpts().OpenCLCPlusPlus) { 14808 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14809 // operate on vector float types. 14810 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14811 if (!T->isIntegerType()) 14812 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14813 << resultType << Input.get()->getSourceRange()); 14814 } 14815 // Vector logical not returns the signed variant of the operand type. 14816 resultType = GetSignedVectorType(resultType); 14817 break; 14818 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14819 const VectorType *VTy = resultType->castAs<VectorType>(); 14820 if (VTy->getVectorKind() != VectorType::GenericVector) 14821 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14822 << resultType << Input.get()->getSourceRange()); 14823 14824 // Vector logical not returns the signed variant of the operand type. 14825 resultType = GetSignedVectorType(resultType); 14826 break; 14827 } else { 14828 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14829 << resultType << Input.get()->getSourceRange()); 14830 } 14831 14832 // LNot always has type int. C99 6.5.3.3p5. 14833 // In C++, it's bool. C++ 5.3.1p8 14834 resultType = Context.getLogicalOperationType(); 14835 break; 14836 case UO_Real: 14837 case UO_Imag: 14838 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14839 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14840 // complex l-values to ordinary l-values and all other values to r-values. 14841 if (Input.isInvalid()) return ExprError(); 14842 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14843 if (Input.get()->getValueKind() != VK_RValue && 14844 Input.get()->getObjectKind() == OK_Ordinary) 14845 VK = Input.get()->getValueKind(); 14846 } else if (!getLangOpts().CPlusPlus) { 14847 // In C, a volatile scalar is read by __imag. In C++, it is not. 14848 Input = DefaultLvalueConversion(Input.get()); 14849 } 14850 break; 14851 case UO_Extension: 14852 resultType = Input.get()->getType(); 14853 VK = Input.get()->getValueKind(); 14854 OK = Input.get()->getObjectKind(); 14855 break; 14856 case UO_Coawait: 14857 // It's unnecessary to represent the pass-through operator co_await in the 14858 // AST; just return the input expression instead. 14859 assert(!Input.get()->getType()->isDependentType() && 14860 "the co_await expression must be non-dependant before " 14861 "building operator co_await"); 14862 return Input; 14863 } 14864 if (resultType.isNull() || Input.isInvalid()) 14865 return ExprError(); 14866 14867 // Check for array bounds violations in the operand of the UnaryOperator, 14868 // except for the '*' and '&' operators that have to be handled specially 14869 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14870 // that are explicitly defined as valid by the standard). 14871 if (Opc != UO_AddrOf && Opc != UO_Deref) 14872 CheckArrayAccess(Input.get()); 14873 14874 auto *UO = 14875 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14876 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14877 14878 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14879 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14880 !isUnevaluatedContext()) 14881 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14882 14883 // Convert the result back to a half vector. 14884 if (ConvertHalfVec) 14885 return convertVector(UO, Context.HalfTy, *this); 14886 return UO; 14887 } 14888 14889 /// Determine whether the given expression is a qualified member 14890 /// access expression, of a form that could be turned into a pointer to member 14891 /// with the address-of operator. 14892 bool Sema::isQualifiedMemberAccess(Expr *E) { 14893 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14894 if (!DRE->getQualifier()) 14895 return false; 14896 14897 ValueDecl *VD = DRE->getDecl(); 14898 if (!VD->isCXXClassMember()) 14899 return false; 14900 14901 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14902 return true; 14903 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14904 return Method->isInstance(); 14905 14906 return false; 14907 } 14908 14909 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14910 if (!ULE->getQualifier()) 14911 return false; 14912 14913 for (NamedDecl *D : ULE->decls()) { 14914 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14915 if (Method->isInstance()) 14916 return true; 14917 } else { 14918 // Overload set does not contain methods. 14919 break; 14920 } 14921 } 14922 14923 return false; 14924 } 14925 14926 return false; 14927 } 14928 14929 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14930 UnaryOperatorKind Opc, Expr *Input) { 14931 // First things first: handle placeholders so that the 14932 // overloaded-operator check considers the right type. 14933 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14934 // Increment and decrement of pseudo-object references. 14935 if (pty->getKind() == BuiltinType::PseudoObject && 14936 UnaryOperator::isIncrementDecrementOp(Opc)) 14937 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14938 14939 // extension is always a builtin operator. 14940 if (Opc == UO_Extension) 14941 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14942 14943 // & gets special logic for several kinds of placeholder. 14944 // The builtin code knows what to do. 14945 if (Opc == UO_AddrOf && 14946 (pty->getKind() == BuiltinType::Overload || 14947 pty->getKind() == BuiltinType::UnknownAny || 14948 pty->getKind() == BuiltinType::BoundMember)) 14949 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14950 14951 // Anything else needs to be handled now. 14952 ExprResult Result = CheckPlaceholderExpr(Input); 14953 if (Result.isInvalid()) return ExprError(); 14954 Input = Result.get(); 14955 } 14956 14957 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14958 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14959 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14960 // Find all of the overloaded operators visible from this point. 14961 UnresolvedSet<16> Functions; 14962 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14963 if (S && OverOp != OO_None) 14964 LookupOverloadedOperatorName(OverOp, S, Functions); 14965 14966 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14967 } 14968 14969 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14970 } 14971 14972 // Unary Operators. 'Tok' is the token for the operator. 14973 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14974 tok::TokenKind Op, Expr *Input) { 14975 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14976 } 14977 14978 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14979 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14980 LabelDecl *TheDecl) { 14981 TheDecl->markUsed(Context); 14982 // Create the AST node. The address of a label always has type 'void*'. 14983 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14984 Context.getPointerType(Context.VoidTy)); 14985 } 14986 14987 void Sema::ActOnStartStmtExpr() { 14988 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14989 } 14990 14991 void Sema::ActOnStmtExprError() { 14992 // Note that function is also called by TreeTransform when leaving a 14993 // StmtExpr scope without rebuilding anything. 14994 14995 DiscardCleanupsInEvaluationContext(); 14996 PopExpressionEvaluationContext(); 14997 } 14998 14999 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15000 SourceLocation RPLoc) { 15001 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15002 } 15003 15004 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15005 SourceLocation RPLoc, unsigned TemplateDepth) { 15006 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15007 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15008 15009 if (hasAnyUnrecoverableErrorsInThisFunction()) 15010 DiscardCleanupsInEvaluationContext(); 15011 assert(!Cleanup.exprNeedsCleanups() && 15012 "cleanups within StmtExpr not correctly bound!"); 15013 PopExpressionEvaluationContext(); 15014 15015 // FIXME: there are a variety of strange constraints to enforce here, for 15016 // example, it is not possible to goto into a stmt expression apparently. 15017 // More semantic analysis is needed. 15018 15019 // If there are sub-stmts in the compound stmt, take the type of the last one 15020 // as the type of the stmtexpr. 15021 QualType Ty = Context.VoidTy; 15022 bool StmtExprMayBindToTemp = false; 15023 if (!Compound->body_empty()) { 15024 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15025 if (const auto *LastStmt = 15026 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15027 if (const Expr *Value = LastStmt->getExprStmt()) { 15028 StmtExprMayBindToTemp = true; 15029 Ty = Value->getType(); 15030 } 15031 } 15032 } 15033 15034 // FIXME: Check that expression type is complete/non-abstract; statement 15035 // expressions are not lvalues. 15036 Expr *ResStmtExpr = 15037 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15038 if (StmtExprMayBindToTemp) 15039 return MaybeBindToTemporary(ResStmtExpr); 15040 return ResStmtExpr; 15041 } 15042 15043 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15044 if (ER.isInvalid()) 15045 return ExprError(); 15046 15047 // Do function/array conversion on the last expression, but not 15048 // lvalue-to-rvalue. However, initialize an unqualified type. 15049 ER = DefaultFunctionArrayConversion(ER.get()); 15050 if (ER.isInvalid()) 15051 return ExprError(); 15052 Expr *E = ER.get(); 15053 15054 if (E->isTypeDependent()) 15055 return E; 15056 15057 // In ARC, if the final expression ends in a consume, splice 15058 // the consume out and bind it later. In the alternate case 15059 // (when dealing with a retainable type), the result 15060 // initialization will create a produce. In both cases the 15061 // result will be +1, and we'll need to balance that out with 15062 // a bind. 15063 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15064 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15065 return Cast->getSubExpr(); 15066 15067 // FIXME: Provide a better location for the initialization. 15068 return PerformCopyInitialization( 15069 InitializedEntity::InitializeStmtExprResult( 15070 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15071 SourceLocation(), E); 15072 } 15073 15074 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15075 TypeSourceInfo *TInfo, 15076 ArrayRef<OffsetOfComponent> Components, 15077 SourceLocation RParenLoc) { 15078 QualType ArgTy = TInfo->getType(); 15079 bool Dependent = ArgTy->isDependentType(); 15080 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15081 15082 // We must have at least one component that refers to the type, and the first 15083 // one is known to be a field designator. Verify that the ArgTy represents 15084 // a struct/union/class. 15085 if (!Dependent && !ArgTy->isRecordType()) 15086 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15087 << ArgTy << TypeRange); 15088 15089 // Type must be complete per C99 7.17p3 because a declaring a variable 15090 // with an incomplete type would be ill-formed. 15091 if (!Dependent 15092 && RequireCompleteType(BuiltinLoc, ArgTy, 15093 diag::err_offsetof_incomplete_type, TypeRange)) 15094 return ExprError(); 15095 15096 bool DidWarnAboutNonPOD = false; 15097 QualType CurrentType = ArgTy; 15098 SmallVector<OffsetOfNode, 4> Comps; 15099 SmallVector<Expr*, 4> Exprs; 15100 for (const OffsetOfComponent &OC : Components) { 15101 if (OC.isBrackets) { 15102 // Offset of an array sub-field. TODO: Should we allow vector elements? 15103 if (!CurrentType->isDependentType()) { 15104 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15105 if(!AT) 15106 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15107 << CurrentType); 15108 CurrentType = AT->getElementType(); 15109 } else 15110 CurrentType = Context.DependentTy; 15111 15112 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15113 if (IdxRval.isInvalid()) 15114 return ExprError(); 15115 Expr *Idx = IdxRval.get(); 15116 15117 // The expression must be an integral expression. 15118 // FIXME: An integral constant expression? 15119 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15120 !Idx->getType()->isIntegerType()) 15121 return ExprError( 15122 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15123 << Idx->getSourceRange()); 15124 15125 // Record this array index. 15126 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15127 Exprs.push_back(Idx); 15128 continue; 15129 } 15130 15131 // Offset of a field. 15132 if (CurrentType->isDependentType()) { 15133 // We have the offset of a field, but we can't look into the dependent 15134 // type. Just record the identifier of the field. 15135 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15136 CurrentType = Context.DependentTy; 15137 continue; 15138 } 15139 15140 // We need to have a complete type to look into. 15141 if (RequireCompleteType(OC.LocStart, CurrentType, 15142 diag::err_offsetof_incomplete_type)) 15143 return ExprError(); 15144 15145 // Look for the designated field. 15146 const RecordType *RC = CurrentType->getAs<RecordType>(); 15147 if (!RC) 15148 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15149 << CurrentType); 15150 RecordDecl *RD = RC->getDecl(); 15151 15152 // C++ [lib.support.types]p5: 15153 // The macro offsetof accepts a restricted set of type arguments in this 15154 // International Standard. type shall be a POD structure or a POD union 15155 // (clause 9). 15156 // C++11 [support.types]p4: 15157 // If type is not a standard-layout class (Clause 9), the results are 15158 // undefined. 15159 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15160 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15161 unsigned DiagID = 15162 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15163 : diag::ext_offsetof_non_pod_type; 15164 15165 if (!IsSafe && !DidWarnAboutNonPOD && 15166 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15167 PDiag(DiagID) 15168 << SourceRange(Components[0].LocStart, OC.LocEnd) 15169 << CurrentType)) 15170 DidWarnAboutNonPOD = true; 15171 } 15172 15173 // Look for the field. 15174 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15175 LookupQualifiedName(R, RD); 15176 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15177 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15178 if (!MemberDecl) { 15179 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15180 MemberDecl = IndirectMemberDecl->getAnonField(); 15181 } 15182 15183 if (!MemberDecl) 15184 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15185 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15186 OC.LocEnd)); 15187 15188 // C99 7.17p3: 15189 // (If the specified member is a bit-field, the behavior is undefined.) 15190 // 15191 // We diagnose this as an error. 15192 if (MemberDecl->isBitField()) { 15193 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15194 << MemberDecl->getDeclName() 15195 << SourceRange(BuiltinLoc, RParenLoc); 15196 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15197 return ExprError(); 15198 } 15199 15200 RecordDecl *Parent = MemberDecl->getParent(); 15201 if (IndirectMemberDecl) 15202 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15203 15204 // If the member was found in a base class, introduce OffsetOfNodes for 15205 // the base class indirections. 15206 CXXBasePaths Paths; 15207 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15208 Paths)) { 15209 if (Paths.getDetectedVirtual()) { 15210 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15211 << MemberDecl->getDeclName() 15212 << SourceRange(BuiltinLoc, RParenLoc); 15213 return ExprError(); 15214 } 15215 15216 CXXBasePath &Path = Paths.front(); 15217 for (const CXXBasePathElement &B : Path) 15218 Comps.push_back(OffsetOfNode(B.Base)); 15219 } 15220 15221 if (IndirectMemberDecl) { 15222 for (auto *FI : IndirectMemberDecl->chain()) { 15223 assert(isa<FieldDecl>(FI)); 15224 Comps.push_back(OffsetOfNode(OC.LocStart, 15225 cast<FieldDecl>(FI), OC.LocEnd)); 15226 } 15227 } else 15228 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15229 15230 CurrentType = MemberDecl->getType().getNonReferenceType(); 15231 } 15232 15233 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15234 Comps, Exprs, RParenLoc); 15235 } 15236 15237 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15238 SourceLocation BuiltinLoc, 15239 SourceLocation TypeLoc, 15240 ParsedType ParsedArgTy, 15241 ArrayRef<OffsetOfComponent> Components, 15242 SourceLocation RParenLoc) { 15243 15244 TypeSourceInfo *ArgTInfo; 15245 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15246 if (ArgTy.isNull()) 15247 return ExprError(); 15248 15249 if (!ArgTInfo) 15250 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15251 15252 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15253 } 15254 15255 15256 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15257 Expr *CondExpr, 15258 Expr *LHSExpr, Expr *RHSExpr, 15259 SourceLocation RPLoc) { 15260 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15261 15262 ExprValueKind VK = VK_RValue; 15263 ExprObjectKind OK = OK_Ordinary; 15264 QualType resType; 15265 bool CondIsTrue = false; 15266 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15267 resType = Context.DependentTy; 15268 } else { 15269 // The conditional expression is required to be a constant expression. 15270 llvm::APSInt condEval(32); 15271 ExprResult CondICE = VerifyIntegerConstantExpression( 15272 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15273 if (CondICE.isInvalid()) 15274 return ExprError(); 15275 CondExpr = CondICE.get(); 15276 CondIsTrue = condEval.getZExtValue(); 15277 15278 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15279 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15280 15281 resType = ActiveExpr->getType(); 15282 VK = ActiveExpr->getValueKind(); 15283 OK = ActiveExpr->getObjectKind(); 15284 } 15285 15286 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15287 resType, VK, OK, RPLoc, CondIsTrue); 15288 } 15289 15290 //===----------------------------------------------------------------------===// 15291 // Clang Extensions. 15292 //===----------------------------------------------------------------------===// 15293 15294 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15295 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15296 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15297 15298 if (LangOpts.CPlusPlus) { 15299 MangleNumberingContext *MCtx; 15300 Decl *ManglingContextDecl; 15301 std::tie(MCtx, ManglingContextDecl) = 15302 getCurrentMangleNumberContext(Block->getDeclContext()); 15303 if (MCtx) { 15304 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15305 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15306 } 15307 } 15308 15309 PushBlockScope(CurScope, Block); 15310 CurContext->addDecl(Block); 15311 if (CurScope) 15312 PushDeclContext(CurScope, Block); 15313 else 15314 CurContext = Block; 15315 15316 getCurBlock()->HasImplicitReturnType = true; 15317 15318 // Enter a new evaluation context to insulate the block from any 15319 // cleanups from the enclosing full-expression. 15320 PushExpressionEvaluationContext( 15321 ExpressionEvaluationContext::PotentiallyEvaluated); 15322 } 15323 15324 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15325 Scope *CurScope) { 15326 assert(ParamInfo.getIdentifier() == nullptr && 15327 "block-id should have no identifier!"); 15328 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15329 BlockScopeInfo *CurBlock = getCurBlock(); 15330 15331 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15332 QualType T = Sig->getType(); 15333 15334 // FIXME: We should allow unexpanded parameter packs here, but that would, 15335 // in turn, make the block expression contain unexpanded parameter packs. 15336 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15337 // Drop the parameters. 15338 FunctionProtoType::ExtProtoInfo EPI; 15339 EPI.HasTrailingReturn = false; 15340 EPI.TypeQuals.addConst(); 15341 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15342 Sig = Context.getTrivialTypeSourceInfo(T); 15343 } 15344 15345 // GetTypeForDeclarator always produces a function type for a block 15346 // literal signature. Furthermore, it is always a FunctionProtoType 15347 // unless the function was written with a typedef. 15348 assert(T->isFunctionType() && 15349 "GetTypeForDeclarator made a non-function block signature"); 15350 15351 // Look for an explicit signature in that function type. 15352 FunctionProtoTypeLoc ExplicitSignature; 15353 15354 if ((ExplicitSignature = Sig->getTypeLoc() 15355 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15356 15357 // Check whether that explicit signature was synthesized by 15358 // GetTypeForDeclarator. If so, don't save that as part of the 15359 // written signature. 15360 if (ExplicitSignature.getLocalRangeBegin() == 15361 ExplicitSignature.getLocalRangeEnd()) { 15362 // This would be much cheaper if we stored TypeLocs instead of 15363 // TypeSourceInfos. 15364 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15365 unsigned Size = Result.getFullDataSize(); 15366 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15367 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15368 15369 ExplicitSignature = FunctionProtoTypeLoc(); 15370 } 15371 } 15372 15373 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15374 CurBlock->FunctionType = T; 15375 15376 const auto *Fn = T->castAs<FunctionType>(); 15377 QualType RetTy = Fn->getReturnType(); 15378 bool isVariadic = 15379 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15380 15381 CurBlock->TheDecl->setIsVariadic(isVariadic); 15382 15383 // Context.DependentTy is used as a placeholder for a missing block 15384 // return type. TODO: what should we do with declarators like: 15385 // ^ * { ... } 15386 // If the answer is "apply template argument deduction".... 15387 if (RetTy != Context.DependentTy) { 15388 CurBlock->ReturnType = RetTy; 15389 CurBlock->TheDecl->setBlockMissingReturnType(false); 15390 CurBlock->HasImplicitReturnType = false; 15391 } 15392 15393 // Push block parameters from the declarator if we had them. 15394 SmallVector<ParmVarDecl*, 8> Params; 15395 if (ExplicitSignature) { 15396 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15397 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15398 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15399 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15400 // Diagnose this as an extension in C17 and earlier. 15401 if (!getLangOpts().C2x) 15402 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15403 } 15404 Params.push_back(Param); 15405 } 15406 15407 // Fake up parameter variables if we have a typedef, like 15408 // ^ fntype { ... } 15409 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15410 for (const auto &I : Fn->param_types()) { 15411 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15412 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15413 Params.push_back(Param); 15414 } 15415 } 15416 15417 // Set the parameters on the block decl. 15418 if (!Params.empty()) { 15419 CurBlock->TheDecl->setParams(Params); 15420 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15421 /*CheckParameterNames=*/false); 15422 } 15423 15424 // Finally we can process decl attributes. 15425 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15426 15427 // Put the parameter variables in scope. 15428 for (auto AI : CurBlock->TheDecl->parameters()) { 15429 AI->setOwningFunction(CurBlock->TheDecl); 15430 15431 // If this has an identifier, add it to the scope stack. 15432 if (AI->getIdentifier()) { 15433 CheckShadow(CurBlock->TheScope, AI); 15434 15435 PushOnScopeChains(AI, CurBlock->TheScope); 15436 } 15437 } 15438 } 15439 15440 /// ActOnBlockError - If there is an error parsing a block, this callback 15441 /// is invoked to pop the information about the block from the action impl. 15442 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15443 // Leave the expression-evaluation context. 15444 DiscardCleanupsInEvaluationContext(); 15445 PopExpressionEvaluationContext(); 15446 15447 // Pop off CurBlock, handle nested blocks. 15448 PopDeclContext(); 15449 PopFunctionScopeInfo(); 15450 } 15451 15452 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15453 /// literal was successfully completed. ^(int x){...} 15454 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15455 Stmt *Body, Scope *CurScope) { 15456 // If blocks are disabled, emit an error. 15457 if (!LangOpts.Blocks) 15458 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15459 15460 // Leave the expression-evaluation context. 15461 if (hasAnyUnrecoverableErrorsInThisFunction()) 15462 DiscardCleanupsInEvaluationContext(); 15463 assert(!Cleanup.exprNeedsCleanups() && 15464 "cleanups within block not correctly bound!"); 15465 PopExpressionEvaluationContext(); 15466 15467 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15468 BlockDecl *BD = BSI->TheDecl; 15469 15470 if (BSI->HasImplicitReturnType) 15471 deduceClosureReturnType(*BSI); 15472 15473 QualType RetTy = Context.VoidTy; 15474 if (!BSI->ReturnType.isNull()) 15475 RetTy = BSI->ReturnType; 15476 15477 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15478 QualType BlockTy; 15479 15480 // If the user wrote a function type in some form, try to use that. 15481 if (!BSI->FunctionType.isNull()) { 15482 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15483 15484 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15485 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15486 15487 // Turn protoless block types into nullary block types. 15488 if (isa<FunctionNoProtoType>(FTy)) { 15489 FunctionProtoType::ExtProtoInfo EPI; 15490 EPI.ExtInfo = Ext; 15491 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15492 15493 // Otherwise, if we don't need to change anything about the function type, 15494 // preserve its sugar structure. 15495 } else if (FTy->getReturnType() == RetTy && 15496 (!NoReturn || FTy->getNoReturnAttr())) { 15497 BlockTy = BSI->FunctionType; 15498 15499 // Otherwise, make the minimal modifications to the function type. 15500 } else { 15501 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15502 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15503 EPI.TypeQuals = Qualifiers(); 15504 EPI.ExtInfo = Ext; 15505 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15506 } 15507 15508 // If we don't have a function type, just build one from nothing. 15509 } else { 15510 FunctionProtoType::ExtProtoInfo EPI; 15511 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15512 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15513 } 15514 15515 DiagnoseUnusedParameters(BD->parameters()); 15516 BlockTy = Context.getBlockPointerType(BlockTy); 15517 15518 // If needed, diagnose invalid gotos and switches in the block. 15519 if (getCurFunction()->NeedsScopeChecking() && 15520 !PP.isCodeCompletionEnabled()) 15521 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15522 15523 BD->setBody(cast<CompoundStmt>(Body)); 15524 15525 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15526 DiagnoseUnguardedAvailabilityViolations(BD); 15527 15528 // Try to apply the named return value optimization. We have to check again 15529 // if we can do this, though, because blocks keep return statements around 15530 // to deduce an implicit return type. 15531 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15532 !BD->isDependentContext()) 15533 computeNRVO(Body, BSI); 15534 15535 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15536 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15537 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15538 NTCUK_Destruct|NTCUK_Copy); 15539 15540 PopDeclContext(); 15541 15542 // Set the captured variables on the block. 15543 SmallVector<BlockDecl::Capture, 4> Captures; 15544 for (Capture &Cap : BSI->Captures) { 15545 if (Cap.isInvalid() || Cap.isThisCapture()) 15546 continue; 15547 15548 VarDecl *Var = Cap.getVariable(); 15549 Expr *CopyExpr = nullptr; 15550 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15551 if (const RecordType *Record = 15552 Cap.getCaptureType()->getAs<RecordType>()) { 15553 // The capture logic needs the destructor, so make sure we mark it. 15554 // Usually this is unnecessary because most local variables have 15555 // their destructors marked at declaration time, but parameters are 15556 // an exception because it's technically only the call site that 15557 // actually requires the destructor. 15558 if (isa<ParmVarDecl>(Var)) 15559 FinalizeVarWithDestructor(Var, Record); 15560 15561 // Enter a separate potentially-evaluated context while building block 15562 // initializers to isolate their cleanups from those of the block 15563 // itself. 15564 // FIXME: Is this appropriate even when the block itself occurs in an 15565 // unevaluated operand? 15566 EnterExpressionEvaluationContext EvalContext( 15567 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15568 15569 SourceLocation Loc = Cap.getLocation(); 15570 15571 ExprResult Result = BuildDeclarationNameExpr( 15572 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15573 15574 // According to the blocks spec, the capture of a variable from 15575 // the stack requires a const copy constructor. This is not true 15576 // of the copy/move done to move a __block variable to the heap. 15577 if (!Result.isInvalid() && 15578 !Result.get()->getType().isConstQualified()) { 15579 Result = ImpCastExprToType(Result.get(), 15580 Result.get()->getType().withConst(), 15581 CK_NoOp, VK_LValue); 15582 } 15583 15584 if (!Result.isInvalid()) { 15585 Result = PerformCopyInitialization( 15586 InitializedEntity::InitializeBlock(Var->getLocation(), 15587 Cap.getCaptureType(), false), 15588 Loc, Result.get()); 15589 } 15590 15591 // Build a full-expression copy expression if initialization 15592 // succeeded and used a non-trivial constructor. Recover from 15593 // errors by pretending that the copy isn't necessary. 15594 if (!Result.isInvalid() && 15595 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15596 ->isTrivial()) { 15597 Result = MaybeCreateExprWithCleanups(Result); 15598 CopyExpr = Result.get(); 15599 } 15600 } 15601 } 15602 15603 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15604 CopyExpr); 15605 Captures.push_back(NewCap); 15606 } 15607 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15608 15609 // Pop the block scope now but keep it alive to the end of this function. 15610 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15611 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15612 15613 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15614 15615 // If the block isn't obviously global, i.e. it captures anything at 15616 // all, then we need to do a few things in the surrounding context: 15617 if (Result->getBlockDecl()->hasCaptures()) { 15618 // First, this expression has a new cleanup object. 15619 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15620 Cleanup.setExprNeedsCleanups(true); 15621 15622 // It also gets a branch-protected scope if any of the captured 15623 // variables needs destruction. 15624 for (const auto &CI : Result->getBlockDecl()->captures()) { 15625 const VarDecl *var = CI.getVariable(); 15626 if (var->getType().isDestructedType() != QualType::DK_none) { 15627 setFunctionHasBranchProtectedScope(); 15628 break; 15629 } 15630 } 15631 } 15632 15633 if (getCurFunction()) 15634 getCurFunction()->addBlock(BD); 15635 15636 return Result; 15637 } 15638 15639 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15640 SourceLocation RPLoc) { 15641 TypeSourceInfo *TInfo; 15642 GetTypeFromParser(Ty, &TInfo); 15643 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15644 } 15645 15646 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15647 Expr *E, TypeSourceInfo *TInfo, 15648 SourceLocation RPLoc) { 15649 Expr *OrigExpr = E; 15650 bool IsMS = false; 15651 15652 // CUDA device code does not support varargs. 15653 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15654 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15655 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15656 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15657 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15658 } 15659 } 15660 15661 // NVPTX does not support va_arg expression. 15662 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15663 Context.getTargetInfo().getTriple().isNVPTX()) 15664 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15665 15666 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15667 // as Microsoft ABI on an actual Microsoft platform, where 15668 // __builtin_ms_va_list and __builtin_va_list are the same.) 15669 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15670 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15671 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15672 if (Context.hasSameType(MSVaListType, E->getType())) { 15673 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15674 return ExprError(); 15675 IsMS = true; 15676 } 15677 } 15678 15679 // Get the va_list type 15680 QualType VaListType = Context.getBuiltinVaListType(); 15681 if (!IsMS) { 15682 if (VaListType->isArrayType()) { 15683 // Deal with implicit array decay; for example, on x86-64, 15684 // va_list is an array, but it's supposed to decay to 15685 // a pointer for va_arg. 15686 VaListType = Context.getArrayDecayedType(VaListType); 15687 // Make sure the input expression also decays appropriately. 15688 ExprResult Result = UsualUnaryConversions(E); 15689 if (Result.isInvalid()) 15690 return ExprError(); 15691 E = Result.get(); 15692 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15693 // If va_list is a record type and we are compiling in C++ mode, 15694 // check the argument using reference binding. 15695 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15696 Context, Context.getLValueReferenceType(VaListType), false); 15697 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15698 if (Init.isInvalid()) 15699 return ExprError(); 15700 E = Init.getAs<Expr>(); 15701 } else { 15702 // Otherwise, the va_list argument must be an l-value because 15703 // it is modified by va_arg. 15704 if (!E->isTypeDependent() && 15705 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15706 return ExprError(); 15707 } 15708 } 15709 15710 if (!IsMS && !E->isTypeDependent() && 15711 !Context.hasSameType(VaListType, E->getType())) 15712 return ExprError( 15713 Diag(E->getBeginLoc(), 15714 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15715 << OrigExpr->getType() << E->getSourceRange()); 15716 15717 if (!TInfo->getType()->isDependentType()) { 15718 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15719 diag::err_second_parameter_to_va_arg_incomplete, 15720 TInfo->getTypeLoc())) 15721 return ExprError(); 15722 15723 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15724 TInfo->getType(), 15725 diag::err_second_parameter_to_va_arg_abstract, 15726 TInfo->getTypeLoc())) 15727 return ExprError(); 15728 15729 if (!TInfo->getType().isPODType(Context)) { 15730 Diag(TInfo->getTypeLoc().getBeginLoc(), 15731 TInfo->getType()->isObjCLifetimeType() 15732 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15733 : diag::warn_second_parameter_to_va_arg_not_pod) 15734 << TInfo->getType() 15735 << TInfo->getTypeLoc().getSourceRange(); 15736 } 15737 15738 // Check for va_arg where arguments of the given type will be promoted 15739 // (i.e. this va_arg is guaranteed to have undefined behavior). 15740 QualType PromoteType; 15741 if (TInfo->getType()->isPromotableIntegerType()) { 15742 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15743 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15744 PromoteType = QualType(); 15745 } 15746 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15747 PromoteType = Context.DoubleTy; 15748 if (!PromoteType.isNull()) 15749 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15750 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15751 << TInfo->getType() 15752 << PromoteType 15753 << TInfo->getTypeLoc().getSourceRange()); 15754 } 15755 15756 QualType T = TInfo->getType().getNonLValueExprType(Context); 15757 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15758 } 15759 15760 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15761 // The type of __null will be int or long, depending on the size of 15762 // pointers on the target. 15763 QualType Ty; 15764 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15765 if (pw == Context.getTargetInfo().getIntWidth()) 15766 Ty = Context.IntTy; 15767 else if (pw == Context.getTargetInfo().getLongWidth()) 15768 Ty = Context.LongTy; 15769 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15770 Ty = Context.LongLongTy; 15771 else { 15772 llvm_unreachable("I don't know size of pointer!"); 15773 } 15774 15775 return new (Context) GNUNullExpr(Ty, TokenLoc); 15776 } 15777 15778 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15779 SourceLocation BuiltinLoc, 15780 SourceLocation RPLoc) { 15781 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15782 } 15783 15784 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15785 SourceLocation BuiltinLoc, 15786 SourceLocation RPLoc, 15787 DeclContext *ParentContext) { 15788 return new (Context) 15789 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15790 } 15791 15792 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15793 bool Diagnose) { 15794 if (!getLangOpts().ObjC) 15795 return false; 15796 15797 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15798 if (!PT) 15799 return false; 15800 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15801 15802 // Ignore any parens, implicit casts (should only be 15803 // array-to-pointer decays), and not-so-opaque values. The last is 15804 // important for making this trigger for property assignments. 15805 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15806 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15807 if (OV->getSourceExpr()) 15808 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15809 15810 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15811 if (!PT->isObjCIdType() && 15812 !(ID && ID->getIdentifier()->isStr("NSString"))) 15813 return false; 15814 if (!SL->isAscii()) 15815 return false; 15816 15817 if (Diagnose) { 15818 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15819 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15820 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15821 } 15822 return true; 15823 } 15824 15825 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15826 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15827 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15828 !SrcExpr->isNullPointerConstant( 15829 getASTContext(), Expr::NPC_NeverValueDependent)) { 15830 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15831 return false; 15832 if (Diagnose) { 15833 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15834 << /*number*/1 15835 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15836 Expr *NumLit = 15837 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15838 if (NumLit) 15839 Exp = NumLit; 15840 } 15841 return true; 15842 } 15843 15844 return false; 15845 } 15846 15847 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15848 const Expr *SrcExpr) { 15849 if (!DstType->isFunctionPointerType() || 15850 !SrcExpr->getType()->isFunctionType()) 15851 return false; 15852 15853 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15854 if (!DRE) 15855 return false; 15856 15857 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15858 if (!FD) 15859 return false; 15860 15861 return !S.checkAddressOfFunctionIsAvailable(FD, 15862 /*Complain=*/true, 15863 SrcExpr->getBeginLoc()); 15864 } 15865 15866 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15867 SourceLocation Loc, 15868 QualType DstType, QualType SrcType, 15869 Expr *SrcExpr, AssignmentAction Action, 15870 bool *Complained) { 15871 if (Complained) 15872 *Complained = false; 15873 15874 // Decode the result (notice that AST's are still created for extensions). 15875 bool CheckInferredResultType = false; 15876 bool isInvalid = false; 15877 unsigned DiagKind = 0; 15878 ConversionFixItGenerator ConvHints; 15879 bool MayHaveConvFixit = false; 15880 bool MayHaveFunctionDiff = false; 15881 const ObjCInterfaceDecl *IFace = nullptr; 15882 const ObjCProtocolDecl *PDecl = nullptr; 15883 15884 switch (ConvTy) { 15885 case Compatible: 15886 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15887 return false; 15888 15889 case PointerToInt: 15890 if (getLangOpts().CPlusPlus) { 15891 DiagKind = diag::err_typecheck_convert_pointer_int; 15892 isInvalid = true; 15893 } else { 15894 DiagKind = diag::ext_typecheck_convert_pointer_int; 15895 } 15896 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15897 MayHaveConvFixit = true; 15898 break; 15899 case IntToPointer: 15900 if (getLangOpts().CPlusPlus) { 15901 DiagKind = diag::err_typecheck_convert_int_pointer; 15902 isInvalid = true; 15903 } else { 15904 DiagKind = diag::ext_typecheck_convert_int_pointer; 15905 } 15906 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15907 MayHaveConvFixit = true; 15908 break; 15909 case IncompatibleFunctionPointer: 15910 if (getLangOpts().CPlusPlus) { 15911 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15912 isInvalid = true; 15913 } else { 15914 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15915 } 15916 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15917 MayHaveConvFixit = true; 15918 break; 15919 case IncompatiblePointer: 15920 if (Action == AA_Passing_CFAudited) { 15921 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15922 } else if (getLangOpts().CPlusPlus) { 15923 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15924 isInvalid = true; 15925 } else { 15926 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15927 } 15928 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15929 SrcType->isObjCObjectPointerType(); 15930 if (!CheckInferredResultType) { 15931 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15932 } else if (CheckInferredResultType) { 15933 SrcType = SrcType.getUnqualifiedType(); 15934 DstType = DstType.getUnqualifiedType(); 15935 } 15936 MayHaveConvFixit = true; 15937 break; 15938 case IncompatiblePointerSign: 15939 if (getLangOpts().CPlusPlus) { 15940 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15941 isInvalid = true; 15942 } else { 15943 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15944 } 15945 break; 15946 case FunctionVoidPointer: 15947 if (getLangOpts().CPlusPlus) { 15948 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15949 isInvalid = true; 15950 } else { 15951 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15952 } 15953 break; 15954 case IncompatiblePointerDiscardsQualifiers: { 15955 // Perform array-to-pointer decay if necessary. 15956 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15957 15958 isInvalid = true; 15959 15960 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15961 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15962 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15963 DiagKind = diag::err_typecheck_incompatible_address_space; 15964 break; 15965 15966 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15967 DiagKind = diag::err_typecheck_incompatible_ownership; 15968 break; 15969 } 15970 15971 llvm_unreachable("unknown error case for discarding qualifiers!"); 15972 // fallthrough 15973 } 15974 case CompatiblePointerDiscardsQualifiers: 15975 // If the qualifiers lost were because we were applying the 15976 // (deprecated) C++ conversion from a string literal to a char* 15977 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15978 // Ideally, this check would be performed in 15979 // checkPointerTypesForAssignment. However, that would require a 15980 // bit of refactoring (so that the second argument is an 15981 // expression, rather than a type), which should be done as part 15982 // of a larger effort to fix checkPointerTypesForAssignment for 15983 // C++ semantics. 15984 if (getLangOpts().CPlusPlus && 15985 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15986 return false; 15987 if (getLangOpts().CPlusPlus) { 15988 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15989 isInvalid = true; 15990 } else { 15991 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15992 } 15993 15994 break; 15995 case IncompatibleNestedPointerQualifiers: 15996 if (getLangOpts().CPlusPlus) { 15997 isInvalid = true; 15998 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15999 } else { 16000 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16001 } 16002 break; 16003 case IncompatibleNestedPointerAddressSpaceMismatch: 16004 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16005 isInvalid = true; 16006 break; 16007 case IntToBlockPointer: 16008 DiagKind = diag::err_int_to_block_pointer; 16009 isInvalid = true; 16010 break; 16011 case IncompatibleBlockPointer: 16012 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16013 isInvalid = true; 16014 break; 16015 case IncompatibleObjCQualifiedId: { 16016 if (SrcType->isObjCQualifiedIdType()) { 16017 const ObjCObjectPointerType *srcOPT = 16018 SrcType->castAs<ObjCObjectPointerType>(); 16019 for (auto *srcProto : srcOPT->quals()) { 16020 PDecl = srcProto; 16021 break; 16022 } 16023 if (const ObjCInterfaceType *IFaceT = 16024 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16025 IFace = IFaceT->getDecl(); 16026 } 16027 else if (DstType->isObjCQualifiedIdType()) { 16028 const ObjCObjectPointerType *dstOPT = 16029 DstType->castAs<ObjCObjectPointerType>(); 16030 for (auto *dstProto : dstOPT->quals()) { 16031 PDecl = dstProto; 16032 break; 16033 } 16034 if (const ObjCInterfaceType *IFaceT = 16035 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16036 IFace = IFaceT->getDecl(); 16037 } 16038 if (getLangOpts().CPlusPlus) { 16039 DiagKind = diag::err_incompatible_qualified_id; 16040 isInvalid = true; 16041 } else { 16042 DiagKind = diag::warn_incompatible_qualified_id; 16043 } 16044 break; 16045 } 16046 case IncompatibleVectors: 16047 if (getLangOpts().CPlusPlus) { 16048 DiagKind = diag::err_incompatible_vectors; 16049 isInvalid = true; 16050 } else { 16051 DiagKind = diag::warn_incompatible_vectors; 16052 } 16053 break; 16054 case IncompatibleObjCWeakRef: 16055 DiagKind = diag::err_arc_weak_unavailable_assign; 16056 isInvalid = true; 16057 break; 16058 case Incompatible: 16059 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16060 if (Complained) 16061 *Complained = true; 16062 return true; 16063 } 16064 16065 DiagKind = diag::err_typecheck_convert_incompatible; 16066 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16067 MayHaveConvFixit = true; 16068 isInvalid = true; 16069 MayHaveFunctionDiff = true; 16070 break; 16071 } 16072 16073 QualType FirstType, SecondType; 16074 switch (Action) { 16075 case AA_Assigning: 16076 case AA_Initializing: 16077 // The destination type comes first. 16078 FirstType = DstType; 16079 SecondType = SrcType; 16080 break; 16081 16082 case AA_Returning: 16083 case AA_Passing: 16084 case AA_Passing_CFAudited: 16085 case AA_Converting: 16086 case AA_Sending: 16087 case AA_Casting: 16088 // The source type comes first. 16089 FirstType = SrcType; 16090 SecondType = DstType; 16091 break; 16092 } 16093 16094 PartialDiagnostic FDiag = PDiag(DiagKind); 16095 if (Action == AA_Passing_CFAudited) 16096 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16097 else 16098 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16099 16100 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16101 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16102 auto isPlainChar = [](const clang::Type *Type) { 16103 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16104 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16105 }; 16106 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16107 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16108 } 16109 16110 // If we can fix the conversion, suggest the FixIts. 16111 if (!ConvHints.isNull()) { 16112 for (FixItHint &H : ConvHints.Hints) 16113 FDiag << H; 16114 } 16115 16116 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16117 16118 if (MayHaveFunctionDiff) 16119 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16120 16121 Diag(Loc, FDiag); 16122 if ((DiagKind == diag::warn_incompatible_qualified_id || 16123 DiagKind == diag::err_incompatible_qualified_id) && 16124 PDecl && IFace && !IFace->hasDefinition()) 16125 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16126 << IFace << PDecl; 16127 16128 if (SecondType == Context.OverloadTy) 16129 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16130 FirstType, /*TakingAddress=*/true); 16131 16132 if (CheckInferredResultType) 16133 EmitRelatedResultTypeNote(SrcExpr); 16134 16135 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16136 EmitRelatedResultTypeNoteForReturn(DstType); 16137 16138 if (Complained) 16139 *Complained = true; 16140 return isInvalid; 16141 } 16142 16143 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16144 llvm::APSInt *Result, 16145 AllowFoldKind CanFold) { 16146 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16147 public: 16148 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16149 QualType T) override { 16150 return S.Diag(Loc, diag::err_ice_not_integral) 16151 << T << S.LangOpts.CPlusPlus; 16152 } 16153 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16154 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16155 } 16156 } Diagnoser; 16157 16158 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16159 } 16160 16161 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16162 llvm::APSInt *Result, 16163 unsigned DiagID, 16164 AllowFoldKind CanFold) { 16165 class IDDiagnoser : public VerifyICEDiagnoser { 16166 unsigned DiagID; 16167 16168 public: 16169 IDDiagnoser(unsigned DiagID) 16170 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16171 16172 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16173 return S.Diag(Loc, DiagID); 16174 } 16175 } Diagnoser(DiagID); 16176 16177 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16178 } 16179 16180 Sema::SemaDiagnosticBuilder 16181 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16182 QualType T) { 16183 return diagnoseNotICE(S, Loc); 16184 } 16185 16186 Sema::SemaDiagnosticBuilder 16187 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16188 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16189 } 16190 16191 ExprResult 16192 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16193 VerifyICEDiagnoser &Diagnoser, 16194 AllowFoldKind CanFold) { 16195 SourceLocation DiagLoc = E->getBeginLoc(); 16196 16197 if (getLangOpts().CPlusPlus11) { 16198 // C++11 [expr.const]p5: 16199 // If an expression of literal class type is used in a context where an 16200 // integral constant expression is required, then that class type shall 16201 // have a single non-explicit conversion function to an integral or 16202 // unscoped enumeration type 16203 ExprResult Converted; 16204 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16205 VerifyICEDiagnoser &BaseDiagnoser; 16206 public: 16207 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16208 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16209 BaseDiagnoser.Suppress, true), 16210 BaseDiagnoser(BaseDiagnoser) {} 16211 16212 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16213 QualType T) override { 16214 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16215 } 16216 16217 SemaDiagnosticBuilder diagnoseIncomplete( 16218 Sema &S, SourceLocation Loc, QualType T) override { 16219 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16220 } 16221 16222 SemaDiagnosticBuilder diagnoseExplicitConv( 16223 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16224 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16225 } 16226 16227 SemaDiagnosticBuilder noteExplicitConv( 16228 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16229 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16230 << ConvTy->isEnumeralType() << ConvTy; 16231 } 16232 16233 SemaDiagnosticBuilder diagnoseAmbiguous( 16234 Sema &S, SourceLocation Loc, QualType T) override { 16235 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16236 } 16237 16238 SemaDiagnosticBuilder noteAmbiguous( 16239 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16240 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16241 << ConvTy->isEnumeralType() << ConvTy; 16242 } 16243 16244 SemaDiagnosticBuilder diagnoseConversion( 16245 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16246 llvm_unreachable("conversion functions are permitted"); 16247 } 16248 } ConvertDiagnoser(Diagnoser); 16249 16250 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16251 ConvertDiagnoser); 16252 if (Converted.isInvalid()) 16253 return Converted; 16254 E = Converted.get(); 16255 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16256 return ExprError(); 16257 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16258 // An ICE must be of integral or unscoped enumeration type. 16259 if (!Diagnoser.Suppress) 16260 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16261 << E->getSourceRange(); 16262 return ExprError(); 16263 } 16264 16265 ExprResult RValueExpr = DefaultLvalueConversion(E); 16266 if (RValueExpr.isInvalid()) 16267 return ExprError(); 16268 16269 E = RValueExpr.get(); 16270 16271 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16272 // in the non-ICE case. 16273 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16274 if (Result) 16275 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16276 if (!isa<ConstantExpr>(E)) 16277 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16278 : ConstantExpr::Create(Context, E); 16279 return E; 16280 } 16281 16282 Expr::EvalResult EvalResult; 16283 SmallVector<PartialDiagnosticAt, 8> Notes; 16284 EvalResult.Diag = &Notes; 16285 16286 // Try to evaluate the expression, and produce diagnostics explaining why it's 16287 // not a constant expression as a side-effect. 16288 bool Folded = 16289 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16290 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16291 16292 if (!isa<ConstantExpr>(E)) 16293 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16294 16295 // In C++11, we can rely on diagnostics being produced for any expression 16296 // which is not a constant expression. If no diagnostics were produced, then 16297 // this is a constant expression. 16298 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16299 if (Result) 16300 *Result = EvalResult.Val.getInt(); 16301 return E; 16302 } 16303 16304 // If our only note is the usual "invalid subexpression" note, just point 16305 // the caret at its location rather than producing an essentially 16306 // redundant note. 16307 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16308 diag::note_invalid_subexpr_in_const_expr) { 16309 DiagLoc = Notes[0].first; 16310 Notes.clear(); 16311 } 16312 16313 if (!Folded || !CanFold) { 16314 if (!Diagnoser.Suppress) { 16315 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16316 for (const PartialDiagnosticAt &Note : Notes) 16317 Diag(Note.first, Note.second); 16318 } 16319 16320 return ExprError(); 16321 } 16322 16323 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16324 for (const PartialDiagnosticAt &Note : Notes) 16325 Diag(Note.first, Note.second); 16326 16327 if (Result) 16328 *Result = EvalResult.Val.getInt(); 16329 return E; 16330 } 16331 16332 namespace { 16333 // Handle the case where we conclude a expression which we speculatively 16334 // considered to be unevaluated is actually evaluated. 16335 class TransformToPE : public TreeTransform<TransformToPE> { 16336 typedef TreeTransform<TransformToPE> BaseTransform; 16337 16338 public: 16339 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16340 16341 // Make sure we redo semantic analysis 16342 bool AlwaysRebuild() { return true; } 16343 bool ReplacingOriginal() { return true; } 16344 16345 // We need to special-case DeclRefExprs referring to FieldDecls which 16346 // are not part of a member pointer formation; normal TreeTransforming 16347 // doesn't catch this case because of the way we represent them in the AST. 16348 // FIXME: This is a bit ugly; is it really the best way to handle this 16349 // case? 16350 // 16351 // Error on DeclRefExprs referring to FieldDecls. 16352 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16353 if (isa<FieldDecl>(E->getDecl()) && 16354 !SemaRef.isUnevaluatedContext()) 16355 return SemaRef.Diag(E->getLocation(), 16356 diag::err_invalid_non_static_member_use) 16357 << E->getDecl() << E->getSourceRange(); 16358 16359 return BaseTransform::TransformDeclRefExpr(E); 16360 } 16361 16362 // Exception: filter out member pointer formation 16363 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16364 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16365 return E; 16366 16367 return BaseTransform::TransformUnaryOperator(E); 16368 } 16369 16370 // The body of a lambda-expression is in a separate expression evaluation 16371 // context so never needs to be transformed. 16372 // FIXME: Ideally we wouldn't transform the closure type either, and would 16373 // just recreate the capture expressions and lambda expression. 16374 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16375 return SkipLambdaBody(E, Body); 16376 } 16377 }; 16378 } 16379 16380 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16381 assert(isUnevaluatedContext() && 16382 "Should only transform unevaluated expressions"); 16383 ExprEvalContexts.back().Context = 16384 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16385 if (isUnevaluatedContext()) 16386 return E; 16387 return TransformToPE(*this).TransformExpr(E); 16388 } 16389 16390 void 16391 Sema::PushExpressionEvaluationContext( 16392 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16393 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16394 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16395 LambdaContextDecl, ExprContext); 16396 Cleanup.reset(); 16397 if (!MaybeODRUseExprs.empty()) 16398 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16399 } 16400 16401 void 16402 Sema::PushExpressionEvaluationContext( 16403 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16404 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16405 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16406 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16407 } 16408 16409 namespace { 16410 16411 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16412 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16413 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16414 if (E->getOpcode() == UO_Deref) 16415 return CheckPossibleDeref(S, E->getSubExpr()); 16416 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16417 return CheckPossibleDeref(S, E->getBase()); 16418 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16419 return CheckPossibleDeref(S, E->getBase()); 16420 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16421 QualType Inner; 16422 QualType Ty = E->getType(); 16423 if (const auto *Ptr = Ty->getAs<PointerType>()) 16424 Inner = Ptr->getPointeeType(); 16425 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16426 Inner = Arr->getElementType(); 16427 else 16428 return nullptr; 16429 16430 if (Inner->hasAttr(attr::NoDeref)) 16431 return E; 16432 } 16433 return nullptr; 16434 } 16435 16436 } // namespace 16437 16438 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16439 for (const Expr *E : Rec.PossibleDerefs) { 16440 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16441 if (DeclRef) { 16442 const ValueDecl *Decl = DeclRef->getDecl(); 16443 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16444 << Decl->getName() << E->getSourceRange(); 16445 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16446 } else { 16447 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16448 << E->getSourceRange(); 16449 } 16450 } 16451 Rec.PossibleDerefs.clear(); 16452 } 16453 16454 /// Check whether E, which is either a discarded-value expression or an 16455 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16456 /// and if so, remove it from the list of volatile-qualified assignments that 16457 /// we are going to warn are deprecated. 16458 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16459 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16460 return; 16461 16462 // Note: ignoring parens here is not justified by the standard rules, but 16463 // ignoring parentheses seems like a more reasonable approach, and this only 16464 // drives a deprecation warning so doesn't affect conformance. 16465 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16466 if (BO->getOpcode() == BO_Assign) { 16467 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16468 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16469 LHSs.end()); 16470 } 16471 } 16472 } 16473 16474 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16475 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16476 RebuildingImmediateInvocation) 16477 return E; 16478 16479 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16480 /// It's OK if this fails; we'll also remove this in 16481 /// HandleImmediateInvocations, but catching it here allows us to avoid 16482 /// walking the AST looking for it in simple cases. 16483 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16484 if (auto *DeclRef = 16485 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16486 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16487 16488 E = MaybeCreateExprWithCleanups(E); 16489 16490 ConstantExpr *Res = ConstantExpr::Create( 16491 getASTContext(), E.get(), 16492 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16493 getASTContext()), 16494 /*IsImmediateInvocation*/ true); 16495 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16496 return Res; 16497 } 16498 16499 static void EvaluateAndDiagnoseImmediateInvocation( 16500 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16501 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16502 Expr::EvalResult Eval; 16503 Eval.Diag = &Notes; 16504 ConstantExpr *CE = Candidate.getPointer(); 16505 bool Result = CE->EvaluateAsConstantExpr( 16506 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16507 if (!Result || !Notes.empty()) { 16508 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16509 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16510 InnerExpr = FunctionalCast->getSubExpr(); 16511 FunctionDecl *FD = nullptr; 16512 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16513 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16514 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16515 FD = Call->getConstructor(); 16516 else 16517 llvm_unreachable("unhandled decl kind"); 16518 assert(FD->isConsteval()); 16519 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16520 for (auto &Note : Notes) 16521 SemaRef.Diag(Note.first, Note.second); 16522 return; 16523 } 16524 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16525 } 16526 16527 static void RemoveNestedImmediateInvocation( 16528 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16529 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16530 struct ComplexRemove : TreeTransform<ComplexRemove> { 16531 using Base = TreeTransform<ComplexRemove>; 16532 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16533 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16534 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16535 CurrentII; 16536 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16537 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16538 SmallVector<Sema::ImmediateInvocationCandidate, 16539 4>::reverse_iterator Current) 16540 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16541 void RemoveImmediateInvocation(ConstantExpr* E) { 16542 auto It = std::find_if(CurrentII, IISet.rend(), 16543 [E](Sema::ImmediateInvocationCandidate Elem) { 16544 return Elem.getPointer() == E; 16545 }); 16546 assert(It != IISet.rend() && 16547 "ConstantExpr marked IsImmediateInvocation should " 16548 "be present"); 16549 It->setInt(1); // Mark as deleted 16550 } 16551 ExprResult TransformConstantExpr(ConstantExpr *E) { 16552 if (!E->isImmediateInvocation()) 16553 return Base::TransformConstantExpr(E); 16554 RemoveImmediateInvocation(E); 16555 return Base::TransformExpr(E->getSubExpr()); 16556 } 16557 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16558 /// we need to remove its DeclRefExpr from the DRSet. 16559 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16560 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16561 return Base::TransformCXXOperatorCallExpr(E); 16562 } 16563 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16564 /// here. 16565 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16566 if (!Init) 16567 return Init; 16568 /// ConstantExpr are the first layer of implicit node to be removed so if 16569 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16570 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16571 if (CE->isImmediateInvocation()) 16572 RemoveImmediateInvocation(CE); 16573 return Base::TransformInitializer(Init, NotCopyInit); 16574 } 16575 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16576 DRSet.erase(E); 16577 return E; 16578 } 16579 bool AlwaysRebuild() { return false; } 16580 bool ReplacingOriginal() { return true; } 16581 bool AllowSkippingCXXConstructExpr() { 16582 bool Res = AllowSkippingFirstCXXConstructExpr; 16583 AllowSkippingFirstCXXConstructExpr = true; 16584 return Res; 16585 } 16586 bool AllowSkippingFirstCXXConstructExpr = true; 16587 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16588 Rec.ImmediateInvocationCandidates, It); 16589 16590 /// CXXConstructExpr with a single argument are getting skipped by 16591 /// TreeTransform in some situtation because they could be implicit. This 16592 /// can only occur for the top-level CXXConstructExpr because it is used 16593 /// nowhere in the expression being transformed therefore will not be rebuilt. 16594 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16595 /// skipping the first CXXConstructExpr. 16596 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16597 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16598 16599 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16600 assert(Res.isUsable()); 16601 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16602 It->getPointer()->setSubExpr(Res.get()); 16603 } 16604 16605 static void 16606 HandleImmediateInvocations(Sema &SemaRef, 16607 Sema::ExpressionEvaluationContextRecord &Rec) { 16608 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16609 Rec.ReferenceToConsteval.size() == 0) || 16610 SemaRef.RebuildingImmediateInvocation) 16611 return; 16612 16613 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16614 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16615 /// need to remove ReferenceToConsteval in the immediate invocation. 16616 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16617 16618 /// Prevent sema calls during the tree transform from adding pointers that 16619 /// are already in the sets. 16620 llvm::SaveAndRestore<bool> DisableIITracking( 16621 SemaRef.RebuildingImmediateInvocation, true); 16622 16623 /// Prevent diagnostic during tree transfrom as they are duplicates 16624 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16625 16626 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16627 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16628 if (!It->getInt()) 16629 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16630 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16631 Rec.ReferenceToConsteval.size()) { 16632 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16633 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16634 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16635 bool VisitDeclRefExpr(DeclRefExpr *E) { 16636 DRSet.erase(E); 16637 return DRSet.size(); 16638 } 16639 } Visitor(Rec.ReferenceToConsteval); 16640 Visitor.TraverseStmt( 16641 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16642 } 16643 for (auto CE : Rec.ImmediateInvocationCandidates) 16644 if (!CE.getInt()) 16645 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16646 for (auto DR : Rec.ReferenceToConsteval) { 16647 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16648 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16649 << FD; 16650 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16651 } 16652 } 16653 16654 void Sema::PopExpressionEvaluationContext() { 16655 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16656 unsigned NumTypos = Rec.NumTypos; 16657 16658 if (!Rec.Lambdas.empty()) { 16659 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16660 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16661 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16662 unsigned D; 16663 if (Rec.isUnevaluated()) { 16664 // C++11 [expr.prim.lambda]p2: 16665 // A lambda-expression shall not appear in an unevaluated operand 16666 // (Clause 5). 16667 D = diag::err_lambda_unevaluated_operand; 16668 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16669 // C++1y [expr.const]p2: 16670 // A conditional-expression e is a core constant expression unless the 16671 // evaluation of e, following the rules of the abstract machine, would 16672 // evaluate [...] a lambda-expression. 16673 D = diag::err_lambda_in_constant_expression; 16674 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16675 // C++17 [expr.prim.lamda]p2: 16676 // A lambda-expression shall not appear [...] in a template-argument. 16677 D = diag::err_lambda_in_invalid_context; 16678 } else 16679 llvm_unreachable("Couldn't infer lambda error message."); 16680 16681 for (const auto *L : Rec.Lambdas) 16682 Diag(L->getBeginLoc(), D); 16683 } 16684 } 16685 16686 WarnOnPendingNoDerefs(Rec); 16687 HandleImmediateInvocations(*this, Rec); 16688 16689 // Warn on any volatile-qualified simple-assignments that are not discarded- 16690 // value expressions nor unevaluated operands (those cases get removed from 16691 // this list by CheckUnusedVolatileAssignment). 16692 for (auto *BO : Rec.VolatileAssignmentLHSs) 16693 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16694 << BO->getType(); 16695 16696 // When are coming out of an unevaluated context, clear out any 16697 // temporaries that we may have created as part of the evaluation of 16698 // the expression in that context: they aren't relevant because they 16699 // will never be constructed. 16700 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16701 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16702 ExprCleanupObjects.end()); 16703 Cleanup = Rec.ParentCleanup; 16704 CleanupVarDeclMarking(); 16705 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16706 // Otherwise, merge the contexts together. 16707 } else { 16708 Cleanup.mergeFrom(Rec.ParentCleanup); 16709 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16710 Rec.SavedMaybeODRUseExprs.end()); 16711 } 16712 16713 // Pop the current expression evaluation context off the stack. 16714 ExprEvalContexts.pop_back(); 16715 16716 // The global expression evaluation context record is never popped. 16717 ExprEvalContexts.back().NumTypos += NumTypos; 16718 } 16719 16720 void Sema::DiscardCleanupsInEvaluationContext() { 16721 ExprCleanupObjects.erase( 16722 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16723 ExprCleanupObjects.end()); 16724 Cleanup.reset(); 16725 MaybeODRUseExprs.clear(); 16726 } 16727 16728 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16729 ExprResult Result = CheckPlaceholderExpr(E); 16730 if (Result.isInvalid()) 16731 return ExprError(); 16732 E = Result.get(); 16733 if (!E->getType()->isVariablyModifiedType()) 16734 return E; 16735 return TransformToPotentiallyEvaluated(E); 16736 } 16737 16738 /// Are we in a context that is potentially constant evaluated per C++20 16739 /// [expr.const]p12? 16740 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16741 /// C++2a [expr.const]p12: 16742 // An expression or conversion is potentially constant evaluated if it is 16743 switch (SemaRef.ExprEvalContexts.back().Context) { 16744 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16745 // -- a manifestly constant-evaluated expression, 16746 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16747 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16748 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16749 // -- a potentially-evaluated expression, 16750 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16751 // -- an immediate subexpression of a braced-init-list, 16752 16753 // -- [FIXME] an expression of the form & cast-expression that occurs 16754 // within a templated entity 16755 // -- a subexpression of one of the above that is not a subexpression of 16756 // a nested unevaluated operand. 16757 return true; 16758 16759 case Sema::ExpressionEvaluationContext::Unevaluated: 16760 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16761 // Expressions in this context are never evaluated. 16762 return false; 16763 } 16764 llvm_unreachable("Invalid context"); 16765 } 16766 16767 /// Return true if this function has a calling convention that requires mangling 16768 /// in the size of the parameter pack. 16769 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16770 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16771 // we don't need parameter type sizes. 16772 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16773 if (!TT.isOSWindows() || !TT.isX86()) 16774 return false; 16775 16776 // If this is C++ and this isn't an extern "C" function, parameters do not 16777 // need to be complete. In this case, C++ mangling will apply, which doesn't 16778 // use the size of the parameters. 16779 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16780 return false; 16781 16782 // Stdcall, fastcall, and vectorcall need this special treatment. 16783 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16784 switch (CC) { 16785 case CC_X86StdCall: 16786 case CC_X86FastCall: 16787 case CC_X86VectorCall: 16788 return true; 16789 default: 16790 break; 16791 } 16792 return false; 16793 } 16794 16795 /// Require that all of the parameter types of function be complete. Normally, 16796 /// parameter types are only required to be complete when a function is called 16797 /// or defined, but to mangle functions with certain calling conventions, the 16798 /// mangler needs to know the size of the parameter list. In this situation, 16799 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16800 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16801 /// result in a linker error. Clang doesn't implement this behavior, and instead 16802 /// attempts to error at compile time. 16803 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16804 SourceLocation Loc) { 16805 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16806 FunctionDecl *FD; 16807 ParmVarDecl *Param; 16808 16809 public: 16810 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16811 : FD(FD), Param(Param) {} 16812 16813 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16814 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16815 StringRef CCName; 16816 switch (CC) { 16817 case CC_X86StdCall: 16818 CCName = "stdcall"; 16819 break; 16820 case CC_X86FastCall: 16821 CCName = "fastcall"; 16822 break; 16823 case CC_X86VectorCall: 16824 CCName = "vectorcall"; 16825 break; 16826 default: 16827 llvm_unreachable("CC does not need mangling"); 16828 } 16829 16830 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16831 << Param->getDeclName() << FD->getDeclName() << CCName; 16832 } 16833 }; 16834 16835 for (ParmVarDecl *Param : FD->parameters()) { 16836 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16837 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16838 } 16839 } 16840 16841 namespace { 16842 enum class OdrUseContext { 16843 /// Declarations in this context are not odr-used. 16844 None, 16845 /// Declarations in this context are formally odr-used, but this is a 16846 /// dependent context. 16847 Dependent, 16848 /// Declarations in this context are odr-used but not actually used (yet). 16849 FormallyOdrUsed, 16850 /// Declarations in this context are used. 16851 Used 16852 }; 16853 } 16854 16855 /// Are we within a context in which references to resolved functions or to 16856 /// variables result in odr-use? 16857 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16858 OdrUseContext Result; 16859 16860 switch (SemaRef.ExprEvalContexts.back().Context) { 16861 case Sema::ExpressionEvaluationContext::Unevaluated: 16862 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16863 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16864 return OdrUseContext::None; 16865 16866 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16867 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16868 Result = OdrUseContext::Used; 16869 break; 16870 16871 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16872 Result = OdrUseContext::FormallyOdrUsed; 16873 break; 16874 16875 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16876 // A default argument formally results in odr-use, but doesn't actually 16877 // result in a use in any real sense until it itself is used. 16878 Result = OdrUseContext::FormallyOdrUsed; 16879 break; 16880 } 16881 16882 if (SemaRef.CurContext->isDependentContext()) 16883 return OdrUseContext::Dependent; 16884 16885 return Result; 16886 } 16887 16888 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16889 if (!Func->isConstexpr()) 16890 return false; 16891 16892 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16893 return true; 16894 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16895 return CCD && CCD->getInheritedConstructor(); 16896 } 16897 16898 /// Mark a function referenced, and check whether it is odr-used 16899 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16900 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16901 bool MightBeOdrUse) { 16902 assert(Func && "No function?"); 16903 16904 Func->setReferenced(); 16905 16906 // Recursive functions aren't really used until they're used from some other 16907 // context. 16908 bool IsRecursiveCall = CurContext == Func; 16909 16910 // C++11 [basic.def.odr]p3: 16911 // A function whose name appears as a potentially-evaluated expression is 16912 // odr-used if it is the unique lookup result or the selected member of a 16913 // set of overloaded functions [...]. 16914 // 16915 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16916 // can just check that here. 16917 OdrUseContext OdrUse = 16918 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16919 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16920 OdrUse = OdrUseContext::FormallyOdrUsed; 16921 16922 // Trivial default constructors and destructors are never actually used. 16923 // FIXME: What about other special members? 16924 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16925 OdrUse == OdrUseContext::Used) { 16926 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16927 if (Constructor->isDefaultConstructor()) 16928 OdrUse = OdrUseContext::FormallyOdrUsed; 16929 if (isa<CXXDestructorDecl>(Func)) 16930 OdrUse = OdrUseContext::FormallyOdrUsed; 16931 } 16932 16933 // C++20 [expr.const]p12: 16934 // A function [...] is needed for constant evaluation if it is [...] a 16935 // constexpr function that is named by an expression that is potentially 16936 // constant evaluated 16937 bool NeededForConstantEvaluation = 16938 isPotentiallyConstantEvaluatedContext(*this) && 16939 isImplicitlyDefinableConstexprFunction(Func); 16940 16941 // Determine whether we require a function definition to exist, per 16942 // C++11 [temp.inst]p3: 16943 // Unless a function template specialization has been explicitly 16944 // instantiated or explicitly specialized, the function template 16945 // specialization is implicitly instantiated when the specialization is 16946 // referenced in a context that requires a function definition to exist. 16947 // C++20 [temp.inst]p7: 16948 // The existence of a definition of a [...] function is considered to 16949 // affect the semantics of the program if the [...] function is needed for 16950 // constant evaluation by an expression 16951 // C++20 [basic.def.odr]p10: 16952 // Every program shall contain exactly one definition of every non-inline 16953 // function or variable that is odr-used in that program outside of a 16954 // discarded statement 16955 // C++20 [special]p1: 16956 // The implementation will implicitly define [defaulted special members] 16957 // if they are odr-used or needed for constant evaluation. 16958 // 16959 // Note that we skip the implicit instantiation of templates that are only 16960 // used in unused default arguments or by recursive calls to themselves. 16961 // This is formally non-conforming, but seems reasonable in practice. 16962 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16963 NeededForConstantEvaluation); 16964 16965 // C++14 [temp.expl.spec]p6: 16966 // If a template [...] is explicitly specialized then that specialization 16967 // shall be declared before the first use of that specialization that would 16968 // cause an implicit instantiation to take place, in every translation unit 16969 // in which such a use occurs 16970 if (NeedDefinition && 16971 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16972 Func->getMemberSpecializationInfo())) 16973 checkSpecializationVisibility(Loc, Func); 16974 16975 if (getLangOpts().CUDA) 16976 CheckCUDACall(Loc, Func); 16977 16978 if (getLangOpts().SYCLIsDevice) 16979 checkSYCLDeviceFunction(Loc, Func); 16980 16981 // If we need a definition, try to create one. 16982 if (NeedDefinition && !Func->getBody()) { 16983 runWithSufficientStackSpace(Loc, [&] { 16984 if (CXXConstructorDecl *Constructor = 16985 dyn_cast<CXXConstructorDecl>(Func)) { 16986 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16987 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16988 if (Constructor->isDefaultConstructor()) { 16989 if (Constructor->isTrivial() && 16990 !Constructor->hasAttr<DLLExportAttr>()) 16991 return; 16992 DefineImplicitDefaultConstructor(Loc, Constructor); 16993 } else if (Constructor->isCopyConstructor()) { 16994 DefineImplicitCopyConstructor(Loc, Constructor); 16995 } else if (Constructor->isMoveConstructor()) { 16996 DefineImplicitMoveConstructor(Loc, Constructor); 16997 } 16998 } else if (Constructor->getInheritedConstructor()) { 16999 DefineInheritingConstructor(Loc, Constructor); 17000 } 17001 } else if (CXXDestructorDecl *Destructor = 17002 dyn_cast<CXXDestructorDecl>(Func)) { 17003 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17004 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17005 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17006 return; 17007 DefineImplicitDestructor(Loc, Destructor); 17008 } 17009 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17010 MarkVTableUsed(Loc, Destructor->getParent()); 17011 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17012 if (MethodDecl->isOverloadedOperator() && 17013 MethodDecl->getOverloadedOperator() == OO_Equal) { 17014 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17015 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17016 if (MethodDecl->isCopyAssignmentOperator()) 17017 DefineImplicitCopyAssignment(Loc, MethodDecl); 17018 else if (MethodDecl->isMoveAssignmentOperator()) 17019 DefineImplicitMoveAssignment(Loc, MethodDecl); 17020 } 17021 } else if (isa<CXXConversionDecl>(MethodDecl) && 17022 MethodDecl->getParent()->isLambda()) { 17023 CXXConversionDecl *Conversion = 17024 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17025 if (Conversion->isLambdaToBlockPointerConversion()) 17026 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17027 else 17028 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17029 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17030 MarkVTableUsed(Loc, MethodDecl->getParent()); 17031 } 17032 17033 if (Func->isDefaulted() && !Func->isDeleted()) { 17034 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17035 if (DCK != DefaultedComparisonKind::None) 17036 DefineDefaultedComparison(Loc, Func, DCK); 17037 } 17038 17039 // Implicit instantiation of function templates and member functions of 17040 // class templates. 17041 if (Func->isImplicitlyInstantiable()) { 17042 TemplateSpecializationKind TSK = 17043 Func->getTemplateSpecializationKindForInstantiation(); 17044 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17045 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17046 if (FirstInstantiation) { 17047 PointOfInstantiation = Loc; 17048 if (auto *MSI = Func->getMemberSpecializationInfo()) 17049 MSI->setPointOfInstantiation(Loc); 17050 // FIXME: Notify listener. 17051 else 17052 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17053 } else if (TSK != TSK_ImplicitInstantiation) { 17054 // Use the point of use as the point of instantiation, instead of the 17055 // point of explicit instantiation (which we track as the actual point 17056 // of instantiation). This gives better backtraces in diagnostics. 17057 PointOfInstantiation = Loc; 17058 } 17059 17060 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17061 Func->isConstexpr()) { 17062 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17063 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17064 CodeSynthesisContexts.size()) 17065 PendingLocalImplicitInstantiations.push_back( 17066 std::make_pair(Func, PointOfInstantiation)); 17067 else if (Func->isConstexpr()) 17068 // Do not defer instantiations of constexpr functions, to avoid the 17069 // expression evaluator needing to call back into Sema if it sees a 17070 // call to such a function. 17071 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17072 else { 17073 Func->setInstantiationIsPending(true); 17074 PendingInstantiations.push_back( 17075 std::make_pair(Func, PointOfInstantiation)); 17076 // Notify the consumer that a function was implicitly instantiated. 17077 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17078 } 17079 } 17080 } else { 17081 // Walk redefinitions, as some of them may be instantiable. 17082 for (auto i : Func->redecls()) { 17083 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17084 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17085 } 17086 } 17087 }); 17088 } 17089 17090 // C++14 [except.spec]p17: 17091 // An exception-specification is considered to be needed when: 17092 // - the function is odr-used or, if it appears in an unevaluated operand, 17093 // would be odr-used if the expression were potentially-evaluated; 17094 // 17095 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17096 // function is a pure virtual function we're calling, and in that case the 17097 // function was selected by overload resolution and we need to resolve its 17098 // exception specification for a different reason. 17099 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17100 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17101 ResolveExceptionSpec(Loc, FPT); 17102 17103 // If this is the first "real" use, act on that. 17104 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17105 // Keep track of used but undefined functions. 17106 if (!Func->isDefined()) { 17107 if (mightHaveNonExternalLinkage(Func)) 17108 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17109 else if (Func->getMostRecentDecl()->isInlined() && 17110 !LangOpts.GNUInline && 17111 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17112 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17113 else if (isExternalWithNoLinkageType(Func)) 17114 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17115 } 17116 17117 // Some x86 Windows calling conventions mangle the size of the parameter 17118 // pack into the name. Computing the size of the parameters requires the 17119 // parameter types to be complete. Check that now. 17120 if (funcHasParameterSizeMangling(*this, Func)) 17121 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17122 17123 // In the MS C++ ABI, the compiler emits destructor variants where they are 17124 // used. If the destructor is used here but defined elsewhere, mark the 17125 // virtual base destructors referenced. If those virtual base destructors 17126 // are inline, this will ensure they are defined when emitting the complete 17127 // destructor variant. This checking may be redundant if the destructor is 17128 // provided later in this TU. 17129 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17130 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17131 CXXRecordDecl *Parent = Dtor->getParent(); 17132 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17133 CheckCompleteDestructorVariant(Loc, Dtor); 17134 } 17135 } 17136 17137 Func->markUsed(Context); 17138 } 17139 } 17140 17141 /// Directly mark a variable odr-used. Given a choice, prefer to use 17142 /// MarkVariableReferenced since it does additional checks and then 17143 /// calls MarkVarDeclODRUsed. 17144 /// If the variable must be captured: 17145 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17146 /// - else capture it in the DeclContext that maps to the 17147 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17148 static void 17149 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17150 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17151 // Keep track of used but undefined variables. 17152 // FIXME: We shouldn't suppress this warning for static data members. 17153 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17154 (!Var->isExternallyVisible() || Var->isInline() || 17155 SemaRef.isExternalWithNoLinkageType(Var)) && 17156 !(Var->isStaticDataMember() && Var->hasInit())) { 17157 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17158 if (old.isInvalid()) 17159 old = Loc; 17160 } 17161 QualType CaptureType, DeclRefType; 17162 if (SemaRef.LangOpts.OpenMP) 17163 SemaRef.tryCaptureOpenMPLambdas(Var); 17164 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17165 /*EllipsisLoc*/ SourceLocation(), 17166 /*BuildAndDiagnose*/ true, 17167 CaptureType, DeclRefType, 17168 FunctionScopeIndexToStopAt); 17169 17170 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17171 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17172 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17173 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17174 if (VarTarget == Sema::CVT_Host && 17175 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17176 UserTarget == Sema::CFT_Global)) { 17177 // Diagnose ODR-use of host global variables in device functions. 17178 // Reference of device global variables in host functions is allowed 17179 // through shadow variables therefore it is not diagnosed. 17180 if (SemaRef.LangOpts.CUDAIsDevice) 17181 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17182 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17183 } else if (VarTarget == Sema::CVT_Device && 17184 (UserTarget == Sema::CFT_Host || 17185 UserTarget == Sema::CFT_HostDevice) && 17186 !Var->hasExternalStorage()) { 17187 // Record a CUDA/HIP device side variable if it is ODR-used 17188 // by host code. This is done conservatively, when the variable is 17189 // referenced in any of the following contexts: 17190 // - a non-function context 17191 // - a host function 17192 // - a host device function 17193 // This makes the ODR-use of the device side variable by host code to 17194 // be visible in the device compilation for the compiler to be able to 17195 // emit template variables instantiated by host code only and to 17196 // externalize the static device side variable ODR-used by host code. 17197 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17198 } 17199 } 17200 17201 Var->markUsed(SemaRef.Context); 17202 } 17203 17204 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17205 SourceLocation Loc, 17206 unsigned CapturingScopeIndex) { 17207 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17208 } 17209 17210 static void 17211 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17212 ValueDecl *var, DeclContext *DC) { 17213 DeclContext *VarDC = var->getDeclContext(); 17214 17215 // If the parameter still belongs to the translation unit, then 17216 // we're actually just using one parameter in the declaration of 17217 // the next. 17218 if (isa<ParmVarDecl>(var) && 17219 isa<TranslationUnitDecl>(VarDC)) 17220 return; 17221 17222 // For C code, don't diagnose about capture if we're not actually in code 17223 // right now; it's impossible to write a non-constant expression outside of 17224 // function context, so we'll get other (more useful) diagnostics later. 17225 // 17226 // For C++, things get a bit more nasty... it would be nice to suppress this 17227 // diagnostic for certain cases like using a local variable in an array bound 17228 // for a member of a local class, but the correct predicate is not obvious. 17229 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17230 return; 17231 17232 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17233 unsigned ContextKind = 3; // unknown 17234 if (isa<CXXMethodDecl>(VarDC) && 17235 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17236 ContextKind = 2; 17237 } else if (isa<FunctionDecl>(VarDC)) { 17238 ContextKind = 0; 17239 } else if (isa<BlockDecl>(VarDC)) { 17240 ContextKind = 1; 17241 } 17242 17243 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17244 << var << ValueKind << ContextKind << VarDC; 17245 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17246 << var; 17247 17248 // FIXME: Add additional diagnostic info about class etc. which prevents 17249 // capture. 17250 } 17251 17252 17253 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17254 bool &SubCapturesAreNested, 17255 QualType &CaptureType, 17256 QualType &DeclRefType) { 17257 // Check whether we've already captured it. 17258 if (CSI->CaptureMap.count(Var)) { 17259 // If we found a capture, any subcaptures are nested. 17260 SubCapturesAreNested = true; 17261 17262 // Retrieve the capture type for this variable. 17263 CaptureType = CSI->getCapture(Var).getCaptureType(); 17264 17265 // Compute the type of an expression that refers to this variable. 17266 DeclRefType = CaptureType.getNonReferenceType(); 17267 17268 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17269 // are mutable in the sense that user can change their value - they are 17270 // private instances of the captured declarations. 17271 const Capture &Cap = CSI->getCapture(Var); 17272 if (Cap.isCopyCapture() && 17273 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17274 !(isa<CapturedRegionScopeInfo>(CSI) && 17275 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17276 DeclRefType.addConst(); 17277 return true; 17278 } 17279 return false; 17280 } 17281 17282 // Only block literals, captured statements, and lambda expressions can 17283 // capture; other scopes don't work. 17284 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17285 SourceLocation Loc, 17286 const bool Diagnose, Sema &S) { 17287 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17288 return getLambdaAwareParentOfDeclContext(DC); 17289 else if (Var->hasLocalStorage()) { 17290 if (Diagnose) 17291 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17292 } 17293 return nullptr; 17294 } 17295 17296 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17297 // certain types of variables (unnamed, variably modified types etc.) 17298 // so check for eligibility. 17299 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17300 SourceLocation Loc, 17301 const bool Diagnose, Sema &S) { 17302 17303 bool IsBlock = isa<BlockScopeInfo>(CSI); 17304 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17305 17306 // Lambdas are not allowed to capture unnamed variables 17307 // (e.g. anonymous unions). 17308 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17309 // assuming that's the intent. 17310 if (IsLambda && !Var->getDeclName()) { 17311 if (Diagnose) { 17312 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17313 S.Diag(Var->getLocation(), diag::note_declared_at); 17314 } 17315 return false; 17316 } 17317 17318 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17319 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17320 if (Diagnose) { 17321 S.Diag(Loc, diag::err_ref_vm_type); 17322 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17323 } 17324 return false; 17325 } 17326 // Prohibit structs with flexible array members too. 17327 // We cannot capture what is in the tail end of the struct. 17328 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17329 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17330 if (Diagnose) { 17331 if (IsBlock) 17332 S.Diag(Loc, diag::err_ref_flexarray_type); 17333 else 17334 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17335 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17336 } 17337 return false; 17338 } 17339 } 17340 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17341 // Lambdas and captured statements are not allowed to capture __block 17342 // variables; they don't support the expected semantics. 17343 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17344 if (Diagnose) { 17345 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17346 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17347 } 17348 return false; 17349 } 17350 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17351 if (S.getLangOpts().OpenCL && IsBlock && 17352 Var->getType()->isBlockPointerType()) { 17353 if (Diagnose) 17354 S.Diag(Loc, diag::err_opencl_block_ref_block); 17355 return false; 17356 } 17357 17358 return true; 17359 } 17360 17361 // Returns true if the capture by block was successful. 17362 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17363 SourceLocation Loc, 17364 const bool BuildAndDiagnose, 17365 QualType &CaptureType, 17366 QualType &DeclRefType, 17367 const bool Nested, 17368 Sema &S, bool Invalid) { 17369 bool ByRef = false; 17370 17371 // Blocks are not allowed to capture arrays, excepting OpenCL. 17372 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17373 // (decayed to pointers). 17374 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17375 if (BuildAndDiagnose) { 17376 S.Diag(Loc, diag::err_ref_array_type); 17377 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17378 Invalid = true; 17379 } else { 17380 return false; 17381 } 17382 } 17383 17384 // Forbid the block-capture of autoreleasing variables. 17385 if (!Invalid && 17386 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17387 if (BuildAndDiagnose) { 17388 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17389 << /*block*/ 0; 17390 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17391 Invalid = true; 17392 } else { 17393 return false; 17394 } 17395 } 17396 17397 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17398 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17399 QualType PointeeTy = PT->getPointeeType(); 17400 17401 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17402 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17403 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17404 if (BuildAndDiagnose) { 17405 SourceLocation VarLoc = Var->getLocation(); 17406 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17407 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17408 } 17409 } 17410 } 17411 17412 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17413 if (HasBlocksAttr || CaptureType->isReferenceType() || 17414 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17415 // Block capture by reference does not change the capture or 17416 // declaration reference types. 17417 ByRef = true; 17418 } else { 17419 // Block capture by copy introduces 'const'. 17420 CaptureType = CaptureType.getNonReferenceType().withConst(); 17421 DeclRefType = CaptureType; 17422 } 17423 17424 // Actually capture the variable. 17425 if (BuildAndDiagnose) 17426 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17427 CaptureType, Invalid); 17428 17429 return !Invalid; 17430 } 17431 17432 17433 /// Capture the given variable in the captured region. 17434 static bool captureInCapturedRegion( 17435 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17436 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17437 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17438 bool IsTopScope, Sema &S, bool Invalid) { 17439 // By default, capture variables by reference. 17440 bool ByRef = true; 17441 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17442 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17443 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17444 // Using an LValue reference type is consistent with Lambdas (see below). 17445 if (S.isOpenMPCapturedDecl(Var)) { 17446 bool HasConst = DeclRefType.isConstQualified(); 17447 DeclRefType = DeclRefType.getUnqualifiedType(); 17448 // Don't lose diagnostics about assignments to const. 17449 if (HasConst) 17450 DeclRefType.addConst(); 17451 } 17452 // Do not capture firstprivates in tasks. 17453 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17454 OMPC_unknown) 17455 return true; 17456 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17457 RSI->OpenMPCaptureLevel); 17458 } 17459 17460 if (ByRef) 17461 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17462 else 17463 CaptureType = DeclRefType; 17464 17465 // Actually capture the variable. 17466 if (BuildAndDiagnose) 17467 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17468 Loc, SourceLocation(), CaptureType, Invalid); 17469 17470 return !Invalid; 17471 } 17472 17473 /// Capture the given variable in the lambda. 17474 static bool captureInLambda(LambdaScopeInfo *LSI, 17475 VarDecl *Var, 17476 SourceLocation Loc, 17477 const bool BuildAndDiagnose, 17478 QualType &CaptureType, 17479 QualType &DeclRefType, 17480 const bool RefersToCapturedVariable, 17481 const Sema::TryCaptureKind Kind, 17482 SourceLocation EllipsisLoc, 17483 const bool IsTopScope, 17484 Sema &S, bool Invalid) { 17485 // Determine whether we are capturing by reference or by value. 17486 bool ByRef = false; 17487 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17488 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17489 } else { 17490 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17491 } 17492 17493 // Compute the type of the field that will capture this variable. 17494 if (ByRef) { 17495 // C++11 [expr.prim.lambda]p15: 17496 // An entity is captured by reference if it is implicitly or 17497 // explicitly captured but not captured by copy. It is 17498 // unspecified whether additional unnamed non-static data 17499 // members are declared in the closure type for entities 17500 // captured by reference. 17501 // 17502 // FIXME: It is not clear whether we want to build an lvalue reference 17503 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17504 // to do the former, while EDG does the latter. Core issue 1249 will 17505 // clarify, but for now we follow GCC because it's a more permissive and 17506 // easily defensible position. 17507 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17508 } else { 17509 // C++11 [expr.prim.lambda]p14: 17510 // For each entity captured by copy, an unnamed non-static 17511 // data member is declared in the closure type. The 17512 // declaration order of these members is unspecified. The type 17513 // of such a data member is the type of the corresponding 17514 // captured entity if the entity is not a reference to an 17515 // object, or the referenced type otherwise. [Note: If the 17516 // captured entity is a reference to a function, the 17517 // corresponding data member is also a reference to a 17518 // function. - end note ] 17519 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17520 if (!RefType->getPointeeType()->isFunctionType()) 17521 CaptureType = RefType->getPointeeType(); 17522 } 17523 17524 // Forbid the lambda copy-capture of autoreleasing variables. 17525 if (!Invalid && 17526 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17527 if (BuildAndDiagnose) { 17528 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17529 S.Diag(Var->getLocation(), diag::note_previous_decl) 17530 << Var->getDeclName(); 17531 Invalid = true; 17532 } else { 17533 return false; 17534 } 17535 } 17536 17537 // Make sure that by-copy captures are of a complete and non-abstract type. 17538 if (!Invalid && BuildAndDiagnose) { 17539 if (!CaptureType->isDependentType() && 17540 S.RequireCompleteSizedType( 17541 Loc, CaptureType, 17542 diag::err_capture_of_incomplete_or_sizeless_type, 17543 Var->getDeclName())) 17544 Invalid = true; 17545 else if (S.RequireNonAbstractType(Loc, CaptureType, 17546 diag::err_capture_of_abstract_type)) 17547 Invalid = true; 17548 } 17549 } 17550 17551 // Compute the type of a reference to this captured variable. 17552 if (ByRef) 17553 DeclRefType = CaptureType.getNonReferenceType(); 17554 else { 17555 // C++ [expr.prim.lambda]p5: 17556 // The closure type for a lambda-expression has a public inline 17557 // function call operator [...]. This function call operator is 17558 // declared const (9.3.1) if and only if the lambda-expression's 17559 // parameter-declaration-clause is not followed by mutable. 17560 DeclRefType = CaptureType.getNonReferenceType(); 17561 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17562 DeclRefType.addConst(); 17563 } 17564 17565 // Add the capture. 17566 if (BuildAndDiagnose) 17567 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17568 Loc, EllipsisLoc, CaptureType, Invalid); 17569 17570 return !Invalid; 17571 } 17572 17573 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17574 // Offer a Copy fix even if the type is dependent. 17575 if (Var->getType()->isDependentType()) 17576 return true; 17577 QualType T = Var->getType().getNonReferenceType(); 17578 if (T.isTriviallyCopyableType(Context)) 17579 return true; 17580 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17581 17582 if (!(RD = RD->getDefinition())) 17583 return false; 17584 if (RD->hasSimpleCopyConstructor()) 17585 return true; 17586 if (RD->hasUserDeclaredCopyConstructor()) 17587 for (CXXConstructorDecl *Ctor : RD->ctors()) 17588 if (Ctor->isCopyConstructor()) 17589 return !Ctor->isDeleted(); 17590 } 17591 return false; 17592 } 17593 17594 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17595 /// default capture. Fixes may be omitted if they aren't allowed by the 17596 /// standard, for example we can't emit a default copy capture fix-it if we 17597 /// already explicitly copy capture capture another variable. 17598 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17599 VarDecl *Var) { 17600 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17601 // Don't offer Capture by copy of default capture by copy fixes if Var is 17602 // known not to be copy constructible. 17603 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17604 17605 SmallString<32> FixBuffer; 17606 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17607 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17608 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17609 if (ShouldOfferCopyFix) { 17610 // Offer fixes to insert an explicit capture for the variable. 17611 // [] -> [VarName] 17612 // [OtherCapture] -> [OtherCapture, VarName] 17613 FixBuffer.assign({Separator, Var->getName()}); 17614 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17615 << Var << /*value*/ 0 17616 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17617 } 17618 // As above but capture by reference. 17619 FixBuffer.assign({Separator, "&", Var->getName()}); 17620 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17621 << Var << /*reference*/ 1 17622 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17623 } 17624 17625 // Only try to offer default capture if there are no captures excluding this 17626 // and init captures. 17627 // [this]: OK. 17628 // [X = Y]: OK. 17629 // [&A, &B]: Don't offer. 17630 // [A, B]: Don't offer. 17631 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17632 return !C.isThisCapture() && !C.isInitCapture(); 17633 })) 17634 return; 17635 17636 // The default capture specifiers, '=' or '&', must appear first in the 17637 // capture body. 17638 SourceLocation DefaultInsertLoc = 17639 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17640 17641 if (ShouldOfferCopyFix) { 17642 bool CanDefaultCopyCapture = true; 17643 // [=, *this] OK since c++17 17644 // [=, this] OK since c++20 17645 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17646 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17647 ? LSI->getCXXThisCapture().isCopyCapture() 17648 : false; 17649 // We can't use default capture by copy if any captures already specified 17650 // capture by copy. 17651 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17652 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17653 })) { 17654 FixBuffer.assign({"=", Separator}); 17655 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17656 << /*value*/ 0 17657 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17658 } 17659 } 17660 17661 // We can't use default capture by reference if any captures already specified 17662 // capture by reference. 17663 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17664 return !C.isInitCapture() && C.isReferenceCapture() && 17665 !C.isThisCapture(); 17666 })) { 17667 FixBuffer.assign({"&", Separator}); 17668 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17669 << /*reference*/ 1 17670 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17671 } 17672 } 17673 17674 bool Sema::tryCaptureVariable( 17675 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17676 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17677 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17678 // An init-capture is notionally from the context surrounding its 17679 // declaration, but its parent DC is the lambda class. 17680 DeclContext *VarDC = Var->getDeclContext(); 17681 if (Var->isInitCapture()) 17682 VarDC = VarDC->getParent(); 17683 17684 DeclContext *DC = CurContext; 17685 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17686 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17687 // We need to sync up the Declaration Context with the 17688 // FunctionScopeIndexToStopAt 17689 if (FunctionScopeIndexToStopAt) { 17690 unsigned FSIndex = FunctionScopes.size() - 1; 17691 while (FSIndex != MaxFunctionScopesIndex) { 17692 DC = getLambdaAwareParentOfDeclContext(DC); 17693 --FSIndex; 17694 } 17695 } 17696 17697 17698 // If the variable is declared in the current context, there is no need to 17699 // capture it. 17700 if (VarDC == DC) return true; 17701 17702 // Capture global variables if it is required to use private copy of this 17703 // variable. 17704 bool IsGlobal = !Var->hasLocalStorage(); 17705 if (IsGlobal && 17706 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17707 MaxFunctionScopesIndex))) 17708 return true; 17709 Var = Var->getCanonicalDecl(); 17710 17711 // Walk up the stack to determine whether we can capture the variable, 17712 // performing the "simple" checks that don't depend on type. We stop when 17713 // we've either hit the declared scope of the variable or find an existing 17714 // capture of that variable. We start from the innermost capturing-entity 17715 // (the DC) and ensure that all intervening capturing-entities 17716 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17717 // declcontext can either capture the variable or have already captured 17718 // the variable. 17719 CaptureType = Var->getType(); 17720 DeclRefType = CaptureType.getNonReferenceType(); 17721 bool Nested = false; 17722 bool Explicit = (Kind != TryCapture_Implicit); 17723 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17724 do { 17725 // Only block literals, captured statements, and lambda expressions can 17726 // capture; other scopes don't work. 17727 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17728 ExprLoc, 17729 BuildAndDiagnose, 17730 *this); 17731 // We need to check for the parent *first* because, if we *have* 17732 // private-captured a global variable, we need to recursively capture it in 17733 // intermediate blocks, lambdas, etc. 17734 if (!ParentDC) { 17735 if (IsGlobal) { 17736 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17737 break; 17738 } 17739 return true; 17740 } 17741 17742 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17743 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17744 17745 17746 // Check whether we've already captured it. 17747 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17748 DeclRefType)) { 17749 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17750 break; 17751 } 17752 // If we are instantiating a generic lambda call operator body, 17753 // we do not want to capture new variables. What was captured 17754 // during either a lambdas transformation or initial parsing 17755 // should be used. 17756 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17757 if (BuildAndDiagnose) { 17758 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17759 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17760 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17761 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17762 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17763 buildLambdaCaptureFixit(*this, LSI, Var); 17764 } else 17765 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17766 } 17767 return true; 17768 } 17769 17770 // Try to capture variable-length arrays types. 17771 if (Var->getType()->isVariablyModifiedType()) { 17772 // We're going to walk down into the type and look for VLA 17773 // expressions. 17774 QualType QTy = Var->getType(); 17775 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17776 QTy = PVD->getOriginalType(); 17777 captureVariablyModifiedType(Context, QTy, CSI); 17778 } 17779 17780 if (getLangOpts().OpenMP) { 17781 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17782 // OpenMP private variables should not be captured in outer scope, so 17783 // just break here. Similarly, global variables that are captured in a 17784 // target region should not be captured outside the scope of the region. 17785 if (RSI->CapRegionKind == CR_OpenMP) { 17786 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17787 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17788 // If the variable is private (i.e. not captured) and has variably 17789 // modified type, we still need to capture the type for correct 17790 // codegen in all regions, associated with the construct. Currently, 17791 // it is captured in the innermost captured region only. 17792 if (IsOpenMPPrivateDecl != OMPC_unknown && 17793 Var->getType()->isVariablyModifiedType()) { 17794 QualType QTy = Var->getType(); 17795 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17796 QTy = PVD->getOriginalType(); 17797 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17798 I < E; ++I) { 17799 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17800 FunctionScopes[FunctionScopesIndex - I]); 17801 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17802 "Wrong number of captured regions associated with the " 17803 "OpenMP construct."); 17804 captureVariablyModifiedType(Context, QTy, OuterRSI); 17805 } 17806 } 17807 bool IsTargetCap = 17808 IsOpenMPPrivateDecl != OMPC_private && 17809 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17810 RSI->OpenMPCaptureLevel); 17811 // Do not capture global if it is not privatized in outer regions. 17812 bool IsGlobalCap = 17813 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17814 RSI->OpenMPCaptureLevel); 17815 17816 // When we detect target captures we are looking from inside the 17817 // target region, therefore we need to propagate the capture from the 17818 // enclosing region. Therefore, the capture is not initially nested. 17819 if (IsTargetCap) 17820 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17821 17822 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17823 (IsGlobal && !IsGlobalCap)) { 17824 Nested = !IsTargetCap; 17825 bool HasConst = DeclRefType.isConstQualified(); 17826 DeclRefType = DeclRefType.getUnqualifiedType(); 17827 // Don't lose diagnostics about assignments to const. 17828 if (HasConst) 17829 DeclRefType.addConst(); 17830 CaptureType = Context.getLValueReferenceType(DeclRefType); 17831 break; 17832 } 17833 } 17834 } 17835 } 17836 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17837 // No capture-default, and this is not an explicit capture 17838 // so cannot capture this variable. 17839 if (BuildAndDiagnose) { 17840 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17841 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17842 auto *LSI = cast<LambdaScopeInfo>(CSI); 17843 if (LSI->Lambda) { 17844 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17845 buildLambdaCaptureFixit(*this, LSI, Var); 17846 } 17847 // FIXME: If we error out because an outer lambda can not implicitly 17848 // capture a variable that an inner lambda explicitly captures, we 17849 // should have the inner lambda do the explicit capture - because 17850 // it makes for cleaner diagnostics later. This would purely be done 17851 // so that the diagnostic does not misleadingly claim that a variable 17852 // can not be captured by a lambda implicitly even though it is captured 17853 // explicitly. Suggestion: 17854 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17855 // at the function head 17856 // - cache the StartingDeclContext - this must be a lambda 17857 // - captureInLambda in the innermost lambda the variable. 17858 } 17859 return true; 17860 } 17861 17862 FunctionScopesIndex--; 17863 DC = ParentDC; 17864 Explicit = false; 17865 } while (!VarDC->Equals(DC)); 17866 17867 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17868 // computing the type of the capture at each step, checking type-specific 17869 // requirements, and adding captures if requested. 17870 // If the variable had already been captured previously, we start capturing 17871 // at the lambda nested within that one. 17872 bool Invalid = false; 17873 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17874 ++I) { 17875 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17876 17877 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17878 // certain types of variables (unnamed, variably modified types etc.) 17879 // so check for eligibility. 17880 if (!Invalid) 17881 Invalid = 17882 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17883 17884 // After encountering an error, if we're actually supposed to capture, keep 17885 // capturing in nested contexts to suppress any follow-on diagnostics. 17886 if (Invalid && !BuildAndDiagnose) 17887 return true; 17888 17889 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17890 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17891 DeclRefType, Nested, *this, Invalid); 17892 Nested = true; 17893 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17894 Invalid = !captureInCapturedRegion( 17895 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 17896 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 17897 Nested = true; 17898 } else { 17899 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17900 Invalid = 17901 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17902 DeclRefType, Nested, Kind, EllipsisLoc, 17903 /*IsTopScope*/ I == N - 1, *this, Invalid); 17904 Nested = true; 17905 } 17906 17907 if (Invalid && !BuildAndDiagnose) 17908 return true; 17909 } 17910 return Invalid; 17911 } 17912 17913 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17914 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17915 QualType CaptureType; 17916 QualType DeclRefType; 17917 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17918 /*BuildAndDiagnose=*/true, CaptureType, 17919 DeclRefType, nullptr); 17920 } 17921 17922 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17923 QualType CaptureType; 17924 QualType DeclRefType; 17925 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17926 /*BuildAndDiagnose=*/false, CaptureType, 17927 DeclRefType, nullptr); 17928 } 17929 17930 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17931 QualType CaptureType; 17932 QualType DeclRefType; 17933 17934 // Determine whether we can capture this variable. 17935 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17936 /*BuildAndDiagnose=*/false, CaptureType, 17937 DeclRefType, nullptr)) 17938 return QualType(); 17939 17940 return DeclRefType; 17941 } 17942 17943 namespace { 17944 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17945 // The produced TemplateArgumentListInfo* points to data stored within this 17946 // object, so should only be used in contexts where the pointer will not be 17947 // used after the CopiedTemplateArgs object is destroyed. 17948 class CopiedTemplateArgs { 17949 bool HasArgs; 17950 TemplateArgumentListInfo TemplateArgStorage; 17951 public: 17952 template<typename RefExpr> 17953 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17954 if (HasArgs) 17955 E->copyTemplateArgumentsInto(TemplateArgStorage); 17956 } 17957 operator TemplateArgumentListInfo*() 17958 #ifdef __has_cpp_attribute 17959 #if __has_cpp_attribute(clang::lifetimebound) 17960 [[clang::lifetimebound]] 17961 #endif 17962 #endif 17963 { 17964 return HasArgs ? &TemplateArgStorage : nullptr; 17965 } 17966 }; 17967 } 17968 17969 /// Walk the set of potential results of an expression and mark them all as 17970 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17971 /// 17972 /// \return A new expression if we found any potential results, ExprEmpty() if 17973 /// not, and ExprError() if we diagnosed an error. 17974 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17975 NonOdrUseReason NOUR) { 17976 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17977 // an object that satisfies the requirements for appearing in a 17978 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17979 // is immediately applied." This function handles the lvalue-to-rvalue 17980 // conversion part. 17981 // 17982 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17983 // transform it into the relevant kind of non-odr-use node and rebuild the 17984 // tree of nodes leading to it. 17985 // 17986 // This is a mini-TreeTransform that only transforms a restricted subset of 17987 // nodes (and only certain operands of them). 17988 17989 // Rebuild a subexpression. 17990 auto Rebuild = [&](Expr *Sub) { 17991 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17992 }; 17993 17994 // Check whether a potential result satisfies the requirements of NOUR. 17995 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17996 // Any entity other than a VarDecl is always odr-used whenever it's named 17997 // in a potentially-evaluated expression. 17998 auto *VD = dyn_cast<VarDecl>(D); 17999 if (!VD) 18000 return true; 18001 18002 // C++2a [basic.def.odr]p4: 18003 // A variable x whose name appears as a potentially-evalauted expression 18004 // e is odr-used by e unless 18005 // -- x is a reference that is usable in constant expressions, or 18006 // -- x is a variable of non-reference type that is usable in constant 18007 // expressions and has no mutable subobjects, and e is an element of 18008 // the set of potential results of an expression of 18009 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18010 // conversion is applied, or 18011 // -- x is a variable of non-reference type, and e is an element of the 18012 // set of potential results of a discarded-value expression to which 18013 // the lvalue-to-rvalue conversion is not applied 18014 // 18015 // We check the first bullet and the "potentially-evaluated" condition in 18016 // BuildDeclRefExpr. We check the type requirements in the second bullet 18017 // in CheckLValueToRValueConversionOperand below. 18018 switch (NOUR) { 18019 case NOUR_None: 18020 case NOUR_Unevaluated: 18021 llvm_unreachable("unexpected non-odr-use-reason"); 18022 18023 case NOUR_Constant: 18024 // Constant references were handled when they were built. 18025 if (VD->getType()->isReferenceType()) 18026 return true; 18027 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18028 if (RD->hasMutableFields()) 18029 return true; 18030 if (!VD->isUsableInConstantExpressions(S.Context)) 18031 return true; 18032 break; 18033 18034 case NOUR_Discarded: 18035 if (VD->getType()->isReferenceType()) 18036 return true; 18037 break; 18038 } 18039 return false; 18040 }; 18041 18042 // Mark that this expression does not constitute an odr-use. 18043 auto MarkNotOdrUsed = [&] { 18044 S.MaybeODRUseExprs.remove(E); 18045 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18046 LSI->markVariableExprAsNonODRUsed(E); 18047 }; 18048 18049 // C++2a [basic.def.odr]p2: 18050 // The set of potential results of an expression e is defined as follows: 18051 switch (E->getStmtClass()) { 18052 // -- If e is an id-expression, ... 18053 case Expr::DeclRefExprClass: { 18054 auto *DRE = cast<DeclRefExpr>(E); 18055 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18056 break; 18057 18058 // Rebuild as a non-odr-use DeclRefExpr. 18059 MarkNotOdrUsed(); 18060 return DeclRefExpr::Create( 18061 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18062 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18063 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18064 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18065 } 18066 18067 case Expr::FunctionParmPackExprClass: { 18068 auto *FPPE = cast<FunctionParmPackExpr>(E); 18069 // If any of the declarations in the pack is odr-used, then the expression 18070 // as a whole constitutes an odr-use. 18071 for (VarDecl *D : *FPPE) 18072 if (IsPotentialResultOdrUsed(D)) 18073 return ExprEmpty(); 18074 18075 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18076 // nothing cares about whether we marked this as an odr-use, but it might 18077 // be useful for non-compiler tools. 18078 MarkNotOdrUsed(); 18079 break; 18080 } 18081 18082 // -- If e is a subscripting operation with an array operand... 18083 case Expr::ArraySubscriptExprClass: { 18084 auto *ASE = cast<ArraySubscriptExpr>(E); 18085 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18086 if (!OldBase->getType()->isArrayType()) 18087 break; 18088 ExprResult Base = Rebuild(OldBase); 18089 if (!Base.isUsable()) 18090 return Base; 18091 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18092 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18093 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18094 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18095 ASE->getRBracketLoc()); 18096 } 18097 18098 case Expr::MemberExprClass: { 18099 auto *ME = cast<MemberExpr>(E); 18100 // -- If e is a class member access expression [...] naming a non-static 18101 // data member... 18102 if (isa<FieldDecl>(ME->getMemberDecl())) { 18103 ExprResult Base = Rebuild(ME->getBase()); 18104 if (!Base.isUsable()) 18105 return Base; 18106 return MemberExpr::Create( 18107 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18108 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18109 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18110 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18111 ME->getObjectKind(), ME->isNonOdrUse()); 18112 } 18113 18114 if (ME->getMemberDecl()->isCXXInstanceMember()) 18115 break; 18116 18117 // -- If e is a class member access expression naming a static data member, 18118 // ... 18119 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18120 break; 18121 18122 // Rebuild as a non-odr-use MemberExpr. 18123 MarkNotOdrUsed(); 18124 return MemberExpr::Create( 18125 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18126 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18127 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18128 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18129 return ExprEmpty(); 18130 } 18131 18132 case Expr::BinaryOperatorClass: { 18133 auto *BO = cast<BinaryOperator>(E); 18134 Expr *LHS = BO->getLHS(); 18135 Expr *RHS = BO->getRHS(); 18136 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18137 if (BO->getOpcode() == BO_PtrMemD) { 18138 ExprResult Sub = Rebuild(LHS); 18139 if (!Sub.isUsable()) 18140 return Sub; 18141 LHS = Sub.get(); 18142 // -- If e is a comma expression, ... 18143 } else if (BO->getOpcode() == BO_Comma) { 18144 ExprResult Sub = Rebuild(RHS); 18145 if (!Sub.isUsable()) 18146 return Sub; 18147 RHS = Sub.get(); 18148 } else { 18149 break; 18150 } 18151 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18152 LHS, RHS); 18153 } 18154 18155 // -- If e has the form (e1)... 18156 case Expr::ParenExprClass: { 18157 auto *PE = cast<ParenExpr>(E); 18158 ExprResult Sub = Rebuild(PE->getSubExpr()); 18159 if (!Sub.isUsable()) 18160 return Sub; 18161 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18162 } 18163 18164 // -- If e is a glvalue conditional expression, ... 18165 // We don't apply this to a binary conditional operator. FIXME: Should we? 18166 case Expr::ConditionalOperatorClass: { 18167 auto *CO = cast<ConditionalOperator>(E); 18168 ExprResult LHS = Rebuild(CO->getLHS()); 18169 if (LHS.isInvalid()) 18170 return ExprError(); 18171 ExprResult RHS = Rebuild(CO->getRHS()); 18172 if (RHS.isInvalid()) 18173 return ExprError(); 18174 if (!LHS.isUsable() && !RHS.isUsable()) 18175 return ExprEmpty(); 18176 if (!LHS.isUsable()) 18177 LHS = CO->getLHS(); 18178 if (!RHS.isUsable()) 18179 RHS = CO->getRHS(); 18180 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18181 CO->getCond(), LHS.get(), RHS.get()); 18182 } 18183 18184 // [Clang extension] 18185 // -- If e has the form __extension__ e1... 18186 case Expr::UnaryOperatorClass: { 18187 auto *UO = cast<UnaryOperator>(E); 18188 if (UO->getOpcode() != UO_Extension) 18189 break; 18190 ExprResult Sub = Rebuild(UO->getSubExpr()); 18191 if (!Sub.isUsable()) 18192 return Sub; 18193 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18194 Sub.get()); 18195 } 18196 18197 // [Clang extension] 18198 // -- If e has the form _Generic(...), the set of potential results is the 18199 // union of the sets of potential results of the associated expressions. 18200 case Expr::GenericSelectionExprClass: { 18201 auto *GSE = cast<GenericSelectionExpr>(E); 18202 18203 SmallVector<Expr *, 4> AssocExprs; 18204 bool AnyChanged = false; 18205 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18206 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18207 if (AssocExpr.isInvalid()) 18208 return ExprError(); 18209 if (AssocExpr.isUsable()) { 18210 AssocExprs.push_back(AssocExpr.get()); 18211 AnyChanged = true; 18212 } else { 18213 AssocExprs.push_back(OrigAssocExpr); 18214 } 18215 } 18216 18217 return AnyChanged ? S.CreateGenericSelectionExpr( 18218 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18219 GSE->getRParenLoc(), GSE->getControllingExpr(), 18220 GSE->getAssocTypeSourceInfos(), AssocExprs) 18221 : ExprEmpty(); 18222 } 18223 18224 // [Clang extension] 18225 // -- If e has the form __builtin_choose_expr(...), the set of potential 18226 // results is the union of the sets of potential results of the 18227 // second and third subexpressions. 18228 case Expr::ChooseExprClass: { 18229 auto *CE = cast<ChooseExpr>(E); 18230 18231 ExprResult LHS = Rebuild(CE->getLHS()); 18232 if (LHS.isInvalid()) 18233 return ExprError(); 18234 18235 ExprResult RHS = Rebuild(CE->getLHS()); 18236 if (RHS.isInvalid()) 18237 return ExprError(); 18238 18239 if (!LHS.get() && !RHS.get()) 18240 return ExprEmpty(); 18241 if (!LHS.isUsable()) 18242 LHS = CE->getLHS(); 18243 if (!RHS.isUsable()) 18244 RHS = CE->getRHS(); 18245 18246 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18247 RHS.get(), CE->getRParenLoc()); 18248 } 18249 18250 // Step through non-syntactic nodes. 18251 case Expr::ConstantExprClass: { 18252 auto *CE = cast<ConstantExpr>(E); 18253 ExprResult Sub = Rebuild(CE->getSubExpr()); 18254 if (!Sub.isUsable()) 18255 return Sub; 18256 return ConstantExpr::Create(S.Context, Sub.get()); 18257 } 18258 18259 // We could mostly rely on the recursive rebuilding to rebuild implicit 18260 // casts, but not at the top level, so rebuild them here. 18261 case Expr::ImplicitCastExprClass: { 18262 auto *ICE = cast<ImplicitCastExpr>(E); 18263 // Only step through the narrow set of cast kinds we expect to encounter. 18264 // Anything else suggests we've left the region in which potential results 18265 // can be found. 18266 switch (ICE->getCastKind()) { 18267 case CK_NoOp: 18268 case CK_DerivedToBase: 18269 case CK_UncheckedDerivedToBase: { 18270 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18271 if (!Sub.isUsable()) 18272 return Sub; 18273 CXXCastPath Path(ICE->path()); 18274 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18275 ICE->getValueKind(), &Path); 18276 } 18277 18278 default: 18279 break; 18280 } 18281 break; 18282 } 18283 18284 default: 18285 break; 18286 } 18287 18288 // Can't traverse through this node. Nothing to do. 18289 return ExprEmpty(); 18290 } 18291 18292 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18293 // Check whether the operand is or contains an object of non-trivial C union 18294 // type. 18295 if (E->getType().isVolatileQualified() && 18296 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18297 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18298 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18299 Sema::NTCUC_LValueToRValueVolatile, 18300 NTCUK_Destruct|NTCUK_Copy); 18301 18302 // C++2a [basic.def.odr]p4: 18303 // [...] an expression of non-volatile-qualified non-class type to which 18304 // the lvalue-to-rvalue conversion is applied [...] 18305 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18306 return E; 18307 18308 ExprResult Result = 18309 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18310 if (Result.isInvalid()) 18311 return ExprError(); 18312 return Result.get() ? Result : E; 18313 } 18314 18315 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18316 Res = CorrectDelayedTyposInExpr(Res); 18317 18318 if (!Res.isUsable()) 18319 return Res; 18320 18321 // If a constant-expression is a reference to a variable where we delay 18322 // deciding whether it is an odr-use, just assume we will apply the 18323 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18324 // (a non-type template argument), we have special handling anyway. 18325 return CheckLValueToRValueConversionOperand(Res.get()); 18326 } 18327 18328 void Sema::CleanupVarDeclMarking() { 18329 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18330 // call. 18331 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18332 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18333 18334 for (Expr *E : LocalMaybeODRUseExprs) { 18335 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18336 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18337 DRE->getLocation(), *this); 18338 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18339 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18340 *this); 18341 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18342 for (VarDecl *VD : *FP) 18343 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18344 } else { 18345 llvm_unreachable("Unexpected expression"); 18346 } 18347 } 18348 18349 assert(MaybeODRUseExprs.empty() && 18350 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18351 } 18352 18353 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 18354 VarDecl *Var, Expr *E) { 18355 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18356 isa<FunctionParmPackExpr>(E)) && 18357 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18358 Var->setReferenced(); 18359 18360 if (Var->isInvalidDecl()) 18361 return; 18362 18363 auto *MSI = Var->getMemberSpecializationInfo(); 18364 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18365 : Var->getTemplateSpecializationKind(); 18366 18367 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18368 bool UsableInConstantExpr = 18369 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18370 18371 // C++20 [expr.const]p12: 18372 // A variable [...] is needed for constant evaluation if it is [...] a 18373 // variable whose name appears as a potentially constant evaluated 18374 // expression that is either a contexpr variable or is of non-volatile 18375 // const-qualified integral type or of reference type 18376 bool NeededForConstantEvaluation = 18377 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18378 18379 bool NeedDefinition = 18380 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18381 18382 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18383 "Can't instantiate a partial template specialization."); 18384 18385 // If this might be a member specialization of a static data member, check 18386 // the specialization is visible. We already did the checks for variable 18387 // template specializations when we created them. 18388 if (NeedDefinition && TSK != TSK_Undeclared && 18389 !isa<VarTemplateSpecializationDecl>(Var)) 18390 SemaRef.checkSpecializationVisibility(Loc, Var); 18391 18392 // Perform implicit instantiation of static data members, static data member 18393 // templates of class templates, and variable template specializations. Delay 18394 // instantiations of variable templates, except for those that could be used 18395 // in a constant expression. 18396 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18397 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18398 // instantiation declaration if a variable is usable in a constant 18399 // expression (among other cases). 18400 bool TryInstantiating = 18401 TSK == TSK_ImplicitInstantiation || 18402 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18403 18404 if (TryInstantiating) { 18405 SourceLocation PointOfInstantiation = 18406 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18407 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18408 if (FirstInstantiation) { 18409 PointOfInstantiation = Loc; 18410 if (MSI) 18411 MSI->setPointOfInstantiation(PointOfInstantiation); 18412 // FIXME: Notify listener. 18413 else 18414 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18415 } 18416 18417 if (UsableInConstantExpr) { 18418 // Do not defer instantiations of variables that could be used in a 18419 // constant expression. 18420 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18421 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18422 }); 18423 18424 // Re-set the member to trigger a recomputation of the dependence bits 18425 // for the expression. 18426 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18427 DRE->setDecl(DRE->getDecl()); 18428 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18429 ME->setMemberDecl(ME->getMemberDecl()); 18430 } else if (FirstInstantiation || 18431 isa<VarTemplateSpecializationDecl>(Var)) { 18432 // FIXME: For a specialization of a variable template, we don't 18433 // distinguish between "declaration and type implicitly instantiated" 18434 // and "implicit instantiation of definition requested", so we have 18435 // no direct way to avoid enqueueing the pending instantiation 18436 // multiple times. 18437 SemaRef.PendingInstantiations 18438 .push_back(std::make_pair(Var, PointOfInstantiation)); 18439 } 18440 } 18441 } 18442 18443 // C++2a [basic.def.odr]p4: 18444 // A variable x whose name appears as a potentially-evaluated expression e 18445 // is odr-used by e unless 18446 // -- x is a reference that is usable in constant expressions 18447 // -- x is a variable of non-reference type that is usable in constant 18448 // expressions and has no mutable subobjects [FIXME], and e is an 18449 // element of the set of potential results of an expression of 18450 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18451 // conversion is applied 18452 // -- x is a variable of non-reference type, and e is an element of the set 18453 // of potential results of a discarded-value expression to which the 18454 // lvalue-to-rvalue conversion is not applied [FIXME] 18455 // 18456 // We check the first part of the second bullet here, and 18457 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18458 // FIXME: To get the third bullet right, we need to delay this even for 18459 // variables that are not usable in constant expressions. 18460 18461 // If we already know this isn't an odr-use, there's nothing more to do. 18462 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18463 if (DRE->isNonOdrUse()) 18464 return; 18465 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18466 if (ME->isNonOdrUse()) 18467 return; 18468 18469 switch (OdrUse) { 18470 case OdrUseContext::None: 18471 assert((!E || isa<FunctionParmPackExpr>(E)) && 18472 "missing non-odr-use marking for unevaluated decl ref"); 18473 break; 18474 18475 case OdrUseContext::FormallyOdrUsed: 18476 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18477 // behavior. 18478 break; 18479 18480 case OdrUseContext::Used: 18481 // If we might later find that this expression isn't actually an odr-use, 18482 // delay the marking. 18483 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18484 SemaRef.MaybeODRUseExprs.insert(E); 18485 else 18486 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18487 break; 18488 18489 case OdrUseContext::Dependent: 18490 // If this is a dependent context, we don't need to mark variables as 18491 // odr-used, but we may still need to track them for lambda capture. 18492 // FIXME: Do we also need to do this inside dependent typeid expressions 18493 // (which are modeled as unevaluated at this point)? 18494 const bool RefersToEnclosingScope = 18495 (SemaRef.CurContext != Var->getDeclContext() && 18496 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18497 if (RefersToEnclosingScope) { 18498 LambdaScopeInfo *const LSI = 18499 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18500 if (LSI && (!LSI->CallOperator || 18501 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18502 // If a variable could potentially be odr-used, defer marking it so 18503 // until we finish analyzing the full expression for any 18504 // lvalue-to-rvalue 18505 // or discarded value conversions that would obviate odr-use. 18506 // Add it to the list of potential captures that will be analyzed 18507 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18508 // unless the variable is a reference that was initialized by a constant 18509 // expression (this will never need to be captured or odr-used). 18510 // 18511 // FIXME: We can simplify this a lot after implementing P0588R1. 18512 assert(E && "Capture variable should be used in an expression."); 18513 if (!Var->getType()->isReferenceType() || 18514 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18515 LSI->addPotentialCapture(E->IgnoreParens()); 18516 } 18517 } 18518 break; 18519 } 18520 } 18521 18522 /// Mark a variable referenced, and check whether it is odr-used 18523 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18524 /// used directly for normal expressions referring to VarDecl. 18525 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18526 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18527 } 18528 18529 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18530 Decl *D, Expr *E, bool MightBeOdrUse) { 18531 if (SemaRef.isInOpenMPDeclareTargetContext()) 18532 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18533 18534 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18535 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18536 return; 18537 } 18538 18539 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18540 18541 // If this is a call to a method via a cast, also mark the method in the 18542 // derived class used in case codegen can devirtualize the call. 18543 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18544 if (!ME) 18545 return; 18546 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18547 if (!MD) 18548 return; 18549 // Only attempt to devirtualize if this is truly a virtual call. 18550 bool IsVirtualCall = MD->isVirtual() && 18551 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18552 if (!IsVirtualCall) 18553 return; 18554 18555 // If it's possible to devirtualize the call, mark the called function 18556 // referenced. 18557 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18558 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18559 if (DM) 18560 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18561 } 18562 18563 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18564 /// 18565 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18566 /// handled with care if the DeclRefExpr is not newly-created. 18567 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18568 // TODO: update this with DR# once a defect report is filed. 18569 // C++11 defect. The address of a pure member should not be an ODR use, even 18570 // if it's a qualified reference. 18571 bool OdrUse = true; 18572 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18573 if (Method->isVirtual() && 18574 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18575 OdrUse = false; 18576 18577 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18578 if (!isConstantEvaluated() && FD->isConsteval() && 18579 !RebuildingImmediateInvocation) 18580 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18581 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18582 } 18583 18584 /// Perform reference-marking and odr-use handling for a MemberExpr. 18585 void Sema::MarkMemberReferenced(MemberExpr *E) { 18586 // C++11 [basic.def.odr]p2: 18587 // A non-overloaded function whose name appears as a potentially-evaluated 18588 // expression or a member of a set of candidate functions, if selected by 18589 // overload resolution when referred to from a potentially-evaluated 18590 // expression, is odr-used, unless it is a pure virtual function and its 18591 // name is not explicitly qualified. 18592 bool MightBeOdrUse = true; 18593 if (E->performsVirtualDispatch(getLangOpts())) { 18594 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18595 if (Method->isPure()) 18596 MightBeOdrUse = false; 18597 } 18598 SourceLocation Loc = 18599 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18600 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18601 } 18602 18603 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18604 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18605 for (VarDecl *VD : *E) 18606 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18607 } 18608 18609 /// Perform marking for a reference to an arbitrary declaration. It 18610 /// marks the declaration referenced, and performs odr-use checking for 18611 /// functions and variables. This method should not be used when building a 18612 /// normal expression which refers to a variable. 18613 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18614 bool MightBeOdrUse) { 18615 if (MightBeOdrUse) { 18616 if (auto *VD = dyn_cast<VarDecl>(D)) { 18617 MarkVariableReferenced(Loc, VD); 18618 return; 18619 } 18620 } 18621 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18622 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18623 return; 18624 } 18625 D->setReferenced(); 18626 } 18627 18628 namespace { 18629 // Mark all of the declarations used by a type as referenced. 18630 // FIXME: Not fully implemented yet! We need to have a better understanding 18631 // of when we're entering a context we should not recurse into. 18632 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18633 // TreeTransforms rebuilding the type in a new context. Rather than 18634 // duplicating the TreeTransform logic, we should consider reusing it here. 18635 // Currently that causes problems when rebuilding LambdaExprs. 18636 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18637 Sema &S; 18638 SourceLocation Loc; 18639 18640 public: 18641 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18642 18643 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18644 18645 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18646 }; 18647 } 18648 18649 bool MarkReferencedDecls::TraverseTemplateArgument( 18650 const TemplateArgument &Arg) { 18651 { 18652 // A non-type template argument is a constant-evaluated context. 18653 EnterExpressionEvaluationContext Evaluated( 18654 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18655 if (Arg.getKind() == TemplateArgument::Declaration) { 18656 if (Decl *D = Arg.getAsDecl()) 18657 S.MarkAnyDeclReferenced(Loc, D, true); 18658 } else if (Arg.getKind() == TemplateArgument::Expression) { 18659 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18660 } 18661 } 18662 18663 return Inherited::TraverseTemplateArgument(Arg); 18664 } 18665 18666 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18667 MarkReferencedDecls Marker(*this, Loc); 18668 Marker.TraverseType(T); 18669 } 18670 18671 namespace { 18672 /// Helper class that marks all of the declarations referenced by 18673 /// potentially-evaluated subexpressions as "referenced". 18674 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18675 public: 18676 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18677 bool SkipLocalVariables; 18678 18679 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18680 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18681 18682 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18683 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18684 } 18685 18686 void VisitDeclRefExpr(DeclRefExpr *E) { 18687 // If we were asked not to visit local variables, don't. 18688 if (SkipLocalVariables) { 18689 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18690 if (VD->hasLocalStorage()) 18691 return; 18692 } 18693 18694 // FIXME: This can trigger the instantiation of the initializer of a 18695 // variable, which can cause the expression to become value-dependent 18696 // or error-dependent. Do we need to propagate the new dependence bits? 18697 S.MarkDeclRefReferenced(E); 18698 } 18699 18700 void VisitMemberExpr(MemberExpr *E) { 18701 S.MarkMemberReferenced(E); 18702 Visit(E->getBase()); 18703 } 18704 }; 18705 } // namespace 18706 18707 /// Mark any declarations that appear within this expression or any 18708 /// potentially-evaluated subexpressions as "referenced". 18709 /// 18710 /// \param SkipLocalVariables If true, don't mark local variables as 18711 /// 'referenced'. 18712 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18713 bool SkipLocalVariables) { 18714 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18715 } 18716 18717 /// Emit a diagnostic that describes an effect on the run-time behavior 18718 /// of the program being compiled. 18719 /// 18720 /// This routine emits the given diagnostic when the code currently being 18721 /// type-checked is "potentially evaluated", meaning that there is a 18722 /// possibility that the code will actually be executable. Code in sizeof() 18723 /// expressions, code used only during overload resolution, etc., are not 18724 /// potentially evaluated. This routine will suppress such diagnostics or, 18725 /// in the absolutely nutty case of potentially potentially evaluated 18726 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18727 /// later. 18728 /// 18729 /// This routine should be used for all diagnostics that describe the run-time 18730 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18731 /// Failure to do so will likely result in spurious diagnostics or failures 18732 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18733 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18734 const PartialDiagnostic &PD) { 18735 switch (ExprEvalContexts.back().Context) { 18736 case ExpressionEvaluationContext::Unevaluated: 18737 case ExpressionEvaluationContext::UnevaluatedList: 18738 case ExpressionEvaluationContext::UnevaluatedAbstract: 18739 case ExpressionEvaluationContext::DiscardedStatement: 18740 // The argument will never be evaluated, so don't complain. 18741 break; 18742 18743 case ExpressionEvaluationContext::ConstantEvaluated: 18744 // Relevant diagnostics should be produced by constant evaluation. 18745 break; 18746 18747 case ExpressionEvaluationContext::PotentiallyEvaluated: 18748 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18749 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18750 FunctionScopes.back()->PossiblyUnreachableDiags. 18751 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18752 return true; 18753 } 18754 18755 // The initializer of a constexpr variable or of the first declaration of a 18756 // static data member is not syntactically a constant evaluated constant, 18757 // but nonetheless is always required to be a constant expression, so we 18758 // can skip diagnosing. 18759 // FIXME: Using the mangling context here is a hack. 18760 if (auto *VD = dyn_cast_or_null<VarDecl>( 18761 ExprEvalContexts.back().ManglingContextDecl)) { 18762 if (VD->isConstexpr() || 18763 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18764 break; 18765 // FIXME: For any other kind of variable, we should build a CFG for its 18766 // initializer and check whether the context in question is reachable. 18767 } 18768 18769 Diag(Loc, PD); 18770 return true; 18771 } 18772 18773 return false; 18774 } 18775 18776 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18777 const PartialDiagnostic &PD) { 18778 return DiagRuntimeBehavior( 18779 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18780 } 18781 18782 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18783 CallExpr *CE, FunctionDecl *FD) { 18784 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18785 return false; 18786 18787 // If we're inside a decltype's expression, don't check for a valid return 18788 // type or construct temporaries until we know whether this is the last call. 18789 if (ExprEvalContexts.back().ExprContext == 18790 ExpressionEvaluationContextRecord::EK_Decltype) { 18791 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18792 return false; 18793 } 18794 18795 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18796 FunctionDecl *FD; 18797 CallExpr *CE; 18798 18799 public: 18800 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18801 : FD(FD), CE(CE) { } 18802 18803 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18804 if (!FD) { 18805 S.Diag(Loc, diag::err_call_incomplete_return) 18806 << T << CE->getSourceRange(); 18807 return; 18808 } 18809 18810 S.Diag(Loc, diag::err_call_function_incomplete_return) 18811 << CE->getSourceRange() << FD << T; 18812 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18813 << FD->getDeclName(); 18814 } 18815 } Diagnoser(FD, CE); 18816 18817 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18818 return true; 18819 18820 return false; 18821 } 18822 18823 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18824 // will prevent this condition from triggering, which is what we want. 18825 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18826 SourceLocation Loc; 18827 18828 unsigned diagnostic = diag::warn_condition_is_assignment; 18829 bool IsOrAssign = false; 18830 18831 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18832 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18833 return; 18834 18835 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18836 18837 // Greylist some idioms by putting them into a warning subcategory. 18838 if (ObjCMessageExpr *ME 18839 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18840 Selector Sel = ME->getSelector(); 18841 18842 // self = [<foo> init...] 18843 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18844 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18845 18846 // <foo> = [<bar> nextObject] 18847 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18848 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18849 } 18850 18851 Loc = Op->getOperatorLoc(); 18852 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18853 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18854 return; 18855 18856 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18857 Loc = Op->getOperatorLoc(); 18858 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18859 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18860 else { 18861 // Not an assignment. 18862 return; 18863 } 18864 18865 Diag(Loc, diagnostic) << E->getSourceRange(); 18866 18867 SourceLocation Open = E->getBeginLoc(); 18868 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18869 Diag(Loc, diag::note_condition_assign_silence) 18870 << FixItHint::CreateInsertion(Open, "(") 18871 << FixItHint::CreateInsertion(Close, ")"); 18872 18873 if (IsOrAssign) 18874 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18875 << FixItHint::CreateReplacement(Loc, "!="); 18876 else 18877 Diag(Loc, diag::note_condition_assign_to_comparison) 18878 << FixItHint::CreateReplacement(Loc, "=="); 18879 } 18880 18881 /// Redundant parentheses over an equality comparison can indicate 18882 /// that the user intended an assignment used as condition. 18883 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18884 // Don't warn if the parens came from a macro. 18885 SourceLocation parenLoc = ParenE->getBeginLoc(); 18886 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18887 return; 18888 // Don't warn for dependent expressions. 18889 if (ParenE->isTypeDependent()) 18890 return; 18891 18892 Expr *E = ParenE->IgnoreParens(); 18893 18894 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18895 if (opE->getOpcode() == BO_EQ && 18896 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18897 == Expr::MLV_Valid) { 18898 SourceLocation Loc = opE->getOperatorLoc(); 18899 18900 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18901 SourceRange ParenERange = ParenE->getSourceRange(); 18902 Diag(Loc, diag::note_equality_comparison_silence) 18903 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18904 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18905 Diag(Loc, diag::note_equality_comparison_to_assign) 18906 << FixItHint::CreateReplacement(Loc, "="); 18907 } 18908 } 18909 18910 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18911 bool IsConstexpr) { 18912 DiagnoseAssignmentAsCondition(E); 18913 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18914 DiagnoseEqualityWithExtraParens(parenE); 18915 18916 ExprResult result = CheckPlaceholderExpr(E); 18917 if (result.isInvalid()) return ExprError(); 18918 E = result.get(); 18919 18920 if (!E->isTypeDependent()) { 18921 if (getLangOpts().CPlusPlus) 18922 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18923 18924 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18925 if (ERes.isInvalid()) 18926 return ExprError(); 18927 E = ERes.get(); 18928 18929 QualType T = E->getType(); 18930 if (!T->isScalarType()) { // C99 6.8.4.1p1 18931 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18932 << T << E->getSourceRange(); 18933 return ExprError(); 18934 } 18935 CheckBoolLikeConversion(E, Loc); 18936 } 18937 18938 return E; 18939 } 18940 18941 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18942 Expr *SubExpr, ConditionKind CK) { 18943 // Empty conditions are valid in for-statements. 18944 if (!SubExpr) 18945 return ConditionResult(); 18946 18947 ExprResult Cond; 18948 switch (CK) { 18949 case ConditionKind::Boolean: 18950 Cond = CheckBooleanCondition(Loc, SubExpr); 18951 break; 18952 18953 case ConditionKind::ConstexprIf: 18954 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18955 break; 18956 18957 case ConditionKind::Switch: 18958 Cond = CheckSwitchCondition(Loc, SubExpr); 18959 break; 18960 } 18961 if (Cond.isInvalid()) { 18962 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18963 {SubExpr}); 18964 if (!Cond.get()) 18965 return ConditionError(); 18966 } 18967 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18968 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18969 if (!FullExpr.get()) 18970 return ConditionError(); 18971 18972 return ConditionResult(*this, nullptr, FullExpr, 18973 CK == ConditionKind::ConstexprIf); 18974 } 18975 18976 namespace { 18977 /// A visitor for rebuilding a call to an __unknown_any expression 18978 /// to have an appropriate type. 18979 struct RebuildUnknownAnyFunction 18980 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18981 18982 Sema &S; 18983 18984 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18985 18986 ExprResult VisitStmt(Stmt *S) { 18987 llvm_unreachable("unexpected statement!"); 18988 } 18989 18990 ExprResult VisitExpr(Expr *E) { 18991 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18992 << E->getSourceRange(); 18993 return ExprError(); 18994 } 18995 18996 /// Rebuild an expression which simply semantically wraps another 18997 /// expression which it shares the type and value kind of. 18998 template <class T> ExprResult rebuildSugarExpr(T *E) { 18999 ExprResult SubResult = Visit(E->getSubExpr()); 19000 if (SubResult.isInvalid()) return ExprError(); 19001 19002 Expr *SubExpr = SubResult.get(); 19003 E->setSubExpr(SubExpr); 19004 E->setType(SubExpr->getType()); 19005 E->setValueKind(SubExpr->getValueKind()); 19006 assert(E->getObjectKind() == OK_Ordinary); 19007 return E; 19008 } 19009 19010 ExprResult VisitParenExpr(ParenExpr *E) { 19011 return rebuildSugarExpr(E); 19012 } 19013 19014 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19015 return rebuildSugarExpr(E); 19016 } 19017 19018 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19019 ExprResult SubResult = Visit(E->getSubExpr()); 19020 if (SubResult.isInvalid()) return ExprError(); 19021 19022 Expr *SubExpr = SubResult.get(); 19023 E->setSubExpr(SubExpr); 19024 E->setType(S.Context.getPointerType(SubExpr->getType())); 19025 assert(E->getValueKind() == VK_RValue); 19026 assert(E->getObjectKind() == OK_Ordinary); 19027 return E; 19028 } 19029 19030 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19031 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19032 19033 E->setType(VD->getType()); 19034 19035 assert(E->getValueKind() == VK_RValue); 19036 if (S.getLangOpts().CPlusPlus && 19037 !(isa<CXXMethodDecl>(VD) && 19038 cast<CXXMethodDecl>(VD)->isInstance())) 19039 E->setValueKind(VK_LValue); 19040 19041 return E; 19042 } 19043 19044 ExprResult VisitMemberExpr(MemberExpr *E) { 19045 return resolveDecl(E, E->getMemberDecl()); 19046 } 19047 19048 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19049 return resolveDecl(E, E->getDecl()); 19050 } 19051 }; 19052 } 19053 19054 /// Given a function expression of unknown-any type, try to rebuild it 19055 /// to have a function type. 19056 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19057 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19058 if (Result.isInvalid()) return ExprError(); 19059 return S.DefaultFunctionArrayConversion(Result.get()); 19060 } 19061 19062 namespace { 19063 /// A visitor for rebuilding an expression of type __unknown_anytype 19064 /// into one which resolves the type directly on the referring 19065 /// expression. Strict preservation of the original source 19066 /// structure is not a goal. 19067 struct RebuildUnknownAnyExpr 19068 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19069 19070 Sema &S; 19071 19072 /// The current destination type. 19073 QualType DestType; 19074 19075 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19076 : S(S), DestType(CastType) {} 19077 19078 ExprResult VisitStmt(Stmt *S) { 19079 llvm_unreachable("unexpected statement!"); 19080 } 19081 19082 ExprResult VisitExpr(Expr *E) { 19083 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19084 << E->getSourceRange(); 19085 return ExprError(); 19086 } 19087 19088 ExprResult VisitCallExpr(CallExpr *E); 19089 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19090 19091 /// Rebuild an expression which simply semantically wraps another 19092 /// expression which it shares the type and value kind of. 19093 template <class T> ExprResult rebuildSugarExpr(T *E) { 19094 ExprResult SubResult = Visit(E->getSubExpr()); 19095 if (SubResult.isInvalid()) return ExprError(); 19096 Expr *SubExpr = SubResult.get(); 19097 E->setSubExpr(SubExpr); 19098 E->setType(SubExpr->getType()); 19099 E->setValueKind(SubExpr->getValueKind()); 19100 assert(E->getObjectKind() == OK_Ordinary); 19101 return E; 19102 } 19103 19104 ExprResult VisitParenExpr(ParenExpr *E) { 19105 return rebuildSugarExpr(E); 19106 } 19107 19108 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19109 return rebuildSugarExpr(E); 19110 } 19111 19112 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19113 const PointerType *Ptr = DestType->getAs<PointerType>(); 19114 if (!Ptr) { 19115 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19116 << E->getSourceRange(); 19117 return ExprError(); 19118 } 19119 19120 if (isa<CallExpr>(E->getSubExpr())) { 19121 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19122 << E->getSourceRange(); 19123 return ExprError(); 19124 } 19125 19126 assert(E->getValueKind() == VK_RValue); 19127 assert(E->getObjectKind() == OK_Ordinary); 19128 E->setType(DestType); 19129 19130 // Build the sub-expression as if it were an object of the pointee type. 19131 DestType = Ptr->getPointeeType(); 19132 ExprResult SubResult = Visit(E->getSubExpr()); 19133 if (SubResult.isInvalid()) return ExprError(); 19134 E->setSubExpr(SubResult.get()); 19135 return E; 19136 } 19137 19138 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19139 19140 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19141 19142 ExprResult VisitMemberExpr(MemberExpr *E) { 19143 return resolveDecl(E, E->getMemberDecl()); 19144 } 19145 19146 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19147 return resolveDecl(E, E->getDecl()); 19148 } 19149 }; 19150 } 19151 19152 /// Rebuilds a call expression which yielded __unknown_anytype. 19153 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19154 Expr *CalleeExpr = E->getCallee(); 19155 19156 enum FnKind { 19157 FK_MemberFunction, 19158 FK_FunctionPointer, 19159 FK_BlockPointer 19160 }; 19161 19162 FnKind Kind; 19163 QualType CalleeType = CalleeExpr->getType(); 19164 if (CalleeType == S.Context.BoundMemberTy) { 19165 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19166 Kind = FK_MemberFunction; 19167 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19168 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19169 CalleeType = Ptr->getPointeeType(); 19170 Kind = FK_FunctionPointer; 19171 } else { 19172 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19173 Kind = FK_BlockPointer; 19174 } 19175 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19176 19177 // Verify that this is a legal result type of a function. 19178 if (DestType->isArrayType() || DestType->isFunctionType()) { 19179 unsigned diagID = diag::err_func_returning_array_function; 19180 if (Kind == FK_BlockPointer) 19181 diagID = diag::err_block_returning_array_function; 19182 19183 S.Diag(E->getExprLoc(), diagID) 19184 << DestType->isFunctionType() << DestType; 19185 return ExprError(); 19186 } 19187 19188 // Otherwise, go ahead and set DestType as the call's result. 19189 E->setType(DestType.getNonLValueExprType(S.Context)); 19190 E->setValueKind(Expr::getValueKindForType(DestType)); 19191 assert(E->getObjectKind() == OK_Ordinary); 19192 19193 // Rebuild the function type, replacing the result type with DestType. 19194 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19195 if (Proto) { 19196 // __unknown_anytype(...) is a special case used by the debugger when 19197 // it has no idea what a function's signature is. 19198 // 19199 // We want to build this call essentially under the K&R 19200 // unprototyped rules, but making a FunctionNoProtoType in C++ 19201 // would foul up all sorts of assumptions. However, we cannot 19202 // simply pass all arguments as variadic arguments, nor can we 19203 // portably just call the function under a non-variadic type; see 19204 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19205 // However, it turns out that in practice it is generally safe to 19206 // call a function declared as "A foo(B,C,D);" under the prototype 19207 // "A foo(B,C,D,...);". The only known exception is with the 19208 // Windows ABI, where any variadic function is implicitly cdecl 19209 // regardless of its normal CC. Therefore we change the parameter 19210 // types to match the types of the arguments. 19211 // 19212 // This is a hack, but it is far superior to moving the 19213 // corresponding target-specific code from IR-gen to Sema/AST. 19214 19215 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19216 SmallVector<QualType, 8> ArgTypes; 19217 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19218 ArgTypes.reserve(E->getNumArgs()); 19219 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19220 Expr *Arg = E->getArg(i); 19221 QualType ArgType = Arg->getType(); 19222 if (E->isLValue()) { 19223 ArgType = S.Context.getLValueReferenceType(ArgType); 19224 } else if (E->isXValue()) { 19225 ArgType = S.Context.getRValueReferenceType(ArgType); 19226 } 19227 ArgTypes.push_back(ArgType); 19228 } 19229 ParamTypes = ArgTypes; 19230 } 19231 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19232 Proto->getExtProtoInfo()); 19233 } else { 19234 DestType = S.Context.getFunctionNoProtoType(DestType, 19235 FnType->getExtInfo()); 19236 } 19237 19238 // Rebuild the appropriate pointer-to-function type. 19239 switch (Kind) { 19240 case FK_MemberFunction: 19241 // Nothing to do. 19242 break; 19243 19244 case FK_FunctionPointer: 19245 DestType = S.Context.getPointerType(DestType); 19246 break; 19247 19248 case FK_BlockPointer: 19249 DestType = S.Context.getBlockPointerType(DestType); 19250 break; 19251 } 19252 19253 // Finally, we can recurse. 19254 ExprResult CalleeResult = Visit(CalleeExpr); 19255 if (!CalleeResult.isUsable()) return ExprError(); 19256 E->setCallee(CalleeResult.get()); 19257 19258 // Bind a temporary if necessary. 19259 return S.MaybeBindToTemporary(E); 19260 } 19261 19262 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19263 // Verify that this is a legal result type of a call. 19264 if (DestType->isArrayType() || DestType->isFunctionType()) { 19265 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19266 << DestType->isFunctionType() << DestType; 19267 return ExprError(); 19268 } 19269 19270 // Rewrite the method result type if available. 19271 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19272 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19273 Method->setReturnType(DestType); 19274 } 19275 19276 // Change the type of the message. 19277 E->setType(DestType.getNonReferenceType()); 19278 E->setValueKind(Expr::getValueKindForType(DestType)); 19279 19280 return S.MaybeBindToTemporary(E); 19281 } 19282 19283 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19284 // The only case we should ever see here is a function-to-pointer decay. 19285 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19286 assert(E->getValueKind() == VK_RValue); 19287 assert(E->getObjectKind() == OK_Ordinary); 19288 19289 E->setType(DestType); 19290 19291 // Rebuild the sub-expression as the pointee (function) type. 19292 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19293 19294 ExprResult Result = Visit(E->getSubExpr()); 19295 if (!Result.isUsable()) return ExprError(); 19296 19297 E->setSubExpr(Result.get()); 19298 return E; 19299 } else if (E->getCastKind() == CK_LValueToRValue) { 19300 assert(E->getValueKind() == VK_RValue); 19301 assert(E->getObjectKind() == OK_Ordinary); 19302 19303 assert(isa<BlockPointerType>(E->getType())); 19304 19305 E->setType(DestType); 19306 19307 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19308 DestType = S.Context.getLValueReferenceType(DestType); 19309 19310 ExprResult Result = Visit(E->getSubExpr()); 19311 if (!Result.isUsable()) return ExprError(); 19312 19313 E->setSubExpr(Result.get()); 19314 return E; 19315 } else { 19316 llvm_unreachable("Unhandled cast type!"); 19317 } 19318 } 19319 19320 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19321 ExprValueKind ValueKind = VK_LValue; 19322 QualType Type = DestType; 19323 19324 // We know how to make this work for certain kinds of decls: 19325 19326 // - functions 19327 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19328 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19329 DestType = Ptr->getPointeeType(); 19330 ExprResult Result = resolveDecl(E, VD); 19331 if (Result.isInvalid()) return ExprError(); 19332 return S.ImpCastExprToType(Result.get(), Type, 19333 CK_FunctionToPointerDecay, VK_RValue); 19334 } 19335 19336 if (!Type->isFunctionType()) { 19337 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19338 << VD << E->getSourceRange(); 19339 return ExprError(); 19340 } 19341 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19342 // We must match the FunctionDecl's type to the hack introduced in 19343 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19344 // type. See the lengthy commentary in that routine. 19345 QualType FDT = FD->getType(); 19346 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19347 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19348 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19349 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19350 SourceLocation Loc = FD->getLocation(); 19351 FunctionDecl *NewFD = FunctionDecl::Create( 19352 S.Context, FD->getDeclContext(), Loc, Loc, 19353 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19354 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19355 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19356 19357 if (FD->getQualifier()) 19358 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19359 19360 SmallVector<ParmVarDecl*, 16> Params; 19361 for (const auto &AI : FT->param_types()) { 19362 ParmVarDecl *Param = 19363 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19364 Param->setScopeInfo(0, Params.size()); 19365 Params.push_back(Param); 19366 } 19367 NewFD->setParams(Params); 19368 DRE->setDecl(NewFD); 19369 VD = DRE->getDecl(); 19370 } 19371 } 19372 19373 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19374 if (MD->isInstance()) { 19375 ValueKind = VK_RValue; 19376 Type = S.Context.BoundMemberTy; 19377 } 19378 19379 // Function references aren't l-values in C. 19380 if (!S.getLangOpts().CPlusPlus) 19381 ValueKind = VK_RValue; 19382 19383 // - variables 19384 } else if (isa<VarDecl>(VD)) { 19385 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19386 Type = RefTy->getPointeeType(); 19387 } else if (Type->isFunctionType()) { 19388 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19389 << VD << E->getSourceRange(); 19390 return ExprError(); 19391 } 19392 19393 // - nothing else 19394 } else { 19395 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19396 << VD << E->getSourceRange(); 19397 return ExprError(); 19398 } 19399 19400 // Modifying the declaration like this is friendly to IR-gen but 19401 // also really dangerous. 19402 VD->setType(DestType); 19403 E->setType(Type); 19404 E->setValueKind(ValueKind); 19405 return E; 19406 } 19407 19408 /// Check a cast of an unknown-any type. We intentionally only 19409 /// trigger this for C-style casts. 19410 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19411 Expr *CastExpr, CastKind &CastKind, 19412 ExprValueKind &VK, CXXCastPath &Path) { 19413 // The type we're casting to must be either void or complete. 19414 if (!CastType->isVoidType() && 19415 RequireCompleteType(TypeRange.getBegin(), CastType, 19416 diag::err_typecheck_cast_to_incomplete)) 19417 return ExprError(); 19418 19419 // Rewrite the casted expression from scratch. 19420 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19421 if (!result.isUsable()) return ExprError(); 19422 19423 CastExpr = result.get(); 19424 VK = CastExpr->getValueKind(); 19425 CastKind = CK_NoOp; 19426 19427 return CastExpr; 19428 } 19429 19430 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19431 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19432 } 19433 19434 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19435 Expr *arg, QualType ¶mType) { 19436 // If the syntactic form of the argument is not an explicit cast of 19437 // any sort, just do default argument promotion. 19438 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19439 if (!castArg) { 19440 ExprResult result = DefaultArgumentPromotion(arg); 19441 if (result.isInvalid()) return ExprError(); 19442 paramType = result.get()->getType(); 19443 return result; 19444 } 19445 19446 // Otherwise, use the type that was written in the explicit cast. 19447 assert(!arg->hasPlaceholderType()); 19448 paramType = castArg->getTypeAsWritten(); 19449 19450 // Copy-initialize a parameter of that type. 19451 InitializedEntity entity = 19452 InitializedEntity::InitializeParameter(Context, paramType, 19453 /*consumed*/ false); 19454 return PerformCopyInitialization(entity, callLoc, arg); 19455 } 19456 19457 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19458 Expr *orig = E; 19459 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19460 while (true) { 19461 E = E->IgnoreParenImpCasts(); 19462 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19463 E = call->getCallee(); 19464 diagID = diag::err_uncasted_call_of_unknown_any; 19465 } else { 19466 break; 19467 } 19468 } 19469 19470 SourceLocation loc; 19471 NamedDecl *d; 19472 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19473 loc = ref->getLocation(); 19474 d = ref->getDecl(); 19475 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19476 loc = mem->getMemberLoc(); 19477 d = mem->getMemberDecl(); 19478 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19479 diagID = diag::err_uncasted_call_of_unknown_any; 19480 loc = msg->getSelectorStartLoc(); 19481 d = msg->getMethodDecl(); 19482 if (!d) { 19483 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19484 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19485 << orig->getSourceRange(); 19486 return ExprError(); 19487 } 19488 } else { 19489 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19490 << E->getSourceRange(); 19491 return ExprError(); 19492 } 19493 19494 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19495 19496 // Never recoverable. 19497 return ExprError(); 19498 } 19499 19500 /// Check for operands with placeholder types and complain if found. 19501 /// Returns ExprError() if there was an error and no recovery was possible. 19502 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19503 if (!Context.isDependenceAllowed()) { 19504 // C cannot handle TypoExpr nodes on either side of a binop because it 19505 // doesn't handle dependent types properly, so make sure any TypoExprs have 19506 // been dealt with before checking the operands. 19507 ExprResult Result = CorrectDelayedTyposInExpr(E); 19508 if (!Result.isUsable()) return ExprError(); 19509 E = Result.get(); 19510 } 19511 19512 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19513 if (!placeholderType) return E; 19514 19515 switch (placeholderType->getKind()) { 19516 19517 // Overloaded expressions. 19518 case BuiltinType::Overload: { 19519 // Try to resolve a single function template specialization. 19520 // This is obligatory. 19521 ExprResult Result = E; 19522 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19523 return Result; 19524 19525 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19526 // leaves Result unchanged on failure. 19527 Result = E; 19528 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19529 return Result; 19530 19531 // If that failed, try to recover with a call. 19532 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19533 /*complain*/ true); 19534 return Result; 19535 } 19536 19537 // Bound member functions. 19538 case BuiltinType::BoundMember: { 19539 ExprResult result = E; 19540 const Expr *BME = E->IgnoreParens(); 19541 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19542 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19543 if (isa<CXXPseudoDestructorExpr>(BME)) { 19544 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19545 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19546 if (ME->getMemberNameInfo().getName().getNameKind() == 19547 DeclarationName::CXXDestructorName) 19548 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19549 } 19550 tryToRecoverWithCall(result, PD, 19551 /*complain*/ true); 19552 return result; 19553 } 19554 19555 // ARC unbridged casts. 19556 case BuiltinType::ARCUnbridgedCast: { 19557 Expr *realCast = stripARCUnbridgedCast(E); 19558 diagnoseARCUnbridgedCast(realCast); 19559 return realCast; 19560 } 19561 19562 // Expressions of unknown type. 19563 case BuiltinType::UnknownAny: 19564 return diagnoseUnknownAnyExpr(*this, E); 19565 19566 // Pseudo-objects. 19567 case BuiltinType::PseudoObject: 19568 return checkPseudoObjectRValue(E); 19569 19570 case BuiltinType::BuiltinFn: { 19571 // Accept __noop without parens by implicitly converting it to a call expr. 19572 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19573 if (DRE) { 19574 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19575 if (FD->getBuiltinID() == Builtin::BI__noop) { 19576 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19577 CK_BuiltinFnToFnPtr) 19578 .get(); 19579 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19580 VK_RValue, SourceLocation(), 19581 FPOptionsOverride()); 19582 } 19583 } 19584 19585 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19586 return ExprError(); 19587 } 19588 19589 case BuiltinType::IncompleteMatrixIdx: 19590 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19591 ->getRowIdx() 19592 ->getBeginLoc(), 19593 diag::err_matrix_incomplete_index); 19594 return ExprError(); 19595 19596 // Expressions of unknown type. 19597 case BuiltinType::OMPArraySection: 19598 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19599 return ExprError(); 19600 19601 // Expressions of unknown type. 19602 case BuiltinType::OMPArrayShaping: 19603 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19604 19605 case BuiltinType::OMPIterator: 19606 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19607 19608 // Everything else should be impossible. 19609 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19610 case BuiltinType::Id: 19611 #include "clang/Basic/OpenCLImageTypes.def" 19612 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19613 case BuiltinType::Id: 19614 #include "clang/Basic/OpenCLExtensionTypes.def" 19615 #define SVE_TYPE(Name, Id, SingletonId) \ 19616 case BuiltinType::Id: 19617 #include "clang/Basic/AArch64SVEACLETypes.def" 19618 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19619 case BuiltinType::Id: 19620 #include "clang/Basic/PPCTypes.def" 19621 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19622 #include "clang/Basic/RISCVVTypes.def" 19623 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19624 #define PLACEHOLDER_TYPE(Id, SingletonId) 19625 #include "clang/AST/BuiltinTypes.def" 19626 break; 19627 } 19628 19629 llvm_unreachable("invalid placeholder type!"); 19630 } 19631 19632 bool Sema::CheckCaseExpression(Expr *E) { 19633 if (E->isTypeDependent()) 19634 return true; 19635 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19636 return E->getType()->isIntegralOrEnumerationType(); 19637 return false; 19638 } 19639 19640 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19641 ExprResult 19642 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19643 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19644 "Unknown Objective-C Boolean value!"); 19645 QualType BoolT = Context.ObjCBuiltinBoolTy; 19646 if (!Context.getBOOLDecl()) { 19647 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19648 Sema::LookupOrdinaryName); 19649 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19650 NamedDecl *ND = Result.getFoundDecl(); 19651 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19652 Context.setBOOLDecl(TD); 19653 } 19654 } 19655 if (Context.getBOOLDecl()) 19656 BoolT = Context.getBOOLType(); 19657 return new (Context) 19658 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19659 } 19660 19661 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19662 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19663 SourceLocation RParen) { 19664 19665 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19666 19667 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19668 return Spec.getPlatform() == Platform; 19669 }); 19670 19671 VersionTuple Version; 19672 if (Spec != AvailSpecs.end()) 19673 Version = Spec->getVersion(); 19674 19675 // The use of `@available` in the enclosing context should be analyzed to 19676 // warn when it's used inappropriately (i.e. not if(@available)). 19677 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19678 Context->HasPotentialAvailabilityViolations = true; 19679 19680 return new (Context) 19681 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19682 } 19683 19684 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19685 ArrayRef<Expr *> SubExprs, QualType T) { 19686 if (!Context.getLangOpts().RecoveryAST) 19687 return ExprError(); 19688 19689 if (isSFINAEContext()) 19690 return ExprError(); 19691 19692 if (T.isNull() || T->isUndeducedType() || 19693 !Context.getLangOpts().RecoveryASTType) 19694 // We don't know the concrete type, fallback to dependent type. 19695 T = Context.DependentTy; 19696 19697 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19698 } 19699