1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/OperationKinds.h" 28 #include "clang/AST/ParentMapContext.h" 29 #include "clang/AST/RecursiveASTVisitor.h" 30 #include "clang/AST/TypeLoc.h" 31 #include "clang/Basic/Builtins.h" 32 #include "clang/Basic/DiagnosticSema.h" 33 #include "clang/Basic/PartialDiagnostic.h" 34 #include "clang/Basic/SourceManager.h" 35 #include "clang/Basic/TargetInfo.h" 36 #include "clang/Lex/LiteralSupport.h" 37 #include "clang/Lex/Preprocessor.h" 38 #include "clang/Sema/AnalysisBasedWarnings.h" 39 #include "clang/Sema/DeclSpec.h" 40 #include "clang/Sema/DelayedDiagnostic.h" 41 #include "clang/Sema/Designator.h" 42 #include "clang/Sema/Initialization.h" 43 #include "clang/Sema/Lookup.h" 44 #include "clang/Sema/Overload.h" 45 #include "clang/Sema/ParsedTemplate.h" 46 #include "clang/Sema/Scope.h" 47 #include "clang/Sema/ScopeInfo.h" 48 #include "clang/Sema/SemaFixItUtils.h" 49 #include "clang/Sema/SemaInternal.h" 50 #include "clang/Sema/Template.h" 51 #include "llvm/ADT/STLExtras.h" 52 #include "llvm/ADT/StringExtras.h" 53 #include "llvm/Support/ConvertUTF.h" 54 #include "llvm/Support/SaveAndRestore.h" 55 56 using namespace clang; 57 using namespace sema; 58 59 /// Determine whether the use of this declaration is valid, without 60 /// emitting diagnostics. 61 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 62 // See if this is an auto-typed variable whose initializer we are parsing. 63 if (ParsingInitForAutoVars.count(D)) 64 return false; 65 66 // See if this is a deleted function. 67 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 68 if (FD->isDeleted()) 69 return false; 70 71 // If the function has a deduced return type, and we can't deduce it, 72 // then we can't use it either. 73 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 74 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 75 return false; 76 77 // See if this is an aligned allocation/deallocation function that is 78 // unavailable. 79 if (TreatUnavailableAsInvalid && 80 isUnavailableAlignedAllocationFunction(*FD)) 81 return false; 82 } 83 84 // See if this function is unavailable. 85 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 86 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 87 return false; 88 89 if (isa<UnresolvedUsingIfExistsDecl>(D)) 90 return false; 91 92 return true; 93 } 94 95 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 96 // Warn if this is used but marked unused. 97 if (const auto *A = D->getAttr<UnusedAttr>()) { 98 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 99 // should diagnose them. 100 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 101 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 102 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 103 if (DC && !DC->hasAttr<UnusedAttr>()) 104 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 105 } 106 } 107 } 108 109 /// Emit a note explaining that this function is deleted. 110 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 111 assert(Decl && Decl->isDeleted()); 112 113 if (Decl->isDefaulted()) { 114 // If the method was explicitly defaulted, point at that declaration. 115 if (!Decl->isImplicit()) 116 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 117 118 // Try to diagnose why this special member function was implicitly 119 // deleted. This might fail, if that reason no longer applies. 120 DiagnoseDeletedDefaultedFunction(Decl); 121 return; 122 } 123 124 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 125 if (Ctor && Ctor->isInheritingConstructor()) 126 return NoteDeletedInheritingConstructor(Ctor); 127 128 Diag(Decl->getLocation(), diag::note_availability_specified_here) 129 << Decl << 1; 130 } 131 132 /// Determine whether a FunctionDecl was ever declared with an 133 /// explicit storage class. 134 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 135 for (auto I : D->redecls()) { 136 if (I->getStorageClass() != SC_None) 137 return true; 138 } 139 return false; 140 } 141 142 /// Check whether we're in an extern inline function and referring to a 143 /// variable or function with internal linkage (C11 6.7.4p3). 144 /// 145 /// This is only a warning because we used to silently accept this code, but 146 /// in many cases it will not behave correctly. This is not enabled in C++ mode 147 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 148 /// and so while there may still be user mistakes, most of the time we can't 149 /// prove that there are errors. 150 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 151 const NamedDecl *D, 152 SourceLocation Loc) { 153 // This is disabled under C++; there are too many ways for this to fire in 154 // contexts where the warning is a false positive, or where it is technically 155 // correct but benign. 156 if (S.getLangOpts().CPlusPlus) 157 return; 158 159 // Check if this is an inlined function or method. 160 FunctionDecl *Current = S.getCurFunctionDecl(); 161 if (!Current) 162 return; 163 if (!Current->isInlined()) 164 return; 165 if (!Current->isExternallyVisible()) 166 return; 167 168 // Check if the decl has internal linkage. 169 if (D->getFormalLinkage() != InternalLinkage) 170 return; 171 172 // Downgrade from ExtWarn to Extension if 173 // (1) the supposedly external inline function is in the main file, 174 // and probably won't be included anywhere else. 175 // (2) the thing we're referencing is a pure function. 176 // (3) the thing we're referencing is another inline function. 177 // This last can give us false negatives, but it's better than warning on 178 // wrappers for simple C library functions. 179 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 180 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 181 if (!DowngradeWarning && UsedFn) 182 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 183 184 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 185 : diag::ext_internal_in_extern_inline) 186 << /*IsVar=*/!UsedFn << D; 187 188 S.MaybeSuggestAddingStaticToDecl(Current); 189 190 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 191 << D; 192 } 193 194 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 195 const FunctionDecl *First = Cur->getFirstDecl(); 196 197 // Suggest "static" on the function, if possible. 198 if (!hasAnyExplicitStorageClass(First)) { 199 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 200 Diag(DeclBegin, diag::note_convert_inline_to_static) 201 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 202 } 203 } 204 205 /// Determine whether the use of this declaration is valid, and 206 /// emit any corresponding diagnostics. 207 /// 208 /// This routine diagnoses various problems with referencing 209 /// declarations that can occur when using a declaration. For example, 210 /// it might warn if a deprecated or unavailable declaration is being 211 /// used, or produce an error (and return true) if a C++0x deleted 212 /// function is being used. 213 /// 214 /// \returns true if there was an error (this declaration cannot be 215 /// referenced), false otherwise. 216 /// 217 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 218 const ObjCInterfaceDecl *UnknownObjCClass, 219 bool ObjCPropertyAccess, 220 bool AvoidPartialAvailabilityChecks, 221 ObjCInterfaceDecl *ClassReceiver) { 222 SourceLocation Loc = Locs.front(); 223 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 224 // If there were any diagnostics suppressed by template argument deduction, 225 // emit them now. 226 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 227 if (Pos != SuppressedDiagnostics.end()) { 228 for (const PartialDiagnosticAt &Suppressed : Pos->second) 229 Diag(Suppressed.first, Suppressed.second); 230 231 // Clear out the list of suppressed diagnostics, so that we don't emit 232 // them again for this specialization. However, we don't obsolete this 233 // entry from the table, because we want to avoid ever emitting these 234 // diagnostics again. 235 Pos->second.clear(); 236 } 237 238 // C++ [basic.start.main]p3: 239 // The function 'main' shall not be used within a program. 240 if (cast<FunctionDecl>(D)->isMain()) 241 Diag(Loc, diag::ext_main_used); 242 243 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 244 } 245 246 // See if this is an auto-typed variable whose initializer we are parsing. 247 if (ParsingInitForAutoVars.count(D)) { 248 if (isa<BindingDecl>(D)) { 249 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 250 << D->getDeclName(); 251 } else { 252 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 253 << D->getDeclName() << cast<VarDecl>(D)->getType(); 254 } 255 return true; 256 } 257 258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 259 // See if this is a deleted function. 260 if (FD->isDeleted()) { 261 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 262 if (Ctor && Ctor->isInheritingConstructor()) 263 Diag(Loc, diag::err_deleted_inherited_ctor_use) 264 << Ctor->getParent() 265 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 266 else 267 Diag(Loc, diag::err_deleted_function_use); 268 NoteDeletedFunction(FD); 269 return true; 270 } 271 272 // [expr.prim.id]p4 273 // A program that refers explicitly or implicitly to a function with a 274 // trailing requires-clause whose constraint-expression is not satisfied, 275 // other than to declare it, is ill-formed. [...] 276 // 277 // See if this is a function with constraints that need to be satisfied. 278 // Check this before deducing the return type, as it might instantiate the 279 // definition. 280 if (FD->getTrailingRequiresClause()) { 281 ConstraintSatisfaction Satisfaction; 282 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 283 // A diagnostic will have already been generated (non-constant 284 // constraint expression, for example) 285 return true; 286 if (!Satisfaction.IsSatisfied) { 287 Diag(Loc, 288 diag::err_reference_to_function_with_unsatisfied_constraints) 289 << D; 290 DiagnoseUnsatisfiedConstraint(Satisfaction); 291 return true; 292 } 293 } 294 295 // If the function has a deduced return type, and we can't deduce it, 296 // then we can't use it either. 297 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 298 DeduceReturnType(FD, Loc)) 299 return true; 300 301 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 302 return true; 303 304 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 305 return true; 306 } 307 308 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 309 // Lambdas are only default-constructible or assignable in C++2a onwards. 310 if (MD->getParent()->isLambda() && 311 ((isa<CXXConstructorDecl>(MD) && 312 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 313 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 314 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 315 << !isa<CXXConstructorDecl>(MD); 316 } 317 } 318 319 auto getReferencedObjCProp = [](const NamedDecl *D) -> 320 const ObjCPropertyDecl * { 321 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 322 return MD->findPropertyDecl(); 323 return nullptr; 324 }; 325 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 326 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 327 return true; 328 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 329 return true; 330 } 331 332 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 333 // Only the variables omp_in and omp_out are allowed in the combiner. 334 // Only the variables omp_priv and omp_orig are allowed in the 335 // initializer-clause. 336 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 337 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 338 isa<VarDecl>(D)) { 339 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 340 << getCurFunction()->HasOMPDeclareReductionCombiner; 341 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 342 return true; 343 } 344 345 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 346 // List-items in map clauses on this construct may only refer to the declared 347 // variable var and entities that could be referenced by a procedure defined 348 // at the same location 349 if (LangOpts.OpenMP && isa<VarDecl>(D) && 350 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 351 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 352 << getOpenMPDeclareMapperVarName(); 353 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 354 return true; 355 } 356 357 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 358 Diag(Loc, diag::err_use_of_empty_using_if_exists); 359 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 360 return true; 361 } 362 363 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 364 AvoidPartialAvailabilityChecks, ClassReceiver); 365 366 DiagnoseUnusedOfDecl(*this, D, Loc); 367 368 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 369 370 if (auto *VD = dyn_cast<ValueDecl>(D)) 371 checkTypeSupport(VD->getType(), Loc, VD); 372 373 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 374 if (!Context.getTargetInfo().isTLSSupported()) 375 if (const auto *VD = dyn_cast<VarDecl>(D)) 376 if (VD->getTLSKind() != VarDecl::TLS_None) 377 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 378 } 379 380 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 381 !isUnevaluatedContext()) { 382 // C++ [expr.prim.req.nested] p3 383 // A local parameter shall only appear as an unevaluated operand 384 // (Clause 8) within the constraint-expression. 385 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 386 << D; 387 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 388 return true; 389 } 390 391 return false; 392 } 393 394 /// DiagnoseSentinelCalls - This routine checks whether a call or 395 /// message-send is to a declaration with the sentinel attribute, and 396 /// if so, it checks that the requirements of the sentinel are 397 /// satisfied. 398 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 399 ArrayRef<Expr *> Args) { 400 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 401 if (!attr) 402 return; 403 404 // The number of formal parameters of the declaration. 405 unsigned numFormalParams; 406 407 // The kind of declaration. This is also an index into a %select in 408 // the diagnostic. 409 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 410 411 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 412 numFormalParams = MD->param_size(); 413 calleeType = CT_Method; 414 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 415 numFormalParams = FD->param_size(); 416 calleeType = CT_Function; 417 } else if (isa<VarDecl>(D)) { 418 QualType type = cast<ValueDecl>(D)->getType(); 419 const FunctionType *fn = nullptr; 420 if (const PointerType *ptr = type->getAs<PointerType>()) { 421 fn = ptr->getPointeeType()->getAs<FunctionType>(); 422 if (!fn) return; 423 calleeType = CT_Function; 424 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 425 fn = ptr->getPointeeType()->castAs<FunctionType>(); 426 calleeType = CT_Block; 427 } else { 428 return; 429 } 430 431 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 432 numFormalParams = proto->getNumParams(); 433 } else { 434 numFormalParams = 0; 435 } 436 } else { 437 return; 438 } 439 440 // "nullPos" is the number of formal parameters at the end which 441 // effectively count as part of the variadic arguments. This is 442 // useful if you would prefer to not have *any* formal parameters, 443 // but the language forces you to have at least one. 444 unsigned nullPos = attr->getNullPos(); 445 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 446 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 447 448 // The number of arguments which should follow the sentinel. 449 unsigned numArgsAfterSentinel = attr->getSentinel(); 450 451 // If there aren't enough arguments for all the formal parameters, 452 // the sentinel, and the args after the sentinel, complain. 453 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 454 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 455 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 456 return; 457 } 458 459 // Otherwise, find the sentinel expression. 460 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 461 if (!sentinelExpr) return; 462 if (sentinelExpr->isValueDependent()) return; 463 if (Context.isSentinelNullExpr(sentinelExpr)) return; 464 465 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 466 // or 'NULL' if those are actually defined in the context. Only use 467 // 'nil' for ObjC methods, where it's much more likely that the 468 // variadic arguments form a list of object pointers. 469 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 470 std::string NullValue; 471 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 472 NullValue = "nil"; 473 else if (getLangOpts().CPlusPlus11) 474 NullValue = "nullptr"; 475 else if (PP.isMacroDefined("NULL")) 476 NullValue = "NULL"; 477 else 478 NullValue = "(void*) 0"; 479 480 if (MissingNilLoc.isInvalid()) 481 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 482 else 483 Diag(MissingNilLoc, diag::warn_missing_sentinel) 484 << int(calleeType) 485 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 486 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 487 } 488 489 SourceRange Sema::getExprRange(Expr *E) const { 490 return E ? E->getSourceRange() : SourceRange(); 491 } 492 493 //===----------------------------------------------------------------------===// 494 // Standard Promotions and Conversions 495 //===----------------------------------------------------------------------===// 496 497 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 498 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 499 // Handle any placeholder expressions which made it here. 500 if (E->hasPlaceholderType()) { 501 ExprResult result = CheckPlaceholderExpr(E); 502 if (result.isInvalid()) return ExprError(); 503 E = result.get(); 504 } 505 506 QualType Ty = E->getType(); 507 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 508 509 if (Ty->isFunctionType()) { 510 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 511 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 512 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 513 return ExprError(); 514 515 E = ImpCastExprToType(E, Context.getPointerType(Ty), 516 CK_FunctionToPointerDecay).get(); 517 } else if (Ty->isArrayType()) { 518 // In C90 mode, arrays only promote to pointers if the array expression is 519 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 520 // type 'array of type' is converted to an expression that has type 'pointer 521 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 522 // that has type 'array of type' ...". The relevant change is "an lvalue" 523 // (C90) to "an expression" (C99). 524 // 525 // C++ 4.2p1: 526 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 527 // T" can be converted to an rvalue of type "pointer to T". 528 // 529 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 530 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 531 CK_ArrayToPointerDecay); 532 if (Res.isInvalid()) 533 return ExprError(); 534 E = Res.get(); 535 } 536 } 537 return E; 538 } 539 540 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 541 // Check to see if we are dereferencing a null pointer. If so, 542 // and if not volatile-qualified, this is undefined behavior that the 543 // optimizer will delete, so warn about it. People sometimes try to use this 544 // to get a deterministic trap and are surprised by clang's behavior. This 545 // only handles the pattern "*null", which is a very syntactic check. 546 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 547 if (UO && UO->getOpcode() == UO_Deref && 548 UO->getSubExpr()->getType()->isPointerType()) { 549 const LangAS AS = 550 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 551 if ((!isTargetAddressSpace(AS) || 552 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 553 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 554 S.Context, Expr::NPC_ValueDependentIsNotNull) && 555 !UO->getType().isVolatileQualified()) { 556 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 557 S.PDiag(diag::warn_indirection_through_null) 558 << UO->getSubExpr()->getSourceRange()); 559 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 560 S.PDiag(diag::note_indirection_through_null)); 561 } 562 } 563 } 564 565 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 566 SourceLocation AssignLoc, 567 const Expr* RHS) { 568 const ObjCIvarDecl *IV = OIRE->getDecl(); 569 if (!IV) 570 return; 571 572 DeclarationName MemberName = IV->getDeclName(); 573 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 574 if (!Member || !Member->isStr("isa")) 575 return; 576 577 const Expr *Base = OIRE->getBase(); 578 QualType BaseType = Base->getType(); 579 if (OIRE->isArrow()) 580 BaseType = BaseType->getPointeeType(); 581 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 582 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 583 ObjCInterfaceDecl *ClassDeclared = nullptr; 584 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 585 if (!ClassDeclared->getSuperClass() 586 && (*ClassDeclared->ivar_begin()) == IV) { 587 if (RHS) { 588 NamedDecl *ObjectSetClass = 589 S.LookupSingleName(S.TUScope, 590 &S.Context.Idents.get("object_setClass"), 591 SourceLocation(), S.LookupOrdinaryName); 592 if (ObjectSetClass) { 593 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 594 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 595 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 596 "object_setClass(") 597 << FixItHint::CreateReplacement( 598 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 599 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 600 } 601 else 602 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 603 } else { 604 NamedDecl *ObjectGetClass = 605 S.LookupSingleName(S.TUScope, 606 &S.Context.Idents.get("object_getClass"), 607 SourceLocation(), S.LookupOrdinaryName); 608 if (ObjectGetClass) 609 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 610 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 611 "object_getClass(") 612 << FixItHint::CreateReplacement( 613 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 614 else 615 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 616 } 617 S.Diag(IV->getLocation(), diag::note_ivar_decl); 618 } 619 } 620 } 621 622 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 623 // Handle any placeholder expressions which made it here. 624 if (E->hasPlaceholderType()) { 625 ExprResult result = CheckPlaceholderExpr(E); 626 if (result.isInvalid()) return ExprError(); 627 E = result.get(); 628 } 629 630 // C++ [conv.lval]p1: 631 // A glvalue of a non-function, non-array type T can be 632 // converted to a prvalue. 633 if (!E->isGLValue()) return E; 634 635 QualType T = E->getType(); 636 assert(!T.isNull() && "r-value conversion on typeless expression?"); 637 638 // lvalue-to-rvalue conversion cannot be applied to function or array types. 639 if (T->isFunctionType() || T->isArrayType()) 640 return E; 641 642 // We don't want to throw lvalue-to-rvalue casts on top of 643 // expressions of certain types in C++. 644 if (getLangOpts().CPlusPlus && 645 (E->getType() == Context.OverloadTy || 646 T->isDependentType() || 647 T->isRecordType())) 648 return E; 649 650 // The C standard is actually really unclear on this point, and 651 // DR106 tells us what the result should be but not why. It's 652 // generally best to say that void types just doesn't undergo 653 // lvalue-to-rvalue at all. Note that expressions of unqualified 654 // 'void' type are never l-values, but qualified void can be. 655 if (T->isVoidType()) 656 return E; 657 658 // OpenCL usually rejects direct accesses to values of 'half' type. 659 if (getLangOpts().OpenCL && 660 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 661 T->isHalfType()) { 662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 663 << 0 << T; 664 return ExprError(); 665 } 666 667 CheckForNullPointerDereference(*this, E); 668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 670 &Context.Idents.get("object_getClass"), 671 SourceLocation(), LookupOrdinaryName); 672 if (ObjectGetClass) 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 674 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 675 << FixItHint::CreateReplacement( 676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 677 else 678 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 679 } 680 else if (const ObjCIvarRefExpr *OIRE = 681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 683 684 // C++ [conv.lval]p1: 685 // [...] If T is a non-class type, the type of the prvalue is the 686 // cv-unqualified version of T. Otherwise, the type of the 687 // rvalue is T. 688 // 689 // C99 6.3.2.1p2: 690 // If the lvalue has qualified type, the value has the unqualified 691 // version of the type of the lvalue; otherwise, the value has the 692 // type of the lvalue. 693 if (T.hasQualifiers()) 694 T = T.getUnqualifiedType(); 695 696 // Under the MS ABI, lock down the inheritance model now. 697 if (T->isMemberPointerType() && 698 Context.getTargetInfo().getCXXABI().isMicrosoft()) 699 (void)isCompleteType(E->getExprLoc(), T); 700 701 ExprResult Res = CheckLValueToRValueConversionOperand(E); 702 if (Res.isInvalid()) 703 return Res; 704 E = Res.get(); 705 706 // Loading a __weak object implicitly retains the value, so we need a cleanup to 707 // balance that. 708 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 709 Cleanup.setExprNeedsCleanups(true); 710 711 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 712 Cleanup.setExprNeedsCleanups(true); 713 714 // C++ [conv.lval]p3: 715 // If T is cv std::nullptr_t, the result is a null pointer constant. 716 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 717 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 718 CurFPFeatureOverrides()); 719 720 // C11 6.3.2.1p2: 721 // ... if the lvalue has atomic type, the value has the non-atomic version 722 // of the type of the lvalue ... 723 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 724 T = Atomic->getValueType().getUnqualifiedType(); 725 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 726 nullptr, VK_PRValue, FPOptionsOverride()); 727 } 728 729 return Res; 730 } 731 732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 733 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 734 if (Res.isInvalid()) 735 return ExprError(); 736 Res = DefaultLvalueConversion(Res.get()); 737 if (Res.isInvalid()) 738 return ExprError(); 739 return Res; 740 } 741 742 /// CallExprUnaryConversions - a special case of an unary conversion 743 /// performed on a function designator of a call expression. 744 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 745 QualType Ty = E->getType(); 746 ExprResult Res = E; 747 // Only do implicit cast for a function type, but not for a pointer 748 // to function type. 749 if (Ty->isFunctionType()) { 750 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 751 CK_FunctionToPointerDecay); 752 if (Res.isInvalid()) 753 return ExprError(); 754 } 755 Res = DefaultLvalueConversion(Res.get()); 756 if (Res.isInvalid()) 757 return ExprError(); 758 return Res.get(); 759 } 760 761 /// UsualUnaryConversions - Performs various conversions that are common to most 762 /// operators (C99 6.3). The conversions of array and function types are 763 /// sometimes suppressed. For example, the array->pointer conversion doesn't 764 /// apply if the array is an argument to the sizeof or address (&) operators. 765 /// In these instances, this routine should *not* be called. 766 ExprResult Sema::UsualUnaryConversions(Expr *E) { 767 // First, convert to an r-value. 768 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 769 if (Res.isInvalid()) 770 return ExprError(); 771 E = Res.get(); 772 773 QualType Ty = E->getType(); 774 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 775 776 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); 777 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() && 778 (getLangOpts().getFPEvalMethod() != 779 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine || 780 PP.getLastFPEvalPragmaLocation().isValid())) { 781 switch (EvalMethod) { 782 default: 783 llvm_unreachable("Unrecognized float evaluation method"); 784 break; 785 case LangOptions::FEM_UnsetOnCommandLine: 786 llvm_unreachable("Float evaluation method should be set by now"); 787 break; 788 case LangOptions::FEM_Double: 789 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0) 790 // Widen the expression to double. 791 return Ty->isComplexType() 792 ? ImpCastExprToType(E, 793 Context.getComplexType(Context.DoubleTy), 794 CK_FloatingComplexCast) 795 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast); 796 break; 797 case LangOptions::FEM_Extended: 798 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0) 799 // Widen the expression to long double. 800 return Ty->isComplexType() 801 ? ImpCastExprToType( 802 E, Context.getComplexType(Context.LongDoubleTy), 803 CK_FloatingComplexCast) 804 : ImpCastExprToType(E, Context.LongDoubleTy, 805 CK_FloatingCast); 806 break; 807 } 808 } 809 810 // Half FP have to be promoted to float unless it is natively supported 811 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 812 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 813 814 // Try to perform integral promotions if the object has a theoretically 815 // promotable type. 816 if (Ty->isIntegralOrUnscopedEnumerationType()) { 817 // C99 6.3.1.1p2: 818 // 819 // The following may be used in an expression wherever an int or 820 // unsigned int may be used: 821 // - an object or expression with an integer type whose integer 822 // conversion rank is less than or equal to the rank of int 823 // and unsigned int. 824 // - A bit-field of type _Bool, int, signed int, or unsigned int. 825 // 826 // If an int can represent all values of the original type, the 827 // value is converted to an int; otherwise, it is converted to an 828 // unsigned int. These are called the integer promotions. All 829 // other types are unchanged by the integer promotions. 830 831 QualType PTy = Context.isPromotableBitField(E); 832 if (!PTy.isNull()) { 833 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 834 return E; 835 } 836 if (Ty->isPromotableIntegerType()) { 837 QualType PT = Context.getPromotedIntegerType(Ty); 838 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 839 return E; 840 } 841 } 842 return E; 843 } 844 845 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 846 /// do not have a prototype. Arguments that have type float or __fp16 847 /// are promoted to double. All other argument types are converted by 848 /// UsualUnaryConversions(). 849 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 850 QualType Ty = E->getType(); 851 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 852 853 ExprResult Res = UsualUnaryConversions(E); 854 if (Res.isInvalid()) 855 return ExprError(); 856 E = Res.get(); 857 858 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 859 // promote to double. 860 // Note that default argument promotion applies only to float (and 861 // half/fp16); it does not apply to _Float16. 862 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 863 if (BTy && (BTy->getKind() == BuiltinType::Half || 864 BTy->getKind() == BuiltinType::Float)) { 865 if (getLangOpts().OpenCL && 866 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 867 if (BTy->getKind() == BuiltinType::Half) { 868 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 869 } 870 } else { 871 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 872 } 873 } 874 if (BTy && 875 getLangOpts().getExtendIntArgs() == 876 LangOptions::ExtendArgsKind::ExtendTo64 && 877 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 878 Context.getTypeSizeInChars(BTy) < 879 Context.getTypeSizeInChars(Context.LongLongTy)) { 880 E = (Ty->isUnsignedIntegerType()) 881 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 882 .get() 883 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 884 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 885 "Unexpected typesize for LongLongTy"); 886 } 887 888 // C++ performs lvalue-to-rvalue conversion as a default argument 889 // promotion, even on class types, but note: 890 // C++11 [conv.lval]p2: 891 // When an lvalue-to-rvalue conversion occurs in an unevaluated 892 // operand or a subexpression thereof the value contained in the 893 // referenced object is not accessed. Otherwise, if the glvalue 894 // has a class type, the conversion copy-initializes a temporary 895 // of type T from the glvalue and the result of the conversion 896 // is a prvalue for the temporary. 897 // FIXME: add some way to gate this entire thing for correctness in 898 // potentially potentially evaluated contexts. 899 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 900 ExprResult Temp = PerformCopyInitialization( 901 InitializedEntity::InitializeTemporary(E->getType()), 902 E->getExprLoc(), E); 903 if (Temp.isInvalid()) 904 return ExprError(); 905 E = Temp.get(); 906 } 907 908 return E; 909 } 910 911 /// Determine the degree of POD-ness for an expression. 912 /// Incomplete types are considered POD, since this check can be performed 913 /// when we're in an unevaluated context. 914 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 915 if (Ty->isIncompleteType()) { 916 // C++11 [expr.call]p7: 917 // After these conversions, if the argument does not have arithmetic, 918 // enumeration, pointer, pointer to member, or class type, the program 919 // is ill-formed. 920 // 921 // Since we've already performed array-to-pointer and function-to-pointer 922 // decay, the only such type in C++ is cv void. This also handles 923 // initializer lists as variadic arguments. 924 if (Ty->isVoidType()) 925 return VAK_Invalid; 926 927 if (Ty->isObjCObjectType()) 928 return VAK_Invalid; 929 return VAK_Valid; 930 } 931 932 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 933 return VAK_Invalid; 934 935 if (Ty.isCXX98PODType(Context)) 936 return VAK_Valid; 937 938 // C++11 [expr.call]p7: 939 // Passing a potentially-evaluated argument of class type (Clause 9) 940 // having a non-trivial copy constructor, a non-trivial move constructor, 941 // or a non-trivial destructor, with no corresponding parameter, 942 // is conditionally-supported with implementation-defined semantics. 943 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 944 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 945 if (!Record->hasNonTrivialCopyConstructor() && 946 !Record->hasNonTrivialMoveConstructor() && 947 !Record->hasNonTrivialDestructor()) 948 return VAK_ValidInCXX11; 949 950 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 951 return VAK_Valid; 952 953 if (Ty->isObjCObjectType()) 954 return VAK_Invalid; 955 956 if (getLangOpts().MSVCCompat) 957 return VAK_MSVCUndefined; 958 959 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 960 // permitted to reject them. We should consider doing so. 961 return VAK_Undefined; 962 } 963 964 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 965 // Don't allow one to pass an Objective-C interface to a vararg. 966 const QualType &Ty = E->getType(); 967 VarArgKind VAK = isValidVarArgType(Ty); 968 969 // Complain about passing non-POD types through varargs. 970 switch (VAK) { 971 case VAK_ValidInCXX11: 972 DiagRuntimeBehavior( 973 E->getBeginLoc(), nullptr, 974 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 975 LLVM_FALLTHROUGH; 976 case VAK_Valid: 977 if (Ty->isRecordType()) { 978 // This is unlikely to be what the user intended. If the class has a 979 // 'c_str' member function, the user probably meant to call that. 980 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 981 PDiag(diag::warn_pass_class_arg_to_vararg) 982 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 983 } 984 break; 985 986 case VAK_Undefined: 987 case VAK_MSVCUndefined: 988 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 989 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 990 << getLangOpts().CPlusPlus11 << Ty << CT); 991 break; 992 993 case VAK_Invalid: 994 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 995 Diag(E->getBeginLoc(), 996 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 997 << Ty << CT; 998 else if (Ty->isObjCObjectType()) 999 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 1000 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 1001 << Ty << CT); 1002 else 1003 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 1004 << isa<InitListExpr>(E) << Ty << CT; 1005 break; 1006 } 1007 } 1008 1009 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 1010 /// will create a trap if the resulting type is not a POD type. 1011 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 1012 FunctionDecl *FDecl) { 1013 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 1014 // Strip the unbridged-cast placeholder expression off, if applicable. 1015 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 1016 (CT == VariadicMethod || 1017 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 1018 E = stripARCUnbridgedCast(E); 1019 1020 // Otherwise, do normal placeholder checking. 1021 } else { 1022 ExprResult ExprRes = CheckPlaceholderExpr(E); 1023 if (ExprRes.isInvalid()) 1024 return ExprError(); 1025 E = ExprRes.get(); 1026 } 1027 } 1028 1029 ExprResult ExprRes = DefaultArgumentPromotion(E); 1030 if (ExprRes.isInvalid()) 1031 return ExprError(); 1032 1033 // Copy blocks to the heap. 1034 if (ExprRes.get()->getType()->isBlockPointerType()) 1035 maybeExtendBlockObject(ExprRes); 1036 1037 E = ExprRes.get(); 1038 1039 // Diagnostics regarding non-POD argument types are 1040 // emitted along with format string checking in Sema::CheckFunctionCall(). 1041 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1042 // Turn this into a trap. 1043 CXXScopeSpec SS; 1044 SourceLocation TemplateKWLoc; 1045 UnqualifiedId Name; 1046 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1047 E->getBeginLoc()); 1048 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1049 /*HasTrailingLParen=*/true, 1050 /*IsAddressOfOperand=*/false); 1051 if (TrapFn.isInvalid()) 1052 return ExprError(); 1053 1054 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1055 None, E->getEndLoc()); 1056 if (Call.isInvalid()) 1057 return ExprError(); 1058 1059 ExprResult Comma = 1060 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1061 if (Comma.isInvalid()) 1062 return ExprError(); 1063 return Comma.get(); 1064 } 1065 1066 if (!getLangOpts().CPlusPlus && 1067 RequireCompleteType(E->getExprLoc(), E->getType(), 1068 diag::err_call_incomplete_argument)) 1069 return ExprError(); 1070 1071 return E; 1072 } 1073 1074 /// Converts an integer to complex float type. Helper function of 1075 /// UsualArithmeticConversions() 1076 /// 1077 /// \return false if the integer expression is an integer type and is 1078 /// successfully converted to the complex type. 1079 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1080 ExprResult &ComplexExpr, 1081 QualType IntTy, 1082 QualType ComplexTy, 1083 bool SkipCast) { 1084 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1085 if (SkipCast) return false; 1086 if (IntTy->isIntegerType()) { 1087 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1088 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1089 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1090 CK_FloatingRealToComplex); 1091 } else { 1092 assert(IntTy->isComplexIntegerType()); 1093 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1094 CK_IntegralComplexToFloatingComplex); 1095 } 1096 return false; 1097 } 1098 1099 /// Handle arithmetic conversion with complex types. Helper function of 1100 /// UsualArithmeticConversions() 1101 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1102 ExprResult &RHS, QualType LHSType, 1103 QualType RHSType, 1104 bool IsCompAssign) { 1105 // if we have an integer operand, the result is the complex type. 1106 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1107 /*skipCast*/false)) 1108 return LHSType; 1109 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1110 /*skipCast*/IsCompAssign)) 1111 return RHSType; 1112 1113 // This handles complex/complex, complex/float, or float/complex. 1114 // When both operands are complex, the shorter operand is converted to the 1115 // type of the longer, and that is the type of the result. This corresponds 1116 // to what is done when combining two real floating-point operands. 1117 // The fun begins when size promotion occur across type domains. 1118 // From H&S 6.3.4: When one operand is complex and the other is a real 1119 // floating-point type, the less precise type is converted, within it's 1120 // real or complex domain, to the precision of the other type. For example, 1121 // when combining a "long double" with a "double _Complex", the 1122 // "double _Complex" is promoted to "long double _Complex". 1123 1124 // Compute the rank of the two types, regardless of whether they are complex. 1125 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1126 1127 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1128 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1129 QualType LHSElementType = 1130 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1131 QualType RHSElementType = 1132 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1133 1134 QualType ResultType = S.Context.getComplexType(LHSElementType); 1135 if (Order < 0) { 1136 // Promote the precision of the LHS if not an assignment. 1137 ResultType = S.Context.getComplexType(RHSElementType); 1138 if (!IsCompAssign) { 1139 if (LHSComplexType) 1140 LHS = 1141 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1142 else 1143 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1144 } 1145 } else if (Order > 0) { 1146 // Promote the precision of the RHS. 1147 if (RHSComplexType) 1148 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1149 else 1150 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1151 } 1152 return ResultType; 1153 } 1154 1155 /// Handle arithmetic conversion from integer to float. Helper function 1156 /// of UsualArithmeticConversions() 1157 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1158 ExprResult &IntExpr, 1159 QualType FloatTy, QualType IntTy, 1160 bool ConvertFloat, bool ConvertInt) { 1161 if (IntTy->isIntegerType()) { 1162 if (ConvertInt) 1163 // Convert intExpr to the lhs floating point type. 1164 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1165 CK_IntegralToFloating); 1166 return FloatTy; 1167 } 1168 1169 // Convert both sides to the appropriate complex float. 1170 assert(IntTy->isComplexIntegerType()); 1171 QualType result = S.Context.getComplexType(FloatTy); 1172 1173 // _Complex int -> _Complex float 1174 if (ConvertInt) 1175 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1176 CK_IntegralComplexToFloatingComplex); 1177 1178 // float -> _Complex float 1179 if (ConvertFloat) 1180 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1181 CK_FloatingRealToComplex); 1182 1183 return result; 1184 } 1185 1186 /// Handle arithmethic conversion with floating point types. Helper 1187 /// function of UsualArithmeticConversions() 1188 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1189 ExprResult &RHS, QualType LHSType, 1190 QualType RHSType, bool IsCompAssign) { 1191 bool LHSFloat = LHSType->isRealFloatingType(); 1192 bool RHSFloat = RHSType->isRealFloatingType(); 1193 1194 // N1169 4.1.4: If one of the operands has a floating type and the other 1195 // operand has a fixed-point type, the fixed-point operand 1196 // is converted to the floating type [...] 1197 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1198 if (LHSFloat) 1199 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1200 else if (!IsCompAssign) 1201 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1202 return LHSFloat ? LHSType : RHSType; 1203 } 1204 1205 // If we have two real floating types, convert the smaller operand 1206 // to the bigger result. 1207 if (LHSFloat && RHSFloat) { 1208 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1209 if (order > 0) { 1210 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1211 return LHSType; 1212 } 1213 1214 assert(order < 0 && "illegal float comparison"); 1215 if (!IsCompAssign) 1216 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1217 return RHSType; 1218 } 1219 1220 if (LHSFloat) { 1221 // Half FP has to be promoted to float unless it is natively supported 1222 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1223 LHSType = S.Context.FloatTy; 1224 1225 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1226 /*ConvertFloat=*/!IsCompAssign, 1227 /*ConvertInt=*/ true); 1228 } 1229 assert(RHSFloat); 1230 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1231 /*ConvertFloat=*/ true, 1232 /*ConvertInt=*/!IsCompAssign); 1233 } 1234 1235 /// Diagnose attempts to convert between __float128, __ibm128 and 1236 /// long double if there is no support for such conversion. 1237 /// Helper function of UsualArithmeticConversions(). 1238 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1239 QualType RHSType) { 1240 // No issue if either is not a floating point type. 1241 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1242 return false; 1243 1244 // No issue if both have the same 128-bit float semantics. 1245 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1246 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1247 1248 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1249 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1250 1251 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1252 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1253 1254 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1255 &RHSSem != &llvm::APFloat::IEEEquad()) && 1256 (&LHSSem != &llvm::APFloat::IEEEquad() || 1257 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1258 return false; 1259 1260 return true; 1261 } 1262 1263 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1264 1265 namespace { 1266 /// These helper callbacks are placed in an anonymous namespace to 1267 /// permit their use as function template parameters. 1268 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1269 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1270 } 1271 1272 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1273 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1274 CK_IntegralComplexCast); 1275 } 1276 } 1277 1278 /// Handle integer arithmetic conversions. Helper function of 1279 /// UsualArithmeticConversions() 1280 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1281 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1282 ExprResult &RHS, QualType LHSType, 1283 QualType RHSType, bool IsCompAssign) { 1284 // The rules for this case are in C99 6.3.1.8 1285 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1286 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1287 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1288 if (LHSSigned == RHSSigned) { 1289 // Same signedness; use the higher-ranked type 1290 if (order >= 0) { 1291 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1292 return LHSType; 1293 } else if (!IsCompAssign) 1294 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1295 return RHSType; 1296 } else if (order != (LHSSigned ? 1 : -1)) { 1297 // The unsigned type has greater than or equal rank to the 1298 // signed type, so use the unsigned type 1299 if (RHSSigned) { 1300 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1301 return LHSType; 1302 } else if (!IsCompAssign) 1303 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1304 return RHSType; 1305 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1306 // The two types are different widths; if we are here, that 1307 // means the signed type is larger than the unsigned type, so 1308 // use the signed type. 1309 if (LHSSigned) { 1310 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1311 return LHSType; 1312 } else if (!IsCompAssign) 1313 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1314 return RHSType; 1315 } else { 1316 // The signed type is higher-ranked than the unsigned type, 1317 // but isn't actually any bigger (like unsigned int and long 1318 // on most 32-bit systems). Use the unsigned type corresponding 1319 // to the signed type. 1320 QualType result = 1321 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1322 RHS = (*doRHSCast)(S, RHS.get(), result); 1323 if (!IsCompAssign) 1324 LHS = (*doLHSCast)(S, LHS.get(), result); 1325 return result; 1326 } 1327 } 1328 1329 /// Handle conversions with GCC complex int extension. Helper function 1330 /// of UsualArithmeticConversions() 1331 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1332 ExprResult &RHS, QualType LHSType, 1333 QualType RHSType, 1334 bool IsCompAssign) { 1335 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1336 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1337 1338 if (LHSComplexInt && RHSComplexInt) { 1339 QualType LHSEltType = LHSComplexInt->getElementType(); 1340 QualType RHSEltType = RHSComplexInt->getElementType(); 1341 QualType ScalarType = 1342 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1343 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1344 1345 return S.Context.getComplexType(ScalarType); 1346 } 1347 1348 if (LHSComplexInt) { 1349 QualType LHSEltType = LHSComplexInt->getElementType(); 1350 QualType ScalarType = 1351 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1352 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1353 QualType ComplexType = S.Context.getComplexType(ScalarType); 1354 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1355 CK_IntegralRealToComplex); 1356 1357 return ComplexType; 1358 } 1359 1360 assert(RHSComplexInt); 1361 1362 QualType RHSEltType = RHSComplexInt->getElementType(); 1363 QualType ScalarType = 1364 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1365 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1366 QualType ComplexType = S.Context.getComplexType(ScalarType); 1367 1368 if (!IsCompAssign) 1369 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1370 CK_IntegralRealToComplex); 1371 return ComplexType; 1372 } 1373 1374 /// Return the rank of a given fixed point or integer type. The value itself 1375 /// doesn't matter, but the values must be increasing with proper increasing 1376 /// rank as described in N1169 4.1.1. 1377 static unsigned GetFixedPointRank(QualType Ty) { 1378 const auto *BTy = Ty->getAs<BuiltinType>(); 1379 assert(BTy && "Expected a builtin type."); 1380 1381 switch (BTy->getKind()) { 1382 case BuiltinType::ShortFract: 1383 case BuiltinType::UShortFract: 1384 case BuiltinType::SatShortFract: 1385 case BuiltinType::SatUShortFract: 1386 return 1; 1387 case BuiltinType::Fract: 1388 case BuiltinType::UFract: 1389 case BuiltinType::SatFract: 1390 case BuiltinType::SatUFract: 1391 return 2; 1392 case BuiltinType::LongFract: 1393 case BuiltinType::ULongFract: 1394 case BuiltinType::SatLongFract: 1395 case BuiltinType::SatULongFract: 1396 return 3; 1397 case BuiltinType::ShortAccum: 1398 case BuiltinType::UShortAccum: 1399 case BuiltinType::SatShortAccum: 1400 case BuiltinType::SatUShortAccum: 1401 return 4; 1402 case BuiltinType::Accum: 1403 case BuiltinType::UAccum: 1404 case BuiltinType::SatAccum: 1405 case BuiltinType::SatUAccum: 1406 return 5; 1407 case BuiltinType::LongAccum: 1408 case BuiltinType::ULongAccum: 1409 case BuiltinType::SatLongAccum: 1410 case BuiltinType::SatULongAccum: 1411 return 6; 1412 default: 1413 if (BTy->isInteger()) 1414 return 0; 1415 llvm_unreachable("Unexpected fixed point or integer type"); 1416 } 1417 } 1418 1419 /// handleFixedPointConversion - Fixed point operations between fixed 1420 /// point types and integers or other fixed point types do not fall under 1421 /// usual arithmetic conversion since these conversions could result in loss 1422 /// of precsision (N1169 4.1.4). These operations should be calculated with 1423 /// the full precision of their result type (N1169 4.1.6.2.1). 1424 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1425 QualType RHSTy) { 1426 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1427 "Expected at least one of the operands to be a fixed point type"); 1428 assert((LHSTy->isFixedPointOrIntegerType() || 1429 RHSTy->isFixedPointOrIntegerType()) && 1430 "Special fixed point arithmetic operation conversions are only " 1431 "applied to ints or other fixed point types"); 1432 1433 // If one operand has signed fixed-point type and the other operand has 1434 // unsigned fixed-point type, then the unsigned fixed-point operand is 1435 // converted to its corresponding signed fixed-point type and the resulting 1436 // type is the type of the converted operand. 1437 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1438 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1439 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1440 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1441 1442 // The result type is the type with the highest rank, whereby a fixed-point 1443 // conversion rank is always greater than an integer conversion rank; if the 1444 // type of either of the operands is a saturating fixedpoint type, the result 1445 // type shall be the saturating fixed-point type corresponding to the type 1446 // with the highest rank; the resulting value is converted (taking into 1447 // account rounding and overflow) to the precision of the resulting type. 1448 // Same ranks between signed and unsigned types are resolved earlier, so both 1449 // types are either signed or both unsigned at this point. 1450 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1451 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1452 1453 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1454 1455 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1456 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1457 1458 return ResultTy; 1459 } 1460 1461 /// Check that the usual arithmetic conversions can be performed on this pair of 1462 /// expressions that might be of enumeration type. 1463 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1464 SourceLocation Loc, 1465 Sema::ArithConvKind ACK) { 1466 // C++2a [expr.arith.conv]p1: 1467 // If one operand is of enumeration type and the other operand is of a 1468 // different enumeration type or a floating-point type, this behavior is 1469 // deprecated ([depr.arith.conv.enum]). 1470 // 1471 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1472 // Eventually we will presumably reject these cases (in C++23 onwards?). 1473 QualType L = LHS->getType(), R = RHS->getType(); 1474 bool LEnum = L->isUnscopedEnumerationType(), 1475 REnum = R->isUnscopedEnumerationType(); 1476 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1477 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1478 (REnum && L->isFloatingType())) { 1479 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1480 ? diag::warn_arith_conv_enum_float_cxx20 1481 : diag::warn_arith_conv_enum_float) 1482 << LHS->getSourceRange() << RHS->getSourceRange() 1483 << (int)ACK << LEnum << L << R; 1484 } else if (!IsCompAssign && LEnum && REnum && 1485 !S.Context.hasSameUnqualifiedType(L, R)) { 1486 unsigned DiagID; 1487 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1488 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1489 // If either enumeration type is unnamed, it's less likely that the 1490 // user cares about this, but this situation is still deprecated in 1491 // C++2a. Use a different warning group. 1492 DiagID = S.getLangOpts().CPlusPlus20 1493 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1494 : diag::warn_arith_conv_mixed_anon_enum_types; 1495 } else if (ACK == Sema::ACK_Conditional) { 1496 // Conditional expressions are separated out because they have 1497 // historically had a different warning flag. 1498 DiagID = S.getLangOpts().CPlusPlus20 1499 ? diag::warn_conditional_mixed_enum_types_cxx20 1500 : diag::warn_conditional_mixed_enum_types; 1501 } else if (ACK == Sema::ACK_Comparison) { 1502 // Comparison expressions are separated out because they have 1503 // historically had a different warning flag. 1504 DiagID = S.getLangOpts().CPlusPlus20 1505 ? diag::warn_comparison_mixed_enum_types_cxx20 1506 : diag::warn_comparison_mixed_enum_types; 1507 } else { 1508 DiagID = S.getLangOpts().CPlusPlus20 1509 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1510 : diag::warn_arith_conv_mixed_enum_types; 1511 } 1512 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1513 << (int)ACK << L << R; 1514 } 1515 } 1516 1517 /// UsualArithmeticConversions - Performs various conversions that are common to 1518 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1519 /// routine returns the first non-arithmetic type found. The client is 1520 /// responsible for emitting appropriate error diagnostics. 1521 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1522 SourceLocation Loc, 1523 ArithConvKind ACK) { 1524 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1525 1526 if (ACK != ACK_CompAssign) { 1527 LHS = UsualUnaryConversions(LHS.get()); 1528 if (LHS.isInvalid()) 1529 return QualType(); 1530 } 1531 1532 RHS = UsualUnaryConversions(RHS.get()); 1533 if (RHS.isInvalid()) 1534 return QualType(); 1535 1536 // For conversion purposes, we ignore any qualifiers. 1537 // For example, "const float" and "float" are equivalent. 1538 QualType LHSType = 1539 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1540 QualType RHSType = 1541 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1542 1543 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1544 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1545 LHSType = AtomicLHS->getValueType(); 1546 1547 // If both types are identical, no conversion is needed. 1548 if (LHSType == RHSType) 1549 return LHSType; 1550 1551 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1552 // The caller can deal with this (e.g. pointer + int). 1553 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1554 return QualType(); 1555 1556 // Apply unary and bitfield promotions to the LHS's type. 1557 QualType LHSUnpromotedType = LHSType; 1558 if (LHSType->isPromotableIntegerType()) 1559 LHSType = Context.getPromotedIntegerType(LHSType); 1560 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1561 if (!LHSBitfieldPromoteTy.isNull()) 1562 LHSType = LHSBitfieldPromoteTy; 1563 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1564 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1565 1566 // If both types are identical, no conversion is needed. 1567 if (LHSType == RHSType) 1568 return LHSType; 1569 1570 // At this point, we have two different arithmetic types. 1571 1572 // Diagnose attempts to convert between __ibm128, __float128 and long double 1573 // where such conversions currently can't be handled. 1574 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1575 return QualType(); 1576 1577 // Handle complex types first (C99 6.3.1.8p1). 1578 if (LHSType->isComplexType() || RHSType->isComplexType()) 1579 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1580 ACK == ACK_CompAssign); 1581 1582 // Now handle "real" floating types (i.e. float, double, long double). 1583 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1584 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1585 ACK == ACK_CompAssign); 1586 1587 // Handle GCC complex int extension. 1588 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1589 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1590 ACK == ACK_CompAssign); 1591 1592 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1593 return handleFixedPointConversion(*this, LHSType, RHSType); 1594 1595 // Finally, we have two differing integer types. 1596 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1597 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1598 } 1599 1600 //===----------------------------------------------------------------------===// 1601 // Semantic Analysis for various Expression Types 1602 //===----------------------------------------------------------------------===// 1603 1604 1605 ExprResult 1606 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1607 SourceLocation DefaultLoc, 1608 SourceLocation RParenLoc, 1609 Expr *ControllingExpr, 1610 ArrayRef<ParsedType> ArgTypes, 1611 ArrayRef<Expr *> ArgExprs) { 1612 unsigned NumAssocs = ArgTypes.size(); 1613 assert(NumAssocs == ArgExprs.size()); 1614 1615 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1616 for (unsigned i = 0; i < NumAssocs; ++i) { 1617 if (ArgTypes[i]) 1618 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1619 else 1620 Types[i] = nullptr; 1621 } 1622 1623 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1624 ControllingExpr, 1625 llvm::makeArrayRef(Types, NumAssocs), 1626 ArgExprs); 1627 delete [] Types; 1628 return ER; 1629 } 1630 1631 ExprResult 1632 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1633 SourceLocation DefaultLoc, 1634 SourceLocation RParenLoc, 1635 Expr *ControllingExpr, 1636 ArrayRef<TypeSourceInfo *> Types, 1637 ArrayRef<Expr *> Exprs) { 1638 unsigned NumAssocs = Types.size(); 1639 assert(NumAssocs == Exprs.size()); 1640 1641 // Decay and strip qualifiers for the controlling expression type, and handle 1642 // placeholder type replacement. See committee discussion from WG14 DR423. 1643 { 1644 EnterExpressionEvaluationContext Unevaluated( 1645 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1646 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1647 if (R.isInvalid()) 1648 return ExprError(); 1649 ControllingExpr = R.get(); 1650 } 1651 1652 // The controlling expression is an unevaluated operand, so side effects are 1653 // likely unintended. 1654 if (!inTemplateInstantiation() && 1655 ControllingExpr->HasSideEffects(Context, false)) 1656 Diag(ControllingExpr->getExprLoc(), 1657 diag::warn_side_effects_unevaluated_context); 1658 1659 bool TypeErrorFound = false, 1660 IsResultDependent = ControllingExpr->isTypeDependent(), 1661 ContainsUnexpandedParameterPack 1662 = ControllingExpr->containsUnexpandedParameterPack(); 1663 1664 for (unsigned i = 0; i < NumAssocs; ++i) { 1665 if (Exprs[i]->containsUnexpandedParameterPack()) 1666 ContainsUnexpandedParameterPack = true; 1667 1668 if (Types[i]) { 1669 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1670 ContainsUnexpandedParameterPack = true; 1671 1672 if (Types[i]->getType()->isDependentType()) { 1673 IsResultDependent = true; 1674 } else { 1675 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1676 // complete object type other than a variably modified type." 1677 unsigned D = 0; 1678 if (Types[i]->getType()->isIncompleteType()) 1679 D = diag::err_assoc_type_incomplete; 1680 else if (!Types[i]->getType()->isObjectType()) 1681 D = diag::err_assoc_type_nonobject; 1682 else if (Types[i]->getType()->isVariablyModifiedType()) 1683 D = diag::err_assoc_type_variably_modified; 1684 1685 if (D != 0) { 1686 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1687 << Types[i]->getTypeLoc().getSourceRange() 1688 << Types[i]->getType(); 1689 TypeErrorFound = true; 1690 } 1691 1692 // C11 6.5.1.1p2 "No two generic associations in the same generic 1693 // selection shall specify compatible types." 1694 for (unsigned j = i+1; j < NumAssocs; ++j) 1695 if (Types[j] && !Types[j]->getType()->isDependentType() && 1696 Context.typesAreCompatible(Types[i]->getType(), 1697 Types[j]->getType())) { 1698 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1699 diag::err_assoc_compatible_types) 1700 << Types[j]->getTypeLoc().getSourceRange() 1701 << Types[j]->getType() 1702 << Types[i]->getType(); 1703 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1704 diag::note_compat_assoc) 1705 << Types[i]->getTypeLoc().getSourceRange() 1706 << Types[i]->getType(); 1707 TypeErrorFound = true; 1708 } 1709 } 1710 } 1711 } 1712 if (TypeErrorFound) 1713 return ExprError(); 1714 1715 // If we determined that the generic selection is result-dependent, don't 1716 // try to compute the result expression. 1717 if (IsResultDependent) 1718 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1719 Exprs, DefaultLoc, RParenLoc, 1720 ContainsUnexpandedParameterPack); 1721 1722 SmallVector<unsigned, 1> CompatIndices; 1723 unsigned DefaultIndex = -1U; 1724 for (unsigned i = 0; i < NumAssocs; ++i) { 1725 if (!Types[i]) 1726 DefaultIndex = i; 1727 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1728 Types[i]->getType())) 1729 CompatIndices.push_back(i); 1730 } 1731 1732 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1733 // type compatible with at most one of the types named in its generic 1734 // association list." 1735 if (CompatIndices.size() > 1) { 1736 // We strip parens here because the controlling expression is typically 1737 // parenthesized in macro definitions. 1738 ControllingExpr = ControllingExpr->IgnoreParens(); 1739 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1740 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1741 << (unsigned)CompatIndices.size(); 1742 for (unsigned I : CompatIndices) { 1743 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1744 diag::note_compat_assoc) 1745 << Types[I]->getTypeLoc().getSourceRange() 1746 << Types[I]->getType(); 1747 } 1748 return ExprError(); 1749 } 1750 1751 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1752 // its controlling expression shall have type compatible with exactly one of 1753 // the types named in its generic association list." 1754 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1755 // We strip parens here because the controlling expression is typically 1756 // parenthesized in macro definitions. 1757 ControllingExpr = ControllingExpr->IgnoreParens(); 1758 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1759 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1760 return ExprError(); 1761 } 1762 1763 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1764 // type name that is compatible with the type of the controlling expression, 1765 // then the result expression of the generic selection is the expression 1766 // in that generic association. Otherwise, the result expression of the 1767 // generic selection is the expression in the default generic association." 1768 unsigned ResultIndex = 1769 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1770 1771 return GenericSelectionExpr::Create( 1772 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1773 ContainsUnexpandedParameterPack, ResultIndex); 1774 } 1775 1776 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1777 /// location of the token and the offset of the ud-suffix within it. 1778 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1779 unsigned Offset) { 1780 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1781 S.getLangOpts()); 1782 } 1783 1784 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1785 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1786 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1787 IdentifierInfo *UDSuffix, 1788 SourceLocation UDSuffixLoc, 1789 ArrayRef<Expr*> Args, 1790 SourceLocation LitEndLoc) { 1791 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1792 1793 QualType ArgTy[2]; 1794 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1795 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1796 if (ArgTy[ArgIdx]->isArrayType()) 1797 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1798 } 1799 1800 DeclarationName OpName = 1801 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1802 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1803 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1804 1805 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1806 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1807 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1808 /*AllowStringTemplatePack*/ false, 1809 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1810 return ExprError(); 1811 1812 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1813 } 1814 1815 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1816 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1817 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1818 /// multiple tokens. However, the common case is that StringToks points to one 1819 /// string. 1820 /// 1821 ExprResult 1822 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1823 assert(!StringToks.empty() && "Must have at least one string!"); 1824 1825 StringLiteralParser Literal(StringToks, PP); 1826 if (Literal.hadError) 1827 return ExprError(); 1828 1829 SmallVector<SourceLocation, 4> StringTokLocs; 1830 for (const Token &Tok : StringToks) 1831 StringTokLocs.push_back(Tok.getLocation()); 1832 1833 QualType CharTy = Context.CharTy; 1834 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1835 if (Literal.isWide()) { 1836 CharTy = Context.getWideCharType(); 1837 Kind = StringLiteral::Wide; 1838 } else if (Literal.isUTF8()) { 1839 if (getLangOpts().Char8) 1840 CharTy = Context.Char8Ty; 1841 Kind = StringLiteral::UTF8; 1842 } else if (Literal.isUTF16()) { 1843 CharTy = Context.Char16Ty; 1844 Kind = StringLiteral::UTF16; 1845 } else if (Literal.isUTF32()) { 1846 CharTy = Context.Char32Ty; 1847 Kind = StringLiteral::UTF32; 1848 } else if (Literal.isPascal()) { 1849 CharTy = Context.UnsignedCharTy; 1850 } 1851 1852 // Warn on initializing an array of char from a u8 string literal; this 1853 // becomes ill-formed in C++2a. 1854 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1855 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1856 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1857 1858 // Create removals for all 'u8' prefixes in the string literal(s). This 1859 // ensures C++2a compatibility (but may change the program behavior when 1860 // built by non-Clang compilers for which the execution character set is 1861 // not always UTF-8). 1862 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1863 SourceLocation RemovalDiagLoc; 1864 for (const Token &Tok : StringToks) { 1865 if (Tok.getKind() == tok::utf8_string_literal) { 1866 if (RemovalDiagLoc.isInvalid()) 1867 RemovalDiagLoc = Tok.getLocation(); 1868 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1869 Tok.getLocation(), 1870 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1871 getSourceManager(), getLangOpts()))); 1872 } 1873 } 1874 Diag(RemovalDiagLoc, RemovalDiag); 1875 } 1876 1877 QualType StrTy = 1878 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1879 1880 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1881 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1882 Kind, Literal.Pascal, StrTy, 1883 &StringTokLocs[0], 1884 StringTokLocs.size()); 1885 if (Literal.getUDSuffix().empty()) 1886 return Lit; 1887 1888 // We're building a user-defined literal. 1889 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1890 SourceLocation UDSuffixLoc = 1891 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1892 Literal.getUDSuffixOffset()); 1893 1894 // Make sure we're allowed user-defined literals here. 1895 if (!UDLScope) 1896 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1897 1898 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1899 // operator "" X (str, len) 1900 QualType SizeType = Context.getSizeType(); 1901 1902 DeclarationName OpName = 1903 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1904 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1905 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1906 1907 QualType ArgTy[] = { 1908 Context.getArrayDecayedType(StrTy), SizeType 1909 }; 1910 1911 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1912 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1913 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1914 /*AllowStringTemplatePack*/ true, 1915 /*DiagnoseMissing*/ true, Lit)) { 1916 1917 case LOLR_Cooked: { 1918 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1919 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1920 StringTokLocs[0]); 1921 Expr *Args[] = { Lit, LenArg }; 1922 1923 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1924 } 1925 1926 case LOLR_Template: { 1927 TemplateArgumentListInfo ExplicitArgs; 1928 TemplateArgument Arg(Lit); 1929 TemplateArgumentLocInfo ArgInfo(Lit); 1930 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1931 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1932 &ExplicitArgs); 1933 } 1934 1935 case LOLR_StringTemplatePack: { 1936 TemplateArgumentListInfo ExplicitArgs; 1937 1938 unsigned CharBits = Context.getIntWidth(CharTy); 1939 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1940 llvm::APSInt Value(CharBits, CharIsUnsigned); 1941 1942 TemplateArgument TypeArg(CharTy); 1943 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1944 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1945 1946 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1947 Value = Lit->getCodeUnit(I); 1948 TemplateArgument Arg(Context, Value, CharTy); 1949 TemplateArgumentLocInfo ArgInfo; 1950 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1951 } 1952 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1953 &ExplicitArgs); 1954 } 1955 case LOLR_Raw: 1956 case LOLR_ErrorNoDiagnostic: 1957 llvm_unreachable("unexpected literal operator lookup result"); 1958 case LOLR_Error: 1959 return ExprError(); 1960 } 1961 llvm_unreachable("unexpected literal operator lookup result"); 1962 } 1963 1964 DeclRefExpr * 1965 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1966 SourceLocation Loc, 1967 const CXXScopeSpec *SS) { 1968 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1969 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1970 } 1971 1972 DeclRefExpr * 1973 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1974 const DeclarationNameInfo &NameInfo, 1975 const CXXScopeSpec *SS, NamedDecl *FoundD, 1976 SourceLocation TemplateKWLoc, 1977 const TemplateArgumentListInfo *TemplateArgs) { 1978 NestedNameSpecifierLoc NNS = 1979 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1980 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1981 TemplateArgs); 1982 } 1983 1984 // CUDA/HIP: Check whether a captured reference variable is referencing a 1985 // host variable in a device or host device lambda. 1986 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1987 VarDecl *VD) { 1988 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1989 return false; 1990 assert(VD->getType()->isReferenceType()); 1991 1992 // Check whether the reference variable is referencing a host variable. 1993 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1994 if (!DRE) 1995 return false; 1996 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1997 if (!Referee || !Referee->hasGlobalStorage() || 1998 Referee->hasAttr<CUDADeviceAttr>()) 1999 return false; 2000 2001 // Check whether the current function is a device or host device lambda. 2002 // Check whether the reference variable is a capture by getDeclContext() 2003 // since refersToEnclosingVariableOrCapture() is not ready at this point. 2004 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 2005 if (MD && MD->getParent()->isLambda() && 2006 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 2007 VD->getDeclContext() != MD) 2008 return true; 2009 2010 return false; 2011 } 2012 2013 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 2014 // A declaration named in an unevaluated operand never constitutes an odr-use. 2015 if (isUnevaluatedContext()) 2016 return NOUR_Unevaluated; 2017 2018 // C++2a [basic.def.odr]p4: 2019 // A variable x whose name appears as a potentially-evaluated expression e 2020 // is odr-used by e unless [...] x is a reference that is usable in 2021 // constant expressions. 2022 // CUDA/HIP: 2023 // If a reference variable referencing a host variable is captured in a 2024 // device or host device lambda, the value of the referee must be copied 2025 // to the capture and the reference variable must be treated as odr-use 2026 // since the value of the referee is not known at compile time and must 2027 // be loaded from the captured. 2028 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2029 if (VD->getType()->isReferenceType() && 2030 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2031 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2032 VD->isUsableInConstantExpressions(Context)) 2033 return NOUR_Constant; 2034 } 2035 2036 // All remaining non-variable cases constitute an odr-use. For variables, we 2037 // need to wait and see how the expression is used. 2038 return NOUR_None; 2039 } 2040 2041 /// BuildDeclRefExpr - Build an expression that references a 2042 /// declaration that does not require a closure capture. 2043 DeclRefExpr * 2044 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2045 const DeclarationNameInfo &NameInfo, 2046 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2047 SourceLocation TemplateKWLoc, 2048 const TemplateArgumentListInfo *TemplateArgs) { 2049 bool RefersToCapturedVariable = 2050 isa<VarDecl>(D) && 2051 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2052 2053 DeclRefExpr *E = DeclRefExpr::Create( 2054 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2055 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2056 MarkDeclRefReferenced(E); 2057 2058 // C++ [except.spec]p17: 2059 // An exception-specification is considered to be needed when: 2060 // - in an expression, the function is the unique lookup result or 2061 // the selected member of a set of overloaded functions. 2062 // 2063 // We delay doing this until after we've built the function reference and 2064 // marked it as used so that: 2065 // a) if the function is defaulted, we get errors from defining it before / 2066 // instead of errors from computing its exception specification, and 2067 // b) if the function is a defaulted comparison, we can use the body we 2068 // build when defining it as input to the exception specification 2069 // computation rather than computing a new body. 2070 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2071 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2072 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2073 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2074 } 2075 } 2076 2077 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2078 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2079 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2080 getCurFunction()->recordUseOfWeak(E); 2081 2082 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2083 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2084 FD = IFD->getAnonField(); 2085 if (FD) { 2086 UnusedPrivateFields.remove(FD); 2087 // Just in case we're building an illegal pointer-to-member. 2088 if (FD->isBitField()) 2089 E->setObjectKind(OK_BitField); 2090 } 2091 2092 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2093 // designates a bit-field. 2094 if (auto *BD = dyn_cast<BindingDecl>(D)) 2095 if (auto *BE = BD->getBinding()) 2096 E->setObjectKind(BE->getObjectKind()); 2097 2098 return E; 2099 } 2100 2101 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2102 /// possibly a list of template arguments. 2103 /// 2104 /// If this produces template arguments, it is permitted to call 2105 /// DecomposeTemplateName. 2106 /// 2107 /// This actually loses a lot of source location information for 2108 /// non-standard name kinds; we should consider preserving that in 2109 /// some way. 2110 void 2111 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2112 TemplateArgumentListInfo &Buffer, 2113 DeclarationNameInfo &NameInfo, 2114 const TemplateArgumentListInfo *&TemplateArgs) { 2115 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2116 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2117 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2118 2119 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2120 Id.TemplateId->NumArgs); 2121 translateTemplateArguments(TemplateArgsPtr, Buffer); 2122 2123 TemplateName TName = Id.TemplateId->Template.get(); 2124 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2125 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2126 TemplateArgs = &Buffer; 2127 } else { 2128 NameInfo = GetNameFromUnqualifiedId(Id); 2129 TemplateArgs = nullptr; 2130 } 2131 } 2132 2133 static void emitEmptyLookupTypoDiagnostic( 2134 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2135 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2136 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2137 DeclContext *Ctx = 2138 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2139 if (!TC) { 2140 // Emit a special diagnostic for failed member lookups. 2141 // FIXME: computing the declaration context might fail here (?) 2142 if (Ctx) 2143 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2144 << SS.getRange(); 2145 else 2146 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2147 return; 2148 } 2149 2150 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2151 bool DroppedSpecifier = 2152 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2153 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2154 ? diag::note_implicit_param_decl 2155 : diag::note_previous_decl; 2156 if (!Ctx) 2157 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2158 SemaRef.PDiag(NoteID)); 2159 else 2160 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2161 << Typo << Ctx << DroppedSpecifier 2162 << SS.getRange(), 2163 SemaRef.PDiag(NoteID)); 2164 } 2165 2166 /// Diagnose a lookup that found results in an enclosing class during error 2167 /// recovery. This usually indicates that the results were found in a dependent 2168 /// base class that could not be searched as part of a template definition. 2169 /// Always issues a diagnostic (though this may be only a warning in MS 2170 /// compatibility mode). 2171 /// 2172 /// Return \c true if the error is unrecoverable, or \c false if the caller 2173 /// should attempt to recover using these lookup results. 2174 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2175 // During a default argument instantiation the CurContext points 2176 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2177 // function parameter list, hence add an explicit check. 2178 bool isDefaultArgument = 2179 !CodeSynthesisContexts.empty() && 2180 CodeSynthesisContexts.back().Kind == 2181 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2182 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2183 bool isInstance = CurMethod && CurMethod->isInstance() && 2184 R.getNamingClass() == CurMethod->getParent() && 2185 !isDefaultArgument; 2186 2187 // There are two ways we can find a class-scope declaration during template 2188 // instantiation that we did not find in the template definition: if it is a 2189 // member of a dependent base class, or if it is declared after the point of 2190 // use in the same class. Distinguish these by comparing the class in which 2191 // the member was found to the naming class of the lookup. 2192 unsigned DiagID = diag::err_found_in_dependent_base; 2193 unsigned NoteID = diag::note_member_declared_at; 2194 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2195 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2196 : diag::err_found_later_in_class; 2197 } else if (getLangOpts().MSVCCompat) { 2198 DiagID = diag::ext_found_in_dependent_base; 2199 NoteID = diag::note_dependent_member_use; 2200 } 2201 2202 if (isInstance) { 2203 // Give a code modification hint to insert 'this->'. 2204 Diag(R.getNameLoc(), DiagID) 2205 << R.getLookupName() 2206 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2207 CheckCXXThisCapture(R.getNameLoc()); 2208 } else { 2209 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2210 // they're not shadowed). 2211 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2212 } 2213 2214 for (NamedDecl *D : R) 2215 Diag(D->getLocation(), NoteID); 2216 2217 // Return true if we are inside a default argument instantiation 2218 // and the found name refers to an instance member function, otherwise 2219 // the caller will try to create an implicit member call and this is wrong 2220 // for default arguments. 2221 // 2222 // FIXME: Is this special case necessary? We could allow the caller to 2223 // diagnose this. 2224 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2225 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2226 return true; 2227 } 2228 2229 // Tell the callee to try to recover. 2230 return false; 2231 } 2232 2233 /// Diagnose an empty lookup. 2234 /// 2235 /// \return false if new lookup candidates were found 2236 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2237 CorrectionCandidateCallback &CCC, 2238 TemplateArgumentListInfo *ExplicitTemplateArgs, 2239 ArrayRef<Expr *> Args, TypoExpr **Out) { 2240 DeclarationName Name = R.getLookupName(); 2241 2242 unsigned diagnostic = diag::err_undeclared_var_use; 2243 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2244 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2245 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2246 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2247 diagnostic = diag::err_undeclared_use; 2248 diagnostic_suggest = diag::err_undeclared_use_suggest; 2249 } 2250 2251 // If the original lookup was an unqualified lookup, fake an 2252 // unqualified lookup. This is useful when (for example) the 2253 // original lookup would not have found something because it was a 2254 // dependent name. 2255 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2256 while (DC) { 2257 if (isa<CXXRecordDecl>(DC)) { 2258 LookupQualifiedName(R, DC); 2259 2260 if (!R.empty()) { 2261 // Don't give errors about ambiguities in this lookup. 2262 R.suppressDiagnostics(); 2263 2264 // If there's a best viable function among the results, only mention 2265 // that one in the notes. 2266 OverloadCandidateSet Candidates(R.getNameLoc(), 2267 OverloadCandidateSet::CSK_Normal); 2268 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2269 OverloadCandidateSet::iterator Best; 2270 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2271 OR_Success) { 2272 R.clear(); 2273 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2274 R.resolveKind(); 2275 } 2276 2277 return DiagnoseDependentMemberLookup(R); 2278 } 2279 2280 R.clear(); 2281 } 2282 2283 DC = DC->getLookupParent(); 2284 } 2285 2286 // We didn't find anything, so try to correct for a typo. 2287 TypoCorrection Corrected; 2288 if (S && Out) { 2289 SourceLocation TypoLoc = R.getNameLoc(); 2290 assert(!ExplicitTemplateArgs && 2291 "Diagnosing an empty lookup with explicit template args!"); 2292 *Out = CorrectTypoDelayed( 2293 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2294 [=](const TypoCorrection &TC) { 2295 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2296 diagnostic, diagnostic_suggest); 2297 }, 2298 nullptr, CTK_ErrorRecovery); 2299 if (*Out) 2300 return true; 2301 } else if (S && 2302 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2303 S, &SS, CCC, CTK_ErrorRecovery))) { 2304 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2305 bool DroppedSpecifier = 2306 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2307 R.setLookupName(Corrected.getCorrection()); 2308 2309 bool AcceptableWithRecovery = false; 2310 bool AcceptableWithoutRecovery = false; 2311 NamedDecl *ND = Corrected.getFoundDecl(); 2312 if (ND) { 2313 if (Corrected.isOverloaded()) { 2314 OverloadCandidateSet OCS(R.getNameLoc(), 2315 OverloadCandidateSet::CSK_Normal); 2316 OverloadCandidateSet::iterator Best; 2317 for (NamedDecl *CD : Corrected) { 2318 if (FunctionTemplateDecl *FTD = 2319 dyn_cast<FunctionTemplateDecl>(CD)) 2320 AddTemplateOverloadCandidate( 2321 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2322 Args, OCS); 2323 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2324 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2325 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2326 Args, OCS); 2327 } 2328 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2329 case OR_Success: 2330 ND = Best->FoundDecl; 2331 Corrected.setCorrectionDecl(ND); 2332 break; 2333 default: 2334 // FIXME: Arbitrarily pick the first declaration for the note. 2335 Corrected.setCorrectionDecl(ND); 2336 break; 2337 } 2338 } 2339 R.addDecl(ND); 2340 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2341 CXXRecordDecl *Record = nullptr; 2342 if (Corrected.getCorrectionSpecifier()) { 2343 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2344 Record = Ty->getAsCXXRecordDecl(); 2345 } 2346 if (!Record) 2347 Record = cast<CXXRecordDecl>( 2348 ND->getDeclContext()->getRedeclContext()); 2349 R.setNamingClass(Record); 2350 } 2351 2352 auto *UnderlyingND = ND->getUnderlyingDecl(); 2353 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2354 isa<FunctionTemplateDecl>(UnderlyingND); 2355 // FIXME: If we ended up with a typo for a type name or 2356 // Objective-C class name, we're in trouble because the parser 2357 // is in the wrong place to recover. Suggest the typo 2358 // correction, but don't make it a fix-it since we're not going 2359 // to recover well anyway. 2360 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2361 getAsTypeTemplateDecl(UnderlyingND) || 2362 isa<ObjCInterfaceDecl>(UnderlyingND); 2363 } else { 2364 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2365 // because we aren't able to recover. 2366 AcceptableWithoutRecovery = true; 2367 } 2368 2369 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2370 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2371 ? diag::note_implicit_param_decl 2372 : diag::note_previous_decl; 2373 if (SS.isEmpty()) 2374 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2375 PDiag(NoteID), AcceptableWithRecovery); 2376 else 2377 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2378 << Name << computeDeclContext(SS, false) 2379 << DroppedSpecifier << SS.getRange(), 2380 PDiag(NoteID), AcceptableWithRecovery); 2381 2382 // Tell the callee whether to try to recover. 2383 return !AcceptableWithRecovery; 2384 } 2385 } 2386 R.clear(); 2387 2388 // Emit a special diagnostic for failed member lookups. 2389 // FIXME: computing the declaration context might fail here (?) 2390 if (!SS.isEmpty()) { 2391 Diag(R.getNameLoc(), diag::err_no_member) 2392 << Name << computeDeclContext(SS, false) 2393 << SS.getRange(); 2394 return true; 2395 } 2396 2397 // Give up, we can't recover. 2398 Diag(R.getNameLoc(), diagnostic) << Name; 2399 return true; 2400 } 2401 2402 /// In Microsoft mode, if we are inside a template class whose parent class has 2403 /// dependent base classes, and we can't resolve an unqualified identifier, then 2404 /// assume the identifier is a member of a dependent base class. We can only 2405 /// recover successfully in static methods, instance methods, and other contexts 2406 /// where 'this' is available. This doesn't precisely match MSVC's 2407 /// instantiation model, but it's close enough. 2408 static Expr * 2409 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2410 DeclarationNameInfo &NameInfo, 2411 SourceLocation TemplateKWLoc, 2412 const TemplateArgumentListInfo *TemplateArgs) { 2413 // Only try to recover from lookup into dependent bases in static methods or 2414 // contexts where 'this' is available. 2415 QualType ThisType = S.getCurrentThisType(); 2416 const CXXRecordDecl *RD = nullptr; 2417 if (!ThisType.isNull()) 2418 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2419 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2420 RD = MD->getParent(); 2421 if (!RD || !RD->hasAnyDependentBases()) 2422 return nullptr; 2423 2424 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2425 // is available, suggest inserting 'this->' as a fixit. 2426 SourceLocation Loc = NameInfo.getLoc(); 2427 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2428 DB << NameInfo.getName() << RD; 2429 2430 if (!ThisType.isNull()) { 2431 DB << FixItHint::CreateInsertion(Loc, "this->"); 2432 return CXXDependentScopeMemberExpr::Create( 2433 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2434 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2435 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2436 } 2437 2438 // Synthesize a fake NNS that points to the derived class. This will 2439 // perform name lookup during template instantiation. 2440 CXXScopeSpec SS; 2441 auto *NNS = 2442 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2443 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2444 return DependentScopeDeclRefExpr::Create( 2445 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2446 TemplateArgs); 2447 } 2448 2449 ExprResult 2450 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2451 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2452 bool HasTrailingLParen, bool IsAddressOfOperand, 2453 CorrectionCandidateCallback *CCC, 2454 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2455 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2456 "cannot be direct & operand and have a trailing lparen"); 2457 if (SS.isInvalid()) 2458 return ExprError(); 2459 2460 TemplateArgumentListInfo TemplateArgsBuffer; 2461 2462 // Decompose the UnqualifiedId into the following data. 2463 DeclarationNameInfo NameInfo; 2464 const TemplateArgumentListInfo *TemplateArgs; 2465 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2466 2467 DeclarationName Name = NameInfo.getName(); 2468 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2469 SourceLocation NameLoc = NameInfo.getLoc(); 2470 2471 if (II && II->isEditorPlaceholder()) { 2472 // FIXME: When typed placeholders are supported we can create a typed 2473 // placeholder expression node. 2474 return ExprError(); 2475 } 2476 2477 // C++ [temp.dep.expr]p3: 2478 // An id-expression is type-dependent if it contains: 2479 // -- an identifier that was declared with a dependent type, 2480 // (note: handled after lookup) 2481 // -- a template-id that is dependent, 2482 // (note: handled in BuildTemplateIdExpr) 2483 // -- a conversion-function-id that specifies a dependent type, 2484 // -- a nested-name-specifier that contains a class-name that 2485 // names a dependent type. 2486 // Determine whether this is a member of an unknown specialization; 2487 // we need to handle these differently. 2488 bool DependentID = false; 2489 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2490 Name.getCXXNameType()->isDependentType()) { 2491 DependentID = true; 2492 } else if (SS.isSet()) { 2493 if (DeclContext *DC = computeDeclContext(SS, false)) { 2494 if (RequireCompleteDeclContext(SS, DC)) 2495 return ExprError(); 2496 } else { 2497 DependentID = true; 2498 } 2499 } 2500 2501 if (DependentID) 2502 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2503 IsAddressOfOperand, TemplateArgs); 2504 2505 // Perform the required lookup. 2506 LookupResult R(*this, NameInfo, 2507 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2508 ? LookupObjCImplicitSelfParam 2509 : LookupOrdinaryName); 2510 if (TemplateKWLoc.isValid() || TemplateArgs) { 2511 // Lookup the template name again to correctly establish the context in 2512 // which it was found. This is really unfortunate as we already did the 2513 // lookup to determine that it was a template name in the first place. If 2514 // this becomes a performance hit, we can work harder to preserve those 2515 // results until we get here but it's likely not worth it. 2516 bool MemberOfUnknownSpecialization; 2517 AssumedTemplateKind AssumedTemplate; 2518 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2519 MemberOfUnknownSpecialization, TemplateKWLoc, 2520 &AssumedTemplate)) 2521 return ExprError(); 2522 2523 if (MemberOfUnknownSpecialization || 2524 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2525 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2526 IsAddressOfOperand, TemplateArgs); 2527 } else { 2528 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2529 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2530 2531 // If the result might be in a dependent base class, this is a dependent 2532 // id-expression. 2533 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2534 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2535 IsAddressOfOperand, TemplateArgs); 2536 2537 // If this reference is in an Objective-C method, then we need to do 2538 // some special Objective-C lookup, too. 2539 if (IvarLookupFollowUp) { 2540 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2541 if (E.isInvalid()) 2542 return ExprError(); 2543 2544 if (Expr *Ex = E.getAs<Expr>()) 2545 return Ex; 2546 } 2547 } 2548 2549 if (R.isAmbiguous()) 2550 return ExprError(); 2551 2552 // This could be an implicitly declared function reference (legal in C90, 2553 // extension in C99, forbidden in C++). 2554 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2555 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2556 if (D) R.addDecl(D); 2557 } 2558 2559 // Determine whether this name might be a candidate for 2560 // argument-dependent lookup. 2561 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2562 2563 if (R.empty() && !ADL) { 2564 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2565 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2566 TemplateKWLoc, TemplateArgs)) 2567 return E; 2568 } 2569 2570 // Don't diagnose an empty lookup for inline assembly. 2571 if (IsInlineAsmIdentifier) 2572 return ExprError(); 2573 2574 // If this name wasn't predeclared and if this is not a function 2575 // call, diagnose the problem. 2576 TypoExpr *TE = nullptr; 2577 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2578 : nullptr); 2579 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2580 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2581 "Typo correction callback misconfigured"); 2582 if (CCC) { 2583 // Make sure the callback knows what the typo being diagnosed is. 2584 CCC->setTypoName(II); 2585 if (SS.isValid()) 2586 CCC->setTypoNNS(SS.getScopeRep()); 2587 } 2588 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2589 // a template name, but we happen to have always already looked up the name 2590 // before we get here if it must be a template name. 2591 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2592 None, &TE)) { 2593 if (TE && KeywordReplacement) { 2594 auto &State = getTypoExprState(TE); 2595 auto BestTC = State.Consumer->getNextCorrection(); 2596 if (BestTC.isKeyword()) { 2597 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2598 if (State.DiagHandler) 2599 State.DiagHandler(BestTC); 2600 KeywordReplacement->startToken(); 2601 KeywordReplacement->setKind(II->getTokenID()); 2602 KeywordReplacement->setIdentifierInfo(II); 2603 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2604 // Clean up the state associated with the TypoExpr, since it has 2605 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2606 clearDelayedTypo(TE); 2607 // Signal that a correction to a keyword was performed by returning a 2608 // valid-but-null ExprResult. 2609 return (Expr*)nullptr; 2610 } 2611 State.Consumer->resetCorrectionStream(); 2612 } 2613 return TE ? TE : ExprError(); 2614 } 2615 2616 assert(!R.empty() && 2617 "DiagnoseEmptyLookup returned false but added no results"); 2618 2619 // If we found an Objective-C instance variable, let 2620 // LookupInObjCMethod build the appropriate expression to 2621 // reference the ivar. 2622 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2623 R.clear(); 2624 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2625 // In a hopelessly buggy code, Objective-C instance variable 2626 // lookup fails and no expression will be built to reference it. 2627 if (!E.isInvalid() && !E.get()) 2628 return ExprError(); 2629 return E; 2630 } 2631 } 2632 2633 // This is guaranteed from this point on. 2634 assert(!R.empty() || ADL); 2635 2636 // Check whether this might be a C++ implicit instance member access. 2637 // C++ [class.mfct.non-static]p3: 2638 // When an id-expression that is not part of a class member access 2639 // syntax and not used to form a pointer to member is used in the 2640 // body of a non-static member function of class X, if name lookup 2641 // resolves the name in the id-expression to a non-static non-type 2642 // member of some class C, the id-expression is transformed into a 2643 // class member access expression using (*this) as the 2644 // postfix-expression to the left of the . operator. 2645 // 2646 // But we don't actually need to do this for '&' operands if R 2647 // resolved to a function or overloaded function set, because the 2648 // expression is ill-formed if it actually works out to be a 2649 // non-static member function: 2650 // 2651 // C++ [expr.ref]p4: 2652 // Otherwise, if E1.E2 refers to a non-static member function. . . 2653 // [t]he expression can be used only as the left-hand operand of a 2654 // member function call. 2655 // 2656 // There are other safeguards against such uses, but it's important 2657 // to get this right here so that we don't end up making a 2658 // spuriously dependent expression if we're inside a dependent 2659 // instance method. 2660 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2661 bool MightBeImplicitMember; 2662 if (!IsAddressOfOperand) 2663 MightBeImplicitMember = true; 2664 else if (!SS.isEmpty()) 2665 MightBeImplicitMember = false; 2666 else if (R.isOverloadedResult()) 2667 MightBeImplicitMember = false; 2668 else if (R.isUnresolvableResult()) 2669 MightBeImplicitMember = true; 2670 else 2671 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2672 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2673 isa<MSPropertyDecl>(R.getFoundDecl()); 2674 2675 if (MightBeImplicitMember) 2676 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2677 R, TemplateArgs, S); 2678 } 2679 2680 if (TemplateArgs || TemplateKWLoc.isValid()) { 2681 2682 // In C++1y, if this is a variable template id, then check it 2683 // in BuildTemplateIdExpr(). 2684 // The single lookup result must be a variable template declaration. 2685 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2686 Id.TemplateId->Kind == TNK_Var_template) { 2687 assert(R.getAsSingle<VarTemplateDecl>() && 2688 "There should only be one declaration found."); 2689 } 2690 2691 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2692 } 2693 2694 return BuildDeclarationNameExpr(SS, R, ADL); 2695 } 2696 2697 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2698 /// declaration name, generally during template instantiation. 2699 /// There's a large number of things which don't need to be done along 2700 /// this path. 2701 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2702 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2703 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2704 DeclContext *DC = computeDeclContext(SS, false); 2705 if (!DC) 2706 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2707 NameInfo, /*TemplateArgs=*/nullptr); 2708 2709 if (RequireCompleteDeclContext(SS, DC)) 2710 return ExprError(); 2711 2712 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2713 LookupQualifiedName(R, DC); 2714 2715 if (R.isAmbiguous()) 2716 return ExprError(); 2717 2718 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2719 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2720 NameInfo, /*TemplateArgs=*/nullptr); 2721 2722 if (R.empty()) { 2723 // Don't diagnose problems with invalid record decl, the secondary no_member 2724 // diagnostic during template instantiation is likely bogus, e.g. if a class 2725 // is invalid because it's derived from an invalid base class, then missing 2726 // members were likely supposed to be inherited. 2727 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2728 if (CD->isInvalidDecl()) 2729 return ExprError(); 2730 Diag(NameInfo.getLoc(), diag::err_no_member) 2731 << NameInfo.getName() << DC << SS.getRange(); 2732 return ExprError(); 2733 } 2734 2735 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2736 // Diagnose a missing typename if this resolved unambiguously to a type in 2737 // a dependent context. If we can recover with a type, downgrade this to 2738 // a warning in Microsoft compatibility mode. 2739 unsigned DiagID = diag::err_typename_missing; 2740 if (RecoveryTSI && getLangOpts().MSVCCompat) 2741 DiagID = diag::ext_typename_missing; 2742 SourceLocation Loc = SS.getBeginLoc(); 2743 auto D = Diag(Loc, DiagID); 2744 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2745 << SourceRange(Loc, NameInfo.getEndLoc()); 2746 2747 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2748 // context. 2749 if (!RecoveryTSI) 2750 return ExprError(); 2751 2752 // Only issue the fixit if we're prepared to recover. 2753 D << FixItHint::CreateInsertion(Loc, "typename "); 2754 2755 // Recover by pretending this was an elaborated type. 2756 QualType Ty = Context.getTypeDeclType(TD); 2757 TypeLocBuilder TLB; 2758 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2759 2760 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2761 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2762 QTL.setElaboratedKeywordLoc(SourceLocation()); 2763 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2764 2765 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2766 2767 return ExprEmpty(); 2768 } 2769 2770 // Defend against this resolving to an implicit member access. We usually 2771 // won't get here if this might be a legitimate a class member (we end up in 2772 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2773 // a pointer-to-member or in an unevaluated context in C++11. 2774 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2775 return BuildPossibleImplicitMemberExpr(SS, 2776 /*TemplateKWLoc=*/SourceLocation(), 2777 R, /*TemplateArgs=*/nullptr, S); 2778 2779 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2780 } 2781 2782 /// The parser has read a name in, and Sema has detected that we're currently 2783 /// inside an ObjC method. Perform some additional checks and determine if we 2784 /// should form a reference to an ivar. 2785 /// 2786 /// Ideally, most of this would be done by lookup, but there's 2787 /// actually quite a lot of extra work involved. 2788 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2789 IdentifierInfo *II) { 2790 SourceLocation Loc = Lookup.getNameLoc(); 2791 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2792 2793 // Check for error condition which is already reported. 2794 if (!CurMethod) 2795 return DeclResult(true); 2796 2797 // There are two cases to handle here. 1) scoped lookup could have failed, 2798 // in which case we should look for an ivar. 2) scoped lookup could have 2799 // found a decl, but that decl is outside the current instance method (i.e. 2800 // a global variable). In these two cases, we do a lookup for an ivar with 2801 // this name, if the lookup sucedes, we replace it our current decl. 2802 2803 // If we're in a class method, we don't normally want to look for 2804 // ivars. But if we don't find anything else, and there's an 2805 // ivar, that's an error. 2806 bool IsClassMethod = CurMethod->isClassMethod(); 2807 2808 bool LookForIvars; 2809 if (Lookup.empty()) 2810 LookForIvars = true; 2811 else if (IsClassMethod) 2812 LookForIvars = false; 2813 else 2814 LookForIvars = (Lookup.isSingleResult() && 2815 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2816 ObjCInterfaceDecl *IFace = nullptr; 2817 if (LookForIvars) { 2818 IFace = CurMethod->getClassInterface(); 2819 ObjCInterfaceDecl *ClassDeclared; 2820 ObjCIvarDecl *IV = nullptr; 2821 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2822 // Diagnose using an ivar in a class method. 2823 if (IsClassMethod) { 2824 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2825 return DeclResult(true); 2826 } 2827 2828 // Diagnose the use of an ivar outside of the declaring class. 2829 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2830 !declaresSameEntity(ClassDeclared, IFace) && 2831 !getLangOpts().DebuggerSupport) 2832 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2833 2834 // Success. 2835 return IV; 2836 } 2837 } else if (CurMethod->isInstanceMethod()) { 2838 // We should warn if a local variable hides an ivar. 2839 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2840 ObjCInterfaceDecl *ClassDeclared; 2841 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2842 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2843 declaresSameEntity(IFace, ClassDeclared)) 2844 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2845 } 2846 } 2847 } else if (Lookup.isSingleResult() && 2848 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2849 // If accessing a stand-alone ivar in a class method, this is an error. 2850 if (const ObjCIvarDecl *IV = 2851 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2852 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2853 return DeclResult(true); 2854 } 2855 } 2856 2857 // Didn't encounter an error, didn't find an ivar. 2858 return DeclResult(false); 2859 } 2860 2861 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2862 ObjCIvarDecl *IV) { 2863 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2864 assert(CurMethod && CurMethod->isInstanceMethod() && 2865 "should not reference ivar from this context"); 2866 2867 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2868 assert(IFace && "should not reference ivar from this context"); 2869 2870 // If we're referencing an invalid decl, just return this as a silent 2871 // error node. The error diagnostic was already emitted on the decl. 2872 if (IV->isInvalidDecl()) 2873 return ExprError(); 2874 2875 // Check if referencing a field with __attribute__((deprecated)). 2876 if (DiagnoseUseOfDecl(IV, Loc)) 2877 return ExprError(); 2878 2879 // FIXME: This should use a new expr for a direct reference, don't 2880 // turn this into Self->ivar, just return a BareIVarExpr or something. 2881 IdentifierInfo &II = Context.Idents.get("self"); 2882 UnqualifiedId SelfName; 2883 SelfName.setImplicitSelfParam(&II); 2884 CXXScopeSpec SelfScopeSpec; 2885 SourceLocation TemplateKWLoc; 2886 ExprResult SelfExpr = 2887 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2888 /*HasTrailingLParen=*/false, 2889 /*IsAddressOfOperand=*/false); 2890 if (SelfExpr.isInvalid()) 2891 return ExprError(); 2892 2893 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2894 if (SelfExpr.isInvalid()) 2895 return ExprError(); 2896 2897 MarkAnyDeclReferenced(Loc, IV, true); 2898 2899 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2900 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2901 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2902 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2903 2904 ObjCIvarRefExpr *Result = new (Context) 2905 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2906 IV->getLocation(), SelfExpr.get(), true, true); 2907 2908 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2909 if (!isUnevaluatedContext() && 2910 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2911 getCurFunction()->recordUseOfWeak(Result); 2912 } 2913 if (getLangOpts().ObjCAutoRefCount) 2914 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2915 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2916 2917 return Result; 2918 } 2919 2920 /// The parser has read a name in, and Sema has detected that we're currently 2921 /// inside an ObjC method. Perform some additional checks and determine if we 2922 /// should form a reference to an ivar. If so, build an expression referencing 2923 /// that ivar. 2924 ExprResult 2925 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2926 IdentifierInfo *II, bool AllowBuiltinCreation) { 2927 // FIXME: Integrate this lookup step into LookupParsedName. 2928 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2929 if (Ivar.isInvalid()) 2930 return ExprError(); 2931 if (Ivar.isUsable()) 2932 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2933 cast<ObjCIvarDecl>(Ivar.get())); 2934 2935 if (Lookup.empty() && II && AllowBuiltinCreation) 2936 LookupBuiltin(Lookup); 2937 2938 // Sentinel value saying that we didn't do anything special. 2939 return ExprResult(false); 2940 } 2941 2942 /// Cast a base object to a member's actual type. 2943 /// 2944 /// There are two relevant checks: 2945 /// 2946 /// C++ [class.access.base]p7: 2947 /// 2948 /// If a class member access operator [...] is used to access a non-static 2949 /// data member or non-static member function, the reference is ill-formed if 2950 /// the left operand [...] cannot be implicitly converted to a pointer to the 2951 /// naming class of the right operand. 2952 /// 2953 /// C++ [expr.ref]p7: 2954 /// 2955 /// If E2 is a non-static data member or a non-static member function, the 2956 /// program is ill-formed if the class of which E2 is directly a member is an 2957 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2958 /// 2959 /// Note that the latter check does not consider access; the access of the 2960 /// "real" base class is checked as appropriate when checking the access of the 2961 /// member name. 2962 ExprResult 2963 Sema::PerformObjectMemberConversion(Expr *From, 2964 NestedNameSpecifier *Qualifier, 2965 NamedDecl *FoundDecl, 2966 NamedDecl *Member) { 2967 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2968 if (!RD) 2969 return From; 2970 2971 QualType DestRecordType; 2972 QualType DestType; 2973 QualType FromRecordType; 2974 QualType FromType = From->getType(); 2975 bool PointerConversions = false; 2976 if (isa<FieldDecl>(Member)) { 2977 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2978 auto FromPtrType = FromType->getAs<PointerType>(); 2979 DestRecordType = Context.getAddrSpaceQualType( 2980 DestRecordType, FromPtrType 2981 ? FromType->getPointeeType().getAddressSpace() 2982 : FromType.getAddressSpace()); 2983 2984 if (FromPtrType) { 2985 DestType = Context.getPointerType(DestRecordType); 2986 FromRecordType = FromPtrType->getPointeeType(); 2987 PointerConversions = true; 2988 } else { 2989 DestType = DestRecordType; 2990 FromRecordType = FromType; 2991 } 2992 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2993 if (Method->isStatic()) 2994 return From; 2995 2996 DestType = Method->getThisType(); 2997 DestRecordType = DestType->getPointeeType(); 2998 2999 if (FromType->getAs<PointerType>()) { 3000 FromRecordType = FromType->getPointeeType(); 3001 PointerConversions = true; 3002 } else { 3003 FromRecordType = FromType; 3004 DestType = DestRecordType; 3005 } 3006 3007 LangAS FromAS = FromRecordType.getAddressSpace(); 3008 LangAS DestAS = DestRecordType.getAddressSpace(); 3009 if (FromAS != DestAS) { 3010 QualType FromRecordTypeWithoutAS = 3011 Context.removeAddrSpaceQualType(FromRecordType); 3012 QualType FromTypeWithDestAS = 3013 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 3014 if (PointerConversions) 3015 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 3016 From = ImpCastExprToType(From, FromTypeWithDestAS, 3017 CK_AddressSpaceConversion, From->getValueKind()) 3018 .get(); 3019 } 3020 } else { 3021 // No conversion necessary. 3022 return From; 3023 } 3024 3025 if (DestType->isDependentType() || FromType->isDependentType()) 3026 return From; 3027 3028 // If the unqualified types are the same, no conversion is necessary. 3029 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3030 return From; 3031 3032 SourceRange FromRange = From->getSourceRange(); 3033 SourceLocation FromLoc = FromRange.getBegin(); 3034 3035 ExprValueKind VK = From->getValueKind(); 3036 3037 // C++ [class.member.lookup]p8: 3038 // [...] Ambiguities can often be resolved by qualifying a name with its 3039 // class name. 3040 // 3041 // If the member was a qualified name and the qualified referred to a 3042 // specific base subobject type, we'll cast to that intermediate type 3043 // first and then to the object in which the member is declared. That allows 3044 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3045 // 3046 // class Base { public: int x; }; 3047 // class Derived1 : public Base { }; 3048 // class Derived2 : public Base { }; 3049 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3050 // 3051 // void VeryDerived::f() { 3052 // x = 17; // error: ambiguous base subobjects 3053 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3054 // } 3055 if (Qualifier && Qualifier->getAsType()) { 3056 QualType QType = QualType(Qualifier->getAsType(), 0); 3057 assert(QType->isRecordType() && "lookup done with non-record type"); 3058 3059 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); 3060 3061 // In C++98, the qualifier type doesn't actually have to be a base 3062 // type of the object type, in which case we just ignore it. 3063 // Otherwise build the appropriate casts. 3064 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3065 CXXCastPath BasePath; 3066 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3067 FromLoc, FromRange, &BasePath)) 3068 return ExprError(); 3069 3070 if (PointerConversions) 3071 QType = Context.getPointerType(QType); 3072 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3073 VK, &BasePath).get(); 3074 3075 FromType = QType; 3076 FromRecordType = QRecordType; 3077 3078 // If the qualifier type was the same as the destination type, 3079 // we're done. 3080 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3081 return From; 3082 } 3083 } 3084 3085 CXXCastPath BasePath; 3086 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3087 FromLoc, FromRange, &BasePath, 3088 /*IgnoreAccess=*/true)) 3089 return ExprError(); 3090 3091 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3092 VK, &BasePath); 3093 } 3094 3095 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3096 const LookupResult &R, 3097 bool HasTrailingLParen) { 3098 // Only when used directly as the postfix-expression of a call. 3099 if (!HasTrailingLParen) 3100 return false; 3101 3102 // Never if a scope specifier was provided. 3103 if (SS.isSet()) 3104 return false; 3105 3106 // Only in C++ or ObjC++. 3107 if (!getLangOpts().CPlusPlus) 3108 return false; 3109 3110 // Turn off ADL when we find certain kinds of declarations during 3111 // normal lookup: 3112 for (NamedDecl *D : R) { 3113 // C++0x [basic.lookup.argdep]p3: 3114 // -- a declaration of a class member 3115 // Since using decls preserve this property, we check this on the 3116 // original decl. 3117 if (D->isCXXClassMember()) 3118 return false; 3119 3120 // C++0x [basic.lookup.argdep]p3: 3121 // -- a block-scope function declaration that is not a 3122 // using-declaration 3123 // NOTE: we also trigger this for function templates (in fact, we 3124 // don't check the decl type at all, since all other decl types 3125 // turn off ADL anyway). 3126 if (isa<UsingShadowDecl>(D)) 3127 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3128 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3129 return false; 3130 3131 // C++0x [basic.lookup.argdep]p3: 3132 // -- a declaration that is neither a function or a function 3133 // template 3134 // And also for builtin functions. 3135 if (isa<FunctionDecl>(D)) { 3136 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3137 3138 // But also builtin functions. 3139 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3140 return false; 3141 } else if (!isa<FunctionTemplateDecl>(D)) 3142 return false; 3143 } 3144 3145 return true; 3146 } 3147 3148 3149 /// Diagnoses obvious problems with the use of the given declaration 3150 /// as an expression. This is only actually called for lookups that 3151 /// were not overloaded, and it doesn't promise that the declaration 3152 /// will in fact be used. 3153 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3154 if (D->isInvalidDecl()) 3155 return true; 3156 3157 if (isa<TypedefNameDecl>(D)) { 3158 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3159 return true; 3160 } 3161 3162 if (isa<ObjCInterfaceDecl>(D)) { 3163 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3164 return true; 3165 } 3166 3167 if (isa<NamespaceDecl>(D)) { 3168 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3169 return true; 3170 } 3171 3172 return false; 3173 } 3174 3175 // Certain multiversion types should be treated as overloaded even when there is 3176 // only one result. 3177 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3178 assert(R.isSingleResult() && "Expected only a single result"); 3179 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3180 return FD && 3181 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3182 } 3183 3184 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3185 LookupResult &R, bool NeedsADL, 3186 bool AcceptInvalidDecl) { 3187 // If this is a single, fully-resolved result and we don't need ADL, 3188 // just build an ordinary singleton decl ref. 3189 if (!NeedsADL && R.isSingleResult() && 3190 !R.getAsSingle<FunctionTemplateDecl>() && 3191 !ShouldLookupResultBeMultiVersionOverload(R)) 3192 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3193 R.getRepresentativeDecl(), nullptr, 3194 AcceptInvalidDecl); 3195 3196 // We only need to check the declaration if there's exactly one 3197 // result, because in the overloaded case the results can only be 3198 // functions and function templates. 3199 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3200 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3201 return ExprError(); 3202 3203 // Otherwise, just build an unresolved lookup expression. Suppress 3204 // any lookup-related diagnostics; we'll hash these out later, when 3205 // we've picked a target. 3206 R.suppressDiagnostics(); 3207 3208 UnresolvedLookupExpr *ULE 3209 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3210 SS.getWithLocInContext(Context), 3211 R.getLookupNameInfo(), 3212 NeedsADL, R.isOverloadedResult(), 3213 R.begin(), R.end()); 3214 3215 return ULE; 3216 } 3217 3218 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3219 ValueDecl *var); 3220 3221 /// Complete semantic analysis for a reference to the given declaration. 3222 ExprResult Sema::BuildDeclarationNameExpr( 3223 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3224 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3225 bool AcceptInvalidDecl) { 3226 assert(D && "Cannot refer to a NULL declaration"); 3227 assert(!isa<FunctionTemplateDecl>(D) && 3228 "Cannot refer unambiguously to a function template"); 3229 3230 SourceLocation Loc = NameInfo.getLoc(); 3231 if (CheckDeclInExpr(*this, Loc, D)) { 3232 // Recovery from invalid cases (e.g. D is an invalid Decl). 3233 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up 3234 // diagnostics, as invalid decls use int as a fallback type. 3235 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {}); 3236 } 3237 3238 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3239 // Specifically diagnose references to class templates that are missing 3240 // a template argument list. 3241 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3242 return ExprError(); 3243 } 3244 3245 // Make sure that we're referring to a value. 3246 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3247 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3248 Diag(D->getLocation(), diag::note_declared_at); 3249 return ExprError(); 3250 } 3251 3252 // Check whether this declaration can be used. Note that we suppress 3253 // this check when we're going to perform argument-dependent lookup 3254 // on this function name, because this might not be the function 3255 // that overload resolution actually selects. 3256 if (DiagnoseUseOfDecl(D, Loc)) 3257 return ExprError(); 3258 3259 auto *VD = cast<ValueDecl>(D); 3260 3261 // Only create DeclRefExpr's for valid Decl's. 3262 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3263 return ExprError(); 3264 3265 // Handle members of anonymous structs and unions. If we got here, 3266 // and the reference is to a class member indirect field, then this 3267 // must be the subject of a pointer-to-member expression. 3268 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3269 if (!indirectField->isCXXClassMember()) 3270 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3271 indirectField); 3272 3273 QualType type = VD->getType(); 3274 if (type.isNull()) 3275 return ExprError(); 3276 ExprValueKind valueKind = VK_PRValue; 3277 3278 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3279 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3280 // is expanded by some outer '...' in the context of the use. 3281 type = type.getNonPackExpansionType(); 3282 3283 switch (D->getKind()) { 3284 // Ignore all the non-ValueDecl kinds. 3285 #define ABSTRACT_DECL(kind) 3286 #define VALUE(type, base) 3287 #define DECL(type, base) case Decl::type: 3288 #include "clang/AST/DeclNodes.inc" 3289 llvm_unreachable("invalid value decl kind"); 3290 3291 // These shouldn't make it here. 3292 case Decl::ObjCAtDefsField: 3293 llvm_unreachable("forming non-member reference to ivar?"); 3294 3295 // Enum constants are always r-values and never references. 3296 // Unresolved using declarations are dependent. 3297 case Decl::EnumConstant: 3298 case Decl::UnresolvedUsingValue: 3299 case Decl::OMPDeclareReduction: 3300 case Decl::OMPDeclareMapper: 3301 valueKind = VK_PRValue; 3302 break; 3303 3304 // Fields and indirect fields that got here must be for 3305 // pointer-to-member expressions; we just call them l-values for 3306 // internal consistency, because this subexpression doesn't really 3307 // exist in the high-level semantics. 3308 case Decl::Field: 3309 case Decl::IndirectField: 3310 case Decl::ObjCIvar: 3311 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3312 3313 // These can't have reference type in well-formed programs, but 3314 // for internal consistency we do this anyway. 3315 type = type.getNonReferenceType(); 3316 valueKind = VK_LValue; 3317 break; 3318 3319 // Non-type template parameters are either l-values or r-values 3320 // depending on the type. 3321 case Decl::NonTypeTemplateParm: { 3322 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3323 type = reftype->getPointeeType(); 3324 valueKind = VK_LValue; // even if the parameter is an r-value reference 3325 break; 3326 } 3327 3328 // [expr.prim.id.unqual]p2: 3329 // If the entity is a template parameter object for a template 3330 // parameter of type T, the type of the expression is const T. 3331 // [...] The expression is an lvalue if the entity is a [...] template 3332 // parameter object. 3333 if (type->isRecordType()) { 3334 type = type.getUnqualifiedType().withConst(); 3335 valueKind = VK_LValue; 3336 break; 3337 } 3338 3339 // For non-references, we need to strip qualifiers just in case 3340 // the template parameter was declared as 'const int' or whatever. 3341 valueKind = VK_PRValue; 3342 type = type.getUnqualifiedType(); 3343 break; 3344 } 3345 3346 case Decl::Var: 3347 case Decl::VarTemplateSpecialization: 3348 case Decl::VarTemplatePartialSpecialization: 3349 case Decl::Decomposition: 3350 case Decl::OMPCapturedExpr: 3351 // In C, "extern void blah;" is valid and is an r-value. 3352 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3353 type->isVoidType()) { 3354 valueKind = VK_PRValue; 3355 break; 3356 } 3357 LLVM_FALLTHROUGH; 3358 3359 case Decl::ImplicitParam: 3360 case Decl::ParmVar: { 3361 // These are always l-values. 3362 valueKind = VK_LValue; 3363 type = type.getNonReferenceType(); 3364 3365 // FIXME: Does the addition of const really only apply in 3366 // potentially-evaluated contexts? Since the variable isn't actually 3367 // captured in an unevaluated context, it seems that the answer is no. 3368 if (!isUnevaluatedContext()) { 3369 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3370 if (!CapturedType.isNull()) 3371 type = CapturedType; 3372 } 3373 3374 break; 3375 } 3376 3377 case Decl::Binding: { 3378 // These are always lvalues. 3379 valueKind = VK_LValue; 3380 type = type.getNonReferenceType(); 3381 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3382 // decides how that's supposed to work. 3383 auto *BD = cast<BindingDecl>(VD); 3384 if (BD->getDeclContext() != CurContext) { 3385 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3386 if (DD && DD->hasLocalStorage()) 3387 diagnoseUncapturableValueReference(*this, Loc, BD); 3388 } 3389 break; 3390 } 3391 3392 case Decl::Function: { 3393 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3394 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3395 type = Context.BuiltinFnTy; 3396 valueKind = VK_PRValue; 3397 break; 3398 } 3399 } 3400 3401 const FunctionType *fty = type->castAs<FunctionType>(); 3402 3403 // If we're referring to a function with an __unknown_anytype 3404 // result type, make the entire expression __unknown_anytype. 3405 if (fty->getReturnType() == Context.UnknownAnyTy) { 3406 type = Context.UnknownAnyTy; 3407 valueKind = VK_PRValue; 3408 break; 3409 } 3410 3411 // Functions are l-values in C++. 3412 if (getLangOpts().CPlusPlus) { 3413 valueKind = VK_LValue; 3414 break; 3415 } 3416 3417 // C99 DR 316 says that, if a function type comes from a 3418 // function definition (without a prototype), that type is only 3419 // used for checking compatibility. Therefore, when referencing 3420 // the function, we pretend that we don't have the full function 3421 // type. 3422 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3423 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3424 fty->getExtInfo()); 3425 3426 // Functions are r-values in C. 3427 valueKind = VK_PRValue; 3428 break; 3429 } 3430 3431 case Decl::CXXDeductionGuide: 3432 llvm_unreachable("building reference to deduction guide"); 3433 3434 case Decl::MSProperty: 3435 case Decl::MSGuid: 3436 case Decl::TemplateParamObject: 3437 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3438 // capture in OpenMP, or duplicated between host and device? 3439 valueKind = VK_LValue; 3440 break; 3441 3442 case Decl::UnnamedGlobalConstant: 3443 valueKind = VK_LValue; 3444 break; 3445 3446 case Decl::CXXMethod: 3447 // If we're referring to a method with an __unknown_anytype 3448 // result type, make the entire expression __unknown_anytype. 3449 // This should only be possible with a type written directly. 3450 if (const FunctionProtoType *proto = 3451 dyn_cast<FunctionProtoType>(VD->getType())) 3452 if (proto->getReturnType() == Context.UnknownAnyTy) { 3453 type = Context.UnknownAnyTy; 3454 valueKind = VK_PRValue; 3455 break; 3456 } 3457 3458 // C++ methods are l-values if static, r-values if non-static. 3459 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3460 valueKind = VK_LValue; 3461 break; 3462 } 3463 LLVM_FALLTHROUGH; 3464 3465 case Decl::CXXConversion: 3466 case Decl::CXXDestructor: 3467 case Decl::CXXConstructor: 3468 valueKind = VK_PRValue; 3469 break; 3470 } 3471 3472 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3473 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3474 TemplateArgs); 3475 } 3476 3477 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3478 SmallString<32> &Target) { 3479 Target.resize(CharByteWidth * (Source.size() + 1)); 3480 char *ResultPtr = &Target[0]; 3481 const llvm::UTF8 *ErrorPtr; 3482 bool success = 3483 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3484 (void)success; 3485 assert(success); 3486 Target.resize(ResultPtr - &Target[0]); 3487 } 3488 3489 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3490 PredefinedExpr::IdentKind IK) { 3491 // Pick the current block, lambda, captured statement or function. 3492 Decl *currentDecl = nullptr; 3493 if (const BlockScopeInfo *BSI = getCurBlock()) 3494 currentDecl = BSI->TheDecl; 3495 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3496 currentDecl = LSI->CallOperator; 3497 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3498 currentDecl = CSI->TheCapturedDecl; 3499 else 3500 currentDecl = getCurFunctionOrMethodDecl(); 3501 3502 if (!currentDecl) { 3503 Diag(Loc, diag::ext_predef_outside_function); 3504 currentDecl = Context.getTranslationUnitDecl(); 3505 } 3506 3507 QualType ResTy; 3508 StringLiteral *SL = nullptr; 3509 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3510 ResTy = Context.DependentTy; 3511 else { 3512 // Pre-defined identifiers are of type char[x], where x is the length of 3513 // the string. 3514 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3515 unsigned Length = Str.length(); 3516 3517 llvm::APInt LengthI(32, Length + 1); 3518 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3519 ResTy = 3520 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3521 SmallString<32> RawChars; 3522 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3523 Str, RawChars); 3524 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3525 ArrayType::Normal, 3526 /*IndexTypeQuals*/ 0); 3527 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3528 /*Pascal*/ false, ResTy, Loc); 3529 } else { 3530 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3531 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3532 ArrayType::Normal, 3533 /*IndexTypeQuals*/ 0); 3534 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3535 /*Pascal*/ false, ResTy, Loc); 3536 } 3537 } 3538 3539 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3540 } 3541 3542 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3543 SourceLocation LParen, 3544 SourceLocation RParen, 3545 TypeSourceInfo *TSI) { 3546 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3547 } 3548 3549 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3550 SourceLocation LParen, 3551 SourceLocation RParen, 3552 ParsedType ParsedTy) { 3553 TypeSourceInfo *TSI = nullptr; 3554 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3555 3556 if (Ty.isNull()) 3557 return ExprError(); 3558 if (!TSI) 3559 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3560 3561 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3562 } 3563 3564 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3565 PredefinedExpr::IdentKind IK; 3566 3567 switch (Kind) { 3568 default: llvm_unreachable("Unknown simple primary expr!"); 3569 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3570 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3571 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3572 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3573 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3574 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3575 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3576 } 3577 3578 return BuildPredefinedExpr(Loc, IK); 3579 } 3580 3581 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3582 SmallString<16> CharBuffer; 3583 bool Invalid = false; 3584 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3585 if (Invalid) 3586 return ExprError(); 3587 3588 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3589 PP, Tok.getKind()); 3590 if (Literal.hadError()) 3591 return ExprError(); 3592 3593 QualType Ty; 3594 if (Literal.isWide()) 3595 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3596 else if (Literal.isUTF8() && getLangOpts().Char8) 3597 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3598 else if (Literal.isUTF16()) 3599 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3600 else if (Literal.isUTF32()) 3601 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3602 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3603 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3604 else 3605 Ty = Context.CharTy; // 'x' -> char in C++ 3606 3607 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3608 if (Literal.isWide()) 3609 Kind = CharacterLiteral::Wide; 3610 else if (Literal.isUTF16()) 3611 Kind = CharacterLiteral::UTF16; 3612 else if (Literal.isUTF32()) 3613 Kind = CharacterLiteral::UTF32; 3614 else if (Literal.isUTF8()) 3615 Kind = CharacterLiteral::UTF8; 3616 3617 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3618 Tok.getLocation()); 3619 3620 if (Literal.getUDSuffix().empty()) 3621 return Lit; 3622 3623 // We're building a user-defined literal. 3624 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3625 SourceLocation UDSuffixLoc = 3626 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3627 3628 // Make sure we're allowed user-defined literals here. 3629 if (!UDLScope) 3630 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3631 3632 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3633 // operator "" X (ch) 3634 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3635 Lit, Tok.getLocation()); 3636 } 3637 3638 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3639 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3640 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3641 Context.IntTy, Loc); 3642 } 3643 3644 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3645 QualType Ty, SourceLocation Loc) { 3646 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3647 3648 using llvm::APFloat; 3649 APFloat Val(Format); 3650 3651 APFloat::opStatus result = Literal.GetFloatValue(Val); 3652 3653 // Overflow is always an error, but underflow is only an error if 3654 // we underflowed to zero (APFloat reports denormals as underflow). 3655 if ((result & APFloat::opOverflow) || 3656 ((result & APFloat::opUnderflow) && Val.isZero())) { 3657 unsigned diagnostic; 3658 SmallString<20> buffer; 3659 if (result & APFloat::opOverflow) { 3660 diagnostic = diag::warn_float_overflow; 3661 APFloat::getLargest(Format).toString(buffer); 3662 } else { 3663 diagnostic = diag::warn_float_underflow; 3664 APFloat::getSmallest(Format).toString(buffer); 3665 } 3666 3667 S.Diag(Loc, diagnostic) 3668 << Ty 3669 << StringRef(buffer.data(), buffer.size()); 3670 } 3671 3672 bool isExact = (result == APFloat::opOK); 3673 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3674 } 3675 3676 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3677 assert(E && "Invalid expression"); 3678 3679 if (E->isValueDependent()) 3680 return false; 3681 3682 QualType QT = E->getType(); 3683 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3684 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3685 return true; 3686 } 3687 3688 llvm::APSInt ValueAPS; 3689 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3690 3691 if (R.isInvalid()) 3692 return true; 3693 3694 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3695 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3696 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3697 << toString(ValueAPS, 10) << ValueIsPositive; 3698 return true; 3699 } 3700 3701 return false; 3702 } 3703 3704 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3705 // Fast path for a single digit (which is quite common). A single digit 3706 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3707 if (Tok.getLength() == 1) { 3708 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3709 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3710 } 3711 3712 SmallString<128> SpellingBuffer; 3713 // NumericLiteralParser wants to overread by one character. Add padding to 3714 // the buffer in case the token is copied to the buffer. If getSpelling() 3715 // returns a StringRef to the memory buffer, it should have a null char at 3716 // the EOF, so it is also safe. 3717 SpellingBuffer.resize(Tok.getLength() + 1); 3718 3719 // Get the spelling of the token, which eliminates trigraphs, etc. 3720 bool Invalid = false; 3721 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3722 if (Invalid) 3723 return ExprError(); 3724 3725 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3726 PP.getSourceManager(), PP.getLangOpts(), 3727 PP.getTargetInfo(), PP.getDiagnostics()); 3728 if (Literal.hadError) 3729 return ExprError(); 3730 3731 if (Literal.hasUDSuffix()) { 3732 // We're building a user-defined literal. 3733 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3734 SourceLocation UDSuffixLoc = 3735 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3736 3737 // Make sure we're allowed user-defined literals here. 3738 if (!UDLScope) 3739 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3740 3741 QualType CookedTy; 3742 if (Literal.isFloatingLiteral()) { 3743 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3744 // long double, the literal is treated as a call of the form 3745 // operator "" X (f L) 3746 CookedTy = Context.LongDoubleTy; 3747 } else { 3748 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3749 // unsigned long long, the literal is treated as a call of the form 3750 // operator "" X (n ULL) 3751 CookedTy = Context.UnsignedLongLongTy; 3752 } 3753 3754 DeclarationName OpName = 3755 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3756 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3757 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3758 3759 SourceLocation TokLoc = Tok.getLocation(); 3760 3761 // Perform literal operator lookup to determine if we're building a raw 3762 // literal or a cooked one. 3763 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3764 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3765 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3766 /*AllowStringTemplatePack*/ false, 3767 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3768 case LOLR_ErrorNoDiagnostic: 3769 // Lookup failure for imaginary constants isn't fatal, there's still the 3770 // GNU extension producing _Complex types. 3771 break; 3772 case LOLR_Error: 3773 return ExprError(); 3774 case LOLR_Cooked: { 3775 Expr *Lit; 3776 if (Literal.isFloatingLiteral()) { 3777 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3778 } else { 3779 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3780 if (Literal.GetIntegerValue(ResultVal)) 3781 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3782 << /* Unsigned */ 1; 3783 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3784 Tok.getLocation()); 3785 } 3786 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3787 } 3788 3789 case LOLR_Raw: { 3790 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3791 // literal is treated as a call of the form 3792 // operator "" X ("n") 3793 unsigned Length = Literal.getUDSuffixOffset(); 3794 QualType StrTy = Context.getConstantArrayType( 3795 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3796 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3797 Expr *Lit = StringLiteral::Create( 3798 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3799 /*Pascal*/false, StrTy, &TokLoc, 1); 3800 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3801 } 3802 3803 case LOLR_Template: { 3804 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3805 // template), L is treated as a call fo the form 3806 // operator "" X <'c1', 'c2', ... 'ck'>() 3807 // where n is the source character sequence c1 c2 ... ck. 3808 TemplateArgumentListInfo ExplicitArgs; 3809 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3810 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3811 llvm::APSInt Value(CharBits, CharIsUnsigned); 3812 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3813 Value = TokSpelling[I]; 3814 TemplateArgument Arg(Context, Value, Context.CharTy); 3815 TemplateArgumentLocInfo ArgInfo; 3816 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3817 } 3818 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3819 &ExplicitArgs); 3820 } 3821 case LOLR_StringTemplatePack: 3822 llvm_unreachable("unexpected literal operator lookup result"); 3823 } 3824 } 3825 3826 Expr *Res; 3827 3828 if (Literal.isFixedPointLiteral()) { 3829 QualType Ty; 3830 3831 if (Literal.isAccum) { 3832 if (Literal.isHalf) { 3833 Ty = Context.ShortAccumTy; 3834 } else if (Literal.isLong) { 3835 Ty = Context.LongAccumTy; 3836 } else { 3837 Ty = Context.AccumTy; 3838 } 3839 } else if (Literal.isFract) { 3840 if (Literal.isHalf) { 3841 Ty = Context.ShortFractTy; 3842 } else if (Literal.isLong) { 3843 Ty = Context.LongFractTy; 3844 } else { 3845 Ty = Context.FractTy; 3846 } 3847 } 3848 3849 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3850 3851 bool isSigned = !Literal.isUnsigned; 3852 unsigned scale = Context.getFixedPointScale(Ty); 3853 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3854 3855 llvm::APInt Val(bit_width, 0, isSigned); 3856 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3857 bool ValIsZero = Val.isZero() && !Overflowed; 3858 3859 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3860 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3861 // Clause 6.4.4 - The value of a constant shall be in the range of 3862 // representable values for its type, with exception for constants of a 3863 // fract type with a value of exactly 1; such a constant shall denote 3864 // the maximal value for the type. 3865 --Val; 3866 else if (Val.ugt(MaxVal) || Overflowed) 3867 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3868 3869 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3870 Tok.getLocation(), scale); 3871 } else if (Literal.isFloatingLiteral()) { 3872 QualType Ty; 3873 if (Literal.isHalf){ 3874 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3875 Ty = Context.HalfTy; 3876 else { 3877 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3878 return ExprError(); 3879 } 3880 } else if (Literal.isFloat) 3881 Ty = Context.FloatTy; 3882 else if (Literal.isLong) 3883 Ty = Context.LongDoubleTy; 3884 else if (Literal.isFloat16) 3885 Ty = Context.Float16Ty; 3886 else if (Literal.isFloat128) 3887 Ty = Context.Float128Ty; 3888 else 3889 Ty = Context.DoubleTy; 3890 3891 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3892 3893 if (Ty == Context.DoubleTy) { 3894 if (getLangOpts().SinglePrecisionConstants) { 3895 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3896 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3897 } 3898 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3899 "cl_khr_fp64", getLangOpts())) { 3900 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3901 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3902 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3903 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3904 } 3905 } 3906 } else if (!Literal.isIntegerLiteral()) { 3907 return ExprError(); 3908 } else { 3909 QualType Ty; 3910 3911 // 'long long' is a C99 or C++11 feature. 3912 if (!getLangOpts().C99 && Literal.isLongLong) { 3913 if (getLangOpts().CPlusPlus) 3914 Diag(Tok.getLocation(), 3915 getLangOpts().CPlusPlus11 ? 3916 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3917 else 3918 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3919 } 3920 3921 // 'z/uz' literals are a C++2b feature. 3922 if (Literal.isSizeT) 3923 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3924 ? getLangOpts().CPlusPlus2b 3925 ? diag::warn_cxx20_compat_size_t_suffix 3926 : diag::ext_cxx2b_size_t_suffix 3927 : diag::err_cxx2b_size_t_suffix); 3928 3929 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++, 3930 // but we do not currently support the suffix in C++ mode because it's not 3931 // entirely clear whether WG21 will prefer this suffix to return a library 3932 // type such as std::bit_int instead of returning a _BitInt. 3933 if (Literal.isBitInt && !getLangOpts().CPlusPlus) 3934 PP.Diag(Tok.getLocation(), getLangOpts().C2x 3935 ? diag::warn_c2x_compat_bitint_suffix 3936 : diag::ext_c2x_bitint_suffix); 3937 3938 // Get the value in the widest-possible width. What is "widest" depends on 3939 // whether the literal is a bit-precise integer or not. For a bit-precise 3940 // integer type, try to scan the source to determine how many bits are 3941 // needed to represent the value. This may seem a bit expensive, but trying 3942 // to get the integer value from an overly-wide APInt is *extremely* 3943 // expensive, so the naive approach of assuming 3944 // llvm::IntegerType::MAX_INT_BITS is a big performance hit. 3945 unsigned BitsNeeded = 3946 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded( 3947 Literal.getLiteralDigits(), Literal.getRadix()) 3948 : Context.getTargetInfo().getIntMaxTWidth(); 3949 llvm::APInt ResultVal(BitsNeeded, 0); 3950 3951 if (Literal.GetIntegerValue(ResultVal)) { 3952 // If this value didn't fit into uintmax_t, error and force to ull. 3953 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3954 << /* Unsigned */ 1; 3955 Ty = Context.UnsignedLongLongTy; 3956 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3957 "long long is not intmax_t?"); 3958 } else { 3959 // If this value fits into a ULL, try to figure out what else it fits into 3960 // according to the rules of C99 6.4.4.1p5. 3961 3962 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3963 // be an unsigned int. 3964 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3965 3966 // Check from smallest to largest, picking the smallest type we can. 3967 unsigned Width = 0; 3968 3969 // Microsoft specific integer suffixes are explicitly sized. 3970 if (Literal.MicrosoftInteger) { 3971 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3972 Width = 8; 3973 Ty = Context.CharTy; 3974 } else { 3975 Width = Literal.MicrosoftInteger; 3976 Ty = Context.getIntTypeForBitwidth(Width, 3977 /*Signed=*/!Literal.isUnsigned); 3978 } 3979 } 3980 3981 // Bit-precise integer literals are automagically-sized based on the 3982 // width required by the literal. 3983 if (Literal.isBitInt) { 3984 // The signed version has one more bit for the sign value. There are no 3985 // zero-width bit-precise integers, even if the literal value is 0. 3986 Width = std::max(ResultVal.getActiveBits(), 1u) + 3987 (Literal.isUnsigned ? 0u : 1u); 3988 3989 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, 3990 // and reset the type to the largest supported width. 3991 unsigned int MaxBitIntWidth = 3992 Context.getTargetInfo().getMaxBitIntWidth(); 3993 if (Width > MaxBitIntWidth) { 3994 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3995 << Literal.isUnsigned; 3996 Width = MaxBitIntWidth; 3997 } 3998 3999 // Reset the result value to the smaller APInt and select the correct 4000 // type to be used. Note, we zext even for signed values because the 4001 // literal itself is always an unsigned value (a preceeding - is a 4002 // unary operator, not part of the literal). 4003 ResultVal = ResultVal.zextOrTrunc(Width); 4004 Ty = Context.getBitIntType(Literal.isUnsigned, Width); 4005 } 4006 4007 // Check C++2b size_t literals. 4008 if (Literal.isSizeT) { 4009 assert(!Literal.MicrosoftInteger && 4010 "size_t literals can't be Microsoft literals"); 4011 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 4012 Context.getTargetInfo().getSizeType()); 4013 4014 // Does it fit in size_t? 4015 if (ResultVal.isIntN(SizeTSize)) { 4016 // Does it fit in ssize_t? 4017 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 4018 Ty = Context.getSignedSizeType(); 4019 else if (AllowUnsigned) 4020 Ty = Context.getSizeType(); 4021 Width = SizeTSize; 4022 } 4023 } 4024 4025 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 4026 !Literal.isSizeT) { 4027 // Are int/unsigned possibilities? 4028 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 4029 4030 // Does it fit in a unsigned int? 4031 if (ResultVal.isIntN(IntSize)) { 4032 // Does it fit in a signed int? 4033 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 4034 Ty = Context.IntTy; 4035 else if (AllowUnsigned) 4036 Ty = Context.UnsignedIntTy; 4037 Width = IntSize; 4038 } 4039 } 4040 4041 // Are long/unsigned long possibilities? 4042 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 4043 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 4044 4045 // Does it fit in a unsigned long? 4046 if (ResultVal.isIntN(LongSize)) { 4047 // Does it fit in a signed long? 4048 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 4049 Ty = Context.LongTy; 4050 else if (AllowUnsigned) 4051 Ty = Context.UnsignedLongTy; 4052 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 4053 // is compatible. 4054 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 4055 const unsigned LongLongSize = 4056 Context.getTargetInfo().getLongLongWidth(); 4057 Diag(Tok.getLocation(), 4058 getLangOpts().CPlusPlus 4059 ? Literal.isLong 4060 ? diag::warn_old_implicitly_unsigned_long_cxx 4061 : /*C++98 UB*/ diag:: 4062 ext_old_implicitly_unsigned_long_cxx 4063 : diag::warn_old_implicitly_unsigned_long) 4064 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4065 : /*will be ill-formed*/ 1); 4066 Ty = Context.UnsignedLongTy; 4067 } 4068 Width = LongSize; 4069 } 4070 } 4071 4072 // Check long long if needed. 4073 if (Ty.isNull() && !Literal.isSizeT) { 4074 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4075 4076 // Does it fit in a unsigned long long? 4077 if (ResultVal.isIntN(LongLongSize)) { 4078 // Does it fit in a signed long long? 4079 // To be compatible with MSVC, hex integer literals ending with the 4080 // LL or i64 suffix are always signed in Microsoft mode. 4081 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4082 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4083 Ty = Context.LongLongTy; 4084 else if (AllowUnsigned) 4085 Ty = Context.UnsignedLongLongTy; 4086 Width = LongLongSize; 4087 } 4088 } 4089 4090 // If we still couldn't decide a type, we either have 'size_t' literal 4091 // that is out of range, or a decimal literal that does not fit in a 4092 // signed long long and has no U suffix. 4093 if (Ty.isNull()) { 4094 if (Literal.isSizeT) 4095 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4096 << Literal.isUnsigned; 4097 else 4098 Diag(Tok.getLocation(), 4099 diag::ext_integer_literal_too_large_for_signed); 4100 Ty = Context.UnsignedLongLongTy; 4101 Width = Context.getTargetInfo().getLongLongWidth(); 4102 } 4103 4104 if (ResultVal.getBitWidth() != Width) 4105 ResultVal = ResultVal.trunc(Width); 4106 } 4107 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4108 } 4109 4110 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4111 if (Literal.isImaginary) { 4112 Res = new (Context) ImaginaryLiteral(Res, 4113 Context.getComplexType(Res->getType())); 4114 4115 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4116 } 4117 return Res; 4118 } 4119 4120 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4121 assert(E && "ActOnParenExpr() missing expr"); 4122 QualType ExprTy = E->getType(); 4123 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4124 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4125 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4126 return new (Context) ParenExpr(L, R, E); 4127 } 4128 4129 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4130 SourceLocation Loc, 4131 SourceRange ArgRange) { 4132 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4133 // scalar or vector data type argument..." 4134 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4135 // type (C99 6.2.5p18) or void. 4136 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4137 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4138 << T << ArgRange; 4139 return true; 4140 } 4141 4142 assert((T->isVoidType() || !T->isIncompleteType()) && 4143 "Scalar types should always be complete"); 4144 return false; 4145 } 4146 4147 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4148 SourceLocation Loc, 4149 SourceRange ArgRange, 4150 UnaryExprOrTypeTrait TraitKind) { 4151 // Invalid types must be hard errors for SFINAE in C++. 4152 if (S.LangOpts.CPlusPlus) 4153 return true; 4154 4155 // C99 6.5.3.4p1: 4156 if (T->isFunctionType() && 4157 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4158 TraitKind == UETT_PreferredAlignOf)) { 4159 // sizeof(function)/alignof(function) is allowed as an extension. 4160 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4161 << getTraitSpelling(TraitKind) << ArgRange; 4162 return false; 4163 } 4164 4165 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4166 // this is an error (OpenCL v1.1 s6.3.k) 4167 if (T->isVoidType()) { 4168 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4169 : diag::ext_sizeof_alignof_void_type; 4170 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4171 return false; 4172 } 4173 4174 return true; 4175 } 4176 4177 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4178 SourceLocation Loc, 4179 SourceRange ArgRange, 4180 UnaryExprOrTypeTrait TraitKind) { 4181 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4182 // runtime doesn't allow it. 4183 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4184 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4185 << T << (TraitKind == UETT_SizeOf) 4186 << ArgRange; 4187 return true; 4188 } 4189 4190 return false; 4191 } 4192 4193 /// Check whether E is a pointer from a decayed array type (the decayed 4194 /// pointer type is equal to T) and emit a warning if it is. 4195 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4196 Expr *E) { 4197 // Don't warn if the operation changed the type. 4198 if (T != E->getType()) 4199 return; 4200 4201 // Now look for array decays. 4202 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4203 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4204 return; 4205 4206 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4207 << ICE->getType() 4208 << ICE->getSubExpr()->getType(); 4209 } 4210 4211 /// Check the constraints on expression operands to unary type expression 4212 /// and type traits. 4213 /// 4214 /// Completes any types necessary and validates the constraints on the operand 4215 /// expression. The logic mostly mirrors the type-based overload, but may modify 4216 /// the expression as it completes the type for that expression through template 4217 /// instantiation, etc. 4218 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4219 UnaryExprOrTypeTrait ExprKind) { 4220 QualType ExprTy = E->getType(); 4221 assert(!ExprTy->isReferenceType()); 4222 4223 bool IsUnevaluatedOperand = 4224 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4225 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4226 if (IsUnevaluatedOperand) { 4227 ExprResult Result = CheckUnevaluatedOperand(E); 4228 if (Result.isInvalid()) 4229 return true; 4230 E = Result.get(); 4231 } 4232 4233 // The operand for sizeof and alignof is in an unevaluated expression context, 4234 // so side effects could result in unintended consequences. 4235 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4236 // used to build SFINAE gadgets. 4237 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4238 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4239 !E->isInstantiationDependent() && 4240 E->HasSideEffects(Context, false)) 4241 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4242 4243 if (ExprKind == UETT_VecStep) 4244 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4245 E->getSourceRange()); 4246 4247 // Explicitly list some types as extensions. 4248 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4249 E->getSourceRange(), ExprKind)) 4250 return false; 4251 4252 // 'alignof' applied to an expression only requires the base element type of 4253 // the expression to be complete. 'sizeof' requires the expression's type to 4254 // be complete (and will attempt to complete it if it's an array of unknown 4255 // bound). 4256 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4257 if (RequireCompleteSizedType( 4258 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4259 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4260 getTraitSpelling(ExprKind), E->getSourceRange())) 4261 return true; 4262 } else { 4263 if (RequireCompleteSizedExprType( 4264 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4265 getTraitSpelling(ExprKind), E->getSourceRange())) 4266 return true; 4267 } 4268 4269 // Completing the expression's type may have changed it. 4270 ExprTy = E->getType(); 4271 assert(!ExprTy->isReferenceType()); 4272 4273 if (ExprTy->isFunctionType()) { 4274 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4275 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4276 return true; 4277 } 4278 4279 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4280 E->getSourceRange(), ExprKind)) 4281 return true; 4282 4283 if (ExprKind == UETT_SizeOf) { 4284 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4285 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4286 QualType OType = PVD->getOriginalType(); 4287 QualType Type = PVD->getType(); 4288 if (Type->isPointerType() && OType->isArrayType()) { 4289 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4290 << Type << OType; 4291 Diag(PVD->getLocation(), diag::note_declared_at); 4292 } 4293 } 4294 } 4295 4296 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4297 // decays into a pointer and returns an unintended result. This is most 4298 // likely a typo for "sizeof(array) op x". 4299 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4300 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4301 BO->getLHS()); 4302 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4303 BO->getRHS()); 4304 } 4305 } 4306 4307 return false; 4308 } 4309 4310 /// Check the constraints on operands to unary expression and type 4311 /// traits. 4312 /// 4313 /// This will complete any types necessary, and validate the various constraints 4314 /// on those operands. 4315 /// 4316 /// The UsualUnaryConversions() function is *not* called by this routine. 4317 /// C99 6.3.2.1p[2-4] all state: 4318 /// Except when it is the operand of the sizeof operator ... 4319 /// 4320 /// C++ [expr.sizeof]p4 4321 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4322 /// standard conversions are not applied to the operand of sizeof. 4323 /// 4324 /// This policy is followed for all of the unary trait expressions. 4325 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4326 SourceLocation OpLoc, 4327 SourceRange ExprRange, 4328 UnaryExprOrTypeTrait ExprKind) { 4329 if (ExprType->isDependentType()) 4330 return false; 4331 4332 // C++ [expr.sizeof]p2: 4333 // When applied to a reference or a reference type, the result 4334 // is the size of the referenced type. 4335 // C++11 [expr.alignof]p3: 4336 // When alignof is applied to a reference type, the result 4337 // shall be the alignment of the referenced type. 4338 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4339 ExprType = Ref->getPointeeType(); 4340 4341 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4342 // When alignof or _Alignof is applied to an array type, the result 4343 // is the alignment of the element type. 4344 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4345 ExprKind == UETT_OpenMPRequiredSimdAlign) 4346 ExprType = Context.getBaseElementType(ExprType); 4347 4348 if (ExprKind == UETT_VecStep) 4349 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4350 4351 // Explicitly list some types as extensions. 4352 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4353 ExprKind)) 4354 return false; 4355 4356 if (RequireCompleteSizedType( 4357 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4358 getTraitSpelling(ExprKind), ExprRange)) 4359 return true; 4360 4361 if (ExprType->isFunctionType()) { 4362 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4363 << getTraitSpelling(ExprKind) << ExprRange; 4364 return true; 4365 } 4366 4367 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4368 ExprKind)) 4369 return true; 4370 4371 return false; 4372 } 4373 4374 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4375 // Cannot know anything else if the expression is dependent. 4376 if (E->isTypeDependent()) 4377 return false; 4378 4379 if (E->getObjectKind() == OK_BitField) { 4380 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4381 << 1 << E->getSourceRange(); 4382 return true; 4383 } 4384 4385 ValueDecl *D = nullptr; 4386 Expr *Inner = E->IgnoreParens(); 4387 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4388 D = DRE->getDecl(); 4389 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4390 D = ME->getMemberDecl(); 4391 } 4392 4393 // If it's a field, require the containing struct to have a 4394 // complete definition so that we can compute the layout. 4395 // 4396 // This can happen in C++11 onwards, either by naming the member 4397 // in a way that is not transformed into a member access expression 4398 // (in an unevaluated operand, for instance), or by naming the member 4399 // in a trailing-return-type. 4400 // 4401 // For the record, since __alignof__ on expressions is a GCC 4402 // extension, GCC seems to permit this but always gives the 4403 // nonsensical answer 0. 4404 // 4405 // We don't really need the layout here --- we could instead just 4406 // directly check for all the appropriate alignment-lowing 4407 // attributes --- but that would require duplicating a lot of 4408 // logic that just isn't worth duplicating for such a marginal 4409 // use-case. 4410 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4411 // Fast path this check, since we at least know the record has a 4412 // definition if we can find a member of it. 4413 if (!FD->getParent()->isCompleteDefinition()) { 4414 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4415 << E->getSourceRange(); 4416 return true; 4417 } 4418 4419 // Otherwise, if it's a field, and the field doesn't have 4420 // reference type, then it must have a complete type (or be a 4421 // flexible array member, which we explicitly want to 4422 // white-list anyway), which makes the following checks trivial. 4423 if (!FD->getType()->isReferenceType()) 4424 return false; 4425 } 4426 4427 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4428 } 4429 4430 bool Sema::CheckVecStepExpr(Expr *E) { 4431 E = E->IgnoreParens(); 4432 4433 // Cannot know anything else if the expression is dependent. 4434 if (E->isTypeDependent()) 4435 return false; 4436 4437 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4438 } 4439 4440 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4441 CapturingScopeInfo *CSI) { 4442 assert(T->isVariablyModifiedType()); 4443 assert(CSI != nullptr); 4444 4445 // We're going to walk down into the type and look for VLA expressions. 4446 do { 4447 const Type *Ty = T.getTypePtr(); 4448 switch (Ty->getTypeClass()) { 4449 #define TYPE(Class, Base) 4450 #define ABSTRACT_TYPE(Class, Base) 4451 #define NON_CANONICAL_TYPE(Class, Base) 4452 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4453 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4454 #include "clang/AST/TypeNodes.inc" 4455 T = QualType(); 4456 break; 4457 // These types are never variably-modified. 4458 case Type::Builtin: 4459 case Type::Complex: 4460 case Type::Vector: 4461 case Type::ExtVector: 4462 case Type::ConstantMatrix: 4463 case Type::Record: 4464 case Type::Enum: 4465 case Type::Elaborated: 4466 case Type::TemplateSpecialization: 4467 case Type::ObjCObject: 4468 case Type::ObjCInterface: 4469 case Type::ObjCObjectPointer: 4470 case Type::ObjCTypeParam: 4471 case Type::Pipe: 4472 case Type::BitInt: 4473 llvm_unreachable("type class is never variably-modified!"); 4474 case Type::Adjusted: 4475 T = cast<AdjustedType>(Ty)->getOriginalType(); 4476 break; 4477 case Type::Decayed: 4478 T = cast<DecayedType>(Ty)->getPointeeType(); 4479 break; 4480 case Type::Pointer: 4481 T = cast<PointerType>(Ty)->getPointeeType(); 4482 break; 4483 case Type::BlockPointer: 4484 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4485 break; 4486 case Type::LValueReference: 4487 case Type::RValueReference: 4488 T = cast<ReferenceType>(Ty)->getPointeeType(); 4489 break; 4490 case Type::MemberPointer: 4491 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4492 break; 4493 case Type::ConstantArray: 4494 case Type::IncompleteArray: 4495 // Losing element qualification here is fine. 4496 T = cast<ArrayType>(Ty)->getElementType(); 4497 break; 4498 case Type::VariableArray: { 4499 // Losing element qualification here is fine. 4500 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4501 4502 // Unknown size indication requires no size computation. 4503 // Otherwise, evaluate and record it. 4504 auto Size = VAT->getSizeExpr(); 4505 if (Size && !CSI->isVLATypeCaptured(VAT) && 4506 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4507 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4508 4509 T = VAT->getElementType(); 4510 break; 4511 } 4512 case Type::FunctionProto: 4513 case Type::FunctionNoProto: 4514 T = cast<FunctionType>(Ty)->getReturnType(); 4515 break; 4516 case Type::Paren: 4517 case Type::TypeOf: 4518 case Type::UnaryTransform: 4519 case Type::Attributed: 4520 case Type::BTFTagAttributed: 4521 case Type::SubstTemplateTypeParm: 4522 case Type::MacroQualified: 4523 // Keep walking after single level desugaring. 4524 T = T.getSingleStepDesugaredType(Context); 4525 break; 4526 case Type::Typedef: 4527 T = cast<TypedefType>(Ty)->desugar(); 4528 break; 4529 case Type::Decltype: 4530 T = cast<DecltypeType>(Ty)->desugar(); 4531 break; 4532 case Type::Using: 4533 T = cast<UsingType>(Ty)->desugar(); 4534 break; 4535 case Type::Auto: 4536 case Type::DeducedTemplateSpecialization: 4537 T = cast<DeducedType>(Ty)->getDeducedType(); 4538 break; 4539 case Type::TypeOfExpr: 4540 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4541 break; 4542 case Type::Atomic: 4543 T = cast<AtomicType>(Ty)->getValueType(); 4544 break; 4545 } 4546 } while (!T.isNull() && T->isVariablyModifiedType()); 4547 } 4548 4549 /// Build a sizeof or alignof expression given a type operand. 4550 ExprResult 4551 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4552 SourceLocation OpLoc, 4553 UnaryExprOrTypeTrait ExprKind, 4554 SourceRange R) { 4555 if (!TInfo) 4556 return ExprError(); 4557 4558 QualType T = TInfo->getType(); 4559 4560 if (!T->isDependentType() && 4561 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4562 return ExprError(); 4563 4564 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4565 if (auto *TT = T->getAs<TypedefType>()) { 4566 for (auto I = FunctionScopes.rbegin(), 4567 E = std::prev(FunctionScopes.rend()); 4568 I != E; ++I) { 4569 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4570 if (CSI == nullptr) 4571 break; 4572 DeclContext *DC = nullptr; 4573 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4574 DC = LSI->CallOperator; 4575 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4576 DC = CRSI->TheCapturedDecl; 4577 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4578 DC = BSI->TheDecl; 4579 if (DC) { 4580 if (DC->containsDecl(TT->getDecl())) 4581 break; 4582 captureVariablyModifiedType(Context, T, CSI); 4583 } 4584 } 4585 } 4586 } 4587 4588 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4589 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && 4590 TInfo->getType()->isVariablyModifiedType()) 4591 TInfo = TransformToPotentiallyEvaluated(TInfo); 4592 4593 return new (Context) UnaryExprOrTypeTraitExpr( 4594 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4595 } 4596 4597 /// Build a sizeof or alignof expression given an expression 4598 /// operand. 4599 ExprResult 4600 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4601 UnaryExprOrTypeTrait ExprKind) { 4602 ExprResult PE = CheckPlaceholderExpr(E); 4603 if (PE.isInvalid()) 4604 return ExprError(); 4605 4606 E = PE.get(); 4607 4608 // Verify that the operand is valid. 4609 bool isInvalid = false; 4610 if (E->isTypeDependent()) { 4611 // Delay type-checking for type-dependent expressions. 4612 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4613 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4614 } else if (ExprKind == UETT_VecStep) { 4615 isInvalid = CheckVecStepExpr(E); 4616 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4617 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4618 isInvalid = true; 4619 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4620 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4621 isInvalid = true; 4622 } else { 4623 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4624 } 4625 4626 if (isInvalid) 4627 return ExprError(); 4628 4629 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4630 PE = TransformToPotentiallyEvaluated(E); 4631 if (PE.isInvalid()) return ExprError(); 4632 E = PE.get(); 4633 } 4634 4635 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4636 return new (Context) UnaryExprOrTypeTraitExpr( 4637 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4638 } 4639 4640 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4641 /// expr and the same for @c alignof and @c __alignof 4642 /// Note that the ArgRange is invalid if isType is false. 4643 ExprResult 4644 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4645 UnaryExprOrTypeTrait ExprKind, bool IsType, 4646 void *TyOrEx, SourceRange ArgRange) { 4647 // If error parsing type, ignore. 4648 if (!TyOrEx) return ExprError(); 4649 4650 if (IsType) { 4651 TypeSourceInfo *TInfo; 4652 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4653 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4654 } 4655 4656 Expr *ArgEx = (Expr *)TyOrEx; 4657 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4658 return Result; 4659 } 4660 4661 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4662 bool IsReal) { 4663 if (V.get()->isTypeDependent()) 4664 return S.Context.DependentTy; 4665 4666 // _Real and _Imag are only l-values for normal l-values. 4667 if (V.get()->getObjectKind() != OK_Ordinary) { 4668 V = S.DefaultLvalueConversion(V.get()); 4669 if (V.isInvalid()) 4670 return QualType(); 4671 } 4672 4673 // These operators return the element type of a complex type. 4674 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4675 return CT->getElementType(); 4676 4677 // Otherwise they pass through real integer and floating point types here. 4678 if (V.get()->getType()->isArithmeticType()) 4679 return V.get()->getType(); 4680 4681 // Test for placeholders. 4682 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4683 if (PR.isInvalid()) return QualType(); 4684 if (PR.get() != V.get()) { 4685 V = PR; 4686 return CheckRealImagOperand(S, V, Loc, IsReal); 4687 } 4688 4689 // Reject anything else. 4690 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4691 << (IsReal ? "__real" : "__imag"); 4692 return QualType(); 4693 } 4694 4695 4696 4697 ExprResult 4698 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4699 tok::TokenKind Kind, Expr *Input) { 4700 UnaryOperatorKind Opc; 4701 switch (Kind) { 4702 default: llvm_unreachable("Unknown unary op!"); 4703 case tok::plusplus: Opc = UO_PostInc; break; 4704 case tok::minusminus: Opc = UO_PostDec; break; 4705 } 4706 4707 // Since this might is a postfix expression, get rid of ParenListExprs. 4708 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4709 if (Result.isInvalid()) return ExprError(); 4710 Input = Result.get(); 4711 4712 return BuildUnaryOp(S, OpLoc, Opc, Input); 4713 } 4714 4715 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4716 /// 4717 /// \return true on error 4718 static bool checkArithmeticOnObjCPointer(Sema &S, 4719 SourceLocation opLoc, 4720 Expr *op) { 4721 assert(op->getType()->isObjCObjectPointerType()); 4722 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4723 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4724 return false; 4725 4726 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4727 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4728 << op->getSourceRange(); 4729 return true; 4730 } 4731 4732 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4733 auto *BaseNoParens = Base->IgnoreParens(); 4734 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4735 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4736 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4737 } 4738 4739 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. 4740 // Typically this is DependentTy, but can sometimes be more precise. 4741 // 4742 // There are cases when we could determine a non-dependent type: 4743 // - LHS and RHS may have non-dependent types despite being type-dependent 4744 // (e.g. unbounded array static members of the current instantiation) 4745 // - one may be a dependent-sized array with known element type 4746 // - one may be a dependent-typed valid index (enum in current instantiation) 4747 // 4748 // We *always* return a dependent type, in such cases it is DependentTy. 4749 // This avoids creating type-dependent expressions with non-dependent types. 4750 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 4751 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, 4752 const ASTContext &Ctx) { 4753 assert(LHS->isTypeDependent() || RHS->isTypeDependent()); 4754 QualType LTy = LHS->getType(), RTy = RHS->getType(); 4755 QualType Result = Ctx.DependentTy; 4756 if (RTy->isIntegralOrUnscopedEnumerationType()) { 4757 if (const PointerType *PT = LTy->getAs<PointerType>()) 4758 Result = PT->getPointeeType(); 4759 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) 4760 Result = AT->getElementType(); 4761 } else if (LTy->isIntegralOrUnscopedEnumerationType()) { 4762 if (const PointerType *PT = RTy->getAs<PointerType>()) 4763 Result = PT->getPointeeType(); 4764 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) 4765 Result = AT->getElementType(); 4766 } 4767 // Ensure we return a dependent type. 4768 return Result->isDependentType() ? Result : Ctx.DependentTy; 4769 } 4770 4771 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args); 4772 4773 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, 4774 SourceLocation lbLoc, 4775 MultiExprArg ArgExprs, 4776 SourceLocation rbLoc) { 4777 4778 if (base && !base->getType().isNull() && 4779 base->hasPlaceholderType(BuiltinType::OMPArraySection)) 4780 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(), 4781 SourceLocation(), /*Length*/ nullptr, 4782 /*Stride=*/nullptr, rbLoc); 4783 4784 // Since this might be a postfix expression, get rid of ParenListExprs. 4785 if (isa<ParenListExpr>(base)) { 4786 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4787 if (result.isInvalid()) 4788 return ExprError(); 4789 base = result.get(); 4790 } 4791 4792 // Check if base and idx form a MatrixSubscriptExpr. 4793 // 4794 // Helper to check for comma expressions, which are not allowed as indices for 4795 // matrix subscript expressions. 4796 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4797 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4798 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4799 << SourceRange(base->getBeginLoc(), rbLoc); 4800 return true; 4801 } 4802 return false; 4803 }; 4804 // The matrix subscript operator ([][])is considered a single operator. 4805 // Separating the index expressions by parenthesis is not allowed. 4806 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) && 4807 !isa<MatrixSubscriptExpr>(base)) { 4808 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4809 << SourceRange(base->getBeginLoc(), rbLoc); 4810 return ExprError(); 4811 } 4812 // If the base is a MatrixSubscriptExpr, try to create a new 4813 // MatrixSubscriptExpr. 4814 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4815 if (matSubscriptE) { 4816 assert(ArgExprs.size() == 1); 4817 if (CheckAndReportCommaError(ArgExprs.front())) 4818 return ExprError(); 4819 4820 assert(matSubscriptE->isIncomplete() && 4821 "base has to be an incomplete matrix subscript"); 4822 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(), 4823 matSubscriptE->getRowIdx(), 4824 ArgExprs.front(), rbLoc); 4825 } 4826 4827 // Handle any non-overload placeholder types in the base and index 4828 // expressions. We can't handle overloads here because the other 4829 // operand might be an overloadable type, in which case the overload 4830 // resolution for the operator overload should get the first crack 4831 // at the overload. 4832 bool IsMSPropertySubscript = false; 4833 if (base->getType()->isNonOverloadPlaceholderType()) { 4834 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4835 if (!IsMSPropertySubscript) { 4836 ExprResult result = CheckPlaceholderExpr(base); 4837 if (result.isInvalid()) 4838 return ExprError(); 4839 base = result.get(); 4840 } 4841 } 4842 4843 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4844 if (base->getType()->isMatrixType()) { 4845 assert(ArgExprs.size() == 1); 4846 if (CheckAndReportCommaError(ArgExprs.front())) 4847 return ExprError(); 4848 4849 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr, 4850 rbLoc); 4851 } 4852 4853 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { 4854 Expr *idx = ArgExprs[0]; 4855 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4856 (isa<CXXOperatorCallExpr>(idx) && 4857 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) { 4858 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4859 << SourceRange(base->getBeginLoc(), rbLoc); 4860 } 4861 } 4862 4863 if (ArgExprs.size() == 1 && 4864 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { 4865 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]); 4866 if (result.isInvalid()) 4867 return ExprError(); 4868 ArgExprs[0] = result.get(); 4869 } else { 4870 if (checkArgsForPlaceholders(*this, ArgExprs)) 4871 return ExprError(); 4872 } 4873 4874 // Build an unanalyzed expression if either operand is type-dependent. 4875 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && 4876 (base->isTypeDependent() || 4877 Expr::hasAnyTypeDependentArguments(ArgExprs))) { 4878 return new (Context) ArraySubscriptExpr( 4879 base, ArgExprs.front(), 4880 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()), 4881 VK_LValue, OK_Ordinary, rbLoc); 4882 } 4883 4884 // MSDN, property (C++) 4885 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4886 // This attribute can also be used in the declaration of an empty array in a 4887 // class or structure definition. For example: 4888 // __declspec(property(get=GetX, put=PutX)) int x[]; 4889 // The above statement indicates that x[] can be used with one or more array 4890 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4891 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4892 if (IsMSPropertySubscript) { 4893 assert(ArgExprs.size() == 1); 4894 // Build MS property subscript expression if base is MS property reference 4895 // or MS property subscript. 4896 return new (Context) 4897 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, 4898 VK_LValue, OK_Ordinary, rbLoc); 4899 } 4900 4901 // Use C++ overloaded-operator rules if either operand has record 4902 // type. The spec says to do this if either type is *overloadable*, 4903 // but enum types can't declare subscript operators or conversion 4904 // operators, so there's nothing interesting for overload resolution 4905 // to do if there aren't any record types involved. 4906 // 4907 // ObjC pointers have their own subscripting logic that is not tied 4908 // to overload resolution and so should not take this path. 4909 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && 4910 ((base->getType()->isRecordType() || 4911 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) { 4912 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs); 4913 } 4914 4915 ExprResult Res = 4916 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc); 4917 4918 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4919 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4920 4921 return Res; 4922 } 4923 4924 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4925 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4926 InitializationKind Kind = 4927 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4928 InitializationSequence InitSeq(*this, Entity, Kind, E); 4929 return InitSeq.Perform(*this, Entity, Kind, E); 4930 } 4931 4932 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4933 Expr *ColumnIdx, 4934 SourceLocation RBLoc) { 4935 ExprResult BaseR = CheckPlaceholderExpr(Base); 4936 if (BaseR.isInvalid()) 4937 return BaseR; 4938 Base = BaseR.get(); 4939 4940 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4941 if (RowR.isInvalid()) 4942 return RowR; 4943 RowIdx = RowR.get(); 4944 4945 if (!ColumnIdx) 4946 return new (Context) MatrixSubscriptExpr( 4947 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4948 4949 // Build an unanalyzed expression if any of the operands is type-dependent. 4950 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4951 ColumnIdx->isTypeDependent()) 4952 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4953 Context.DependentTy, RBLoc); 4954 4955 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4956 if (ColumnR.isInvalid()) 4957 return ColumnR; 4958 ColumnIdx = ColumnR.get(); 4959 4960 // Check that IndexExpr is an integer expression. If it is a constant 4961 // expression, check that it is less than Dim (= the number of elements in the 4962 // corresponding dimension). 4963 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4964 bool IsColumnIdx) -> Expr * { 4965 if (!IndexExpr->getType()->isIntegerType() && 4966 !IndexExpr->isTypeDependent()) { 4967 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4968 << IsColumnIdx; 4969 return nullptr; 4970 } 4971 4972 if (Optional<llvm::APSInt> Idx = 4973 IndexExpr->getIntegerConstantExpr(Context)) { 4974 if ((*Idx < 0 || *Idx >= Dim)) { 4975 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4976 << IsColumnIdx << Dim; 4977 return nullptr; 4978 } 4979 } 4980 4981 ExprResult ConvExpr = 4982 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4983 assert(!ConvExpr.isInvalid() && 4984 "should be able to convert any integer type to size type"); 4985 return ConvExpr.get(); 4986 }; 4987 4988 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4989 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4990 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4991 if (!RowIdx || !ColumnIdx) 4992 return ExprError(); 4993 4994 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4995 MTy->getElementType(), RBLoc); 4996 } 4997 4998 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4999 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5000 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 5001 5002 // For expressions like `&(*s).b`, the base is recorded and what should be 5003 // checked. 5004 const MemberExpr *Member = nullptr; 5005 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 5006 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 5007 5008 LastRecord.PossibleDerefs.erase(StrippedExpr); 5009 } 5010 5011 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 5012 if (isUnevaluatedContext()) 5013 return; 5014 5015 QualType ResultTy = E->getType(); 5016 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5017 5018 // Bail if the element is an array since it is not memory access. 5019 if (isa<ArrayType>(ResultTy)) 5020 return; 5021 5022 if (ResultTy->hasAttr(attr::NoDeref)) { 5023 LastRecord.PossibleDerefs.insert(E); 5024 return; 5025 } 5026 5027 // Check if the base type is a pointer to a member access of a struct 5028 // marked with noderef. 5029 const Expr *Base = E->getBase(); 5030 QualType BaseTy = Base->getType(); 5031 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 5032 // Not a pointer access 5033 return; 5034 5035 const MemberExpr *Member = nullptr; 5036 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 5037 Member->isArrow()) 5038 Base = Member->getBase(); 5039 5040 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 5041 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 5042 LastRecord.PossibleDerefs.insert(E); 5043 } 5044 } 5045 5046 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 5047 Expr *LowerBound, 5048 SourceLocation ColonLocFirst, 5049 SourceLocation ColonLocSecond, 5050 Expr *Length, Expr *Stride, 5051 SourceLocation RBLoc) { 5052 if (Base->hasPlaceholderType() && 5053 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5054 ExprResult Result = CheckPlaceholderExpr(Base); 5055 if (Result.isInvalid()) 5056 return ExprError(); 5057 Base = Result.get(); 5058 } 5059 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 5060 ExprResult Result = CheckPlaceholderExpr(LowerBound); 5061 if (Result.isInvalid()) 5062 return ExprError(); 5063 Result = DefaultLvalueConversion(Result.get()); 5064 if (Result.isInvalid()) 5065 return ExprError(); 5066 LowerBound = Result.get(); 5067 } 5068 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 5069 ExprResult Result = CheckPlaceholderExpr(Length); 5070 if (Result.isInvalid()) 5071 return ExprError(); 5072 Result = DefaultLvalueConversion(Result.get()); 5073 if (Result.isInvalid()) 5074 return ExprError(); 5075 Length = Result.get(); 5076 } 5077 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 5078 ExprResult Result = CheckPlaceholderExpr(Stride); 5079 if (Result.isInvalid()) 5080 return ExprError(); 5081 Result = DefaultLvalueConversion(Result.get()); 5082 if (Result.isInvalid()) 5083 return ExprError(); 5084 Stride = Result.get(); 5085 } 5086 5087 // Build an unanalyzed expression if either operand is type-dependent. 5088 if (Base->isTypeDependent() || 5089 (LowerBound && 5090 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 5091 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 5092 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 5093 return new (Context) OMPArraySectionExpr( 5094 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 5095 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5096 } 5097 5098 // Perform default conversions. 5099 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 5100 QualType ResultTy; 5101 if (OriginalTy->isAnyPointerType()) { 5102 ResultTy = OriginalTy->getPointeeType(); 5103 } else if (OriginalTy->isArrayType()) { 5104 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 5105 } else { 5106 return ExprError( 5107 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 5108 << Base->getSourceRange()); 5109 } 5110 // C99 6.5.2.1p1 5111 if (LowerBound) { 5112 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 5113 LowerBound); 5114 if (Res.isInvalid()) 5115 return ExprError(Diag(LowerBound->getExprLoc(), 5116 diag::err_omp_typecheck_section_not_integer) 5117 << 0 << LowerBound->getSourceRange()); 5118 LowerBound = Res.get(); 5119 5120 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5121 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5122 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5123 << 0 << LowerBound->getSourceRange(); 5124 } 5125 if (Length) { 5126 auto Res = 5127 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5128 if (Res.isInvalid()) 5129 return ExprError(Diag(Length->getExprLoc(), 5130 diag::err_omp_typecheck_section_not_integer) 5131 << 1 << Length->getSourceRange()); 5132 Length = Res.get(); 5133 5134 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5135 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5136 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5137 << 1 << Length->getSourceRange(); 5138 } 5139 if (Stride) { 5140 ExprResult Res = 5141 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5142 if (Res.isInvalid()) 5143 return ExprError(Diag(Stride->getExprLoc(), 5144 diag::err_omp_typecheck_section_not_integer) 5145 << 1 << Stride->getSourceRange()); 5146 Stride = Res.get(); 5147 5148 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5149 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5150 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5151 << 1 << Stride->getSourceRange(); 5152 } 5153 5154 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5155 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5156 // type. Note that functions are not objects, and that (in C99 parlance) 5157 // incomplete types are not object types. 5158 if (ResultTy->isFunctionType()) { 5159 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5160 << ResultTy << Base->getSourceRange(); 5161 return ExprError(); 5162 } 5163 5164 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5165 diag::err_omp_section_incomplete_type, Base)) 5166 return ExprError(); 5167 5168 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5169 Expr::EvalResult Result; 5170 if (LowerBound->EvaluateAsInt(Result, Context)) { 5171 // OpenMP 5.0, [2.1.5 Array Sections] 5172 // The array section must be a subset of the original array. 5173 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5174 if (LowerBoundValue.isNegative()) { 5175 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5176 << LowerBound->getSourceRange(); 5177 return ExprError(); 5178 } 5179 } 5180 } 5181 5182 if (Length) { 5183 Expr::EvalResult Result; 5184 if (Length->EvaluateAsInt(Result, Context)) { 5185 // OpenMP 5.0, [2.1.5 Array Sections] 5186 // The length must evaluate to non-negative integers. 5187 llvm::APSInt LengthValue = Result.Val.getInt(); 5188 if (LengthValue.isNegative()) { 5189 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5190 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5191 << Length->getSourceRange(); 5192 return ExprError(); 5193 } 5194 } 5195 } else if (ColonLocFirst.isValid() && 5196 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5197 !OriginalTy->isVariableArrayType()))) { 5198 // OpenMP 5.0, [2.1.5 Array Sections] 5199 // When the size of the array dimension is not known, the length must be 5200 // specified explicitly. 5201 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5202 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5203 return ExprError(); 5204 } 5205 5206 if (Stride) { 5207 Expr::EvalResult Result; 5208 if (Stride->EvaluateAsInt(Result, Context)) { 5209 // OpenMP 5.0, [2.1.5 Array Sections] 5210 // The stride must evaluate to a positive integer. 5211 llvm::APSInt StrideValue = Result.Val.getInt(); 5212 if (!StrideValue.isStrictlyPositive()) { 5213 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5214 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5215 << Stride->getSourceRange(); 5216 return ExprError(); 5217 } 5218 } 5219 } 5220 5221 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5222 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5223 if (Result.isInvalid()) 5224 return ExprError(); 5225 Base = Result.get(); 5226 } 5227 return new (Context) OMPArraySectionExpr( 5228 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5229 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5230 } 5231 5232 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5233 SourceLocation RParenLoc, 5234 ArrayRef<Expr *> Dims, 5235 ArrayRef<SourceRange> Brackets) { 5236 if (Base->hasPlaceholderType()) { 5237 ExprResult Result = CheckPlaceholderExpr(Base); 5238 if (Result.isInvalid()) 5239 return ExprError(); 5240 Result = DefaultLvalueConversion(Result.get()); 5241 if (Result.isInvalid()) 5242 return ExprError(); 5243 Base = Result.get(); 5244 } 5245 QualType BaseTy = Base->getType(); 5246 // Delay analysis of the types/expressions if instantiation/specialization is 5247 // required. 5248 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5249 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5250 LParenLoc, RParenLoc, Dims, Brackets); 5251 if (!BaseTy->isPointerType() || 5252 (!Base->isTypeDependent() && 5253 BaseTy->getPointeeType()->isIncompleteType())) 5254 return ExprError(Diag(Base->getExprLoc(), 5255 diag::err_omp_non_pointer_type_array_shaping_base) 5256 << Base->getSourceRange()); 5257 5258 SmallVector<Expr *, 4> NewDims; 5259 bool ErrorFound = false; 5260 for (Expr *Dim : Dims) { 5261 if (Dim->hasPlaceholderType()) { 5262 ExprResult Result = CheckPlaceholderExpr(Dim); 5263 if (Result.isInvalid()) { 5264 ErrorFound = true; 5265 continue; 5266 } 5267 Result = DefaultLvalueConversion(Result.get()); 5268 if (Result.isInvalid()) { 5269 ErrorFound = true; 5270 continue; 5271 } 5272 Dim = Result.get(); 5273 } 5274 if (!Dim->isTypeDependent()) { 5275 ExprResult Result = 5276 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5277 if (Result.isInvalid()) { 5278 ErrorFound = true; 5279 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5280 << Dim->getSourceRange(); 5281 continue; 5282 } 5283 Dim = Result.get(); 5284 Expr::EvalResult EvResult; 5285 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5286 // OpenMP 5.0, [2.1.4 Array Shaping] 5287 // Each si is an integral type expression that must evaluate to a 5288 // positive integer. 5289 llvm::APSInt Value = EvResult.Val.getInt(); 5290 if (!Value.isStrictlyPositive()) { 5291 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5292 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5293 << Dim->getSourceRange(); 5294 ErrorFound = true; 5295 continue; 5296 } 5297 } 5298 } 5299 NewDims.push_back(Dim); 5300 } 5301 if (ErrorFound) 5302 return ExprError(); 5303 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5304 LParenLoc, RParenLoc, NewDims, Brackets); 5305 } 5306 5307 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5308 SourceLocation LLoc, SourceLocation RLoc, 5309 ArrayRef<OMPIteratorData> Data) { 5310 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5311 bool IsCorrect = true; 5312 for (const OMPIteratorData &D : Data) { 5313 TypeSourceInfo *TInfo = nullptr; 5314 SourceLocation StartLoc; 5315 QualType DeclTy; 5316 if (!D.Type.getAsOpaquePtr()) { 5317 // OpenMP 5.0, 2.1.6 Iterators 5318 // In an iterator-specifier, if the iterator-type is not specified then 5319 // the type of that iterator is of int type. 5320 DeclTy = Context.IntTy; 5321 StartLoc = D.DeclIdentLoc; 5322 } else { 5323 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5324 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5325 } 5326 5327 bool IsDeclTyDependent = DeclTy->isDependentType() || 5328 DeclTy->containsUnexpandedParameterPack() || 5329 DeclTy->isInstantiationDependentType(); 5330 if (!IsDeclTyDependent) { 5331 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5332 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5333 // The iterator-type must be an integral or pointer type. 5334 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5335 << DeclTy; 5336 IsCorrect = false; 5337 continue; 5338 } 5339 if (DeclTy.isConstant(Context)) { 5340 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5341 // The iterator-type must not be const qualified. 5342 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5343 << DeclTy; 5344 IsCorrect = false; 5345 continue; 5346 } 5347 } 5348 5349 // Iterator declaration. 5350 assert(D.DeclIdent && "Identifier expected."); 5351 // Always try to create iterator declarator to avoid extra error messages 5352 // about unknown declarations use. 5353 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5354 D.DeclIdent, DeclTy, TInfo, SC_None); 5355 VD->setImplicit(); 5356 if (S) { 5357 // Check for conflicting previous declaration. 5358 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5359 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5360 ForVisibleRedeclaration); 5361 Previous.suppressDiagnostics(); 5362 LookupName(Previous, S); 5363 5364 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5365 /*AllowInlineNamespace=*/false); 5366 if (!Previous.empty()) { 5367 NamedDecl *Old = Previous.getRepresentativeDecl(); 5368 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5369 Diag(Old->getLocation(), diag::note_previous_definition); 5370 } else { 5371 PushOnScopeChains(VD, S); 5372 } 5373 } else { 5374 CurContext->addDecl(VD); 5375 } 5376 Expr *Begin = D.Range.Begin; 5377 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5378 ExprResult BeginRes = 5379 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5380 Begin = BeginRes.get(); 5381 } 5382 Expr *End = D.Range.End; 5383 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5384 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5385 End = EndRes.get(); 5386 } 5387 Expr *Step = D.Range.Step; 5388 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5389 if (!Step->getType()->isIntegralType(Context)) { 5390 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5391 << Step << Step->getSourceRange(); 5392 IsCorrect = false; 5393 continue; 5394 } 5395 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5396 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5397 // If the step expression of a range-specification equals zero, the 5398 // behavior is unspecified. 5399 if (Result && Result->isZero()) { 5400 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5401 << Step << Step->getSourceRange(); 5402 IsCorrect = false; 5403 continue; 5404 } 5405 } 5406 if (!Begin || !End || !IsCorrect) { 5407 IsCorrect = false; 5408 continue; 5409 } 5410 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5411 IDElem.IteratorDecl = VD; 5412 IDElem.AssignmentLoc = D.AssignLoc; 5413 IDElem.Range.Begin = Begin; 5414 IDElem.Range.End = End; 5415 IDElem.Range.Step = Step; 5416 IDElem.ColonLoc = D.ColonLoc; 5417 IDElem.SecondColonLoc = D.SecColonLoc; 5418 } 5419 if (!IsCorrect) { 5420 // Invalidate all created iterator declarations if error is found. 5421 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5422 if (Decl *ID = D.IteratorDecl) 5423 ID->setInvalidDecl(); 5424 } 5425 return ExprError(); 5426 } 5427 SmallVector<OMPIteratorHelperData, 4> Helpers; 5428 if (!CurContext->isDependentContext()) { 5429 // Build number of ityeration for each iteration range. 5430 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5431 // ((Begini-Stepi-1-Endi) / -Stepi); 5432 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5433 // (Endi - Begini) 5434 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5435 D.Range.Begin); 5436 if(!Res.isUsable()) { 5437 IsCorrect = false; 5438 continue; 5439 } 5440 ExprResult St, St1; 5441 if (D.Range.Step) { 5442 St = D.Range.Step; 5443 // (Endi - Begini) + Stepi 5444 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5445 if (!Res.isUsable()) { 5446 IsCorrect = false; 5447 continue; 5448 } 5449 // (Endi - Begini) + Stepi - 1 5450 Res = 5451 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5452 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5453 if (!Res.isUsable()) { 5454 IsCorrect = false; 5455 continue; 5456 } 5457 // ((Endi - Begini) + Stepi - 1) / Stepi 5458 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5459 if (!Res.isUsable()) { 5460 IsCorrect = false; 5461 continue; 5462 } 5463 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5464 // (Begini - Endi) 5465 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5466 D.Range.Begin, D.Range.End); 5467 if (!Res1.isUsable()) { 5468 IsCorrect = false; 5469 continue; 5470 } 5471 // (Begini - Endi) - Stepi 5472 Res1 = 5473 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5474 if (!Res1.isUsable()) { 5475 IsCorrect = false; 5476 continue; 5477 } 5478 // (Begini - Endi) - Stepi - 1 5479 Res1 = 5480 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5481 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5482 if (!Res1.isUsable()) { 5483 IsCorrect = false; 5484 continue; 5485 } 5486 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5487 Res1 = 5488 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5489 if (!Res1.isUsable()) { 5490 IsCorrect = false; 5491 continue; 5492 } 5493 // Stepi > 0. 5494 ExprResult CmpRes = 5495 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5496 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5497 if (!CmpRes.isUsable()) { 5498 IsCorrect = false; 5499 continue; 5500 } 5501 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5502 Res.get(), Res1.get()); 5503 if (!Res.isUsable()) { 5504 IsCorrect = false; 5505 continue; 5506 } 5507 } 5508 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5509 if (!Res.isUsable()) { 5510 IsCorrect = false; 5511 continue; 5512 } 5513 5514 // Build counter update. 5515 // Build counter. 5516 auto *CounterVD = 5517 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5518 D.IteratorDecl->getBeginLoc(), nullptr, 5519 Res.get()->getType(), nullptr, SC_None); 5520 CounterVD->setImplicit(); 5521 ExprResult RefRes = 5522 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5523 D.IteratorDecl->getBeginLoc()); 5524 // Build counter update. 5525 // I = Begini + counter * Stepi; 5526 ExprResult UpdateRes; 5527 if (D.Range.Step) { 5528 UpdateRes = CreateBuiltinBinOp( 5529 D.AssignmentLoc, BO_Mul, 5530 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5531 } else { 5532 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5533 } 5534 if (!UpdateRes.isUsable()) { 5535 IsCorrect = false; 5536 continue; 5537 } 5538 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5539 UpdateRes.get()); 5540 if (!UpdateRes.isUsable()) { 5541 IsCorrect = false; 5542 continue; 5543 } 5544 ExprResult VDRes = 5545 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5546 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5547 D.IteratorDecl->getBeginLoc()); 5548 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5549 UpdateRes.get()); 5550 if (!UpdateRes.isUsable()) { 5551 IsCorrect = false; 5552 continue; 5553 } 5554 UpdateRes = 5555 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5556 if (!UpdateRes.isUsable()) { 5557 IsCorrect = false; 5558 continue; 5559 } 5560 ExprResult CounterUpdateRes = 5561 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5562 if (!CounterUpdateRes.isUsable()) { 5563 IsCorrect = false; 5564 continue; 5565 } 5566 CounterUpdateRes = 5567 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5568 if (!CounterUpdateRes.isUsable()) { 5569 IsCorrect = false; 5570 continue; 5571 } 5572 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5573 HD.CounterVD = CounterVD; 5574 HD.Upper = Res.get(); 5575 HD.Update = UpdateRes.get(); 5576 HD.CounterUpdate = CounterUpdateRes.get(); 5577 } 5578 } else { 5579 Helpers.assign(ID.size(), {}); 5580 } 5581 if (!IsCorrect) { 5582 // Invalidate all created iterator declarations if error is found. 5583 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5584 if (Decl *ID = D.IteratorDecl) 5585 ID->setInvalidDecl(); 5586 } 5587 return ExprError(); 5588 } 5589 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5590 LLoc, RLoc, ID, Helpers); 5591 } 5592 5593 ExprResult 5594 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5595 Expr *Idx, SourceLocation RLoc) { 5596 Expr *LHSExp = Base; 5597 Expr *RHSExp = Idx; 5598 5599 ExprValueKind VK = VK_LValue; 5600 ExprObjectKind OK = OK_Ordinary; 5601 5602 // Per C++ core issue 1213, the result is an xvalue if either operand is 5603 // a non-lvalue array, and an lvalue otherwise. 5604 if (getLangOpts().CPlusPlus11) { 5605 for (auto *Op : {LHSExp, RHSExp}) { 5606 Op = Op->IgnoreImplicit(); 5607 if (Op->getType()->isArrayType() && !Op->isLValue()) 5608 VK = VK_XValue; 5609 } 5610 } 5611 5612 // Perform default conversions. 5613 if (!LHSExp->getType()->getAs<VectorType>()) { 5614 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5615 if (Result.isInvalid()) 5616 return ExprError(); 5617 LHSExp = Result.get(); 5618 } 5619 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5620 if (Result.isInvalid()) 5621 return ExprError(); 5622 RHSExp = Result.get(); 5623 5624 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5625 5626 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5627 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5628 // in the subscript position. As a result, we need to derive the array base 5629 // and index from the expression types. 5630 Expr *BaseExpr, *IndexExpr; 5631 QualType ResultType; 5632 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5633 BaseExpr = LHSExp; 5634 IndexExpr = RHSExp; 5635 ResultType = 5636 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); 5637 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5638 BaseExpr = LHSExp; 5639 IndexExpr = RHSExp; 5640 ResultType = PTy->getPointeeType(); 5641 } else if (const ObjCObjectPointerType *PTy = 5642 LHSTy->getAs<ObjCObjectPointerType>()) { 5643 BaseExpr = LHSExp; 5644 IndexExpr = RHSExp; 5645 5646 // Use custom logic if this should be the pseudo-object subscript 5647 // expression. 5648 if (!LangOpts.isSubscriptPointerArithmetic()) 5649 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5650 nullptr); 5651 5652 ResultType = PTy->getPointeeType(); 5653 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5654 // Handle the uncommon case of "123[Ptr]". 5655 BaseExpr = RHSExp; 5656 IndexExpr = LHSExp; 5657 ResultType = PTy->getPointeeType(); 5658 } else if (const ObjCObjectPointerType *PTy = 5659 RHSTy->getAs<ObjCObjectPointerType>()) { 5660 // Handle the uncommon case of "123[Ptr]". 5661 BaseExpr = RHSExp; 5662 IndexExpr = LHSExp; 5663 ResultType = PTy->getPointeeType(); 5664 if (!LangOpts.isSubscriptPointerArithmetic()) { 5665 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5666 << ResultType << BaseExpr->getSourceRange(); 5667 return ExprError(); 5668 } 5669 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5670 BaseExpr = LHSExp; // vectors: V[123] 5671 IndexExpr = RHSExp; 5672 // We apply C++ DR1213 to vector subscripting too. 5673 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5674 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5675 if (Materialized.isInvalid()) 5676 return ExprError(); 5677 LHSExp = Materialized.get(); 5678 } 5679 VK = LHSExp->getValueKind(); 5680 if (VK != VK_PRValue) 5681 OK = OK_VectorComponent; 5682 5683 ResultType = VTy->getElementType(); 5684 QualType BaseType = BaseExpr->getType(); 5685 Qualifiers BaseQuals = BaseType.getQualifiers(); 5686 Qualifiers MemberQuals = ResultType.getQualifiers(); 5687 Qualifiers Combined = BaseQuals + MemberQuals; 5688 if (Combined != MemberQuals) 5689 ResultType = Context.getQualifiedType(ResultType, Combined); 5690 } else if (LHSTy->isArrayType()) { 5691 // If we see an array that wasn't promoted by 5692 // DefaultFunctionArrayLvalueConversion, it must be an array that 5693 // wasn't promoted because of the C90 rule that doesn't 5694 // allow promoting non-lvalue arrays. Warn, then 5695 // force the promotion here. 5696 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5697 << LHSExp->getSourceRange(); 5698 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5699 CK_ArrayToPointerDecay).get(); 5700 LHSTy = LHSExp->getType(); 5701 5702 BaseExpr = LHSExp; 5703 IndexExpr = RHSExp; 5704 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5705 } else if (RHSTy->isArrayType()) { 5706 // Same as previous, except for 123[f().a] case 5707 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5708 << RHSExp->getSourceRange(); 5709 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5710 CK_ArrayToPointerDecay).get(); 5711 RHSTy = RHSExp->getType(); 5712 5713 BaseExpr = RHSExp; 5714 IndexExpr = LHSExp; 5715 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5716 } else { 5717 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5718 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5719 } 5720 // C99 6.5.2.1p1 5721 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5722 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5723 << IndexExpr->getSourceRange()); 5724 5725 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5726 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5727 && !IndexExpr->isTypeDependent()) 5728 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5729 5730 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5731 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5732 // type. Note that Functions are not objects, and that (in C99 parlance) 5733 // incomplete types are not object types. 5734 if (ResultType->isFunctionType()) { 5735 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5736 << ResultType << BaseExpr->getSourceRange(); 5737 return ExprError(); 5738 } 5739 5740 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5741 // GNU extension: subscripting on pointer to void 5742 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5743 << BaseExpr->getSourceRange(); 5744 5745 // C forbids expressions of unqualified void type from being l-values. 5746 // See IsCForbiddenLValueType. 5747 if (!ResultType.hasQualifiers()) 5748 VK = VK_PRValue; 5749 } else if (!ResultType->isDependentType() && 5750 RequireCompleteSizedType( 5751 LLoc, ResultType, 5752 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5753 return ExprError(); 5754 5755 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5756 !ResultType.isCForbiddenLValueType()); 5757 5758 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5759 FunctionScopes.size() > 1) { 5760 if (auto *TT = 5761 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5762 for (auto I = FunctionScopes.rbegin(), 5763 E = std::prev(FunctionScopes.rend()); 5764 I != E; ++I) { 5765 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5766 if (CSI == nullptr) 5767 break; 5768 DeclContext *DC = nullptr; 5769 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5770 DC = LSI->CallOperator; 5771 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5772 DC = CRSI->TheCapturedDecl; 5773 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5774 DC = BSI->TheDecl; 5775 if (DC) { 5776 if (DC->containsDecl(TT->getDecl())) 5777 break; 5778 captureVariablyModifiedType( 5779 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5780 } 5781 } 5782 } 5783 } 5784 5785 return new (Context) 5786 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5787 } 5788 5789 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5790 ParmVarDecl *Param) { 5791 if (Param->hasUnparsedDefaultArg()) { 5792 // If we've already cleared out the location for the default argument, 5793 // that means we're parsing it right now. 5794 if (!UnparsedDefaultArgLocs.count(Param)) { 5795 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5796 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5797 Param->setInvalidDecl(); 5798 return true; 5799 } 5800 5801 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5802 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5803 Diag(UnparsedDefaultArgLocs[Param], 5804 diag::note_default_argument_declared_here); 5805 return true; 5806 } 5807 5808 if (Param->hasUninstantiatedDefaultArg() && 5809 InstantiateDefaultArgument(CallLoc, FD, Param)) 5810 return true; 5811 5812 assert(Param->hasInit() && "default argument but no initializer?"); 5813 5814 // If the default expression creates temporaries, we need to 5815 // push them to the current stack of expression temporaries so they'll 5816 // be properly destroyed. 5817 // FIXME: We should really be rebuilding the default argument with new 5818 // bound temporaries; see the comment in PR5810. 5819 // We don't need to do that with block decls, though, because 5820 // blocks in default argument expression can never capture anything. 5821 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5822 // Set the "needs cleanups" bit regardless of whether there are 5823 // any explicit objects. 5824 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5825 5826 // Append all the objects to the cleanup list. Right now, this 5827 // should always be a no-op, because blocks in default argument 5828 // expressions should never be able to capture anything. 5829 assert(!Init->getNumObjects() && 5830 "default argument expression has capturing blocks?"); 5831 } 5832 5833 // We already type-checked the argument, so we know it works. 5834 // Just mark all of the declarations in this potentially-evaluated expression 5835 // as being "referenced". 5836 EnterExpressionEvaluationContext EvalContext( 5837 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5838 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5839 /*SkipLocalVariables=*/true); 5840 return false; 5841 } 5842 5843 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5844 FunctionDecl *FD, ParmVarDecl *Param) { 5845 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5846 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5847 return ExprError(); 5848 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5849 } 5850 5851 Sema::VariadicCallType 5852 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5853 Expr *Fn) { 5854 if (Proto && Proto->isVariadic()) { 5855 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 5856 return VariadicConstructor; 5857 else if (Fn && Fn->getType()->isBlockPointerType()) 5858 return VariadicBlock; 5859 else if (FDecl) { 5860 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5861 if (Method->isInstance()) 5862 return VariadicMethod; 5863 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5864 return VariadicMethod; 5865 return VariadicFunction; 5866 } 5867 return VariadicDoesNotApply; 5868 } 5869 5870 namespace { 5871 class FunctionCallCCC final : public FunctionCallFilterCCC { 5872 public: 5873 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5874 unsigned NumArgs, MemberExpr *ME) 5875 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5876 FunctionName(FuncName) {} 5877 5878 bool ValidateCandidate(const TypoCorrection &candidate) override { 5879 if (!candidate.getCorrectionSpecifier() || 5880 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5881 return false; 5882 } 5883 5884 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5885 } 5886 5887 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5888 return std::make_unique<FunctionCallCCC>(*this); 5889 } 5890 5891 private: 5892 const IdentifierInfo *const FunctionName; 5893 }; 5894 } 5895 5896 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5897 FunctionDecl *FDecl, 5898 ArrayRef<Expr *> Args) { 5899 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5900 DeclarationName FuncName = FDecl->getDeclName(); 5901 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5902 5903 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5904 if (TypoCorrection Corrected = S.CorrectTypo( 5905 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5906 S.getScopeForContext(S.CurContext), nullptr, CCC, 5907 Sema::CTK_ErrorRecovery)) { 5908 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5909 if (Corrected.isOverloaded()) { 5910 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5911 OverloadCandidateSet::iterator Best; 5912 for (NamedDecl *CD : Corrected) { 5913 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5914 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5915 OCS); 5916 } 5917 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5918 case OR_Success: 5919 ND = Best->FoundDecl; 5920 Corrected.setCorrectionDecl(ND); 5921 break; 5922 default: 5923 break; 5924 } 5925 } 5926 ND = ND->getUnderlyingDecl(); 5927 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5928 return Corrected; 5929 } 5930 } 5931 return TypoCorrection(); 5932 } 5933 5934 /// ConvertArgumentsForCall - Converts the arguments specified in 5935 /// Args/NumArgs to the parameter types of the function FDecl with 5936 /// function prototype Proto. Call is the call expression itself, and 5937 /// Fn is the function expression. For a C++ member function, this 5938 /// routine does not attempt to convert the object argument. Returns 5939 /// true if the call is ill-formed. 5940 bool 5941 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5942 FunctionDecl *FDecl, 5943 const FunctionProtoType *Proto, 5944 ArrayRef<Expr *> Args, 5945 SourceLocation RParenLoc, 5946 bool IsExecConfig) { 5947 // Bail out early if calling a builtin with custom typechecking. 5948 if (FDecl) 5949 if (unsigned ID = FDecl->getBuiltinID()) 5950 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5951 return false; 5952 5953 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5954 // assignment, to the types of the corresponding parameter, ... 5955 unsigned NumParams = Proto->getNumParams(); 5956 bool Invalid = false; 5957 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5958 unsigned FnKind = Fn->getType()->isBlockPointerType() 5959 ? 1 /* block */ 5960 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5961 : 0 /* function */); 5962 5963 // If too few arguments are available (and we don't have default 5964 // arguments for the remaining parameters), don't make the call. 5965 if (Args.size() < NumParams) { 5966 if (Args.size() < MinArgs) { 5967 TypoCorrection TC; 5968 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5969 unsigned diag_id = 5970 MinArgs == NumParams && !Proto->isVariadic() 5971 ? diag::err_typecheck_call_too_few_args_suggest 5972 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5973 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5974 << static_cast<unsigned>(Args.size()) 5975 << TC.getCorrectionRange()); 5976 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5977 Diag(RParenLoc, 5978 MinArgs == NumParams && !Proto->isVariadic() 5979 ? diag::err_typecheck_call_too_few_args_one 5980 : diag::err_typecheck_call_too_few_args_at_least_one) 5981 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5982 else 5983 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5984 ? diag::err_typecheck_call_too_few_args 5985 : diag::err_typecheck_call_too_few_args_at_least) 5986 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5987 << Fn->getSourceRange(); 5988 5989 // Emit the location of the prototype. 5990 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5991 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5992 5993 return true; 5994 } 5995 // We reserve space for the default arguments when we create 5996 // the call expression, before calling ConvertArgumentsForCall. 5997 assert((Call->getNumArgs() == NumParams) && 5998 "We should have reserved space for the default arguments before!"); 5999 } 6000 6001 // If too many are passed and not variadic, error on the extras and drop 6002 // them. 6003 if (Args.size() > NumParams) { 6004 if (!Proto->isVariadic()) { 6005 TypoCorrection TC; 6006 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6007 unsigned diag_id = 6008 MinArgs == NumParams && !Proto->isVariadic() 6009 ? diag::err_typecheck_call_too_many_args_suggest 6010 : diag::err_typecheck_call_too_many_args_at_most_suggest; 6011 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 6012 << static_cast<unsigned>(Args.size()) 6013 << TC.getCorrectionRange()); 6014 } else if (NumParams == 1 && FDecl && 6015 FDecl->getParamDecl(0)->getDeclName()) 6016 Diag(Args[NumParams]->getBeginLoc(), 6017 MinArgs == NumParams 6018 ? diag::err_typecheck_call_too_many_args_one 6019 : diag::err_typecheck_call_too_many_args_at_most_one) 6020 << FnKind << FDecl->getParamDecl(0) 6021 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 6022 << SourceRange(Args[NumParams]->getBeginLoc(), 6023 Args.back()->getEndLoc()); 6024 else 6025 Diag(Args[NumParams]->getBeginLoc(), 6026 MinArgs == NumParams 6027 ? diag::err_typecheck_call_too_many_args 6028 : diag::err_typecheck_call_too_many_args_at_most) 6029 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 6030 << Fn->getSourceRange() 6031 << SourceRange(Args[NumParams]->getBeginLoc(), 6032 Args.back()->getEndLoc()); 6033 6034 // Emit the location of the prototype. 6035 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6036 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6037 6038 // This deletes the extra arguments. 6039 Call->shrinkNumArgs(NumParams); 6040 return true; 6041 } 6042 } 6043 SmallVector<Expr *, 8> AllArgs; 6044 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 6045 6046 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 6047 AllArgs, CallType); 6048 if (Invalid) 6049 return true; 6050 unsigned TotalNumArgs = AllArgs.size(); 6051 for (unsigned i = 0; i < TotalNumArgs; ++i) 6052 Call->setArg(i, AllArgs[i]); 6053 6054 Call->computeDependence(); 6055 return false; 6056 } 6057 6058 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 6059 const FunctionProtoType *Proto, 6060 unsigned FirstParam, ArrayRef<Expr *> Args, 6061 SmallVectorImpl<Expr *> &AllArgs, 6062 VariadicCallType CallType, bool AllowExplicit, 6063 bool IsListInitialization) { 6064 unsigned NumParams = Proto->getNumParams(); 6065 bool Invalid = false; 6066 size_t ArgIx = 0; 6067 // Continue to check argument types (even if we have too few/many args). 6068 for (unsigned i = FirstParam; i < NumParams; i++) { 6069 QualType ProtoArgType = Proto->getParamType(i); 6070 6071 Expr *Arg; 6072 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 6073 if (ArgIx < Args.size()) { 6074 Arg = Args[ArgIx++]; 6075 6076 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 6077 diag::err_call_incomplete_argument, Arg)) 6078 return true; 6079 6080 // Strip the unbridged-cast placeholder expression off, if applicable. 6081 bool CFAudited = false; 6082 if (Arg->getType() == Context.ARCUnbridgedCastTy && 6083 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6084 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6085 Arg = stripARCUnbridgedCast(Arg); 6086 else if (getLangOpts().ObjCAutoRefCount && 6087 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6088 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6089 CFAudited = true; 6090 6091 if (Proto->getExtParameterInfo(i).isNoEscape() && 6092 ProtoArgType->isBlockPointerType()) 6093 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 6094 BE->getBlockDecl()->setDoesNotEscape(); 6095 6096 InitializedEntity Entity = 6097 Param ? InitializedEntity::InitializeParameter(Context, Param, 6098 ProtoArgType) 6099 : InitializedEntity::InitializeParameter( 6100 Context, ProtoArgType, Proto->isParamConsumed(i)); 6101 6102 // Remember that parameter belongs to a CF audited API. 6103 if (CFAudited) 6104 Entity.setParameterCFAudited(); 6105 6106 ExprResult ArgE = PerformCopyInitialization( 6107 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 6108 if (ArgE.isInvalid()) 6109 return true; 6110 6111 Arg = ArgE.getAs<Expr>(); 6112 } else { 6113 assert(Param && "can't use default arguments without a known callee"); 6114 6115 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 6116 if (ArgExpr.isInvalid()) 6117 return true; 6118 6119 Arg = ArgExpr.getAs<Expr>(); 6120 } 6121 6122 // Check for array bounds violations for each argument to the call. This 6123 // check only triggers warnings when the argument isn't a more complex Expr 6124 // with its own checking, such as a BinaryOperator. 6125 CheckArrayAccess(Arg); 6126 6127 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6128 CheckStaticArrayArgument(CallLoc, Param, Arg); 6129 6130 AllArgs.push_back(Arg); 6131 } 6132 6133 // If this is a variadic call, handle args passed through "...". 6134 if (CallType != VariadicDoesNotApply) { 6135 // Assume that extern "C" functions with variadic arguments that 6136 // return __unknown_anytype aren't *really* variadic. 6137 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6138 FDecl->isExternC()) { 6139 for (Expr *A : Args.slice(ArgIx)) { 6140 QualType paramType; // ignored 6141 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6142 Invalid |= arg.isInvalid(); 6143 AllArgs.push_back(arg.get()); 6144 } 6145 6146 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6147 } else { 6148 for (Expr *A : Args.slice(ArgIx)) { 6149 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6150 Invalid |= Arg.isInvalid(); 6151 AllArgs.push_back(Arg.get()); 6152 } 6153 } 6154 6155 // Check for array bounds violations. 6156 for (Expr *A : Args.slice(ArgIx)) 6157 CheckArrayAccess(A); 6158 } 6159 return Invalid; 6160 } 6161 6162 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6163 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6164 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6165 TL = DTL.getOriginalLoc(); 6166 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6167 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6168 << ATL.getLocalSourceRange(); 6169 } 6170 6171 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6172 /// array parameter, check that it is non-null, and that if it is formed by 6173 /// array-to-pointer decay, the underlying array is sufficiently large. 6174 /// 6175 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6176 /// array type derivation, then for each call to the function, the value of the 6177 /// corresponding actual argument shall provide access to the first element of 6178 /// an array with at least as many elements as specified by the size expression. 6179 void 6180 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6181 ParmVarDecl *Param, 6182 const Expr *ArgExpr) { 6183 // Static array parameters are not supported in C++. 6184 if (!Param || getLangOpts().CPlusPlus) 6185 return; 6186 6187 QualType OrigTy = Param->getOriginalType(); 6188 6189 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6190 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6191 return; 6192 6193 if (ArgExpr->isNullPointerConstant(Context, 6194 Expr::NPC_NeverValueDependent)) { 6195 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6196 DiagnoseCalleeStaticArrayParam(*this, Param); 6197 return; 6198 } 6199 6200 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6201 if (!CAT) 6202 return; 6203 6204 const ConstantArrayType *ArgCAT = 6205 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6206 if (!ArgCAT) 6207 return; 6208 6209 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6210 ArgCAT->getElementType())) { 6211 if (ArgCAT->getSize().ult(CAT->getSize())) { 6212 Diag(CallLoc, diag::warn_static_array_too_small) 6213 << ArgExpr->getSourceRange() 6214 << (unsigned)ArgCAT->getSize().getZExtValue() 6215 << (unsigned)CAT->getSize().getZExtValue() << 0; 6216 DiagnoseCalleeStaticArrayParam(*this, Param); 6217 } 6218 return; 6219 } 6220 6221 Optional<CharUnits> ArgSize = 6222 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6223 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6224 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6225 Diag(CallLoc, diag::warn_static_array_too_small) 6226 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6227 << (unsigned)ParmSize->getQuantity() << 1; 6228 DiagnoseCalleeStaticArrayParam(*this, Param); 6229 } 6230 } 6231 6232 /// Given a function expression of unknown-any type, try to rebuild it 6233 /// to have a function type. 6234 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6235 6236 /// Is the given type a placeholder that we need to lower out 6237 /// immediately during argument processing? 6238 static bool isPlaceholderToRemoveAsArg(QualType type) { 6239 // Placeholders are never sugared. 6240 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6241 if (!placeholder) return false; 6242 6243 switch (placeholder->getKind()) { 6244 // Ignore all the non-placeholder types. 6245 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6246 case BuiltinType::Id: 6247 #include "clang/Basic/OpenCLImageTypes.def" 6248 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6249 case BuiltinType::Id: 6250 #include "clang/Basic/OpenCLExtensionTypes.def" 6251 // In practice we'll never use this, since all SVE types are sugared 6252 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6253 #define SVE_TYPE(Name, Id, SingletonId) \ 6254 case BuiltinType::Id: 6255 #include "clang/Basic/AArch64SVEACLETypes.def" 6256 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6257 case BuiltinType::Id: 6258 #include "clang/Basic/PPCTypes.def" 6259 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6260 #include "clang/Basic/RISCVVTypes.def" 6261 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6262 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6263 #include "clang/AST/BuiltinTypes.def" 6264 return false; 6265 6266 // We cannot lower out overload sets; they might validly be resolved 6267 // by the call machinery. 6268 case BuiltinType::Overload: 6269 return false; 6270 6271 // Unbridged casts in ARC can be handled in some call positions and 6272 // should be left in place. 6273 case BuiltinType::ARCUnbridgedCast: 6274 return false; 6275 6276 // Pseudo-objects should be converted as soon as possible. 6277 case BuiltinType::PseudoObject: 6278 return true; 6279 6280 // The debugger mode could theoretically but currently does not try 6281 // to resolve unknown-typed arguments based on known parameter types. 6282 case BuiltinType::UnknownAny: 6283 return true; 6284 6285 // These are always invalid as call arguments and should be reported. 6286 case BuiltinType::BoundMember: 6287 case BuiltinType::BuiltinFn: 6288 case BuiltinType::IncompleteMatrixIdx: 6289 case BuiltinType::OMPArraySection: 6290 case BuiltinType::OMPArrayShaping: 6291 case BuiltinType::OMPIterator: 6292 return true; 6293 6294 } 6295 llvm_unreachable("bad builtin type kind"); 6296 } 6297 6298 /// Check an argument list for placeholders that we won't try to 6299 /// handle later. 6300 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6301 // Apply this processing to all the arguments at once instead of 6302 // dying at the first failure. 6303 bool hasInvalid = false; 6304 for (size_t i = 0, e = args.size(); i != e; i++) { 6305 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6306 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6307 if (result.isInvalid()) hasInvalid = true; 6308 else args[i] = result.get(); 6309 } 6310 } 6311 return hasInvalid; 6312 } 6313 6314 /// If a builtin function has a pointer argument with no explicit address 6315 /// space, then it should be able to accept a pointer to any address 6316 /// space as input. In order to do this, we need to replace the 6317 /// standard builtin declaration with one that uses the same address space 6318 /// as the call. 6319 /// 6320 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6321 /// it does not contain any pointer arguments without 6322 /// an address space qualifer. Otherwise the rewritten 6323 /// FunctionDecl is returned. 6324 /// TODO: Handle pointer return types. 6325 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6326 FunctionDecl *FDecl, 6327 MultiExprArg ArgExprs) { 6328 6329 QualType DeclType = FDecl->getType(); 6330 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6331 6332 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6333 ArgExprs.size() < FT->getNumParams()) 6334 return nullptr; 6335 6336 bool NeedsNewDecl = false; 6337 unsigned i = 0; 6338 SmallVector<QualType, 8> OverloadParams; 6339 6340 for (QualType ParamType : FT->param_types()) { 6341 6342 // Convert array arguments to pointer to simplify type lookup. 6343 ExprResult ArgRes = 6344 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6345 if (ArgRes.isInvalid()) 6346 return nullptr; 6347 Expr *Arg = ArgRes.get(); 6348 QualType ArgType = Arg->getType(); 6349 if (!ParamType->isPointerType() || 6350 ParamType.hasAddressSpace() || 6351 !ArgType->isPointerType() || 6352 !ArgType->getPointeeType().hasAddressSpace()) { 6353 OverloadParams.push_back(ParamType); 6354 continue; 6355 } 6356 6357 QualType PointeeType = ParamType->getPointeeType(); 6358 if (PointeeType.hasAddressSpace()) 6359 continue; 6360 6361 NeedsNewDecl = true; 6362 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6363 6364 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6365 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6366 } 6367 6368 if (!NeedsNewDecl) 6369 return nullptr; 6370 6371 FunctionProtoType::ExtProtoInfo EPI; 6372 EPI.Variadic = FT->isVariadic(); 6373 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6374 OverloadParams, EPI); 6375 DeclContext *Parent = FDecl->getParent(); 6376 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6377 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6378 FDecl->getIdentifier(), OverloadTy, 6379 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6380 false, 6381 /*hasPrototype=*/true); 6382 SmallVector<ParmVarDecl*, 16> Params; 6383 FT = cast<FunctionProtoType>(OverloadTy); 6384 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6385 QualType ParamType = FT->getParamType(i); 6386 ParmVarDecl *Parm = 6387 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6388 SourceLocation(), nullptr, ParamType, 6389 /*TInfo=*/nullptr, SC_None, nullptr); 6390 Parm->setScopeInfo(0, i); 6391 Params.push_back(Parm); 6392 } 6393 OverloadDecl->setParams(Params); 6394 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6395 return OverloadDecl; 6396 } 6397 6398 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6399 FunctionDecl *Callee, 6400 MultiExprArg ArgExprs) { 6401 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6402 // similar attributes) really don't like it when functions are called with an 6403 // invalid number of args. 6404 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6405 /*PartialOverloading=*/false) && 6406 !Callee->isVariadic()) 6407 return; 6408 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6409 return; 6410 6411 if (const EnableIfAttr *Attr = 6412 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6413 S.Diag(Fn->getBeginLoc(), 6414 isa<CXXMethodDecl>(Callee) 6415 ? diag::err_ovl_no_viable_member_function_in_call 6416 : diag::err_ovl_no_viable_function_in_call) 6417 << Callee << Callee->getSourceRange(); 6418 S.Diag(Callee->getLocation(), 6419 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6420 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6421 return; 6422 } 6423 } 6424 6425 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6426 const UnresolvedMemberExpr *const UME, Sema &S) { 6427 6428 const auto GetFunctionLevelDCIfCXXClass = 6429 [](Sema &S) -> const CXXRecordDecl * { 6430 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6431 if (!DC || !DC->getParent()) 6432 return nullptr; 6433 6434 // If the call to some member function was made from within a member 6435 // function body 'M' return return 'M's parent. 6436 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6437 return MD->getParent()->getCanonicalDecl(); 6438 // else the call was made from within a default member initializer of a 6439 // class, so return the class. 6440 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6441 return RD->getCanonicalDecl(); 6442 return nullptr; 6443 }; 6444 // If our DeclContext is neither a member function nor a class (in the 6445 // case of a lambda in a default member initializer), we can't have an 6446 // enclosing 'this'. 6447 6448 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6449 if (!CurParentClass) 6450 return false; 6451 6452 // The naming class for implicit member functions call is the class in which 6453 // name lookup starts. 6454 const CXXRecordDecl *const NamingClass = 6455 UME->getNamingClass()->getCanonicalDecl(); 6456 assert(NamingClass && "Must have naming class even for implicit access"); 6457 6458 // If the unresolved member functions were found in a 'naming class' that is 6459 // related (either the same or derived from) to the class that contains the 6460 // member function that itself contained the implicit member access. 6461 6462 return CurParentClass == NamingClass || 6463 CurParentClass->isDerivedFrom(NamingClass); 6464 } 6465 6466 static void 6467 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6468 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6469 6470 if (!UME) 6471 return; 6472 6473 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6474 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6475 // already been captured, or if this is an implicit member function call (if 6476 // it isn't, an attempt to capture 'this' should already have been made). 6477 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6478 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6479 return; 6480 6481 // Check if the naming class in which the unresolved members were found is 6482 // related (same as or is a base of) to the enclosing class. 6483 6484 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6485 return; 6486 6487 6488 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6489 // If the enclosing function is not dependent, then this lambda is 6490 // capture ready, so if we can capture this, do so. 6491 if (!EnclosingFunctionCtx->isDependentContext()) { 6492 // If the current lambda and all enclosing lambdas can capture 'this' - 6493 // then go ahead and capture 'this' (since our unresolved overload set 6494 // contains at least one non-static member function). 6495 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6496 S.CheckCXXThisCapture(CallLoc); 6497 } else if (S.CurContext->isDependentContext()) { 6498 // ... since this is an implicit member reference, that might potentially 6499 // involve a 'this' capture, mark 'this' for potential capture in 6500 // enclosing lambdas. 6501 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6502 CurLSI->addPotentialThisCapture(CallLoc); 6503 } 6504 } 6505 6506 // Once a call is fully resolved, warn for unqualified calls to specific 6507 // C++ standard functions, like move and forward. 6508 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) { 6509 // We are only checking unary move and forward so exit early here. 6510 if (Call->getNumArgs() != 1) 6511 return; 6512 6513 Expr *E = Call->getCallee()->IgnoreParenImpCasts(); 6514 if (!E || isa<UnresolvedLookupExpr>(E)) 6515 return; 6516 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E); 6517 if (!DRE || !DRE->getLocation().isValid()) 6518 return; 6519 6520 if (DRE->getQualifier()) 6521 return; 6522 6523 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl()); 6524 if (!D || !D->isInStdNamespace()) 6525 return; 6526 6527 // Only warn for some functions deemed more frequent or problematic. 6528 static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"}; 6529 auto it = llvm::find(SpecialFunctions, D->getName()); 6530 if (it == std::end(SpecialFunctions)) 6531 return; 6532 6533 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function) 6534 << D->getQualifiedNameAsString() 6535 << FixItHint::CreateInsertion(DRE->getLocation(), "std::"); 6536 } 6537 6538 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6539 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6540 Expr *ExecConfig) { 6541 ExprResult Call = 6542 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6543 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6544 if (Call.isInvalid()) 6545 return Call; 6546 6547 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6548 // language modes. 6549 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6550 if (ULE->hasExplicitTemplateArgs() && 6551 ULE->decls_begin() == ULE->decls_end()) { 6552 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6553 ? diag::warn_cxx17_compat_adl_only_template_id 6554 : diag::ext_adl_only_template_id) 6555 << ULE->getName(); 6556 } 6557 } 6558 6559 if (LangOpts.OpenMP) 6560 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6561 ExecConfig); 6562 if (LangOpts.CPlusPlus) { 6563 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6564 if (CE) 6565 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE); 6566 } 6567 return Call; 6568 } 6569 6570 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6571 /// This provides the location of the left/right parens and a list of comma 6572 /// locations. 6573 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6574 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6575 Expr *ExecConfig, bool IsExecConfig, 6576 bool AllowRecovery) { 6577 // Since this might be a postfix expression, get rid of ParenListExprs. 6578 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6579 if (Result.isInvalid()) return ExprError(); 6580 Fn = Result.get(); 6581 6582 if (checkArgsForPlaceholders(*this, ArgExprs)) 6583 return ExprError(); 6584 6585 if (getLangOpts().CPlusPlus) { 6586 // If this is a pseudo-destructor expression, build the call immediately. 6587 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6588 if (!ArgExprs.empty()) { 6589 // Pseudo-destructor calls should not have any arguments. 6590 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6591 << FixItHint::CreateRemoval( 6592 SourceRange(ArgExprs.front()->getBeginLoc(), 6593 ArgExprs.back()->getEndLoc())); 6594 } 6595 6596 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6597 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6598 } 6599 if (Fn->getType() == Context.PseudoObjectTy) { 6600 ExprResult result = CheckPlaceholderExpr(Fn); 6601 if (result.isInvalid()) return ExprError(); 6602 Fn = result.get(); 6603 } 6604 6605 // Determine whether this is a dependent call inside a C++ template, 6606 // in which case we won't do any semantic analysis now. 6607 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6608 if (ExecConfig) { 6609 return CUDAKernelCallExpr::Create(Context, Fn, 6610 cast<CallExpr>(ExecConfig), ArgExprs, 6611 Context.DependentTy, VK_PRValue, 6612 RParenLoc, CurFPFeatureOverrides()); 6613 } else { 6614 6615 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6616 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6617 Fn->getBeginLoc()); 6618 6619 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6620 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6621 } 6622 } 6623 6624 // Determine whether this is a call to an object (C++ [over.call.object]). 6625 if (Fn->getType()->isRecordType()) 6626 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6627 RParenLoc); 6628 6629 if (Fn->getType() == Context.UnknownAnyTy) { 6630 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6631 if (result.isInvalid()) return ExprError(); 6632 Fn = result.get(); 6633 } 6634 6635 if (Fn->getType() == Context.BoundMemberTy) { 6636 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6637 RParenLoc, ExecConfig, IsExecConfig, 6638 AllowRecovery); 6639 } 6640 } 6641 6642 // Check for overloaded calls. This can happen even in C due to extensions. 6643 if (Fn->getType() == Context.OverloadTy) { 6644 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6645 6646 // We aren't supposed to apply this logic if there's an '&' involved. 6647 if (!find.HasFormOfMemberPointer) { 6648 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6649 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6650 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6651 OverloadExpr *ovl = find.Expression; 6652 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6653 return BuildOverloadedCallExpr( 6654 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6655 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6656 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6657 RParenLoc, ExecConfig, IsExecConfig, 6658 AllowRecovery); 6659 } 6660 } 6661 6662 // If we're directly calling a function, get the appropriate declaration. 6663 if (Fn->getType() == Context.UnknownAnyTy) { 6664 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6665 if (result.isInvalid()) return ExprError(); 6666 Fn = result.get(); 6667 } 6668 6669 Expr *NakedFn = Fn->IgnoreParens(); 6670 6671 bool CallingNDeclIndirectly = false; 6672 NamedDecl *NDecl = nullptr; 6673 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6674 if (UnOp->getOpcode() == UO_AddrOf) { 6675 CallingNDeclIndirectly = true; 6676 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6677 } 6678 } 6679 6680 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6681 NDecl = DRE->getDecl(); 6682 6683 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6684 if (FDecl && FDecl->getBuiltinID()) { 6685 // Rewrite the function decl for this builtin by replacing parameters 6686 // with no explicit address space with the address space of the arguments 6687 // in ArgExprs. 6688 if ((FDecl = 6689 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6690 NDecl = FDecl; 6691 Fn = DeclRefExpr::Create( 6692 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6693 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6694 nullptr, DRE->isNonOdrUse()); 6695 } 6696 } 6697 } else if (isa<MemberExpr>(NakedFn)) 6698 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6699 6700 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6701 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6702 FD, /*Complain=*/true, Fn->getBeginLoc())) 6703 return ExprError(); 6704 6705 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6706 6707 // If this expression is a call to a builtin function in HIP device 6708 // compilation, allow a pointer-type argument to default address space to be 6709 // passed as a pointer-type parameter to a non-default address space. 6710 // If Arg is declared in the default address space and Param is declared 6711 // in a non-default address space, perform an implicit address space cast to 6712 // the parameter type. 6713 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6714 FD->getBuiltinID()) { 6715 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6716 ParmVarDecl *Param = FD->getParamDecl(Idx); 6717 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6718 !ArgExprs[Idx]->getType()->isPointerType()) 6719 continue; 6720 6721 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6722 auto ArgTy = ArgExprs[Idx]->getType(); 6723 auto ArgPtTy = ArgTy->getPointeeType(); 6724 auto ArgAS = ArgPtTy.getAddressSpace(); 6725 6726 // Add address space cast if target address spaces are different 6727 bool NeedImplicitASC = 6728 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6729 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6730 // or from specific AS which has target AS matching that of Param. 6731 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6732 if (!NeedImplicitASC) 6733 continue; 6734 6735 // First, ensure that the Arg is an RValue. 6736 if (ArgExprs[Idx]->isGLValue()) { 6737 ArgExprs[Idx] = ImplicitCastExpr::Create( 6738 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6739 nullptr, VK_PRValue, FPOptionsOverride()); 6740 } 6741 6742 // Construct a new arg type with address space of Param 6743 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6744 ArgPtQuals.setAddressSpace(ParamAS); 6745 auto NewArgPtTy = 6746 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6747 auto NewArgTy = 6748 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6749 ArgTy.getQualifiers()); 6750 6751 // Finally perform an implicit address space cast 6752 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6753 CK_AddressSpaceConversion) 6754 .get(); 6755 } 6756 } 6757 } 6758 6759 if (Context.isDependenceAllowed() && 6760 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6761 assert(!getLangOpts().CPlusPlus); 6762 assert((Fn->containsErrors() || 6763 llvm::any_of(ArgExprs, 6764 [](clang::Expr *E) { return E->containsErrors(); })) && 6765 "should only occur in error-recovery path."); 6766 QualType ReturnType = 6767 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6768 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6769 : Context.DependentTy; 6770 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6771 Expr::getValueKindForType(ReturnType), RParenLoc, 6772 CurFPFeatureOverrides()); 6773 } 6774 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6775 ExecConfig, IsExecConfig); 6776 } 6777 6778 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6779 // with the specified CallArgs 6780 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6781 MultiExprArg CallArgs) { 6782 StringRef Name = Context.BuiltinInfo.getName(Id); 6783 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6784 Sema::LookupOrdinaryName); 6785 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6786 6787 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6788 assert(BuiltInDecl && "failed to find builtin declaration"); 6789 6790 ExprResult DeclRef = 6791 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6792 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6793 6794 ExprResult Call = 6795 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6796 6797 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6798 return Call.get(); 6799 } 6800 6801 /// Parse a __builtin_astype expression. 6802 /// 6803 /// __builtin_astype( value, dst type ) 6804 /// 6805 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6806 SourceLocation BuiltinLoc, 6807 SourceLocation RParenLoc) { 6808 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6809 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6810 } 6811 6812 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6813 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6814 SourceLocation BuiltinLoc, 6815 SourceLocation RParenLoc) { 6816 ExprValueKind VK = VK_PRValue; 6817 ExprObjectKind OK = OK_Ordinary; 6818 QualType SrcTy = E->getType(); 6819 if (!SrcTy->isDependentType() && 6820 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6821 return ExprError( 6822 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6823 << DestTy << SrcTy << E->getSourceRange()); 6824 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6825 } 6826 6827 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6828 /// provided arguments. 6829 /// 6830 /// __builtin_convertvector( value, dst type ) 6831 /// 6832 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6833 SourceLocation BuiltinLoc, 6834 SourceLocation RParenLoc) { 6835 TypeSourceInfo *TInfo; 6836 GetTypeFromParser(ParsedDestTy, &TInfo); 6837 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6838 } 6839 6840 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6841 /// i.e. an expression not of \p OverloadTy. The expression should 6842 /// unary-convert to an expression of function-pointer or 6843 /// block-pointer type. 6844 /// 6845 /// \param NDecl the declaration being called, if available 6846 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6847 SourceLocation LParenLoc, 6848 ArrayRef<Expr *> Args, 6849 SourceLocation RParenLoc, Expr *Config, 6850 bool IsExecConfig, ADLCallKind UsesADL) { 6851 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6852 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6853 6854 // Functions with 'interrupt' attribute cannot be called directly. 6855 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6856 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6857 return ExprError(); 6858 } 6859 6860 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6861 // so there's some risk when calling out to non-interrupt handler functions 6862 // that the callee might not preserve them. This is easy to diagnose here, 6863 // but can be very challenging to debug. 6864 // Likewise, X86 interrupt handlers may only call routines with attribute 6865 // no_caller_saved_registers since there is no efficient way to 6866 // save and restore the non-GPR state. 6867 if (auto *Caller = getCurFunctionDecl()) { 6868 if (Caller->hasAttr<ARMInterruptAttr>()) { 6869 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6870 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6871 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6872 if (FDecl) 6873 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6874 } 6875 } 6876 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6877 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6878 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6879 if (FDecl) 6880 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6881 } 6882 } 6883 6884 // Promote the function operand. 6885 // We special-case function promotion here because we only allow promoting 6886 // builtin functions to function pointers in the callee of a call. 6887 ExprResult Result; 6888 QualType ResultTy; 6889 if (BuiltinID && 6890 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6891 // Extract the return type from the (builtin) function pointer type. 6892 // FIXME Several builtins still have setType in 6893 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6894 // Builtins.def to ensure they are correct before removing setType calls. 6895 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6896 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6897 ResultTy = FDecl->getCallResultType(); 6898 } else { 6899 Result = CallExprUnaryConversions(Fn); 6900 ResultTy = Context.BoolTy; 6901 } 6902 if (Result.isInvalid()) 6903 return ExprError(); 6904 Fn = Result.get(); 6905 6906 // Check for a valid function type, but only if it is not a builtin which 6907 // requires custom type checking. These will be handled by 6908 // CheckBuiltinFunctionCall below just after creation of the call expression. 6909 const FunctionType *FuncT = nullptr; 6910 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6911 retry: 6912 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6913 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6914 // have type pointer to function". 6915 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6916 if (!FuncT) 6917 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6918 << Fn->getType() << Fn->getSourceRange()); 6919 } else if (const BlockPointerType *BPT = 6920 Fn->getType()->getAs<BlockPointerType>()) { 6921 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6922 } else { 6923 // Handle calls to expressions of unknown-any type. 6924 if (Fn->getType() == Context.UnknownAnyTy) { 6925 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6926 if (rewrite.isInvalid()) 6927 return ExprError(); 6928 Fn = rewrite.get(); 6929 goto retry; 6930 } 6931 6932 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6933 << Fn->getType() << Fn->getSourceRange()); 6934 } 6935 } 6936 6937 // Get the number of parameters in the function prototype, if any. 6938 // We will allocate space for max(Args.size(), NumParams) arguments 6939 // in the call expression. 6940 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6941 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6942 6943 CallExpr *TheCall; 6944 if (Config) { 6945 assert(UsesADL == ADLCallKind::NotADL && 6946 "CUDAKernelCallExpr should not use ADL"); 6947 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6948 Args, ResultTy, VK_PRValue, RParenLoc, 6949 CurFPFeatureOverrides(), NumParams); 6950 } else { 6951 TheCall = 6952 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6953 CurFPFeatureOverrides(), NumParams, UsesADL); 6954 } 6955 6956 if (!Context.isDependenceAllowed()) { 6957 // Forget about the nulled arguments since typo correction 6958 // do not handle them well. 6959 TheCall->shrinkNumArgs(Args.size()); 6960 // C cannot always handle TypoExpr nodes in builtin calls and direct 6961 // function calls as their argument checking don't necessarily handle 6962 // dependent types properly, so make sure any TypoExprs have been 6963 // dealt with. 6964 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6965 if (!Result.isUsable()) return ExprError(); 6966 CallExpr *TheOldCall = TheCall; 6967 TheCall = dyn_cast<CallExpr>(Result.get()); 6968 bool CorrectedTypos = TheCall != TheOldCall; 6969 if (!TheCall) return Result; 6970 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6971 6972 // A new call expression node was created if some typos were corrected. 6973 // However it may not have been constructed with enough storage. In this 6974 // case, rebuild the node with enough storage. The waste of space is 6975 // immaterial since this only happens when some typos were corrected. 6976 if (CorrectedTypos && Args.size() < NumParams) { 6977 if (Config) 6978 TheCall = CUDAKernelCallExpr::Create( 6979 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6980 RParenLoc, CurFPFeatureOverrides(), NumParams); 6981 else 6982 TheCall = 6983 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6984 CurFPFeatureOverrides(), NumParams, UsesADL); 6985 } 6986 // We can now handle the nulled arguments for the default arguments. 6987 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6988 } 6989 6990 // Bail out early if calling a builtin with custom type checking. 6991 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6992 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6993 6994 if (getLangOpts().CUDA) { 6995 if (Config) { 6996 // CUDA: Kernel calls must be to global functions 6997 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6998 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6999 << FDecl << Fn->getSourceRange()); 7000 7001 // CUDA: Kernel function must have 'void' return type 7002 if (!FuncT->getReturnType()->isVoidType() && 7003 !FuncT->getReturnType()->getAs<AutoType>() && 7004 !FuncT->getReturnType()->isInstantiationDependentType()) 7005 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 7006 << Fn->getType() << Fn->getSourceRange()); 7007 } else { 7008 // CUDA: Calls to global functions must be configured 7009 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 7010 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 7011 << FDecl << Fn->getSourceRange()); 7012 } 7013 } 7014 7015 // Check for a valid return type 7016 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 7017 FDecl)) 7018 return ExprError(); 7019 7020 // We know the result type of the call, set it. 7021 TheCall->setType(FuncT->getCallResultType(Context)); 7022 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 7023 7024 if (Proto) { 7025 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 7026 IsExecConfig)) 7027 return ExprError(); 7028 } else { 7029 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 7030 7031 if (FDecl) { 7032 // Check if we have too few/too many template arguments, based 7033 // on our knowledge of the function definition. 7034 const FunctionDecl *Def = nullptr; 7035 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 7036 Proto = Def->getType()->getAs<FunctionProtoType>(); 7037 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 7038 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 7039 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 7040 } 7041 7042 // If the function we're calling isn't a function prototype, but we have 7043 // a function prototype from a prior declaratiom, use that prototype. 7044 if (!FDecl->hasPrototype()) 7045 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 7046 } 7047 7048 // Promote the arguments (C99 6.5.2.2p6). 7049 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7050 Expr *Arg = Args[i]; 7051 7052 if (Proto && i < Proto->getNumParams()) { 7053 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7054 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 7055 ExprResult ArgE = 7056 PerformCopyInitialization(Entity, SourceLocation(), Arg); 7057 if (ArgE.isInvalid()) 7058 return true; 7059 7060 Arg = ArgE.getAs<Expr>(); 7061 7062 } else { 7063 ExprResult ArgE = DefaultArgumentPromotion(Arg); 7064 7065 if (ArgE.isInvalid()) 7066 return true; 7067 7068 Arg = ArgE.getAs<Expr>(); 7069 } 7070 7071 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 7072 diag::err_call_incomplete_argument, Arg)) 7073 return ExprError(); 7074 7075 TheCall->setArg(i, Arg); 7076 } 7077 TheCall->computeDependence(); 7078 } 7079 7080 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 7081 if (!Method->isStatic()) 7082 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 7083 << Fn->getSourceRange()); 7084 7085 // Check for sentinels 7086 if (NDecl) 7087 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 7088 7089 // Warn for unions passing across security boundary (CMSE). 7090 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 7091 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7092 if (const auto *RT = 7093 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 7094 if (RT->getDecl()->isOrContainsUnion()) 7095 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 7096 << 0 << i; 7097 } 7098 } 7099 } 7100 7101 // Do special checking on direct calls to functions. 7102 if (FDecl) { 7103 if (CheckFunctionCall(FDecl, TheCall, Proto)) 7104 return ExprError(); 7105 7106 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 7107 7108 if (BuiltinID) 7109 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7110 } else if (NDecl) { 7111 if (CheckPointerCall(NDecl, TheCall, Proto)) 7112 return ExprError(); 7113 } else { 7114 if (CheckOtherCall(TheCall, Proto)) 7115 return ExprError(); 7116 } 7117 7118 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 7119 } 7120 7121 ExprResult 7122 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 7123 SourceLocation RParenLoc, Expr *InitExpr) { 7124 assert(Ty && "ActOnCompoundLiteral(): missing type"); 7125 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 7126 7127 TypeSourceInfo *TInfo; 7128 QualType literalType = GetTypeFromParser(Ty, &TInfo); 7129 if (!TInfo) 7130 TInfo = Context.getTrivialTypeSourceInfo(literalType); 7131 7132 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 7133 } 7134 7135 ExprResult 7136 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 7137 SourceLocation RParenLoc, Expr *LiteralExpr) { 7138 QualType literalType = TInfo->getType(); 7139 7140 if (literalType->isArrayType()) { 7141 if (RequireCompleteSizedType( 7142 LParenLoc, Context.getBaseElementType(literalType), 7143 diag::err_array_incomplete_or_sizeless_type, 7144 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7145 return ExprError(); 7146 if (literalType->isVariableArrayType()) { 7147 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 7148 diag::err_variable_object_no_init)) { 7149 return ExprError(); 7150 } 7151 } 7152 } else if (!literalType->isDependentType() && 7153 RequireCompleteType(LParenLoc, literalType, 7154 diag::err_typecheck_decl_incomplete_type, 7155 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7156 return ExprError(); 7157 7158 InitializedEntity Entity 7159 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 7160 InitializationKind Kind 7161 = InitializationKind::CreateCStyleCast(LParenLoc, 7162 SourceRange(LParenLoc, RParenLoc), 7163 /*InitList=*/true); 7164 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 7165 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 7166 &literalType); 7167 if (Result.isInvalid()) 7168 return ExprError(); 7169 LiteralExpr = Result.get(); 7170 7171 bool isFileScope = !CurContext->isFunctionOrMethod(); 7172 7173 // In C, compound literals are l-values for some reason. 7174 // For GCC compatibility, in C++, file-scope array compound literals with 7175 // constant initializers are also l-values, and compound literals are 7176 // otherwise prvalues. 7177 // 7178 // (GCC also treats C++ list-initialized file-scope array prvalues with 7179 // constant initializers as l-values, but that's non-conforming, so we don't 7180 // follow it there.) 7181 // 7182 // FIXME: It would be better to handle the lvalue cases as materializing and 7183 // lifetime-extending a temporary object, but our materialized temporaries 7184 // representation only supports lifetime extension from a variable, not "out 7185 // of thin air". 7186 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7187 // is bound to the result of applying array-to-pointer decay to the compound 7188 // literal. 7189 // FIXME: GCC supports compound literals of reference type, which should 7190 // obviously have a value kind derived from the kind of reference involved. 7191 ExprValueKind VK = 7192 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7193 ? VK_PRValue 7194 : VK_LValue; 7195 7196 if (isFileScope) 7197 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7198 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7199 Expr *Init = ILE->getInit(i); 7200 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7201 } 7202 7203 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7204 VK, LiteralExpr, isFileScope); 7205 if (isFileScope) { 7206 if (!LiteralExpr->isTypeDependent() && 7207 !LiteralExpr->isValueDependent() && 7208 !literalType->isDependentType()) // C99 6.5.2.5p3 7209 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7210 return ExprError(); 7211 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7212 literalType.getAddressSpace() != LangAS::Default) { 7213 // Embedded-C extensions to C99 6.5.2.5: 7214 // "If the compound literal occurs inside the body of a function, the 7215 // type name shall not be qualified by an address-space qualifier." 7216 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7217 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7218 return ExprError(); 7219 } 7220 7221 if (!isFileScope && !getLangOpts().CPlusPlus) { 7222 // Compound literals that have automatic storage duration are destroyed at 7223 // the end of the scope in C; in C++, they're just temporaries. 7224 7225 // Emit diagnostics if it is or contains a C union type that is non-trivial 7226 // to destruct. 7227 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7228 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7229 NTCUC_CompoundLiteral, NTCUK_Destruct); 7230 7231 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7232 if (literalType.isDestructedType()) { 7233 Cleanup.setExprNeedsCleanups(true); 7234 ExprCleanupObjects.push_back(E); 7235 getCurFunction()->setHasBranchProtectedScope(); 7236 } 7237 } 7238 7239 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7240 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7241 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7242 E->getInitializer()->getExprLoc()); 7243 7244 return MaybeBindToTemporary(E); 7245 } 7246 7247 ExprResult 7248 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7249 SourceLocation RBraceLoc) { 7250 // Only produce each kind of designated initialization diagnostic once. 7251 SourceLocation FirstDesignator; 7252 bool DiagnosedArrayDesignator = false; 7253 bool DiagnosedNestedDesignator = false; 7254 bool DiagnosedMixedDesignator = false; 7255 7256 // Check that any designated initializers are syntactically valid in the 7257 // current language mode. 7258 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7259 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7260 if (FirstDesignator.isInvalid()) 7261 FirstDesignator = DIE->getBeginLoc(); 7262 7263 if (!getLangOpts().CPlusPlus) 7264 break; 7265 7266 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7267 DiagnosedNestedDesignator = true; 7268 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7269 << DIE->getDesignatorsSourceRange(); 7270 } 7271 7272 for (auto &Desig : DIE->designators()) { 7273 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7274 DiagnosedArrayDesignator = true; 7275 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7276 << Desig.getSourceRange(); 7277 } 7278 } 7279 7280 if (!DiagnosedMixedDesignator && 7281 !isa<DesignatedInitExpr>(InitArgList[0])) { 7282 DiagnosedMixedDesignator = true; 7283 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7284 << DIE->getSourceRange(); 7285 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7286 << InitArgList[0]->getSourceRange(); 7287 } 7288 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7289 isa<DesignatedInitExpr>(InitArgList[0])) { 7290 DiagnosedMixedDesignator = true; 7291 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7292 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7293 << DIE->getSourceRange(); 7294 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7295 << InitArgList[I]->getSourceRange(); 7296 } 7297 } 7298 7299 if (FirstDesignator.isValid()) { 7300 // Only diagnose designated initiaization as a C++20 extension if we didn't 7301 // already diagnose use of (non-C++20) C99 designator syntax. 7302 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7303 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7304 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7305 ? diag::warn_cxx17_compat_designated_init 7306 : diag::ext_cxx_designated_init); 7307 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7308 Diag(FirstDesignator, diag::ext_designated_init); 7309 } 7310 } 7311 7312 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7313 } 7314 7315 ExprResult 7316 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7317 SourceLocation RBraceLoc) { 7318 // Semantic analysis for initializers is done by ActOnDeclarator() and 7319 // CheckInitializer() - it requires knowledge of the object being initialized. 7320 7321 // Immediately handle non-overload placeholders. Overloads can be 7322 // resolved contextually, but everything else here can't. 7323 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7324 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7325 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7326 7327 // Ignore failures; dropping the entire initializer list because 7328 // of one failure would be terrible for indexing/etc. 7329 if (result.isInvalid()) continue; 7330 7331 InitArgList[I] = result.get(); 7332 } 7333 } 7334 7335 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7336 RBraceLoc); 7337 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7338 return E; 7339 } 7340 7341 /// Do an explicit extend of the given block pointer if we're in ARC. 7342 void Sema::maybeExtendBlockObject(ExprResult &E) { 7343 assert(E.get()->getType()->isBlockPointerType()); 7344 assert(E.get()->isPRValue()); 7345 7346 // Only do this in an r-value context. 7347 if (!getLangOpts().ObjCAutoRefCount) return; 7348 7349 E = ImplicitCastExpr::Create( 7350 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7351 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7352 Cleanup.setExprNeedsCleanups(true); 7353 } 7354 7355 /// Prepare a conversion of the given expression to an ObjC object 7356 /// pointer type. 7357 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7358 QualType type = E.get()->getType(); 7359 if (type->isObjCObjectPointerType()) { 7360 return CK_BitCast; 7361 } else if (type->isBlockPointerType()) { 7362 maybeExtendBlockObject(E); 7363 return CK_BlockPointerToObjCPointerCast; 7364 } else { 7365 assert(type->isPointerType()); 7366 return CK_CPointerToObjCPointerCast; 7367 } 7368 } 7369 7370 /// Prepares for a scalar cast, performing all the necessary stages 7371 /// except the final cast and returning the kind required. 7372 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7373 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7374 // Also, callers should have filtered out the invalid cases with 7375 // pointers. Everything else should be possible. 7376 7377 QualType SrcTy = Src.get()->getType(); 7378 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7379 return CK_NoOp; 7380 7381 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7382 case Type::STK_MemberPointer: 7383 llvm_unreachable("member pointer type in C"); 7384 7385 case Type::STK_CPointer: 7386 case Type::STK_BlockPointer: 7387 case Type::STK_ObjCObjectPointer: 7388 switch (DestTy->getScalarTypeKind()) { 7389 case Type::STK_CPointer: { 7390 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7391 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7392 if (SrcAS != DestAS) 7393 return CK_AddressSpaceConversion; 7394 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7395 return CK_NoOp; 7396 return CK_BitCast; 7397 } 7398 case Type::STK_BlockPointer: 7399 return (SrcKind == Type::STK_BlockPointer 7400 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7401 case Type::STK_ObjCObjectPointer: 7402 if (SrcKind == Type::STK_ObjCObjectPointer) 7403 return CK_BitCast; 7404 if (SrcKind == Type::STK_CPointer) 7405 return CK_CPointerToObjCPointerCast; 7406 maybeExtendBlockObject(Src); 7407 return CK_BlockPointerToObjCPointerCast; 7408 case Type::STK_Bool: 7409 return CK_PointerToBoolean; 7410 case Type::STK_Integral: 7411 return CK_PointerToIntegral; 7412 case Type::STK_Floating: 7413 case Type::STK_FloatingComplex: 7414 case Type::STK_IntegralComplex: 7415 case Type::STK_MemberPointer: 7416 case Type::STK_FixedPoint: 7417 llvm_unreachable("illegal cast from pointer"); 7418 } 7419 llvm_unreachable("Should have returned before this"); 7420 7421 case Type::STK_FixedPoint: 7422 switch (DestTy->getScalarTypeKind()) { 7423 case Type::STK_FixedPoint: 7424 return CK_FixedPointCast; 7425 case Type::STK_Bool: 7426 return CK_FixedPointToBoolean; 7427 case Type::STK_Integral: 7428 return CK_FixedPointToIntegral; 7429 case Type::STK_Floating: 7430 return CK_FixedPointToFloating; 7431 case Type::STK_IntegralComplex: 7432 case Type::STK_FloatingComplex: 7433 Diag(Src.get()->getExprLoc(), 7434 diag::err_unimplemented_conversion_with_fixed_point_type) 7435 << DestTy; 7436 return CK_IntegralCast; 7437 case Type::STK_CPointer: 7438 case Type::STK_ObjCObjectPointer: 7439 case Type::STK_BlockPointer: 7440 case Type::STK_MemberPointer: 7441 llvm_unreachable("illegal cast to pointer type"); 7442 } 7443 llvm_unreachable("Should have returned before this"); 7444 7445 case Type::STK_Bool: // casting from bool is like casting from an integer 7446 case Type::STK_Integral: 7447 switch (DestTy->getScalarTypeKind()) { 7448 case Type::STK_CPointer: 7449 case Type::STK_ObjCObjectPointer: 7450 case Type::STK_BlockPointer: 7451 if (Src.get()->isNullPointerConstant(Context, 7452 Expr::NPC_ValueDependentIsNull)) 7453 return CK_NullToPointer; 7454 return CK_IntegralToPointer; 7455 case Type::STK_Bool: 7456 return CK_IntegralToBoolean; 7457 case Type::STK_Integral: 7458 return CK_IntegralCast; 7459 case Type::STK_Floating: 7460 return CK_IntegralToFloating; 7461 case Type::STK_IntegralComplex: 7462 Src = ImpCastExprToType(Src.get(), 7463 DestTy->castAs<ComplexType>()->getElementType(), 7464 CK_IntegralCast); 7465 return CK_IntegralRealToComplex; 7466 case Type::STK_FloatingComplex: 7467 Src = ImpCastExprToType(Src.get(), 7468 DestTy->castAs<ComplexType>()->getElementType(), 7469 CK_IntegralToFloating); 7470 return CK_FloatingRealToComplex; 7471 case Type::STK_MemberPointer: 7472 llvm_unreachable("member pointer type in C"); 7473 case Type::STK_FixedPoint: 7474 return CK_IntegralToFixedPoint; 7475 } 7476 llvm_unreachable("Should have returned before this"); 7477 7478 case Type::STK_Floating: 7479 switch (DestTy->getScalarTypeKind()) { 7480 case Type::STK_Floating: 7481 return CK_FloatingCast; 7482 case Type::STK_Bool: 7483 return CK_FloatingToBoolean; 7484 case Type::STK_Integral: 7485 return CK_FloatingToIntegral; 7486 case Type::STK_FloatingComplex: 7487 Src = ImpCastExprToType(Src.get(), 7488 DestTy->castAs<ComplexType>()->getElementType(), 7489 CK_FloatingCast); 7490 return CK_FloatingRealToComplex; 7491 case Type::STK_IntegralComplex: 7492 Src = ImpCastExprToType(Src.get(), 7493 DestTy->castAs<ComplexType>()->getElementType(), 7494 CK_FloatingToIntegral); 7495 return CK_IntegralRealToComplex; 7496 case Type::STK_CPointer: 7497 case Type::STK_ObjCObjectPointer: 7498 case Type::STK_BlockPointer: 7499 llvm_unreachable("valid float->pointer cast?"); 7500 case Type::STK_MemberPointer: 7501 llvm_unreachable("member pointer type in C"); 7502 case Type::STK_FixedPoint: 7503 return CK_FloatingToFixedPoint; 7504 } 7505 llvm_unreachable("Should have returned before this"); 7506 7507 case Type::STK_FloatingComplex: 7508 switch (DestTy->getScalarTypeKind()) { 7509 case Type::STK_FloatingComplex: 7510 return CK_FloatingComplexCast; 7511 case Type::STK_IntegralComplex: 7512 return CK_FloatingComplexToIntegralComplex; 7513 case Type::STK_Floating: { 7514 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7515 if (Context.hasSameType(ET, DestTy)) 7516 return CK_FloatingComplexToReal; 7517 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7518 return CK_FloatingCast; 7519 } 7520 case Type::STK_Bool: 7521 return CK_FloatingComplexToBoolean; 7522 case Type::STK_Integral: 7523 Src = ImpCastExprToType(Src.get(), 7524 SrcTy->castAs<ComplexType>()->getElementType(), 7525 CK_FloatingComplexToReal); 7526 return CK_FloatingToIntegral; 7527 case Type::STK_CPointer: 7528 case Type::STK_ObjCObjectPointer: 7529 case Type::STK_BlockPointer: 7530 llvm_unreachable("valid complex float->pointer cast?"); 7531 case Type::STK_MemberPointer: 7532 llvm_unreachable("member pointer type in C"); 7533 case Type::STK_FixedPoint: 7534 Diag(Src.get()->getExprLoc(), 7535 diag::err_unimplemented_conversion_with_fixed_point_type) 7536 << SrcTy; 7537 return CK_IntegralCast; 7538 } 7539 llvm_unreachable("Should have returned before this"); 7540 7541 case Type::STK_IntegralComplex: 7542 switch (DestTy->getScalarTypeKind()) { 7543 case Type::STK_FloatingComplex: 7544 return CK_IntegralComplexToFloatingComplex; 7545 case Type::STK_IntegralComplex: 7546 return CK_IntegralComplexCast; 7547 case Type::STK_Integral: { 7548 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7549 if (Context.hasSameType(ET, DestTy)) 7550 return CK_IntegralComplexToReal; 7551 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7552 return CK_IntegralCast; 7553 } 7554 case Type::STK_Bool: 7555 return CK_IntegralComplexToBoolean; 7556 case Type::STK_Floating: 7557 Src = ImpCastExprToType(Src.get(), 7558 SrcTy->castAs<ComplexType>()->getElementType(), 7559 CK_IntegralComplexToReal); 7560 return CK_IntegralToFloating; 7561 case Type::STK_CPointer: 7562 case Type::STK_ObjCObjectPointer: 7563 case Type::STK_BlockPointer: 7564 llvm_unreachable("valid complex int->pointer cast?"); 7565 case Type::STK_MemberPointer: 7566 llvm_unreachable("member pointer type in C"); 7567 case Type::STK_FixedPoint: 7568 Diag(Src.get()->getExprLoc(), 7569 diag::err_unimplemented_conversion_with_fixed_point_type) 7570 << SrcTy; 7571 return CK_IntegralCast; 7572 } 7573 llvm_unreachable("Should have returned before this"); 7574 } 7575 7576 llvm_unreachable("Unhandled scalar cast"); 7577 } 7578 7579 static bool breakDownVectorType(QualType type, uint64_t &len, 7580 QualType &eltType) { 7581 // Vectors are simple. 7582 if (const VectorType *vecType = type->getAs<VectorType>()) { 7583 len = vecType->getNumElements(); 7584 eltType = vecType->getElementType(); 7585 assert(eltType->isScalarType()); 7586 return true; 7587 } 7588 7589 // We allow lax conversion to and from non-vector types, but only if 7590 // they're real types (i.e. non-complex, non-pointer scalar types). 7591 if (!type->isRealType()) return false; 7592 7593 len = 1; 7594 eltType = type; 7595 return true; 7596 } 7597 7598 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7599 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7600 /// allowed? 7601 /// 7602 /// This will also return false if the two given types do not make sense from 7603 /// the perspective of SVE bitcasts. 7604 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7605 assert(srcTy->isVectorType() || destTy->isVectorType()); 7606 7607 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7608 if (!FirstType->isSizelessBuiltinType()) 7609 return false; 7610 7611 const auto *VecTy = SecondType->getAs<VectorType>(); 7612 return VecTy && 7613 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7614 }; 7615 7616 return ValidScalableConversion(srcTy, destTy) || 7617 ValidScalableConversion(destTy, srcTy); 7618 } 7619 7620 /// Are the two types matrix types and do they have the same dimensions i.e. 7621 /// do they have the same number of rows and the same number of columns? 7622 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7623 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7624 return false; 7625 7626 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7627 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7628 7629 return matSrcType->getNumRows() == matDestType->getNumRows() && 7630 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7631 } 7632 7633 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7634 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7635 7636 uint64_t SrcLen, DestLen; 7637 QualType SrcEltTy, DestEltTy; 7638 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7639 return false; 7640 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7641 return false; 7642 7643 // ASTContext::getTypeSize will return the size rounded up to a 7644 // power of 2, so instead of using that, we need to use the raw 7645 // element size multiplied by the element count. 7646 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7647 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7648 7649 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7650 } 7651 7652 /// Are the two types lax-compatible vector types? That is, given 7653 /// that one of them is a vector, do they have equal storage sizes, 7654 /// where the storage size is the number of elements times the element 7655 /// size? 7656 /// 7657 /// This will also return false if either of the types is neither a 7658 /// vector nor a real type. 7659 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7660 assert(destTy->isVectorType() || srcTy->isVectorType()); 7661 7662 // Disallow lax conversions between scalars and ExtVectors (these 7663 // conversions are allowed for other vector types because common headers 7664 // depend on them). Most scalar OP ExtVector cases are handled by the 7665 // splat path anyway, which does what we want (convert, not bitcast). 7666 // What this rules out for ExtVectors is crazy things like char4*float. 7667 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7668 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7669 7670 return areVectorTypesSameSize(srcTy, destTy); 7671 } 7672 7673 /// Is this a legal conversion between two types, one of which is 7674 /// known to be a vector type? 7675 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7676 assert(destTy->isVectorType() || srcTy->isVectorType()); 7677 7678 switch (Context.getLangOpts().getLaxVectorConversions()) { 7679 case LangOptions::LaxVectorConversionKind::None: 7680 return false; 7681 7682 case LangOptions::LaxVectorConversionKind::Integer: 7683 if (!srcTy->isIntegralOrEnumerationType()) { 7684 auto *Vec = srcTy->getAs<VectorType>(); 7685 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7686 return false; 7687 } 7688 if (!destTy->isIntegralOrEnumerationType()) { 7689 auto *Vec = destTy->getAs<VectorType>(); 7690 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7691 return false; 7692 } 7693 // OK, integer (vector) -> integer (vector) bitcast. 7694 break; 7695 7696 case LangOptions::LaxVectorConversionKind::All: 7697 break; 7698 } 7699 7700 return areLaxCompatibleVectorTypes(srcTy, destTy); 7701 } 7702 7703 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7704 CastKind &Kind) { 7705 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7706 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7707 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7708 << DestTy << SrcTy << R; 7709 } 7710 } else if (SrcTy->isMatrixType()) { 7711 return Diag(R.getBegin(), 7712 diag::err_invalid_conversion_between_matrix_and_type) 7713 << SrcTy << DestTy << R; 7714 } else if (DestTy->isMatrixType()) { 7715 return Diag(R.getBegin(), 7716 diag::err_invalid_conversion_between_matrix_and_type) 7717 << DestTy << SrcTy << R; 7718 } 7719 7720 Kind = CK_MatrixCast; 7721 return false; 7722 } 7723 7724 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7725 CastKind &Kind) { 7726 assert(VectorTy->isVectorType() && "Not a vector type!"); 7727 7728 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7729 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7730 return Diag(R.getBegin(), 7731 Ty->isVectorType() ? 7732 diag::err_invalid_conversion_between_vectors : 7733 diag::err_invalid_conversion_between_vector_and_integer) 7734 << VectorTy << Ty << R; 7735 } else 7736 return Diag(R.getBegin(), 7737 diag::err_invalid_conversion_between_vector_and_scalar) 7738 << VectorTy << Ty << R; 7739 7740 Kind = CK_BitCast; 7741 return false; 7742 } 7743 7744 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7745 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7746 7747 if (DestElemTy == SplattedExpr->getType()) 7748 return SplattedExpr; 7749 7750 assert(DestElemTy->isFloatingType() || 7751 DestElemTy->isIntegralOrEnumerationType()); 7752 7753 CastKind CK; 7754 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7755 // OpenCL requires that we convert `true` boolean expressions to -1, but 7756 // only when splatting vectors. 7757 if (DestElemTy->isFloatingType()) { 7758 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7759 // in two steps: boolean to signed integral, then to floating. 7760 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7761 CK_BooleanToSignedIntegral); 7762 SplattedExpr = CastExprRes.get(); 7763 CK = CK_IntegralToFloating; 7764 } else { 7765 CK = CK_BooleanToSignedIntegral; 7766 } 7767 } else { 7768 ExprResult CastExprRes = SplattedExpr; 7769 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7770 if (CastExprRes.isInvalid()) 7771 return ExprError(); 7772 SplattedExpr = CastExprRes.get(); 7773 } 7774 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7775 } 7776 7777 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7778 Expr *CastExpr, CastKind &Kind) { 7779 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7780 7781 QualType SrcTy = CastExpr->getType(); 7782 7783 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7784 // an ExtVectorType. 7785 // In OpenCL, casts between vectors of different types are not allowed. 7786 // (See OpenCL 6.2). 7787 if (SrcTy->isVectorType()) { 7788 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7789 (getLangOpts().OpenCL && 7790 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7791 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7792 << DestTy << SrcTy << R; 7793 return ExprError(); 7794 } 7795 Kind = CK_BitCast; 7796 return CastExpr; 7797 } 7798 7799 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7800 // conversion will take place first from scalar to elt type, and then 7801 // splat from elt type to vector. 7802 if (SrcTy->isPointerType()) 7803 return Diag(R.getBegin(), 7804 diag::err_invalid_conversion_between_vector_and_scalar) 7805 << DestTy << SrcTy << R; 7806 7807 Kind = CK_VectorSplat; 7808 return prepareVectorSplat(DestTy, CastExpr); 7809 } 7810 7811 ExprResult 7812 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7813 Declarator &D, ParsedType &Ty, 7814 SourceLocation RParenLoc, Expr *CastExpr) { 7815 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7816 "ActOnCastExpr(): missing type or expr"); 7817 7818 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7819 if (D.isInvalidType()) 7820 return ExprError(); 7821 7822 if (getLangOpts().CPlusPlus) { 7823 // Check that there are no default arguments (C++ only). 7824 CheckExtraCXXDefaultArguments(D); 7825 } else { 7826 // Make sure any TypoExprs have been dealt with. 7827 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7828 if (!Res.isUsable()) 7829 return ExprError(); 7830 CastExpr = Res.get(); 7831 } 7832 7833 checkUnusedDeclAttributes(D); 7834 7835 QualType castType = castTInfo->getType(); 7836 Ty = CreateParsedType(castType, castTInfo); 7837 7838 bool isVectorLiteral = false; 7839 7840 // Check for an altivec or OpenCL literal, 7841 // i.e. all the elements are integer constants. 7842 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7843 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7844 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7845 && castType->isVectorType() && (PE || PLE)) { 7846 if (PLE && PLE->getNumExprs() == 0) { 7847 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7848 return ExprError(); 7849 } 7850 if (PE || PLE->getNumExprs() == 1) { 7851 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7852 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7853 isVectorLiteral = true; 7854 } 7855 else 7856 isVectorLiteral = true; 7857 } 7858 7859 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7860 // then handle it as such. 7861 if (isVectorLiteral) 7862 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7863 7864 // If the Expr being casted is a ParenListExpr, handle it specially. 7865 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7866 // sequence of BinOp comma operators. 7867 if (isa<ParenListExpr>(CastExpr)) { 7868 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7869 if (Result.isInvalid()) return ExprError(); 7870 CastExpr = Result.get(); 7871 } 7872 7873 if (getLangOpts().CPlusPlus && !castType->isVoidType()) 7874 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7875 7876 CheckTollFreeBridgeCast(castType, CastExpr); 7877 7878 CheckObjCBridgeRelatedCast(castType, CastExpr); 7879 7880 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7881 7882 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7883 } 7884 7885 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7886 SourceLocation RParenLoc, Expr *E, 7887 TypeSourceInfo *TInfo) { 7888 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7889 "Expected paren or paren list expression"); 7890 7891 Expr **exprs; 7892 unsigned numExprs; 7893 Expr *subExpr; 7894 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7895 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7896 LiteralLParenLoc = PE->getLParenLoc(); 7897 LiteralRParenLoc = PE->getRParenLoc(); 7898 exprs = PE->getExprs(); 7899 numExprs = PE->getNumExprs(); 7900 } else { // isa<ParenExpr> by assertion at function entrance 7901 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7902 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7903 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7904 exprs = &subExpr; 7905 numExprs = 1; 7906 } 7907 7908 QualType Ty = TInfo->getType(); 7909 assert(Ty->isVectorType() && "Expected vector type"); 7910 7911 SmallVector<Expr *, 8> initExprs; 7912 const VectorType *VTy = Ty->castAs<VectorType>(); 7913 unsigned numElems = VTy->getNumElements(); 7914 7915 // '(...)' form of vector initialization in AltiVec: the number of 7916 // initializers must be one or must match the size of the vector. 7917 // If a single value is specified in the initializer then it will be 7918 // replicated to all the components of the vector 7919 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7920 VTy->getElementType())) 7921 return ExprError(); 7922 if (ShouldSplatAltivecScalarInCast(VTy)) { 7923 // The number of initializers must be one or must match the size of the 7924 // vector. If a single value is specified in the initializer then it will 7925 // be replicated to all the components of the vector 7926 if (numExprs == 1) { 7927 QualType ElemTy = VTy->getElementType(); 7928 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7929 if (Literal.isInvalid()) 7930 return ExprError(); 7931 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7932 PrepareScalarCast(Literal, ElemTy)); 7933 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7934 } 7935 else if (numExprs < numElems) { 7936 Diag(E->getExprLoc(), 7937 diag::err_incorrect_number_of_vector_initializers); 7938 return ExprError(); 7939 } 7940 else 7941 initExprs.append(exprs, exprs + numExprs); 7942 } 7943 else { 7944 // For OpenCL, when the number of initializers is a single value, 7945 // it will be replicated to all components of the vector. 7946 if (getLangOpts().OpenCL && 7947 VTy->getVectorKind() == VectorType::GenericVector && 7948 numExprs == 1) { 7949 QualType ElemTy = VTy->getElementType(); 7950 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7951 if (Literal.isInvalid()) 7952 return ExprError(); 7953 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7954 PrepareScalarCast(Literal, ElemTy)); 7955 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7956 } 7957 7958 initExprs.append(exprs, exprs + numExprs); 7959 } 7960 // FIXME: This means that pretty-printing the final AST will produce curly 7961 // braces instead of the original commas. 7962 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7963 initExprs, LiteralRParenLoc); 7964 initE->setType(Ty); 7965 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7966 } 7967 7968 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7969 /// the ParenListExpr into a sequence of comma binary operators. 7970 ExprResult 7971 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7972 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7973 if (!E) 7974 return OrigExpr; 7975 7976 ExprResult Result(E->getExpr(0)); 7977 7978 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7979 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7980 E->getExpr(i)); 7981 7982 if (Result.isInvalid()) return ExprError(); 7983 7984 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7985 } 7986 7987 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7988 SourceLocation R, 7989 MultiExprArg Val) { 7990 return ParenListExpr::Create(Context, L, Val, R); 7991 } 7992 7993 /// Emit a specialized diagnostic when one expression is a null pointer 7994 /// constant and the other is not a pointer. Returns true if a diagnostic is 7995 /// emitted. 7996 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7997 SourceLocation QuestionLoc) { 7998 Expr *NullExpr = LHSExpr; 7999 Expr *NonPointerExpr = RHSExpr; 8000 Expr::NullPointerConstantKind NullKind = 8001 NullExpr->isNullPointerConstant(Context, 8002 Expr::NPC_ValueDependentIsNotNull); 8003 8004 if (NullKind == Expr::NPCK_NotNull) { 8005 NullExpr = RHSExpr; 8006 NonPointerExpr = LHSExpr; 8007 NullKind = 8008 NullExpr->isNullPointerConstant(Context, 8009 Expr::NPC_ValueDependentIsNotNull); 8010 } 8011 8012 if (NullKind == Expr::NPCK_NotNull) 8013 return false; 8014 8015 if (NullKind == Expr::NPCK_ZeroExpression) 8016 return false; 8017 8018 if (NullKind == Expr::NPCK_ZeroLiteral) { 8019 // In this case, check to make sure that we got here from a "NULL" 8020 // string in the source code. 8021 NullExpr = NullExpr->IgnoreParenImpCasts(); 8022 SourceLocation loc = NullExpr->getExprLoc(); 8023 if (!findMacroSpelling(loc, "NULL")) 8024 return false; 8025 } 8026 8027 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 8028 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 8029 << NonPointerExpr->getType() << DiagType 8030 << NonPointerExpr->getSourceRange(); 8031 return true; 8032 } 8033 8034 /// Return false if the condition expression is valid, true otherwise. 8035 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 8036 QualType CondTy = Cond->getType(); 8037 8038 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 8039 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 8040 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8041 << CondTy << Cond->getSourceRange(); 8042 return true; 8043 } 8044 8045 // C99 6.5.15p2 8046 if (CondTy->isScalarType()) return false; 8047 8048 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 8049 << CondTy << Cond->getSourceRange(); 8050 return true; 8051 } 8052 8053 /// Handle when one or both operands are void type. 8054 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 8055 ExprResult &RHS) { 8056 Expr *LHSExpr = LHS.get(); 8057 Expr *RHSExpr = RHS.get(); 8058 8059 if (!LHSExpr->getType()->isVoidType()) 8060 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8061 << RHSExpr->getSourceRange(); 8062 if (!RHSExpr->getType()->isVoidType()) 8063 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8064 << LHSExpr->getSourceRange(); 8065 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 8066 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 8067 return S.Context.VoidTy; 8068 } 8069 8070 /// Return false if the NullExpr can be promoted to PointerTy, 8071 /// true otherwise. 8072 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 8073 QualType PointerTy) { 8074 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 8075 !NullExpr.get()->isNullPointerConstant(S.Context, 8076 Expr::NPC_ValueDependentIsNull)) 8077 return true; 8078 8079 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 8080 return false; 8081 } 8082 8083 /// Checks compatibility between two pointers and return the resulting 8084 /// type. 8085 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 8086 ExprResult &RHS, 8087 SourceLocation Loc) { 8088 QualType LHSTy = LHS.get()->getType(); 8089 QualType RHSTy = RHS.get()->getType(); 8090 8091 if (S.Context.hasSameType(LHSTy, RHSTy)) { 8092 // Two identical pointers types are always compatible. 8093 return LHSTy; 8094 } 8095 8096 QualType lhptee, rhptee; 8097 8098 // Get the pointee types. 8099 bool IsBlockPointer = false; 8100 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 8101 lhptee = LHSBTy->getPointeeType(); 8102 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 8103 IsBlockPointer = true; 8104 } else { 8105 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8106 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8107 } 8108 8109 // C99 6.5.15p6: If both operands are pointers to compatible types or to 8110 // differently qualified versions of compatible types, the result type is 8111 // a pointer to an appropriately qualified version of the composite 8112 // type. 8113 8114 // Only CVR-qualifiers exist in the standard, and the differently-qualified 8115 // clause doesn't make sense for our extensions. E.g. address space 2 should 8116 // be incompatible with address space 3: they may live on different devices or 8117 // anything. 8118 Qualifiers lhQual = lhptee.getQualifiers(); 8119 Qualifiers rhQual = rhptee.getQualifiers(); 8120 8121 LangAS ResultAddrSpace = LangAS::Default; 8122 LangAS LAddrSpace = lhQual.getAddressSpace(); 8123 LangAS RAddrSpace = rhQual.getAddressSpace(); 8124 8125 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 8126 // spaces is disallowed. 8127 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 8128 ResultAddrSpace = LAddrSpace; 8129 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 8130 ResultAddrSpace = RAddrSpace; 8131 else { 8132 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8133 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 8134 << RHS.get()->getSourceRange(); 8135 return QualType(); 8136 } 8137 8138 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 8139 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 8140 lhQual.removeCVRQualifiers(); 8141 rhQual.removeCVRQualifiers(); 8142 8143 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 8144 // (C99 6.7.3) for address spaces. We assume that the check should behave in 8145 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 8146 // qual types are compatible iff 8147 // * corresponded types are compatible 8148 // * CVR qualifiers are equal 8149 // * address spaces are equal 8150 // Thus for conditional operator we merge CVR and address space unqualified 8151 // pointees and if there is a composite type we return a pointer to it with 8152 // merged qualifiers. 8153 LHSCastKind = 8154 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8155 RHSCastKind = 8156 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8157 lhQual.removeAddressSpace(); 8158 rhQual.removeAddressSpace(); 8159 8160 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 8161 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 8162 8163 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 8164 8165 if (CompositeTy.isNull()) { 8166 // In this situation, we assume void* type. No especially good 8167 // reason, but this is what gcc does, and we do have to pick 8168 // to get a consistent AST. 8169 QualType incompatTy; 8170 incompatTy = S.Context.getPointerType( 8171 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 8172 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 8173 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 8174 8175 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 8176 // for casts between types with incompatible address space qualifiers. 8177 // For the following code the compiler produces casts between global and 8178 // local address spaces of the corresponded innermost pointees: 8179 // local int *global *a; 8180 // global int *global *b; 8181 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8182 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8183 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8184 << RHS.get()->getSourceRange(); 8185 8186 return incompatTy; 8187 } 8188 8189 // The pointer types are compatible. 8190 // In case of OpenCL ResultTy should have the address space qualifier 8191 // which is a superset of address spaces of both the 2nd and the 3rd 8192 // operands of the conditional operator. 8193 QualType ResultTy = [&, ResultAddrSpace]() { 8194 if (S.getLangOpts().OpenCL) { 8195 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8196 CompositeQuals.setAddressSpace(ResultAddrSpace); 8197 return S.Context 8198 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8199 .withCVRQualifiers(MergedCVRQual); 8200 } 8201 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8202 }(); 8203 if (IsBlockPointer) 8204 ResultTy = S.Context.getBlockPointerType(ResultTy); 8205 else 8206 ResultTy = S.Context.getPointerType(ResultTy); 8207 8208 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8209 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8210 return ResultTy; 8211 } 8212 8213 /// Return the resulting type when the operands are both block pointers. 8214 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8215 ExprResult &LHS, 8216 ExprResult &RHS, 8217 SourceLocation Loc) { 8218 QualType LHSTy = LHS.get()->getType(); 8219 QualType RHSTy = RHS.get()->getType(); 8220 8221 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8222 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8223 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8224 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8225 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8226 return destType; 8227 } 8228 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8229 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8230 << RHS.get()->getSourceRange(); 8231 return QualType(); 8232 } 8233 8234 // We have 2 block pointer types. 8235 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8236 } 8237 8238 /// Return the resulting type when the operands are both pointers. 8239 static QualType 8240 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8241 ExprResult &RHS, 8242 SourceLocation Loc) { 8243 // get the pointer types 8244 QualType LHSTy = LHS.get()->getType(); 8245 QualType RHSTy = RHS.get()->getType(); 8246 8247 // get the "pointed to" types 8248 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8249 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8250 8251 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8252 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8253 // Figure out necessary qualifiers (C99 6.5.15p6) 8254 QualType destPointee 8255 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8256 QualType destType = S.Context.getPointerType(destPointee); 8257 // Add qualifiers if necessary. 8258 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8259 // Promote to void*. 8260 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8261 return destType; 8262 } 8263 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8264 QualType destPointee 8265 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8266 QualType destType = S.Context.getPointerType(destPointee); 8267 // Add qualifiers if necessary. 8268 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8269 // Promote to void*. 8270 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8271 return destType; 8272 } 8273 8274 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8275 } 8276 8277 /// Return false if the first expression is not an integer and the second 8278 /// expression is not a pointer, true otherwise. 8279 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8280 Expr* PointerExpr, SourceLocation Loc, 8281 bool IsIntFirstExpr) { 8282 if (!PointerExpr->getType()->isPointerType() || 8283 !Int.get()->getType()->isIntegerType()) 8284 return false; 8285 8286 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8287 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8288 8289 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8290 << Expr1->getType() << Expr2->getType() 8291 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8292 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8293 CK_IntegralToPointer); 8294 return true; 8295 } 8296 8297 /// Simple conversion between integer and floating point types. 8298 /// 8299 /// Used when handling the OpenCL conditional operator where the 8300 /// condition is a vector while the other operands are scalar. 8301 /// 8302 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8303 /// types are either integer or floating type. Between the two 8304 /// operands, the type with the higher rank is defined as the "result 8305 /// type". The other operand needs to be promoted to the same type. No 8306 /// other type promotion is allowed. We cannot use 8307 /// UsualArithmeticConversions() for this purpose, since it always 8308 /// promotes promotable types. 8309 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8310 ExprResult &RHS, 8311 SourceLocation QuestionLoc) { 8312 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8313 if (LHS.isInvalid()) 8314 return QualType(); 8315 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8316 if (RHS.isInvalid()) 8317 return QualType(); 8318 8319 // For conversion purposes, we ignore any qualifiers. 8320 // For example, "const float" and "float" are equivalent. 8321 QualType LHSType = 8322 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8323 QualType RHSType = 8324 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8325 8326 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8327 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8328 << LHSType << LHS.get()->getSourceRange(); 8329 return QualType(); 8330 } 8331 8332 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8333 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8334 << RHSType << RHS.get()->getSourceRange(); 8335 return QualType(); 8336 } 8337 8338 // If both types are identical, no conversion is needed. 8339 if (LHSType == RHSType) 8340 return LHSType; 8341 8342 // Now handle "real" floating types (i.e. float, double, long double). 8343 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8344 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8345 /*IsCompAssign = */ false); 8346 8347 // Finally, we have two differing integer types. 8348 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8349 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8350 } 8351 8352 /// Convert scalar operands to a vector that matches the 8353 /// condition in length. 8354 /// 8355 /// Used when handling the OpenCL conditional operator where the 8356 /// condition is a vector while the other operands are scalar. 8357 /// 8358 /// We first compute the "result type" for the scalar operands 8359 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8360 /// into a vector of that type where the length matches the condition 8361 /// vector type. s6.11.6 requires that the element types of the result 8362 /// and the condition must have the same number of bits. 8363 static QualType 8364 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8365 QualType CondTy, SourceLocation QuestionLoc) { 8366 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8367 if (ResTy.isNull()) return QualType(); 8368 8369 const VectorType *CV = CondTy->getAs<VectorType>(); 8370 assert(CV); 8371 8372 // Determine the vector result type 8373 unsigned NumElements = CV->getNumElements(); 8374 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8375 8376 // Ensure that all types have the same number of bits 8377 if (S.Context.getTypeSize(CV->getElementType()) 8378 != S.Context.getTypeSize(ResTy)) { 8379 // Since VectorTy is created internally, it does not pretty print 8380 // with an OpenCL name. Instead, we just print a description. 8381 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8382 SmallString<64> Str; 8383 llvm::raw_svector_ostream OS(Str); 8384 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8385 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8386 << CondTy << OS.str(); 8387 return QualType(); 8388 } 8389 8390 // Convert operands to the vector result type 8391 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8392 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8393 8394 return VectorTy; 8395 } 8396 8397 /// Return false if this is a valid OpenCL condition vector 8398 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8399 SourceLocation QuestionLoc) { 8400 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8401 // integral type. 8402 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8403 assert(CondTy); 8404 QualType EleTy = CondTy->getElementType(); 8405 if (EleTy->isIntegerType()) return false; 8406 8407 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8408 << Cond->getType() << Cond->getSourceRange(); 8409 return true; 8410 } 8411 8412 /// Return false if the vector condition type and the vector 8413 /// result type are compatible. 8414 /// 8415 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8416 /// number of elements, and their element types have the same number 8417 /// of bits. 8418 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8419 SourceLocation QuestionLoc) { 8420 const VectorType *CV = CondTy->getAs<VectorType>(); 8421 const VectorType *RV = VecResTy->getAs<VectorType>(); 8422 assert(CV && RV); 8423 8424 if (CV->getNumElements() != RV->getNumElements()) { 8425 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8426 << CondTy << VecResTy; 8427 return true; 8428 } 8429 8430 QualType CVE = CV->getElementType(); 8431 QualType RVE = RV->getElementType(); 8432 8433 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8434 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8435 << CondTy << VecResTy; 8436 return true; 8437 } 8438 8439 return false; 8440 } 8441 8442 /// Return the resulting type for the conditional operator in 8443 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8444 /// s6.3.i) when the condition is a vector type. 8445 static QualType 8446 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8447 ExprResult &LHS, ExprResult &RHS, 8448 SourceLocation QuestionLoc) { 8449 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8450 if (Cond.isInvalid()) 8451 return QualType(); 8452 QualType CondTy = Cond.get()->getType(); 8453 8454 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8455 return QualType(); 8456 8457 // If either operand is a vector then find the vector type of the 8458 // result as specified in OpenCL v1.1 s6.3.i. 8459 if (LHS.get()->getType()->isVectorType() || 8460 RHS.get()->getType()->isVectorType()) { 8461 bool IsBoolVecLang = 8462 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; 8463 QualType VecResTy = 8464 S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8465 /*isCompAssign*/ false, 8466 /*AllowBothBool*/ true, 8467 /*AllowBoolConversions*/ false, 8468 /*AllowBooleanOperation*/ IsBoolVecLang, 8469 /*ReportInvalid*/ true); 8470 if (VecResTy.isNull()) 8471 return QualType(); 8472 // The result type must match the condition type as specified in 8473 // OpenCL v1.1 s6.11.6. 8474 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8475 return QualType(); 8476 return VecResTy; 8477 } 8478 8479 // Both operands are scalar. 8480 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8481 } 8482 8483 /// Return true if the Expr is block type 8484 static bool checkBlockType(Sema &S, const Expr *E) { 8485 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8486 QualType Ty = CE->getCallee()->getType(); 8487 if (Ty->isBlockPointerType()) { 8488 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8489 return true; 8490 } 8491 } 8492 return false; 8493 } 8494 8495 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8496 /// In that case, LHS = cond. 8497 /// C99 6.5.15 8498 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8499 ExprResult &RHS, ExprValueKind &VK, 8500 ExprObjectKind &OK, 8501 SourceLocation QuestionLoc) { 8502 8503 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8504 if (!LHSResult.isUsable()) return QualType(); 8505 LHS = LHSResult; 8506 8507 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8508 if (!RHSResult.isUsable()) return QualType(); 8509 RHS = RHSResult; 8510 8511 // C++ is sufficiently different to merit its own checker. 8512 if (getLangOpts().CPlusPlus) 8513 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8514 8515 VK = VK_PRValue; 8516 OK = OK_Ordinary; 8517 8518 if (Context.isDependenceAllowed() && 8519 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8520 RHS.get()->isTypeDependent())) { 8521 assert(!getLangOpts().CPlusPlus); 8522 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8523 RHS.get()->containsErrors()) && 8524 "should only occur in error-recovery path."); 8525 return Context.DependentTy; 8526 } 8527 8528 // The OpenCL operator with a vector condition is sufficiently 8529 // different to merit its own checker. 8530 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8531 Cond.get()->getType()->isExtVectorType()) 8532 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8533 8534 // First, check the condition. 8535 Cond = UsualUnaryConversions(Cond.get()); 8536 if (Cond.isInvalid()) 8537 return QualType(); 8538 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8539 return QualType(); 8540 8541 // Now check the two expressions. 8542 if (LHS.get()->getType()->isVectorType() || 8543 RHS.get()->getType()->isVectorType()) 8544 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, 8545 /*AllowBothBool*/ true, 8546 /*AllowBoolConversions*/ false, 8547 /*AllowBooleanOperation*/ false, 8548 /*ReportInvalid*/ true); 8549 8550 QualType ResTy = 8551 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8552 if (LHS.isInvalid() || RHS.isInvalid()) 8553 return QualType(); 8554 8555 QualType LHSTy = LHS.get()->getType(); 8556 QualType RHSTy = RHS.get()->getType(); 8557 8558 // Diagnose attempts to convert between __ibm128, __float128 and long double 8559 // where such conversions currently can't be handled. 8560 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8561 Diag(QuestionLoc, 8562 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8563 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8564 return QualType(); 8565 } 8566 8567 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8568 // selection operator (?:). 8569 if (getLangOpts().OpenCL && 8570 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8571 return QualType(); 8572 } 8573 8574 // If both operands have arithmetic type, do the usual arithmetic conversions 8575 // to find a common type: C99 6.5.15p3,5. 8576 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8577 // Disallow invalid arithmetic conversions, such as those between bit- 8578 // precise integers types of different sizes, or between a bit-precise 8579 // integer and another type. 8580 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { 8581 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8582 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8583 << RHS.get()->getSourceRange(); 8584 return QualType(); 8585 } 8586 8587 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8588 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8589 8590 return ResTy; 8591 } 8592 8593 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8594 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8595 return LHSTy; 8596 } 8597 8598 // If both operands are the same structure or union type, the result is that 8599 // type. 8600 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8601 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8602 if (LHSRT->getDecl() == RHSRT->getDecl()) 8603 // "If both the operands have structure or union type, the result has 8604 // that type." This implies that CV qualifiers are dropped. 8605 return LHSTy.getUnqualifiedType(); 8606 // FIXME: Type of conditional expression must be complete in C mode. 8607 } 8608 8609 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8610 // The following || allows only one side to be void (a GCC-ism). 8611 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8612 return checkConditionalVoidType(*this, LHS, RHS); 8613 } 8614 8615 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8616 // the type of the other operand." 8617 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8618 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8619 8620 // All objective-c pointer type analysis is done here. 8621 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8622 QuestionLoc); 8623 if (LHS.isInvalid() || RHS.isInvalid()) 8624 return QualType(); 8625 if (!compositeType.isNull()) 8626 return compositeType; 8627 8628 8629 // Handle block pointer types. 8630 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8631 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8632 QuestionLoc); 8633 8634 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8635 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8636 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8637 QuestionLoc); 8638 8639 // GCC compatibility: soften pointer/integer mismatch. Note that 8640 // null pointers have been filtered out by this point. 8641 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8642 /*IsIntFirstExpr=*/true)) 8643 return RHSTy; 8644 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8645 /*IsIntFirstExpr=*/false)) 8646 return LHSTy; 8647 8648 // Allow ?: operations in which both operands have the same 8649 // built-in sizeless type. 8650 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8651 return LHSTy; 8652 8653 // Emit a better diagnostic if one of the expressions is a null pointer 8654 // constant and the other is not a pointer type. In this case, the user most 8655 // likely forgot to take the address of the other expression. 8656 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8657 return QualType(); 8658 8659 // Otherwise, the operands are not compatible. 8660 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8661 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8662 << RHS.get()->getSourceRange(); 8663 return QualType(); 8664 } 8665 8666 /// FindCompositeObjCPointerType - Helper method to find composite type of 8667 /// two objective-c pointer types of the two input expressions. 8668 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8669 SourceLocation QuestionLoc) { 8670 QualType LHSTy = LHS.get()->getType(); 8671 QualType RHSTy = RHS.get()->getType(); 8672 8673 // Handle things like Class and struct objc_class*. Here we case the result 8674 // to the pseudo-builtin, because that will be implicitly cast back to the 8675 // redefinition type if an attempt is made to access its fields. 8676 if (LHSTy->isObjCClassType() && 8677 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8678 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8679 return LHSTy; 8680 } 8681 if (RHSTy->isObjCClassType() && 8682 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8683 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8684 return RHSTy; 8685 } 8686 // And the same for struct objc_object* / id 8687 if (LHSTy->isObjCIdType() && 8688 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8689 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8690 return LHSTy; 8691 } 8692 if (RHSTy->isObjCIdType() && 8693 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8694 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8695 return RHSTy; 8696 } 8697 // And the same for struct objc_selector* / SEL 8698 if (Context.isObjCSelType(LHSTy) && 8699 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8700 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8701 return LHSTy; 8702 } 8703 if (Context.isObjCSelType(RHSTy) && 8704 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8705 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8706 return RHSTy; 8707 } 8708 // Check constraints for Objective-C object pointers types. 8709 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8710 8711 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8712 // Two identical object pointer types are always compatible. 8713 return LHSTy; 8714 } 8715 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8716 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8717 QualType compositeType = LHSTy; 8718 8719 // If both operands are interfaces and either operand can be 8720 // assigned to the other, use that type as the composite 8721 // type. This allows 8722 // xxx ? (A*) a : (B*) b 8723 // where B is a subclass of A. 8724 // 8725 // Additionally, as for assignment, if either type is 'id' 8726 // allow silent coercion. Finally, if the types are 8727 // incompatible then make sure to use 'id' as the composite 8728 // type so the result is acceptable for sending messages to. 8729 8730 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8731 // It could return the composite type. 8732 if (!(compositeType = 8733 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8734 // Nothing more to do. 8735 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8736 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8737 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8738 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8739 } else if ((LHSOPT->isObjCQualifiedIdType() || 8740 RHSOPT->isObjCQualifiedIdType()) && 8741 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8742 true)) { 8743 // Need to handle "id<xx>" explicitly. 8744 // GCC allows qualified id and any Objective-C type to devolve to 8745 // id. Currently localizing to here until clear this should be 8746 // part of ObjCQualifiedIdTypesAreCompatible. 8747 compositeType = Context.getObjCIdType(); 8748 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8749 compositeType = Context.getObjCIdType(); 8750 } else { 8751 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8752 << LHSTy << RHSTy 8753 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8754 QualType incompatTy = Context.getObjCIdType(); 8755 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8756 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8757 return incompatTy; 8758 } 8759 // The object pointer types are compatible. 8760 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8761 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8762 return compositeType; 8763 } 8764 // Check Objective-C object pointer types and 'void *' 8765 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8766 if (getLangOpts().ObjCAutoRefCount) { 8767 // ARC forbids the implicit conversion of object pointers to 'void *', 8768 // so these types are not compatible. 8769 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8770 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8771 LHS = RHS = true; 8772 return QualType(); 8773 } 8774 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8775 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8776 QualType destPointee 8777 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8778 QualType destType = Context.getPointerType(destPointee); 8779 // Add qualifiers if necessary. 8780 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8781 // Promote to void*. 8782 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8783 return destType; 8784 } 8785 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8786 if (getLangOpts().ObjCAutoRefCount) { 8787 // ARC forbids the implicit conversion of object pointers to 'void *', 8788 // so these types are not compatible. 8789 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8790 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8791 LHS = RHS = true; 8792 return QualType(); 8793 } 8794 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8795 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8796 QualType destPointee 8797 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8798 QualType destType = Context.getPointerType(destPointee); 8799 // Add qualifiers if necessary. 8800 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8801 // Promote to void*. 8802 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8803 return destType; 8804 } 8805 return QualType(); 8806 } 8807 8808 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8809 /// ParenRange in parentheses. 8810 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8811 const PartialDiagnostic &Note, 8812 SourceRange ParenRange) { 8813 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8814 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8815 EndLoc.isValid()) { 8816 Self.Diag(Loc, Note) 8817 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8818 << FixItHint::CreateInsertion(EndLoc, ")"); 8819 } else { 8820 // We can't display the parentheses, so just show the bare note. 8821 Self.Diag(Loc, Note) << ParenRange; 8822 } 8823 } 8824 8825 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8826 return BinaryOperator::isAdditiveOp(Opc) || 8827 BinaryOperator::isMultiplicativeOp(Opc) || 8828 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8829 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8830 // not any of the logical operators. Bitwise-xor is commonly used as a 8831 // logical-xor because there is no logical-xor operator. The logical 8832 // operators, including uses of xor, have a high false positive rate for 8833 // precedence warnings. 8834 } 8835 8836 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8837 /// expression, either using a built-in or overloaded operator, 8838 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8839 /// expression. 8840 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8841 Expr **RHSExprs) { 8842 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8843 E = E->IgnoreImpCasts(); 8844 E = E->IgnoreConversionOperatorSingleStep(); 8845 E = E->IgnoreImpCasts(); 8846 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8847 E = MTE->getSubExpr(); 8848 E = E->IgnoreImpCasts(); 8849 } 8850 8851 // Built-in binary operator. 8852 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8853 if (IsArithmeticOp(OP->getOpcode())) { 8854 *Opcode = OP->getOpcode(); 8855 *RHSExprs = OP->getRHS(); 8856 return true; 8857 } 8858 } 8859 8860 // Overloaded operator. 8861 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8862 if (Call->getNumArgs() != 2) 8863 return false; 8864 8865 // Make sure this is really a binary operator that is safe to pass into 8866 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8867 OverloadedOperatorKind OO = Call->getOperator(); 8868 if (OO < OO_Plus || OO > OO_Arrow || 8869 OO == OO_PlusPlus || OO == OO_MinusMinus) 8870 return false; 8871 8872 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8873 if (IsArithmeticOp(OpKind)) { 8874 *Opcode = OpKind; 8875 *RHSExprs = Call->getArg(1); 8876 return true; 8877 } 8878 } 8879 8880 return false; 8881 } 8882 8883 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8884 /// or is a logical expression such as (x==y) which has int type, but is 8885 /// commonly interpreted as boolean. 8886 static bool ExprLooksBoolean(Expr *E) { 8887 E = E->IgnoreParenImpCasts(); 8888 8889 if (E->getType()->isBooleanType()) 8890 return true; 8891 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8892 return OP->isComparisonOp() || OP->isLogicalOp(); 8893 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8894 return OP->getOpcode() == UO_LNot; 8895 if (E->getType()->isPointerType()) 8896 return true; 8897 // FIXME: What about overloaded operator calls returning "unspecified boolean 8898 // type"s (commonly pointer-to-members)? 8899 8900 return false; 8901 } 8902 8903 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8904 /// and binary operator are mixed in a way that suggests the programmer assumed 8905 /// the conditional operator has higher precedence, for example: 8906 /// "int x = a + someBinaryCondition ? 1 : 2". 8907 static void DiagnoseConditionalPrecedence(Sema &Self, 8908 SourceLocation OpLoc, 8909 Expr *Condition, 8910 Expr *LHSExpr, 8911 Expr *RHSExpr) { 8912 BinaryOperatorKind CondOpcode; 8913 Expr *CondRHS; 8914 8915 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8916 return; 8917 if (!ExprLooksBoolean(CondRHS)) 8918 return; 8919 8920 // The condition is an arithmetic binary expression, with a right- 8921 // hand side that looks boolean, so warn. 8922 8923 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8924 ? diag::warn_precedence_bitwise_conditional 8925 : diag::warn_precedence_conditional; 8926 8927 Self.Diag(OpLoc, DiagID) 8928 << Condition->getSourceRange() 8929 << BinaryOperator::getOpcodeStr(CondOpcode); 8930 8931 SuggestParentheses( 8932 Self, OpLoc, 8933 Self.PDiag(diag::note_precedence_silence) 8934 << BinaryOperator::getOpcodeStr(CondOpcode), 8935 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8936 8937 SuggestParentheses(Self, OpLoc, 8938 Self.PDiag(diag::note_precedence_conditional_first), 8939 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8940 } 8941 8942 /// Compute the nullability of a conditional expression. 8943 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8944 QualType LHSTy, QualType RHSTy, 8945 ASTContext &Ctx) { 8946 if (!ResTy->isAnyPointerType()) 8947 return ResTy; 8948 8949 auto GetNullability = [&Ctx](QualType Ty) { 8950 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8951 if (Kind) { 8952 // For our purposes, treat _Nullable_result as _Nullable. 8953 if (*Kind == NullabilityKind::NullableResult) 8954 return NullabilityKind::Nullable; 8955 return *Kind; 8956 } 8957 return NullabilityKind::Unspecified; 8958 }; 8959 8960 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8961 NullabilityKind MergedKind; 8962 8963 // Compute nullability of a binary conditional expression. 8964 if (IsBin) { 8965 if (LHSKind == NullabilityKind::NonNull) 8966 MergedKind = NullabilityKind::NonNull; 8967 else 8968 MergedKind = RHSKind; 8969 // Compute nullability of a normal conditional expression. 8970 } else { 8971 if (LHSKind == NullabilityKind::Nullable || 8972 RHSKind == NullabilityKind::Nullable) 8973 MergedKind = NullabilityKind::Nullable; 8974 else if (LHSKind == NullabilityKind::NonNull) 8975 MergedKind = RHSKind; 8976 else if (RHSKind == NullabilityKind::NonNull) 8977 MergedKind = LHSKind; 8978 else 8979 MergedKind = NullabilityKind::Unspecified; 8980 } 8981 8982 // Return if ResTy already has the correct nullability. 8983 if (GetNullability(ResTy) == MergedKind) 8984 return ResTy; 8985 8986 // Strip all nullability from ResTy. 8987 while (ResTy->getNullability(Ctx)) 8988 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8989 8990 // Create a new AttributedType with the new nullability kind. 8991 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8992 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8993 } 8994 8995 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8996 /// in the case of a the GNU conditional expr extension. 8997 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8998 SourceLocation ColonLoc, 8999 Expr *CondExpr, Expr *LHSExpr, 9000 Expr *RHSExpr) { 9001 if (!Context.isDependenceAllowed()) { 9002 // C cannot handle TypoExpr nodes in the condition because it 9003 // doesn't handle dependent types properly, so make sure any TypoExprs have 9004 // been dealt with before checking the operands. 9005 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 9006 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 9007 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 9008 9009 if (!CondResult.isUsable()) 9010 return ExprError(); 9011 9012 if (LHSExpr) { 9013 if (!LHSResult.isUsable()) 9014 return ExprError(); 9015 } 9016 9017 if (!RHSResult.isUsable()) 9018 return ExprError(); 9019 9020 CondExpr = CondResult.get(); 9021 LHSExpr = LHSResult.get(); 9022 RHSExpr = RHSResult.get(); 9023 } 9024 9025 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 9026 // was the condition. 9027 OpaqueValueExpr *opaqueValue = nullptr; 9028 Expr *commonExpr = nullptr; 9029 if (!LHSExpr) { 9030 commonExpr = CondExpr; 9031 // Lower out placeholder types first. This is important so that we don't 9032 // try to capture a placeholder. This happens in few cases in C++; such 9033 // as Objective-C++'s dictionary subscripting syntax. 9034 if (commonExpr->hasPlaceholderType()) { 9035 ExprResult result = CheckPlaceholderExpr(commonExpr); 9036 if (!result.isUsable()) return ExprError(); 9037 commonExpr = result.get(); 9038 } 9039 // We usually want to apply unary conversions *before* saving, except 9040 // in the special case of a C++ l-value conditional. 9041 if (!(getLangOpts().CPlusPlus 9042 && !commonExpr->isTypeDependent() 9043 && commonExpr->getValueKind() == RHSExpr->getValueKind() 9044 && commonExpr->isGLValue() 9045 && commonExpr->isOrdinaryOrBitFieldObject() 9046 && RHSExpr->isOrdinaryOrBitFieldObject() 9047 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 9048 ExprResult commonRes = UsualUnaryConversions(commonExpr); 9049 if (commonRes.isInvalid()) 9050 return ExprError(); 9051 commonExpr = commonRes.get(); 9052 } 9053 9054 // If the common expression is a class or array prvalue, materialize it 9055 // so that we can safely refer to it multiple times. 9056 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 9057 commonExpr->getType()->isArrayType())) { 9058 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 9059 if (MatExpr.isInvalid()) 9060 return ExprError(); 9061 commonExpr = MatExpr.get(); 9062 } 9063 9064 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 9065 commonExpr->getType(), 9066 commonExpr->getValueKind(), 9067 commonExpr->getObjectKind(), 9068 commonExpr); 9069 LHSExpr = CondExpr = opaqueValue; 9070 } 9071 9072 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 9073 ExprValueKind VK = VK_PRValue; 9074 ExprObjectKind OK = OK_Ordinary; 9075 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 9076 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 9077 VK, OK, QuestionLoc); 9078 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 9079 RHS.isInvalid()) 9080 return ExprError(); 9081 9082 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 9083 RHS.get()); 9084 9085 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 9086 9087 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 9088 Context); 9089 9090 if (!commonExpr) 9091 return new (Context) 9092 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 9093 RHS.get(), result, VK, OK); 9094 9095 return new (Context) BinaryConditionalOperator( 9096 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 9097 ColonLoc, result, VK, OK); 9098 } 9099 9100 // Check if we have a conversion between incompatible cmse function pointer 9101 // types, that is, a conversion between a function pointer with the 9102 // cmse_nonsecure_call attribute and one without. 9103 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 9104 QualType ToType) { 9105 if (const auto *ToFn = 9106 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 9107 if (const auto *FromFn = 9108 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 9109 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 9110 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 9111 9112 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 9113 } 9114 } 9115 return false; 9116 } 9117 9118 // checkPointerTypesForAssignment - This is a very tricky routine (despite 9119 // being closely modeled after the C99 spec:-). The odd characteristic of this 9120 // routine is it effectively iqnores the qualifiers on the top level pointee. 9121 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 9122 // FIXME: add a couple examples in this comment. 9123 static Sema::AssignConvertType 9124 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 9125 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9126 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9127 9128 // get the "pointed to" type (ignoring qualifiers at the top level) 9129 const Type *lhptee, *rhptee; 9130 Qualifiers lhq, rhq; 9131 std::tie(lhptee, lhq) = 9132 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 9133 std::tie(rhptee, rhq) = 9134 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 9135 9136 Sema::AssignConvertType ConvTy = Sema::Compatible; 9137 9138 // C99 6.5.16.1p1: This following citation is common to constraints 9139 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 9140 // qualifiers of the type *pointed to* by the right; 9141 9142 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 9143 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 9144 lhq.compatiblyIncludesObjCLifetime(rhq)) { 9145 // Ignore lifetime for further calculation. 9146 lhq.removeObjCLifetime(); 9147 rhq.removeObjCLifetime(); 9148 } 9149 9150 if (!lhq.compatiblyIncludes(rhq)) { 9151 // Treat address-space mismatches as fatal. 9152 if (!lhq.isAddressSpaceSupersetOf(rhq)) 9153 return Sema::IncompatiblePointerDiscardsQualifiers; 9154 9155 // It's okay to add or remove GC or lifetime qualifiers when converting to 9156 // and from void*. 9157 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 9158 .compatiblyIncludes( 9159 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 9160 && (lhptee->isVoidType() || rhptee->isVoidType())) 9161 ; // keep old 9162 9163 // Treat lifetime mismatches as fatal. 9164 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 9165 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 9166 9167 // For GCC/MS compatibility, other qualifier mismatches are treated 9168 // as still compatible in C. 9169 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9170 } 9171 9172 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 9173 // incomplete type and the other is a pointer to a qualified or unqualified 9174 // version of void... 9175 if (lhptee->isVoidType()) { 9176 if (rhptee->isIncompleteOrObjectType()) 9177 return ConvTy; 9178 9179 // As an extension, we allow cast to/from void* to function pointer. 9180 assert(rhptee->isFunctionType()); 9181 return Sema::FunctionVoidPointer; 9182 } 9183 9184 if (rhptee->isVoidType()) { 9185 if (lhptee->isIncompleteOrObjectType()) 9186 return ConvTy; 9187 9188 // As an extension, we allow cast to/from void* to function pointer. 9189 assert(lhptee->isFunctionType()); 9190 return Sema::FunctionVoidPointer; 9191 } 9192 9193 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9194 // unqualified versions of compatible types, ... 9195 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9196 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9197 // Check if the pointee types are compatible ignoring the sign. 9198 // We explicitly check for char so that we catch "char" vs 9199 // "unsigned char" on systems where "char" is unsigned. 9200 if (lhptee->isCharType()) 9201 ltrans = S.Context.UnsignedCharTy; 9202 else if (lhptee->hasSignedIntegerRepresentation()) 9203 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9204 9205 if (rhptee->isCharType()) 9206 rtrans = S.Context.UnsignedCharTy; 9207 else if (rhptee->hasSignedIntegerRepresentation()) 9208 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9209 9210 if (ltrans == rtrans) { 9211 // Types are compatible ignoring the sign. Qualifier incompatibility 9212 // takes priority over sign incompatibility because the sign 9213 // warning can be disabled. 9214 if (ConvTy != Sema::Compatible) 9215 return ConvTy; 9216 9217 return Sema::IncompatiblePointerSign; 9218 } 9219 9220 // If we are a multi-level pointer, it's possible that our issue is simply 9221 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9222 // the eventual target type is the same and the pointers have the same 9223 // level of indirection, this must be the issue. 9224 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9225 do { 9226 std::tie(lhptee, lhq) = 9227 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9228 std::tie(rhptee, rhq) = 9229 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9230 9231 // Inconsistent address spaces at this point is invalid, even if the 9232 // address spaces would be compatible. 9233 // FIXME: This doesn't catch address space mismatches for pointers of 9234 // different nesting levels, like: 9235 // __local int *** a; 9236 // int ** b = a; 9237 // It's not clear how to actually determine when such pointers are 9238 // invalidly incompatible. 9239 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9240 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9241 9242 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9243 9244 if (lhptee == rhptee) 9245 return Sema::IncompatibleNestedPointerQualifiers; 9246 } 9247 9248 // General pointer incompatibility takes priority over qualifiers. 9249 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9250 return Sema::IncompatibleFunctionPointer; 9251 return Sema::IncompatiblePointer; 9252 } 9253 if (!S.getLangOpts().CPlusPlus && 9254 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9255 return Sema::IncompatibleFunctionPointer; 9256 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9257 return Sema::IncompatibleFunctionPointer; 9258 return ConvTy; 9259 } 9260 9261 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9262 /// block pointer types are compatible or whether a block and normal pointer 9263 /// are compatible. It is more restrict than comparing two function pointer 9264 // types. 9265 static Sema::AssignConvertType 9266 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9267 QualType RHSType) { 9268 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9269 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9270 9271 QualType lhptee, rhptee; 9272 9273 // get the "pointed to" type (ignoring qualifiers at the top level) 9274 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9275 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9276 9277 // In C++, the types have to match exactly. 9278 if (S.getLangOpts().CPlusPlus) 9279 return Sema::IncompatibleBlockPointer; 9280 9281 Sema::AssignConvertType ConvTy = Sema::Compatible; 9282 9283 // For blocks we enforce that qualifiers are identical. 9284 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9285 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9286 if (S.getLangOpts().OpenCL) { 9287 LQuals.removeAddressSpace(); 9288 RQuals.removeAddressSpace(); 9289 } 9290 if (LQuals != RQuals) 9291 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9292 9293 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9294 // assignment. 9295 // The current behavior is similar to C++ lambdas. A block might be 9296 // assigned to a variable iff its return type and parameters are compatible 9297 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9298 // an assignment. Presumably it should behave in way that a function pointer 9299 // assignment does in C, so for each parameter and return type: 9300 // * CVR and address space of LHS should be a superset of CVR and address 9301 // space of RHS. 9302 // * unqualified types should be compatible. 9303 if (S.getLangOpts().OpenCL) { 9304 if (!S.Context.typesAreBlockPointerCompatible( 9305 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9306 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9307 return Sema::IncompatibleBlockPointer; 9308 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9309 return Sema::IncompatibleBlockPointer; 9310 9311 return ConvTy; 9312 } 9313 9314 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9315 /// for assignment compatibility. 9316 static Sema::AssignConvertType 9317 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9318 QualType RHSType) { 9319 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9320 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9321 9322 if (LHSType->isObjCBuiltinType()) { 9323 // Class is not compatible with ObjC object pointers. 9324 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9325 !RHSType->isObjCQualifiedClassType()) 9326 return Sema::IncompatiblePointer; 9327 return Sema::Compatible; 9328 } 9329 if (RHSType->isObjCBuiltinType()) { 9330 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9331 !LHSType->isObjCQualifiedClassType()) 9332 return Sema::IncompatiblePointer; 9333 return Sema::Compatible; 9334 } 9335 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9336 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9337 9338 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9339 // make an exception for id<P> 9340 !LHSType->isObjCQualifiedIdType()) 9341 return Sema::CompatiblePointerDiscardsQualifiers; 9342 9343 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9344 return Sema::Compatible; 9345 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9346 return Sema::IncompatibleObjCQualifiedId; 9347 return Sema::IncompatiblePointer; 9348 } 9349 9350 Sema::AssignConvertType 9351 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9352 QualType LHSType, QualType RHSType) { 9353 // Fake up an opaque expression. We don't actually care about what 9354 // cast operations are required, so if CheckAssignmentConstraints 9355 // adds casts to this they'll be wasted, but fortunately that doesn't 9356 // usually happen on valid code. 9357 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9358 ExprResult RHSPtr = &RHSExpr; 9359 CastKind K; 9360 9361 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9362 } 9363 9364 /// This helper function returns true if QT is a vector type that has element 9365 /// type ElementType. 9366 static bool isVector(QualType QT, QualType ElementType) { 9367 if (const VectorType *VT = QT->getAs<VectorType>()) 9368 return VT->getElementType().getCanonicalType() == ElementType; 9369 return false; 9370 } 9371 9372 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9373 /// has code to accommodate several GCC extensions when type checking 9374 /// pointers. Here are some objectionable examples that GCC considers warnings: 9375 /// 9376 /// int a, *pint; 9377 /// short *pshort; 9378 /// struct foo *pfoo; 9379 /// 9380 /// pint = pshort; // warning: assignment from incompatible pointer type 9381 /// a = pint; // warning: assignment makes integer from pointer without a cast 9382 /// pint = a; // warning: assignment makes pointer from integer without a cast 9383 /// pint = pfoo; // warning: assignment from incompatible pointer type 9384 /// 9385 /// As a result, the code for dealing with pointers is more complex than the 9386 /// C99 spec dictates. 9387 /// 9388 /// Sets 'Kind' for any result kind except Incompatible. 9389 Sema::AssignConvertType 9390 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9391 CastKind &Kind, bool ConvertRHS) { 9392 QualType RHSType = RHS.get()->getType(); 9393 QualType OrigLHSType = LHSType; 9394 9395 // Get canonical types. We're not formatting these types, just comparing 9396 // them. 9397 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9398 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9399 9400 // Common case: no conversion required. 9401 if (LHSType == RHSType) { 9402 Kind = CK_NoOp; 9403 return Compatible; 9404 } 9405 9406 // If the LHS has an __auto_type, there are no additional type constraints 9407 // to be worried about. 9408 if (const auto *AT = dyn_cast<AutoType>(LHSType)) { 9409 if (AT->isGNUAutoType()) { 9410 Kind = CK_NoOp; 9411 return Compatible; 9412 } 9413 } 9414 9415 // If we have an atomic type, try a non-atomic assignment, then just add an 9416 // atomic qualification step. 9417 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9418 Sema::AssignConvertType result = 9419 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9420 if (result != Compatible) 9421 return result; 9422 if (Kind != CK_NoOp && ConvertRHS) 9423 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9424 Kind = CK_NonAtomicToAtomic; 9425 return Compatible; 9426 } 9427 9428 // If the left-hand side is a reference type, then we are in a 9429 // (rare!) case where we've allowed the use of references in C, 9430 // e.g., as a parameter type in a built-in function. In this case, 9431 // just make sure that the type referenced is compatible with the 9432 // right-hand side type. The caller is responsible for adjusting 9433 // LHSType so that the resulting expression does not have reference 9434 // type. 9435 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9436 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9437 Kind = CK_LValueBitCast; 9438 return Compatible; 9439 } 9440 return Incompatible; 9441 } 9442 9443 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9444 // to the same ExtVector type. 9445 if (LHSType->isExtVectorType()) { 9446 if (RHSType->isExtVectorType()) 9447 return Incompatible; 9448 if (RHSType->isArithmeticType()) { 9449 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9450 if (ConvertRHS) 9451 RHS = prepareVectorSplat(LHSType, RHS.get()); 9452 Kind = CK_VectorSplat; 9453 return Compatible; 9454 } 9455 } 9456 9457 // Conversions to or from vector type. 9458 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9459 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9460 // Allow assignments of an AltiVec vector type to an equivalent GCC 9461 // vector type and vice versa 9462 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9463 Kind = CK_BitCast; 9464 return Compatible; 9465 } 9466 9467 // If we are allowing lax vector conversions, and LHS and RHS are both 9468 // vectors, the total size only needs to be the same. This is a bitcast; 9469 // no bits are changed but the result type is different. 9470 if (isLaxVectorConversion(RHSType, LHSType)) { 9471 Kind = CK_BitCast; 9472 return IncompatibleVectors; 9473 } 9474 } 9475 9476 // When the RHS comes from another lax conversion (e.g. binops between 9477 // scalars and vectors) the result is canonicalized as a vector. When the 9478 // LHS is also a vector, the lax is allowed by the condition above. Handle 9479 // the case where LHS is a scalar. 9480 if (LHSType->isScalarType()) { 9481 const VectorType *VecType = RHSType->getAs<VectorType>(); 9482 if (VecType && VecType->getNumElements() == 1 && 9483 isLaxVectorConversion(RHSType, LHSType)) { 9484 ExprResult *VecExpr = &RHS; 9485 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9486 Kind = CK_BitCast; 9487 return Compatible; 9488 } 9489 } 9490 9491 // Allow assignments between fixed-length and sizeless SVE vectors. 9492 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9493 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9494 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9495 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9496 Kind = CK_BitCast; 9497 return Compatible; 9498 } 9499 9500 return Incompatible; 9501 } 9502 9503 // Diagnose attempts to convert between __ibm128, __float128 and long double 9504 // where such conversions currently can't be handled. 9505 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9506 return Incompatible; 9507 9508 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9509 // discards the imaginary part. 9510 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9511 !LHSType->getAs<ComplexType>()) 9512 return Incompatible; 9513 9514 // Arithmetic conversions. 9515 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9516 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9517 if (ConvertRHS) 9518 Kind = PrepareScalarCast(RHS, LHSType); 9519 return Compatible; 9520 } 9521 9522 // Conversions to normal pointers. 9523 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9524 // U* -> T* 9525 if (isa<PointerType>(RHSType)) { 9526 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9527 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9528 if (AddrSpaceL != AddrSpaceR) 9529 Kind = CK_AddressSpaceConversion; 9530 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9531 Kind = CK_NoOp; 9532 else 9533 Kind = CK_BitCast; 9534 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9535 } 9536 9537 // int -> T* 9538 if (RHSType->isIntegerType()) { 9539 Kind = CK_IntegralToPointer; // FIXME: null? 9540 return IntToPointer; 9541 } 9542 9543 // C pointers are not compatible with ObjC object pointers, 9544 // with two exceptions: 9545 if (isa<ObjCObjectPointerType>(RHSType)) { 9546 // - conversions to void* 9547 if (LHSPointer->getPointeeType()->isVoidType()) { 9548 Kind = CK_BitCast; 9549 return Compatible; 9550 } 9551 9552 // - conversions from 'Class' to the redefinition type 9553 if (RHSType->isObjCClassType() && 9554 Context.hasSameType(LHSType, 9555 Context.getObjCClassRedefinitionType())) { 9556 Kind = CK_BitCast; 9557 return Compatible; 9558 } 9559 9560 Kind = CK_BitCast; 9561 return IncompatiblePointer; 9562 } 9563 9564 // U^ -> void* 9565 if (RHSType->getAs<BlockPointerType>()) { 9566 if (LHSPointer->getPointeeType()->isVoidType()) { 9567 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9568 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9569 ->getPointeeType() 9570 .getAddressSpace(); 9571 Kind = 9572 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9573 return Compatible; 9574 } 9575 } 9576 9577 return Incompatible; 9578 } 9579 9580 // Conversions to block pointers. 9581 if (isa<BlockPointerType>(LHSType)) { 9582 // U^ -> T^ 9583 if (RHSType->isBlockPointerType()) { 9584 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9585 ->getPointeeType() 9586 .getAddressSpace(); 9587 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9588 ->getPointeeType() 9589 .getAddressSpace(); 9590 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9591 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9592 } 9593 9594 // int or null -> T^ 9595 if (RHSType->isIntegerType()) { 9596 Kind = CK_IntegralToPointer; // FIXME: null 9597 return IntToBlockPointer; 9598 } 9599 9600 // id -> T^ 9601 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9602 Kind = CK_AnyPointerToBlockPointerCast; 9603 return Compatible; 9604 } 9605 9606 // void* -> T^ 9607 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9608 if (RHSPT->getPointeeType()->isVoidType()) { 9609 Kind = CK_AnyPointerToBlockPointerCast; 9610 return Compatible; 9611 } 9612 9613 return Incompatible; 9614 } 9615 9616 // Conversions to Objective-C pointers. 9617 if (isa<ObjCObjectPointerType>(LHSType)) { 9618 // A* -> B* 9619 if (RHSType->isObjCObjectPointerType()) { 9620 Kind = CK_BitCast; 9621 Sema::AssignConvertType result = 9622 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9623 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9624 result == Compatible && 9625 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9626 result = IncompatibleObjCWeakRef; 9627 return result; 9628 } 9629 9630 // int or null -> A* 9631 if (RHSType->isIntegerType()) { 9632 Kind = CK_IntegralToPointer; // FIXME: null 9633 return IntToPointer; 9634 } 9635 9636 // In general, C pointers are not compatible with ObjC object pointers, 9637 // with two exceptions: 9638 if (isa<PointerType>(RHSType)) { 9639 Kind = CK_CPointerToObjCPointerCast; 9640 9641 // - conversions from 'void*' 9642 if (RHSType->isVoidPointerType()) { 9643 return Compatible; 9644 } 9645 9646 // - conversions to 'Class' from its redefinition type 9647 if (LHSType->isObjCClassType() && 9648 Context.hasSameType(RHSType, 9649 Context.getObjCClassRedefinitionType())) { 9650 return Compatible; 9651 } 9652 9653 return IncompatiblePointer; 9654 } 9655 9656 // Only under strict condition T^ is compatible with an Objective-C pointer. 9657 if (RHSType->isBlockPointerType() && 9658 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9659 if (ConvertRHS) 9660 maybeExtendBlockObject(RHS); 9661 Kind = CK_BlockPointerToObjCPointerCast; 9662 return Compatible; 9663 } 9664 9665 return Incompatible; 9666 } 9667 9668 // Conversions from pointers that are not covered by the above. 9669 if (isa<PointerType>(RHSType)) { 9670 // T* -> _Bool 9671 if (LHSType == Context.BoolTy) { 9672 Kind = CK_PointerToBoolean; 9673 return Compatible; 9674 } 9675 9676 // T* -> int 9677 if (LHSType->isIntegerType()) { 9678 Kind = CK_PointerToIntegral; 9679 return PointerToInt; 9680 } 9681 9682 return Incompatible; 9683 } 9684 9685 // Conversions from Objective-C pointers that are not covered by the above. 9686 if (isa<ObjCObjectPointerType>(RHSType)) { 9687 // T* -> _Bool 9688 if (LHSType == Context.BoolTy) { 9689 Kind = CK_PointerToBoolean; 9690 return Compatible; 9691 } 9692 9693 // T* -> int 9694 if (LHSType->isIntegerType()) { 9695 Kind = CK_PointerToIntegral; 9696 return PointerToInt; 9697 } 9698 9699 return Incompatible; 9700 } 9701 9702 // struct A -> struct B 9703 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9704 if (Context.typesAreCompatible(LHSType, RHSType)) { 9705 Kind = CK_NoOp; 9706 return Compatible; 9707 } 9708 } 9709 9710 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9711 Kind = CK_IntToOCLSampler; 9712 return Compatible; 9713 } 9714 9715 return Incompatible; 9716 } 9717 9718 /// Constructs a transparent union from an expression that is 9719 /// used to initialize the transparent union. 9720 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9721 ExprResult &EResult, QualType UnionType, 9722 FieldDecl *Field) { 9723 // Build an initializer list that designates the appropriate member 9724 // of the transparent union. 9725 Expr *E = EResult.get(); 9726 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9727 E, SourceLocation()); 9728 Initializer->setType(UnionType); 9729 Initializer->setInitializedFieldInUnion(Field); 9730 9731 // Build a compound literal constructing a value of the transparent 9732 // union type from this initializer list. 9733 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9734 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9735 VK_PRValue, Initializer, false); 9736 } 9737 9738 Sema::AssignConvertType 9739 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9740 ExprResult &RHS) { 9741 QualType RHSType = RHS.get()->getType(); 9742 9743 // If the ArgType is a Union type, we want to handle a potential 9744 // transparent_union GCC extension. 9745 const RecordType *UT = ArgType->getAsUnionType(); 9746 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9747 return Incompatible; 9748 9749 // The field to initialize within the transparent union. 9750 RecordDecl *UD = UT->getDecl(); 9751 FieldDecl *InitField = nullptr; 9752 // It's compatible if the expression matches any of the fields. 9753 for (auto *it : UD->fields()) { 9754 if (it->getType()->isPointerType()) { 9755 // If the transparent union contains a pointer type, we allow: 9756 // 1) void pointer 9757 // 2) null pointer constant 9758 if (RHSType->isPointerType()) 9759 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9760 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9761 InitField = it; 9762 break; 9763 } 9764 9765 if (RHS.get()->isNullPointerConstant(Context, 9766 Expr::NPC_ValueDependentIsNull)) { 9767 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9768 CK_NullToPointer); 9769 InitField = it; 9770 break; 9771 } 9772 } 9773 9774 CastKind Kind; 9775 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9776 == Compatible) { 9777 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9778 InitField = it; 9779 break; 9780 } 9781 } 9782 9783 if (!InitField) 9784 return Incompatible; 9785 9786 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9787 return Compatible; 9788 } 9789 9790 Sema::AssignConvertType 9791 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9792 bool Diagnose, 9793 bool DiagnoseCFAudited, 9794 bool ConvertRHS) { 9795 // We need to be able to tell the caller whether we diagnosed a problem, if 9796 // they ask us to issue diagnostics. 9797 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9798 9799 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9800 // we can't avoid *all* modifications at the moment, so we need some somewhere 9801 // to put the updated value. 9802 ExprResult LocalRHS = CallerRHS; 9803 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9804 9805 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9806 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9807 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9808 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9809 Diag(RHS.get()->getExprLoc(), 9810 diag::warn_noderef_to_dereferenceable_pointer) 9811 << RHS.get()->getSourceRange(); 9812 } 9813 } 9814 } 9815 9816 if (getLangOpts().CPlusPlus) { 9817 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9818 // C++ 5.17p3: If the left operand is not of class type, the 9819 // expression is implicitly converted (C++ 4) to the 9820 // cv-unqualified type of the left operand. 9821 QualType RHSType = RHS.get()->getType(); 9822 if (Diagnose) { 9823 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9824 AA_Assigning); 9825 } else { 9826 ImplicitConversionSequence ICS = 9827 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9828 /*SuppressUserConversions=*/false, 9829 AllowedExplicit::None, 9830 /*InOverloadResolution=*/false, 9831 /*CStyle=*/false, 9832 /*AllowObjCWritebackConversion=*/false); 9833 if (ICS.isFailure()) 9834 return Incompatible; 9835 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9836 ICS, AA_Assigning); 9837 } 9838 if (RHS.isInvalid()) 9839 return Incompatible; 9840 Sema::AssignConvertType result = Compatible; 9841 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9842 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9843 result = IncompatibleObjCWeakRef; 9844 return result; 9845 } 9846 9847 // FIXME: Currently, we fall through and treat C++ classes like C 9848 // structures. 9849 // FIXME: We also fall through for atomics; not sure what should 9850 // happen there, though. 9851 } else if (RHS.get()->getType() == Context.OverloadTy) { 9852 // As a set of extensions to C, we support overloading on functions. These 9853 // functions need to be resolved here. 9854 DeclAccessPair DAP; 9855 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9856 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9857 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9858 else 9859 return Incompatible; 9860 } 9861 9862 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9863 // a null pointer constant. 9864 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9865 LHSType->isBlockPointerType()) && 9866 RHS.get()->isNullPointerConstant(Context, 9867 Expr::NPC_ValueDependentIsNull)) { 9868 if (Diagnose || ConvertRHS) { 9869 CastKind Kind; 9870 CXXCastPath Path; 9871 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9872 /*IgnoreBaseAccess=*/false, Diagnose); 9873 if (ConvertRHS) 9874 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9875 } 9876 return Compatible; 9877 } 9878 9879 // OpenCL queue_t type assignment. 9880 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9881 Context, Expr::NPC_ValueDependentIsNull)) { 9882 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9883 return Compatible; 9884 } 9885 9886 // This check seems unnatural, however it is necessary to ensure the proper 9887 // conversion of functions/arrays. If the conversion were done for all 9888 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9889 // expressions that suppress this implicit conversion (&, sizeof). 9890 // 9891 // Suppress this for references: C++ 8.5.3p5. 9892 if (!LHSType->isReferenceType()) { 9893 // FIXME: We potentially allocate here even if ConvertRHS is false. 9894 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9895 if (RHS.isInvalid()) 9896 return Incompatible; 9897 } 9898 CastKind Kind; 9899 Sema::AssignConvertType result = 9900 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9901 9902 // C99 6.5.16.1p2: The value of the right operand is converted to the 9903 // type of the assignment expression. 9904 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9905 // so that we can use references in built-in functions even in C. 9906 // The getNonReferenceType() call makes sure that the resulting expression 9907 // does not have reference type. 9908 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9909 QualType Ty = LHSType.getNonLValueExprType(Context); 9910 Expr *E = RHS.get(); 9911 9912 // Check for various Objective-C errors. If we are not reporting 9913 // diagnostics and just checking for errors, e.g., during overload 9914 // resolution, return Incompatible to indicate the failure. 9915 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9916 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9917 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9918 if (!Diagnose) 9919 return Incompatible; 9920 } 9921 if (getLangOpts().ObjC && 9922 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9923 E->getType(), E, Diagnose) || 9924 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9925 if (!Diagnose) 9926 return Incompatible; 9927 // Replace the expression with a corrected version and continue so we 9928 // can find further errors. 9929 RHS = E; 9930 return Compatible; 9931 } 9932 9933 if (ConvertRHS) 9934 RHS = ImpCastExprToType(E, Ty, Kind); 9935 } 9936 9937 return result; 9938 } 9939 9940 namespace { 9941 /// The original operand to an operator, prior to the application of the usual 9942 /// arithmetic conversions and converting the arguments of a builtin operator 9943 /// candidate. 9944 struct OriginalOperand { 9945 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9946 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9947 Op = MTE->getSubExpr(); 9948 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9949 Op = BTE->getSubExpr(); 9950 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9951 Orig = ICE->getSubExprAsWritten(); 9952 Conversion = ICE->getConversionFunction(); 9953 } 9954 } 9955 9956 QualType getType() const { return Orig->getType(); } 9957 9958 Expr *Orig; 9959 NamedDecl *Conversion; 9960 }; 9961 } 9962 9963 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9964 ExprResult &RHS) { 9965 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9966 9967 Diag(Loc, diag::err_typecheck_invalid_operands) 9968 << OrigLHS.getType() << OrigRHS.getType() 9969 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9970 9971 // If a user-defined conversion was applied to either of the operands prior 9972 // to applying the built-in operator rules, tell the user about it. 9973 if (OrigLHS.Conversion) { 9974 Diag(OrigLHS.Conversion->getLocation(), 9975 diag::note_typecheck_invalid_operands_converted) 9976 << 0 << LHS.get()->getType(); 9977 } 9978 if (OrigRHS.Conversion) { 9979 Diag(OrigRHS.Conversion->getLocation(), 9980 diag::note_typecheck_invalid_operands_converted) 9981 << 1 << RHS.get()->getType(); 9982 } 9983 9984 return QualType(); 9985 } 9986 9987 // Diagnose cases where a scalar was implicitly converted to a vector and 9988 // diagnose the underlying types. Otherwise, diagnose the error 9989 // as invalid vector logical operands for non-C++ cases. 9990 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9991 ExprResult &RHS) { 9992 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9993 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9994 9995 bool LHSNatVec = LHSType->isVectorType(); 9996 bool RHSNatVec = RHSType->isVectorType(); 9997 9998 if (!(LHSNatVec && RHSNatVec)) { 9999 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 10000 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 10001 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10002 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 10003 << Vector->getSourceRange(); 10004 return QualType(); 10005 } 10006 10007 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10008 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 10009 << RHS.get()->getSourceRange(); 10010 10011 return QualType(); 10012 } 10013 10014 /// Try to convert a value of non-vector type to a vector type by converting 10015 /// the type to the element type of the vector and then performing a splat. 10016 /// If the language is OpenCL, we only use conversions that promote scalar 10017 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 10018 /// for float->int. 10019 /// 10020 /// OpenCL V2.0 6.2.6.p2: 10021 /// An error shall occur if any scalar operand type has greater rank 10022 /// than the type of the vector element. 10023 /// 10024 /// \param scalar - if non-null, actually perform the conversions 10025 /// \return true if the operation fails (but without diagnosing the failure) 10026 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 10027 QualType scalarTy, 10028 QualType vectorEltTy, 10029 QualType vectorTy, 10030 unsigned &DiagID) { 10031 // The conversion to apply to the scalar before splatting it, 10032 // if necessary. 10033 CastKind scalarCast = CK_NoOp; 10034 10035 if (vectorEltTy->isIntegralType(S.Context)) { 10036 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 10037 (scalarTy->isIntegerType() && 10038 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 10039 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10040 return true; 10041 } 10042 if (!scalarTy->isIntegralType(S.Context)) 10043 return true; 10044 scalarCast = CK_IntegralCast; 10045 } else if (vectorEltTy->isRealFloatingType()) { 10046 if (scalarTy->isRealFloatingType()) { 10047 if (S.getLangOpts().OpenCL && 10048 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 10049 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10050 return true; 10051 } 10052 scalarCast = CK_FloatingCast; 10053 } 10054 else if (scalarTy->isIntegralType(S.Context)) 10055 scalarCast = CK_IntegralToFloating; 10056 else 10057 return true; 10058 } else { 10059 return true; 10060 } 10061 10062 // Adjust scalar if desired. 10063 if (scalar) { 10064 if (scalarCast != CK_NoOp) 10065 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 10066 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 10067 } 10068 return false; 10069 } 10070 10071 /// Convert vector E to a vector with the same number of elements but different 10072 /// element type. 10073 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 10074 const auto *VecTy = E->getType()->getAs<VectorType>(); 10075 assert(VecTy && "Expression E must be a vector"); 10076 QualType NewVecTy = 10077 VecTy->isExtVectorType() 10078 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements()) 10079 : S.Context.getVectorType(ElementType, VecTy->getNumElements(), 10080 VecTy->getVectorKind()); 10081 10082 // Look through the implicit cast. Return the subexpression if its type is 10083 // NewVecTy. 10084 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10085 if (ICE->getSubExpr()->getType() == NewVecTy) 10086 return ICE->getSubExpr(); 10087 10088 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 10089 return S.ImpCastExprToType(E, NewVecTy, Cast); 10090 } 10091 10092 /// Test if a (constant) integer Int can be casted to another integer type 10093 /// IntTy without losing precision. 10094 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 10095 QualType OtherIntTy) { 10096 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10097 10098 // Reject cases where the value of the Int is unknown as that would 10099 // possibly cause truncation, but accept cases where the scalar can be 10100 // demoted without loss of precision. 10101 Expr::EvalResult EVResult; 10102 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10103 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 10104 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 10105 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 10106 10107 if (CstInt) { 10108 // If the scalar is constant and is of a higher order and has more active 10109 // bits that the vector element type, reject it. 10110 llvm::APSInt Result = EVResult.Val.getInt(); 10111 unsigned NumBits = IntSigned 10112 ? (Result.isNegative() ? Result.getMinSignedBits() 10113 : Result.getActiveBits()) 10114 : Result.getActiveBits(); 10115 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 10116 return true; 10117 10118 // If the signedness of the scalar type and the vector element type 10119 // differs and the number of bits is greater than that of the vector 10120 // element reject it. 10121 return (IntSigned != OtherIntSigned && 10122 NumBits > S.Context.getIntWidth(OtherIntTy)); 10123 } 10124 10125 // Reject cases where the value of the scalar is not constant and it's 10126 // order is greater than that of the vector element type. 10127 return (Order < 0); 10128 } 10129 10130 /// Test if a (constant) integer Int can be casted to floating point type 10131 /// FloatTy without losing precision. 10132 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 10133 QualType FloatTy) { 10134 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10135 10136 // Determine if the integer constant can be expressed as a floating point 10137 // number of the appropriate type. 10138 Expr::EvalResult EVResult; 10139 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10140 10141 uint64_t Bits = 0; 10142 if (CstInt) { 10143 // Reject constants that would be truncated if they were converted to 10144 // the floating point type. Test by simple to/from conversion. 10145 // FIXME: Ideally the conversion to an APFloat and from an APFloat 10146 // could be avoided if there was a convertFromAPInt method 10147 // which could signal back if implicit truncation occurred. 10148 llvm::APSInt Result = EVResult.Val.getInt(); 10149 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 10150 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 10151 llvm::APFloat::rmTowardZero); 10152 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 10153 !IntTy->hasSignedIntegerRepresentation()); 10154 bool Ignored = false; 10155 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 10156 &Ignored); 10157 if (Result != ConvertBack) 10158 return true; 10159 } else { 10160 // Reject types that cannot be fully encoded into the mantissa of 10161 // the float. 10162 Bits = S.Context.getTypeSize(IntTy); 10163 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 10164 S.Context.getFloatTypeSemantics(FloatTy)); 10165 if (Bits > FloatPrec) 10166 return true; 10167 } 10168 10169 return false; 10170 } 10171 10172 /// Attempt to convert and splat Scalar into a vector whose types matches 10173 /// Vector following GCC conversion rules. The rule is that implicit 10174 /// conversion can occur when Scalar can be casted to match Vector's element 10175 /// type without causing truncation of Scalar. 10176 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 10177 ExprResult *Vector) { 10178 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 10179 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 10180 const auto *VT = VectorTy->castAs<VectorType>(); 10181 10182 assert(!isa<ExtVectorType>(VT) && 10183 "ExtVectorTypes should not be handled here!"); 10184 10185 QualType VectorEltTy = VT->getElementType(); 10186 10187 // Reject cases where the vector element type or the scalar element type are 10188 // not integral or floating point types. 10189 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 10190 return true; 10191 10192 // The conversion to apply to the scalar before splatting it, 10193 // if necessary. 10194 CastKind ScalarCast = CK_NoOp; 10195 10196 // Accept cases where the vector elements are integers and the scalar is 10197 // an integer. 10198 // FIXME: Notionally if the scalar was a floating point value with a precise 10199 // integral representation, we could cast it to an appropriate integer 10200 // type and then perform the rest of the checks here. GCC will perform 10201 // this conversion in some cases as determined by the input language. 10202 // We should accept it on a language independent basis. 10203 if (VectorEltTy->isIntegralType(S.Context) && 10204 ScalarTy->isIntegralType(S.Context) && 10205 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10206 10207 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10208 return true; 10209 10210 ScalarCast = CK_IntegralCast; 10211 } else if (VectorEltTy->isIntegralType(S.Context) && 10212 ScalarTy->isRealFloatingType()) { 10213 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10214 ScalarCast = CK_FloatingToIntegral; 10215 else 10216 return true; 10217 } else if (VectorEltTy->isRealFloatingType()) { 10218 if (ScalarTy->isRealFloatingType()) { 10219 10220 // Reject cases where the scalar type is not a constant and has a higher 10221 // Order than the vector element type. 10222 llvm::APFloat Result(0.0); 10223 10224 // Determine whether this is a constant scalar. In the event that the 10225 // value is dependent (and thus cannot be evaluated by the constant 10226 // evaluator), skip the evaluation. This will then diagnose once the 10227 // expression is instantiated. 10228 bool CstScalar = Scalar->get()->isValueDependent() || 10229 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10230 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10231 if (!CstScalar && Order < 0) 10232 return true; 10233 10234 // If the scalar cannot be safely casted to the vector element type, 10235 // reject it. 10236 if (CstScalar) { 10237 bool Truncated = false; 10238 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10239 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10240 if (Truncated) 10241 return true; 10242 } 10243 10244 ScalarCast = CK_FloatingCast; 10245 } else if (ScalarTy->isIntegralType(S.Context)) { 10246 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10247 return true; 10248 10249 ScalarCast = CK_IntegralToFloating; 10250 } else 10251 return true; 10252 } else if (ScalarTy->isEnumeralType()) 10253 return true; 10254 10255 // Adjust scalar if desired. 10256 if (Scalar) { 10257 if (ScalarCast != CK_NoOp) 10258 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10259 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10260 } 10261 return false; 10262 } 10263 10264 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10265 SourceLocation Loc, bool IsCompAssign, 10266 bool AllowBothBool, 10267 bool AllowBoolConversions, 10268 bool AllowBoolOperation, 10269 bool ReportInvalid) { 10270 if (!IsCompAssign) { 10271 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10272 if (LHS.isInvalid()) 10273 return QualType(); 10274 } 10275 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10276 if (RHS.isInvalid()) 10277 return QualType(); 10278 10279 // For conversion purposes, we ignore any qualifiers. 10280 // For example, "const float" and "float" are equivalent. 10281 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10282 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10283 10284 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10285 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10286 assert(LHSVecType || RHSVecType); 10287 10288 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10289 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10290 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10291 10292 // AltiVec-style "vector bool op vector bool" combinations are allowed 10293 // for some operators but not others. 10294 if (!AllowBothBool && 10295 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10296 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10297 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10298 10299 // This operation may not be performed on boolean vectors. 10300 if (!AllowBoolOperation && 10301 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) 10302 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10303 10304 // If the vector types are identical, return. 10305 if (Context.hasSameType(LHSType, RHSType)) 10306 return LHSType; 10307 10308 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10309 if (LHSVecType && RHSVecType && 10310 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10311 if (isa<ExtVectorType>(LHSVecType)) { 10312 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10313 return LHSType; 10314 } 10315 10316 if (!IsCompAssign) 10317 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10318 return RHSType; 10319 } 10320 10321 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10322 // can be mixed, with the result being the non-bool type. The non-bool 10323 // operand must have integer element type. 10324 if (AllowBoolConversions && LHSVecType && RHSVecType && 10325 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10326 (Context.getTypeSize(LHSVecType->getElementType()) == 10327 Context.getTypeSize(RHSVecType->getElementType()))) { 10328 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10329 LHSVecType->getElementType()->isIntegerType() && 10330 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10331 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10332 return LHSType; 10333 } 10334 if (!IsCompAssign && 10335 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10336 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10337 RHSVecType->getElementType()->isIntegerType()) { 10338 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10339 return RHSType; 10340 } 10341 } 10342 10343 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10344 // since the ambiguity can affect the ABI. 10345 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10346 const VectorType *VecType = SecondType->getAs<VectorType>(); 10347 return FirstType->isSizelessBuiltinType() && VecType && 10348 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10349 VecType->getVectorKind() == 10350 VectorType::SveFixedLengthPredicateVector); 10351 }; 10352 10353 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10354 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10355 return QualType(); 10356 } 10357 10358 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10359 // since the ambiguity can affect the ABI. 10360 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10361 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10362 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10363 10364 if (FirstVecType && SecondVecType) 10365 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10366 (SecondVecType->getVectorKind() == 10367 VectorType::SveFixedLengthDataVector || 10368 SecondVecType->getVectorKind() == 10369 VectorType::SveFixedLengthPredicateVector); 10370 10371 return FirstType->isSizelessBuiltinType() && SecondVecType && 10372 SecondVecType->getVectorKind() == VectorType::GenericVector; 10373 }; 10374 10375 if (IsSveGnuConversion(LHSType, RHSType) || 10376 IsSveGnuConversion(RHSType, LHSType)) { 10377 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10378 return QualType(); 10379 } 10380 10381 // If there's a vector type and a scalar, try to convert the scalar to 10382 // the vector element type and splat. 10383 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10384 if (!RHSVecType) { 10385 if (isa<ExtVectorType>(LHSVecType)) { 10386 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10387 LHSVecType->getElementType(), LHSType, 10388 DiagID)) 10389 return LHSType; 10390 } else { 10391 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10392 return LHSType; 10393 } 10394 } 10395 if (!LHSVecType) { 10396 if (isa<ExtVectorType>(RHSVecType)) { 10397 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10398 LHSType, RHSVecType->getElementType(), 10399 RHSType, DiagID)) 10400 return RHSType; 10401 } else { 10402 if (LHS.get()->isLValue() || 10403 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10404 return RHSType; 10405 } 10406 } 10407 10408 // FIXME: The code below also handles conversion between vectors and 10409 // non-scalars, we should break this down into fine grained specific checks 10410 // and emit proper diagnostics. 10411 QualType VecType = LHSVecType ? LHSType : RHSType; 10412 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10413 QualType OtherType = LHSVecType ? RHSType : LHSType; 10414 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10415 if (isLaxVectorConversion(OtherType, VecType)) { 10416 // If we're allowing lax vector conversions, only the total (data) size 10417 // needs to be the same. For non compound assignment, if one of the types is 10418 // scalar, the result is always the vector type. 10419 if (!IsCompAssign) { 10420 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10421 return VecType; 10422 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10423 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10424 // type. Note that this is already done by non-compound assignments in 10425 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10426 // <1 x T> -> T. The result is also a vector type. 10427 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10428 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10429 ExprResult *RHSExpr = &RHS; 10430 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10431 return VecType; 10432 } 10433 } 10434 10435 // Okay, the expression is invalid. 10436 10437 // If there's a non-vector, non-real operand, diagnose that. 10438 if ((!RHSVecType && !RHSType->isRealType()) || 10439 (!LHSVecType && !LHSType->isRealType())) { 10440 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10441 << LHSType << RHSType 10442 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10443 return QualType(); 10444 } 10445 10446 // OpenCL V1.1 6.2.6.p1: 10447 // If the operands are of more than one vector type, then an error shall 10448 // occur. Implicit conversions between vector types are not permitted, per 10449 // section 6.2.1. 10450 if (getLangOpts().OpenCL && 10451 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10452 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10453 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10454 << RHSType; 10455 return QualType(); 10456 } 10457 10458 10459 // If there is a vector type that is not a ExtVector and a scalar, we reach 10460 // this point if scalar could not be converted to the vector's element type 10461 // without truncation. 10462 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10463 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10464 QualType Scalar = LHSVecType ? RHSType : LHSType; 10465 QualType Vector = LHSVecType ? LHSType : RHSType; 10466 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10467 Diag(Loc, 10468 diag::err_typecheck_vector_not_convertable_implict_truncation) 10469 << ScalarOrVector << Scalar << Vector; 10470 10471 return QualType(); 10472 } 10473 10474 // Otherwise, use the generic diagnostic. 10475 Diag(Loc, DiagID) 10476 << LHSType << RHSType 10477 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10478 return QualType(); 10479 } 10480 10481 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, 10482 SourceLocation Loc, 10483 bool IsCompAssign, 10484 ArithConvKind OperationKind) { 10485 if (!IsCompAssign) { 10486 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10487 if (LHS.isInvalid()) 10488 return QualType(); 10489 } 10490 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10491 if (RHS.isInvalid()) 10492 return QualType(); 10493 10494 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10495 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10496 10497 unsigned DiagID = diag::err_typecheck_invalid_operands; 10498 if ((OperationKind == ACK_Arithmetic) && 10499 (LHSType->castAs<BuiltinType>()->isSVEBool() || 10500 RHSType->castAs<BuiltinType>()->isSVEBool())) { 10501 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10502 << RHS.get()->getSourceRange(); 10503 return QualType(); 10504 } 10505 10506 if (Context.hasSameType(LHSType, RHSType)) 10507 return LHSType; 10508 10509 auto tryScalableVectorConvert = [this](ExprResult *Src, QualType SrcType, 10510 QualType DestType) { 10511 const QualType DestBaseType = DestType->getSveEltType(Context); 10512 if (DestBaseType->getUnqualifiedDesugaredType() == 10513 SrcType->getUnqualifiedDesugaredType()) { 10514 unsigned DiagID = diag::err_typecheck_invalid_operands; 10515 if (!tryVectorConvertAndSplat(*this, Src, SrcType, DestBaseType, DestType, 10516 DiagID)) 10517 return DestType; 10518 } 10519 return QualType(); 10520 }; 10521 10522 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) { 10523 auto DestType = tryScalableVectorConvert(&RHS, RHSType, LHSType); 10524 if (DestType == QualType()) 10525 return InvalidOperands(Loc, LHS, RHS); 10526 return DestType; 10527 } 10528 10529 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) { 10530 auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS), 10531 LHSType, RHSType); 10532 if (DestType == QualType()) 10533 return InvalidOperands(Loc, LHS, RHS); 10534 return DestType; 10535 } 10536 10537 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10538 << RHS.get()->getSourceRange(); 10539 return QualType(); 10540 } 10541 10542 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10543 // expression. These are mainly cases where the null pointer is used as an 10544 // integer instead of a pointer. 10545 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10546 SourceLocation Loc, bool IsCompare) { 10547 // The canonical way to check for a GNU null is with isNullPointerConstant, 10548 // but we use a bit of a hack here for speed; this is a relatively 10549 // hot path, and isNullPointerConstant is slow. 10550 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10551 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10552 10553 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10554 10555 // Avoid analyzing cases where the result will either be invalid (and 10556 // diagnosed as such) or entirely valid and not something to warn about. 10557 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10558 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10559 return; 10560 10561 // Comparison operations would not make sense with a null pointer no matter 10562 // what the other expression is. 10563 if (!IsCompare) { 10564 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10565 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10566 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10567 return; 10568 } 10569 10570 // The rest of the operations only make sense with a null pointer 10571 // if the other expression is a pointer. 10572 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10573 NonNullType->canDecayToPointerType()) 10574 return; 10575 10576 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10577 << LHSNull /* LHS is NULL */ << NonNullType 10578 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10579 } 10580 10581 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10582 SourceLocation Loc) { 10583 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10584 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10585 if (!LUE || !RUE) 10586 return; 10587 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10588 RUE->getKind() != UETT_SizeOf) 10589 return; 10590 10591 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10592 QualType LHSTy = LHSArg->getType(); 10593 QualType RHSTy; 10594 10595 if (RUE->isArgumentType()) 10596 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10597 else 10598 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10599 10600 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10601 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10602 return; 10603 10604 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10605 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10606 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10607 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10608 << LHSArgDecl; 10609 } 10610 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10611 QualType ArrayElemTy = ArrayTy->getElementType(); 10612 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10613 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10614 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10615 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10616 return; 10617 S.Diag(Loc, diag::warn_division_sizeof_array) 10618 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10619 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10620 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10621 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10622 << LHSArgDecl; 10623 } 10624 10625 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10626 } 10627 } 10628 10629 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10630 ExprResult &RHS, 10631 SourceLocation Loc, bool IsDiv) { 10632 // Check for division/remainder by zero. 10633 Expr::EvalResult RHSValue; 10634 if (!RHS.get()->isValueDependent() && 10635 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10636 RHSValue.Val.getInt() == 0) 10637 S.DiagRuntimeBehavior(Loc, RHS.get(), 10638 S.PDiag(diag::warn_remainder_division_by_zero) 10639 << IsDiv << RHS.get()->getSourceRange()); 10640 } 10641 10642 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10643 SourceLocation Loc, 10644 bool IsCompAssign, bool IsDiv) { 10645 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10646 10647 QualType LHSTy = LHS.get()->getType(); 10648 QualType RHSTy = RHS.get()->getType(); 10649 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10650 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10651 /*AllowBothBool*/ getLangOpts().AltiVec, 10652 /*AllowBoolConversions*/ false, 10653 /*AllowBooleanOperation*/ false, 10654 /*ReportInvalid*/ true); 10655 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType()) 10656 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 10657 ACK_Arithmetic); 10658 if (!IsDiv && 10659 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10660 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10661 // For division, only matrix-by-scalar is supported. Other combinations with 10662 // matrix types are invalid. 10663 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10664 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10665 10666 QualType compType = UsualArithmeticConversions( 10667 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10668 if (LHS.isInvalid() || RHS.isInvalid()) 10669 return QualType(); 10670 10671 10672 if (compType.isNull() || !compType->isArithmeticType()) 10673 return InvalidOperands(Loc, LHS, RHS); 10674 if (IsDiv) { 10675 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10676 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10677 } 10678 return compType; 10679 } 10680 10681 QualType Sema::CheckRemainderOperands( 10682 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10683 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10684 10685 if (LHS.get()->getType()->isVectorType() || 10686 RHS.get()->getType()->isVectorType()) { 10687 if (LHS.get()->getType()->hasIntegerRepresentation() && 10688 RHS.get()->getType()->hasIntegerRepresentation()) 10689 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10690 /*AllowBothBool*/ getLangOpts().AltiVec, 10691 /*AllowBoolConversions*/ false, 10692 /*AllowBooleanOperation*/ false, 10693 /*ReportInvalid*/ true); 10694 return InvalidOperands(Loc, LHS, RHS); 10695 } 10696 10697 if (LHS.get()->getType()->isVLSTBuiltinType() || 10698 RHS.get()->getType()->isVLSTBuiltinType()) { 10699 if (LHS.get()->getType()->hasIntegerRepresentation() && 10700 RHS.get()->getType()->hasIntegerRepresentation()) 10701 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 10702 ACK_Arithmetic); 10703 10704 return InvalidOperands(Loc, LHS, RHS); 10705 } 10706 10707 QualType compType = UsualArithmeticConversions( 10708 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10709 if (LHS.isInvalid() || RHS.isInvalid()) 10710 return QualType(); 10711 10712 if (compType.isNull() || !compType->isIntegerType()) 10713 return InvalidOperands(Loc, LHS, RHS); 10714 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10715 return compType; 10716 } 10717 10718 /// Diagnose invalid arithmetic on two void pointers. 10719 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10720 Expr *LHSExpr, Expr *RHSExpr) { 10721 S.Diag(Loc, S.getLangOpts().CPlusPlus 10722 ? diag::err_typecheck_pointer_arith_void_type 10723 : diag::ext_gnu_void_ptr) 10724 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10725 << RHSExpr->getSourceRange(); 10726 } 10727 10728 /// Diagnose invalid arithmetic on a void pointer. 10729 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10730 Expr *Pointer) { 10731 S.Diag(Loc, S.getLangOpts().CPlusPlus 10732 ? diag::err_typecheck_pointer_arith_void_type 10733 : diag::ext_gnu_void_ptr) 10734 << 0 /* one pointer */ << Pointer->getSourceRange(); 10735 } 10736 10737 /// Diagnose invalid arithmetic on a null pointer. 10738 /// 10739 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10740 /// idiom, which we recognize as a GNU extension. 10741 /// 10742 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10743 Expr *Pointer, bool IsGNUIdiom) { 10744 if (IsGNUIdiom) 10745 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10746 << Pointer->getSourceRange(); 10747 else 10748 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10749 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10750 } 10751 10752 /// Diagnose invalid subraction on a null pointer. 10753 /// 10754 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10755 Expr *Pointer, bool BothNull) { 10756 // Null - null is valid in C++ [expr.add]p7 10757 if (BothNull && S.getLangOpts().CPlusPlus) 10758 return; 10759 10760 // Is this s a macro from a system header? 10761 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10762 return; 10763 10764 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10765 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10766 } 10767 10768 /// Diagnose invalid arithmetic on two function pointers. 10769 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10770 Expr *LHS, Expr *RHS) { 10771 assert(LHS->getType()->isAnyPointerType()); 10772 assert(RHS->getType()->isAnyPointerType()); 10773 S.Diag(Loc, S.getLangOpts().CPlusPlus 10774 ? diag::err_typecheck_pointer_arith_function_type 10775 : diag::ext_gnu_ptr_func_arith) 10776 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10777 // We only show the second type if it differs from the first. 10778 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10779 RHS->getType()) 10780 << RHS->getType()->getPointeeType() 10781 << LHS->getSourceRange() << RHS->getSourceRange(); 10782 } 10783 10784 /// Diagnose invalid arithmetic on a function pointer. 10785 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10786 Expr *Pointer) { 10787 assert(Pointer->getType()->isAnyPointerType()); 10788 S.Diag(Loc, S.getLangOpts().CPlusPlus 10789 ? diag::err_typecheck_pointer_arith_function_type 10790 : diag::ext_gnu_ptr_func_arith) 10791 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10792 << 0 /* one pointer, so only one type */ 10793 << Pointer->getSourceRange(); 10794 } 10795 10796 /// Emit error if Operand is incomplete pointer type 10797 /// 10798 /// \returns True if pointer has incomplete type 10799 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10800 Expr *Operand) { 10801 QualType ResType = Operand->getType(); 10802 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10803 ResType = ResAtomicType->getValueType(); 10804 10805 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10806 QualType PointeeTy = ResType->getPointeeType(); 10807 return S.RequireCompleteSizedType( 10808 Loc, PointeeTy, 10809 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10810 Operand->getSourceRange()); 10811 } 10812 10813 /// Check the validity of an arithmetic pointer operand. 10814 /// 10815 /// If the operand has pointer type, this code will check for pointer types 10816 /// which are invalid in arithmetic operations. These will be diagnosed 10817 /// appropriately, including whether or not the use is supported as an 10818 /// extension. 10819 /// 10820 /// \returns True when the operand is valid to use (even if as an extension). 10821 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10822 Expr *Operand) { 10823 QualType ResType = Operand->getType(); 10824 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10825 ResType = ResAtomicType->getValueType(); 10826 10827 if (!ResType->isAnyPointerType()) return true; 10828 10829 QualType PointeeTy = ResType->getPointeeType(); 10830 if (PointeeTy->isVoidType()) { 10831 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10832 return !S.getLangOpts().CPlusPlus; 10833 } 10834 if (PointeeTy->isFunctionType()) { 10835 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10836 return !S.getLangOpts().CPlusPlus; 10837 } 10838 10839 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10840 10841 return true; 10842 } 10843 10844 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10845 /// operands. 10846 /// 10847 /// This routine will diagnose any invalid arithmetic on pointer operands much 10848 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10849 /// for emitting a single diagnostic even for operations where both LHS and RHS 10850 /// are (potentially problematic) pointers. 10851 /// 10852 /// \returns True when the operand is valid to use (even if as an extension). 10853 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10854 Expr *LHSExpr, Expr *RHSExpr) { 10855 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10856 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10857 if (!isLHSPointer && !isRHSPointer) return true; 10858 10859 QualType LHSPointeeTy, RHSPointeeTy; 10860 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10861 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10862 10863 // if both are pointers check if operation is valid wrt address spaces 10864 if (isLHSPointer && isRHSPointer) { 10865 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10866 S.Diag(Loc, 10867 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10868 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10869 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10870 return false; 10871 } 10872 } 10873 10874 // Check for arithmetic on pointers to incomplete types. 10875 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10876 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10877 if (isLHSVoidPtr || isRHSVoidPtr) { 10878 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10879 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10880 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10881 10882 return !S.getLangOpts().CPlusPlus; 10883 } 10884 10885 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10886 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10887 if (isLHSFuncPtr || isRHSFuncPtr) { 10888 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10889 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10890 RHSExpr); 10891 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10892 10893 return !S.getLangOpts().CPlusPlus; 10894 } 10895 10896 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10897 return false; 10898 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10899 return false; 10900 10901 return true; 10902 } 10903 10904 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10905 /// literal. 10906 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10907 Expr *LHSExpr, Expr *RHSExpr) { 10908 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10909 Expr* IndexExpr = RHSExpr; 10910 if (!StrExpr) { 10911 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10912 IndexExpr = LHSExpr; 10913 } 10914 10915 bool IsStringPlusInt = StrExpr && 10916 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10917 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10918 return; 10919 10920 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10921 Self.Diag(OpLoc, diag::warn_string_plus_int) 10922 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10923 10924 // Only print a fixit for "str" + int, not for int + "str". 10925 if (IndexExpr == RHSExpr) { 10926 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10927 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10928 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10929 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10930 << FixItHint::CreateInsertion(EndLoc, "]"); 10931 } else 10932 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10933 } 10934 10935 /// Emit a warning when adding a char literal to a string. 10936 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10937 Expr *LHSExpr, Expr *RHSExpr) { 10938 const Expr *StringRefExpr = LHSExpr; 10939 const CharacterLiteral *CharExpr = 10940 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10941 10942 if (!CharExpr) { 10943 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10944 StringRefExpr = RHSExpr; 10945 } 10946 10947 if (!CharExpr || !StringRefExpr) 10948 return; 10949 10950 const QualType StringType = StringRefExpr->getType(); 10951 10952 // Return if not a PointerType. 10953 if (!StringType->isAnyPointerType()) 10954 return; 10955 10956 // Return if not a CharacterType. 10957 if (!StringType->getPointeeType()->isAnyCharacterType()) 10958 return; 10959 10960 ASTContext &Ctx = Self.getASTContext(); 10961 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10962 10963 const QualType CharType = CharExpr->getType(); 10964 if (!CharType->isAnyCharacterType() && 10965 CharType->isIntegerType() && 10966 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10967 Self.Diag(OpLoc, diag::warn_string_plus_char) 10968 << DiagRange << Ctx.CharTy; 10969 } else { 10970 Self.Diag(OpLoc, diag::warn_string_plus_char) 10971 << DiagRange << CharExpr->getType(); 10972 } 10973 10974 // Only print a fixit for str + char, not for char + str. 10975 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10976 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10977 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10978 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10979 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10980 << FixItHint::CreateInsertion(EndLoc, "]"); 10981 } else { 10982 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10983 } 10984 } 10985 10986 /// Emit error when two pointers are incompatible. 10987 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10988 Expr *LHSExpr, Expr *RHSExpr) { 10989 assert(LHSExpr->getType()->isAnyPointerType()); 10990 assert(RHSExpr->getType()->isAnyPointerType()); 10991 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10992 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10993 << RHSExpr->getSourceRange(); 10994 } 10995 10996 // C99 6.5.6 10997 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10998 SourceLocation Loc, BinaryOperatorKind Opc, 10999 QualType* CompLHSTy) { 11000 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11001 11002 if (LHS.get()->getType()->isVectorType() || 11003 RHS.get()->getType()->isVectorType()) { 11004 QualType compType = 11005 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11006 /*AllowBothBool*/ getLangOpts().AltiVec, 11007 /*AllowBoolConversions*/ getLangOpts().ZVector, 11008 /*AllowBooleanOperation*/ false, 11009 /*ReportInvalid*/ true); 11010 if (CompLHSTy) *CompLHSTy = compType; 11011 return compType; 11012 } 11013 11014 if (LHS.get()->getType()->isVLSTBuiltinType() || 11015 RHS.get()->getType()->isVLSTBuiltinType()) { 11016 QualType compType = 11017 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11018 if (CompLHSTy) 11019 *CompLHSTy = compType; 11020 return compType; 11021 } 11022 11023 if (LHS.get()->getType()->isConstantMatrixType() || 11024 RHS.get()->getType()->isConstantMatrixType()) { 11025 QualType compType = 11026 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11027 if (CompLHSTy) 11028 *CompLHSTy = compType; 11029 return compType; 11030 } 11031 11032 QualType compType = UsualArithmeticConversions( 11033 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11034 if (LHS.isInvalid() || RHS.isInvalid()) 11035 return QualType(); 11036 11037 // Diagnose "string literal" '+' int and string '+' "char literal". 11038 if (Opc == BO_Add) { 11039 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 11040 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 11041 } 11042 11043 // handle the common case first (both operands are arithmetic). 11044 if (!compType.isNull() && compType->isArithmeticType()) { 11045 if (CompLHSTy) *CompLHSTy = compType; 11046 return compType; 11047 } 11048 11049 // Type-checking. Ultimately the pointer's going to be in PExp; 11050 // note that we bias towards the LHS being the pointer. 11051 Expr *PExp = LHS.get(), *IExp = RHS.get(); 11052 11053 bool isObjCPointer; 11054 if (PExp->getType()->isPointerType()) { 11055 isObjCPointer = false; 11056 } else if (PExp->getType()->isObjCObjectPointerType()) { 11057 isObjCPointer = true; 11058 } else { 11059 std::swap(PExp, IExp); 11060 if (PExp->getType()->isPointerType()) { 11061 isObjCPointer = false; 11062 } else if (PExp->getType()->isObjCObjectPointerType()) { 11063 isObjCPointer = true; 11064 } else { 11065 return InvalidOperands(Loc, LHS, RHS); 11066 } 11067 } 11068 assert(PExp->getType()->isAnyPointerType()); 11069 11070 if (!IExp->getType()->isIntegerType()) 11071 return InvalidOperands(Loc, LHS, RHS); 11072 11073 // Adding to a null pointer results in undefined behavior. 11074 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 11075 Context, Expr::NPC_ValueDependentIsNotNull)) { 11076 // In C++ adding zero to a null pointer is defined. 11077 Expr::EvalResult KnownVal; 11078 if (!getLangOpts().CPlusPlus || 11079 (!IExp->isValueDependent() && 11080 (!IExp->EvaluateAsInt(KnownVal, Context) || 11081 KnownVal.Val.getInt() != 0))) { 11082 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 11083 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 11084 Context, BO_Add, PExp, IExp); 11085 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 11086 } 11087 } 11088 11089 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 11090 return QualType(); 11091 11092 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 11093 return QualType(); 11094 11095 // Check array bounds for pointer arithemtic 11096 CheckArrayAccess(PExp, IExp); 11097 11098 if (CompLHSTy) { 11099 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 11100 if (LHSTy.isNull()) { 11101 LHSTy = LHS.get()->getType(); 11102 if (LHSTy->isPromotableIntegerType()) 11103 LHSTy = Context.getPromotedIntegerType(LHSTy); 11104 } 11105 *CompLHSTy = LHSTy; 11106 } 11107 11108 return PExp->getType(); 11109 } 11110 11111 // C99 6.5.6 11112 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 11113 SourceLocation Loc, 11114 QualType* CompLHSTy) { 11115 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11116 11117 if (LHS.get()->getType()->isVectorType() || 11118 RHS.get()->getType()->isVectorType()) { 11119 QualType compType = 11120 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11121 /*AllowBothBool*/ getLangOpts().AltiVec, 11122 /*AllowBoolConversions*/ getLangOpts().ZVector, 11123 /*AllowBooleanOperation*/ false, 11124 /*ReportInvalid*/ true); 11125 if (CompLHSTy) *CompLHSTy = compType; 11126 return compType; 11127 } 11128 11129 if (LHS.get()->getType()->isVLSTBuiltinType() || 11130 RHS.get()->getType()->isVLSTBuiltinType()) { 11131 QualType compType = 11132 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11133 if (CompLHSTy) 11134 *CompLHSTy = compType; 11135 return compType; 11136 } 11137 11138 if (LHS.get()->getType()->isConstantMatrixType() || 11139 RHS.get()->getType()->isConstantMatrixType()) { 11140 QualType compType = 11141 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11142 if (CompLHSTy) 11143 *CompLHSTy = compType; 11144 return compType; 11145 } 11146 11147 QualType compType = UsualArithmeticConversions( 11148 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11149 if (LHS.isInvalid() || RHS.isInvalid()) 11150 return QualType(); 11151 11152 // Enforce type constraints: C99 6.5.6p3. 11153 11154 // Handle the common case first (both operands are arithmetic). 11155 if (!compType.isNull() && compType->isArithmeticType()) { 11156 if (CompLHSTy) *CompLHSTy = compType; 11157 return compType; 11158 } 11159 11160 // Either ptr - int or ptr - ptr. 11161 if (LHS.get()->getType()->isAnyPointerType()) { 11162 QualType lpointee = LHS.get()->getType()->getPointeeType(); 11163 11164 // Diagnose bad cases where we step over interface counts. 11165 if (LHS.get()->getType()->isObjCObjectPointerType() && 11166 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 11167 return QualType(); 11168 11169 // The result type of a pointer-int computation is the pointer type. 11170 if (RHS.get()->getType()->isIntegerType()) { 11171 // Subtracting from a null pointer should produce a warning. 11172 // The last argument to the diagnose call says this doesn't match the 11173 // GNU int-to-pointer idiom. 11174 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 11175 Expr::NPC_ValueDependentIsNotNull)) { 11176 // In C++ adding zero to a null pointer is defined. 11177 Expr::EvalResult KnownVal; 11178 if (!getLangOpts().CPlusPlus || 11179 (!RHS.get()->isValueDependent() && 11180 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 11181 KnownVal.Val.getInt() != 0))) { 11182 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 11183 } 11184 } 11185 11186 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 11187 return QualType(); 11188 11189 // Check array bounds for pointer arithemtic 11190 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 11191 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 11192 11193 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11194 return LHS.get()->getType(); 11195 } 11196 11197 // Handle pointer-pointer subtractions. 11198 if (const PointerType *RHSPTy 11199 = RHS.get()->getType()->getAs<PointerType>()) { 11200 QualType rpointee = RHSPTy->getPointeeType(); 11201 11202 if (getLangOpts().CPlusPlus) { 11203 // Pointee types must be the same: C++ [expr.add] 11204 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 11205 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11206 } 11207 } else { 11208 // Pointee types must be compatible C99 6.5.6p3 11209 if (!Context.typesAreCompatible( 11210 Context.getCanonicalType(lpointee).getUnqualifiedType(), 11211 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 11212 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11213 return QualType(); 11214 } 11215 } 11216 11217 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 11218 LHS.get(), RHS.get())) 11219 return QualType(); 11220 11221 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11222 Context, Expr::NPC_ValueDependentIsNotNull); 11223 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11224 Context, Expr::NPC_ValueDependentIsNotNull); 11225 11226 // Subtracting nullptr or from nullptr is suspect 11227 if (LHSIsNullPtr) 11228 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 11229 if (RHSIsNullPtr) 11230 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 11231 11232 // The pointee type may have zero size. As an extension, a structure or 11233 // union may have zero size or an array may have zero length. In this 11234 // case subtraction does not make sense. 11235 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 11236 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 11237 if (ElementSize.isZero()) { 11238 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 11239 << rpointee.getUnqualifiedType() 11240 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11241 } 11242 } 11243 11244 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11245 return Context.getPointerDiffType(); 11246 } 11247 } 11248 11249 return InvalidOperands(Loc, LHS, RHS); 11250 } 11251 11252 static bool isScopedEnumerationType(QualType T) { 11253 if (const EnumType *ET = T->getAs<EnumType>()) 11254 return ET->getDecl()->isScoped(); 11255 return false; 11256 } 11257 11258 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 11259 SourceLocation Loc, BinaryOperatorKind Opc, 11260 QualType LHSType) { 11261 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 11262 // so skip remaining warnings as we don't want to modify values within Sema. 11263 if (S.getLangOpts().OpenCL) 11264 return; 11265 11266 // Check right/shifter operand 11267 Expr::EvalResult RHSResult; 11268 if (RHS.get()->isValueDependent() || 11269 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 11270 return; 11271 llvm::APSInt Right = RHSResult.Val.getInt(); 11272 11273 if (Right.isNegative()) { 11274 S.DiagRuntimeBehavior(Loc, RHS.get(), 11275 S.PDiag(diag::warn_shift_negative) 11276 << RHS.get()->getSourceRange()); 11277 return; 11278 } 11279 11280 QualType LHSExprType = LHS.get()->getType(); 11281 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 11282 if (LHSExprType->isBitIntType()) 11283 LeftSize = S.Context.getIntWidth(LHSExprType); 11284 else if (LHSExprType->isFixedPointType()) { 11285 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 11286 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 11287 } 11288 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 11289 if (Right.uge(LeftBits)) { 11290 S.DiagRuntimeBehavior(Loc, RHS.get(), 11291 S.PDiag(diag::warn_shift_gt_typewidth) 11292 << RHS.get()->getSourceRange()); 11293 return; 11294 } 11295 11296 // FIXME: We probably need to handle fixed point types specially here. 11297 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 11298 return; 11299 11300 // When left shifting an ICE which is signed, we can check for overflow which 11301 // according to C++ standards prior to C++2a has undefined behavior 11302 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 11303 // more than the maximum value representable in the result type, so never 11304 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11305 // expression is still probably a bug.) 11306 Expr::EvalResult LHSResult; 11307 if (LHS.get()->isValueDependent() || 11308 LHSType->hasUnsignedIntegerRepresentation() || 11309 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11310 return; 11311 llvm::APSInt Left = LHSResult.Val.getInt(); 11312 11313 // If LHS does not have a signed type and non-negative value 11314 // then, the behavior is undefined before C++2a. Warn about it. 11315 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11316 !S.getLangOpts().CPlusPlus20) { 11317 S.DiagRuntimeBehavior(Loc, LHS.get(), 11318 S.PDiag(diag::warn_shift_lhs_negative) 11319 << LHS.get()->getSourceRange()); 11320 return; 11321 } 11322 11323 llvm::APInt ResultBits = 11324 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11325 if (LeftBits.uge(ResultBits)) 11326 return; 11327 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11328 Result = Result.shl(Right); 11329 11330 // Print the bit representation of the signed integer as an unsigned 11331 // hexadecimal number. 11332 SmallString<40> HexResult; 11333 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11334 11335 // If we are only missing a sign bit, this is less likely to result in actual 11336 // bugs -- if the result is cast back to an unsigned type, it will have the 11337 // expected value. Thus we place this behind a different warning that can be 11338 // turned off separately if needed. 11339 if (LeftBits == ResultBits - 1) { 11340 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11341 << HexResult << LHSType 11342 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11343 return; 11344 } 11345 11346 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11347 << HexResult.str() << Result.getMinSignedBits() << LHSType 11348 << Left.getBitWidth() << LHS.get()->getSourceRange() 11349 << RHS.get()->getSourceRange(); 11350 } 11351 11352 /// Return the resulting type when a vector is shifted 11353 /// by a scalar or vector shift amount. 11354 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11355 SourceLocation Loc, bool IsCompAssign) { 11356 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11357 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11358 !LHS.get()->getType()->isVectorType()) { 11359 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11360 << RHS.get()->getType() << LHS.get()->getType() 11361 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11362 return QualType(); 11363 } 11364 11365 if (!IsCompAssign) { 11366 LHS = S.UsualUnaryConversions(LHS.get()); 11367 if (LHS.isInvalid()) return QualType(); 11368 } 11369 11370 RHS = S.UsualUnaryConversions(RHS.get()); 11371 if (RHS.isInvalid()) return QualType(); 11372 11373 QualType LHSType = LHS.get()->getType(); 11374 // Note that LHS might be a scalar because the routine calls not only in 11375 // OpenCL case. 11376 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11377 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11378 11379 // Note that RHS might not be a vector. 11380 QualType RHSType = RHS.get()->getType(); 11381 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11382 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11383 11384 // Do not allow shifts for boolean vectors. 11385 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || 11386 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { 11387 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11388 << LHS.get()->getType() << RHS.get()->getType() 11389 << LHS.get()->getSourceRange(); 11390 return QualType(); 11391 } 11392 11393 // The operands need to be integers. 11394 if (!LHSEleType->isIntegerType()) { 11395 S.Diag(Loc, diag::err_typecheck_expect_int) 11396 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11397 return QualType(); 11398 } 11399 11400 if (!RHSEleType->isIntegerType()) { 11401 S.Diag(Loc, diag::err_typecheck_expect_int) 11402 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11403 return QualType(); 11404 } 11405 11406 if (!LHSVecTy) { 11407 assert(RHSVecTy); 11408 if (IsCompAssign) 11409 return RHSType; 11410 if (LHSEleType != RHSEleType) { 11411 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11412 LHSEleType = RHSEleType; 11413 } 11414 QualType VecTy = 11415 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11416 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11417 LHSType = VecTy; 11418 } else if (RHSVecTy) { 11419 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11420 // are applied component-wise. So if RHS is a vector, then ensure 11421 // that the number of elements is the same as LHS... 11422 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11423 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11424 << LHS.get()->getType() << RHS.get()->getType() 11425 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11426 return QualType(); 11427 } 11428 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11429 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11430 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11431 if (LHSBT != RHSBT && 11432 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11433 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11434 << LHS.get()->getType() << RHS.get()->getType() 11435 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11436 } 11437 } 11438 } else { 11439 // ...else expand RHS to match the number of elements in LHS. 11440 QualType VecTy = 11441 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11442 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11443 } 11444 11445 return LHSType; 11446 } 11447 11448 // C99 6.5.7 11449 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11450 SourceLocation Loc, BinaryOperatorKind Opc, 11451 bool IsCompAssign) { 11452 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11453 11454 // Vector shifts promote their scalar inputs to vector type. 11455 if (LHS.get()->getType()->isVectorType() || 11456 RHS.get()->getType()->isVectorType()) { 11457 if (LangOpts.ZVector) { 11458 // The shift operators for the z vector extensions work basically 11459 // like general shifts, except that neither the LHS nor the RHS is 11460 // allowed to be a "vector bool". 11461 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11462 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11463 return InvalidOperands(Loc, LHS, RHS); 11464 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11465 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11466 return InvalidOperands(Loc, LHS, RHS); 11467 } 11468 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11469 } 11470 11471 if (LHS.get()->getType()->isVLSTBuiltinType() || 11472 RHS.get()->getType()->isVLSTBuiltinType()) 11473 return InvalidOperands(Loc, LHS, RHS); 11474 11475 // Shifts don't perform usual arithmetic conversions, they just do integer 11476 // promotions on each operand. C99 6.5.7p3 11477 11478 // For the LHS, do usual unary conversions, but then reset them away 11479 // if this is a compound assignment. 11480 ExprResult OldLHS = LHS; 11481 LHS = UsualUnaryConversions(LHS.get()); 11482 if (LHS.isInvalid()) 11483 return QualType(); 11484 QualType LHSType = LHS.get()->getType(); 11485 if (IsCompAssign) LHS = OldLHS; 11486 11487 // The RHS is simpler. 11488 RHS = UsualUnaryConversions(RHS.get()); 11489 if (RHS.isInvalid()) 11490 return QualType(); 11491 QualType RHSType = RHS.get()->getType(); 11492 11493 // C99 6.5.7p2: Each of the operands shall have integer type. 11494 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11495 if ((!LHSType->isFixedPointOrIntegerType() && 11496 !LHSType->hasIntegerRepresentation()) || 11497 !RHSType->hasIntegerRepresentation()) 11498 return InvalidOperands(Loc, LHS, RHS); 11499 11500 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11501 // hasIntegerRepresentation() above instead of this. 11502 if (isScopedEnumerationType(LHSType) || 11503 isScopedEnumerationType(RHSType)) { 11504 return InvalidOperands(Loc, LHS, RHS); 11505 } 11506 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11507 11508 // "The type of the result is that of the promoted left operand." 11509 return LHSType; 11510 } 11511 11512 /// Diagnose bad pointer comparisons. 11513 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11514 ExprResult &LHS, ExprResult &RHS, 11515 bool IsError) { 11516 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11517 : diag::ext_typecheck_comparison_of_distinct_pointers) 11518 << LHS.get()->getType() << RHS.get()->getType() 11519 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11520 } 11521 11522 /// Returns false if the pointers are converted to a composite type, 11523 /// true otherwise. 11524 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11525 ExprResult &LHS, ExprResult &RHS) { 11526 // C++ [expr.rel]p2: 11527 // [...] Pointer conversions (4.10) and qualification 11528 // conversions (4.4) are performed on pointer operands (or on 11529 // a pointer operand and a null pointer constant) to bring 11530 // them to their composite pointer type. [...] 11531 // 11532 // C++ [expr.eq]p1 uses the same notion for (in)equality 11533 // comparisons of pointers. 11534 11535 QualType LHSType = LHS.get()->getType(); 11536 QualType RHSType = RHS.get()->getType(); 11537 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11538 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11539 11540 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11541 if (T.isNull()) { 11542 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11543 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11544 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11545 else 11546 S.InvalidOperands(Loc, LHS, RHS); 11547 return true; 11548 } 11549 11550 return false; 11551 } 11552 11553 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11554 ExprResult &LHS, 11555 ExprResult &RHS, 11556 bool IsError) { 11557 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11558 : diag::ext_typecheck_comparison_of_fptr_to_void) 11559 << LHS.get()->getType() << RHS.get()->getType() 11560 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11561 } 11562 11563 static bool isObjCObjectLiteral(ExprResult &E) { 11564 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11565 case Stmt::ObjCArrayLiteralClass: 11566 case Stmt::ObjCDictionaryLiteralClass: 11567 case Stmt::ObjCStringLiteralClass: 11568 case Stmt::ObjCBoxedExprClass: 11569 return true; 11570 default: 11571 // Note that ObjCBoolLiteral is NOT an object literal! 11572 return false; 11573 } 11574 } 11575 11576 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11577 const ObjCObjectPointerType *Type = 11578 LHS->getType()->getAs<ObjCObjectPointerType>(); 11579 11580 // If this is not actually an Objective-C object, bail out. 11581 if (!Type) 11582 return false; 11583 11584 // Get the LHS object's interface type. 11585 QualType InterfaceType = Type->getPointeeType(); 11586 11587 // If the RHS isn't an Objective-C object, bail out. 11588 if (!RHS->getType()->isObjCObjectPointerType()) 11589 return false; 11590 11591 // Try to find the -isEqual: method. 11592 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11593 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11594 InterfaceType, 11595 /*IsInstance=*/true); 11596 if (!Method) { 11597 if (Type->isObjCIdType()) { 11598 // For 'id', just check the global pool. 11599 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11600 /*receiverId=*/true); 11601 } else { 11602 // Check protocols. 11603 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11604 /*IsInstance=*/true); 11605 } 11606 } 11607 11608 if (!Method) 11609 return false; 11610 11611 QualType T = Method->parameters()[0]->getType(); 11612 if (!T->isObjCObjectPointerType()) 11613 return false; 11614 11615 QualType R = Method->getReturnType(); 11616 if (!R->isScalarType()) 11617 return false; 11618 11619 return true; 11620 } 11621 11622 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11623 FromE = FromE->IgnoreParenImpCasts(); 11624 switch (FromE->getStmtClass()) { 11625 default: 11626 break; 11627 case Stmt::ObjCStringLiteralClass: 11628 // "string literal" 11629 return LK_String; 11630 case Stmt::ObjCArrayLiteralClass: 11631 // "array literal" 11632 return LK_Array; 11633 case Stmt::ObjCDictionaryLiteralClass: 11634 // "dictionary literal" 11635 return LK_Dictionary; 11636 case Stmt::BlockExprClass: 11637 return LK_Block; 11638 case Stmt::ObjCBoxedExprClass: { 11639 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11640 switch (Inner->getStmtClass()) { 11641 case Stmt::IntegerLiteralClass: 11642 case Stmt::FloatingLiteralClass: 11643 case Stmt::CharacterLiteralClass: 11644 case Stmt::ObjCBoolLiteralExprClass: 11645 case Stmt::CXXBoolLiteralExprClass: 11646 // "numeric literal" 11647 return LK_Numeric; 11648 case Stmt::ImplicitCastExprClass: { 11649 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11650 // Boolean literals can be represented by implicit casts. 11651 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11652 return LK_Numeric; 11653 break; 11654 } 11655 default: 11656 break; 11657 } 11658 return LK_Boxed; 11659 } 11660 } 11661 return LK_None; 11662 } 11663 11664 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11665 ExprResult &LHS, ExprResult &RHS, 11666 BinaryOperator::Opcode Opc){ 11667 Expr *Literal; 11668 Expr *Other; 11669 if (isObjCObjectLiteral(LHS)) { 11670 Literal = LHS.get(); 11671 Other = RHS.get(); 11672 } else { 11673 Literal = RHS.get(); 11674 Other = LHS.get(); 11675 } 11676 11677 // Don't warn on comparisons against nil. 11678 Other = Other->IgnoreParenCasts(); 11679 if (Other->isNullPointerConstant(S.getASTContext(), 11680 Expr::NPC_ValueDependentIsNotNull)) 11681 return; 11682 11683 // This should be kept in sync with warn_objc_literal_comparison. 11684 // LK_String should always be after the other literals, since it has its own 11685 // warning flag. 11686 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11687 assert(LiteralKind != Sema::LK_Block); 11688 if (LiteralKind == Sema::LK_None) { 11689 llvm_unreachable("Unknown Objective-C object literal kind"); 11690 } 11691 11692 if (LiteralKind == Sema::LK_String) 11693 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11694 << Literal->getSourceRange(); 11695 else 11696 S.Diag(Loc, diag::warn_objc_literal_comparison) 11697 << LiteralKind << Literal->getSourceRange(); 11698 11699 if (BinaryOperator::isEqualityOp(Opc) && 11700 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11701 SourceLocation Start = LHS.get()->getBeginLoc(); 11702 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11703 CharSourceRange OpRange = 11704 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11705 11706 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11707 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11708 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11709 << FixItHint::CreateInsertion(End, "]"); 11710 } 11711 } 11712 11713 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11714 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11715 ExprResult &RHS, SourceLocation Loc, 11716 BinaryOperatorKind Opc) { 11717 // Check that left hand side is !something. 11718 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11719 if (!UO || UO->getOpcode() != UO_LNot) return; 11720 11721 // Only check if the right hand side is non-bool arithmetic type. 11722 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11723 11724 // Make sure that the something in !something is not bool. 11725 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11726 if (SubExpr->isKnownToHaveBooleanValue()) return; 11727 11728 // Emit warning. 11729 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11730 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11731 << Loc << IsBitwiseOp; 11732 11733 // First note suggest !(x < y) 11734 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11735 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11736 FirstClose = S.getLocForEndOfToken(FirstClose); 11737 if (FirstClose.isInvalid()) 11738 FirstOpen = SourceLocation(); 11739 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11740 << IsBitwiseOp 11741 << FixItHint::CreateInsertion(FirstOpen, "(") 11742 << FixItHint::CreateInsertion(FirstClose, ")"); 11743 11744 // Second note suggests (!x) < y 11745 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11746 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11747 SecondClose = S.getLocForEndOfToken(SecondClose); 11748 if (SecondClose.isInvalid()) 11749 SecondOpen = SourceLocation(); 11750 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11751 << FixItHint::CreateInsertion(SecondOpen, "(") 11752 << FixItHint::CreateInsertion(SecondClose, ")"); 11753 } 11754 11755 // Returns true if E refers to a non-weak array. 11756 static bool checkForArray(const Expr *E) { 11757 const ValueDecl *D = nullptr; 11758 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11759 D = DR->getDecl(); 11760 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11761 if (Mem->isImplicitAccess()) 11762 D = Mem->getMemberDecl(); 11763 } 11764 if (!D) 11765 return false; 11766 return D->getType()->isArrayType() && !D->isWeak(); 11767 } 11768 11769 /// Diagnose some forms of syntactically-obvious tautological comparison. 11770 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11771 Expr *LHS, Expr *RHS, 11772 BinaryOperatorKind Opc) { 11773 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11774 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11775 11776 QualType LHSType = LHS->getType(); 11777 QualType RHSType = RHS->getType(); 11778 if (LHSType->hasFloatingRepresentation() || 11779 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11780 S.inTemplateInstantiation()) 11781 return; 11782 11783 // Comparisons between two array types are ill-formed for operator<=>, so 11784 // we shouldn't emit any additional warnings about it. 11785 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11786 return; 11787 11788 // For non-floating point types, check for self-comparisons of the form 11789 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11790 // often indicate logic errors in the program. 11791 // 11792 // NOTE: Don't warn about comparison expressions resulting from macro 11793 // expansion. Also don't warn about comparisons which are only self 11794 // comparisons within a template instantiation. The warnings should catch 11795 // obvious cases in the definition of the template anyways. The idea is to 11796 // warn when the typed comparison operator will always evaluate to the same 11797 // result. 11798 11799 // Used for indexing into %select in warn_comparison_always 11800 enum { 11801 AlwaysConstant, 11802 AlwaysTrue, 11803 AlwaysFalse, 11804 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11805 }; 11806 11807 // C++2a [depr.array.comp]: 11808 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11809 // operands of array type are deprecated. 11810 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11811 RHSStripped->getType()->isArrayType()) { 11812 S.Diag(Loc, diag::warn_depr_array_comparison) 11813 << LHS->getSourceRange() << RHS->getSourceRange() 11814 << LHSStripped->getType() << RHSStripped->getType(); 11815 // Carry on to produce the tautological comparison warning, if this 11816 // expression is potentially-evaluated, we can resolve the array to a 11817 // non-weak declaration, and so on. 11818 } 11819 11820 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11821 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11822 unsigned Result; 11823 switch (Opc) { 11824 case BO_EQ: 11825 case BO_LE: 11826 case BO_GE: 11827 Result = AlwaysTrue; 11828 break; 11829 case BO_NE: 11830 case BO_LT: 11831 case BO_GT: 11832 Result = AlwaysFalse; 11833 break; 11834 case BO_Cmp: 11835 Result = AlwaysEqual; 11836 break; 11837 default: 11838 Result = AlwaysConstant; 11839 break; 11840 } 11841 S.DiagRuntimeBehavior(Loc, nullptr, 11842 S.PDiag(diag::warn_comparison_always) 11843 << 0 /*self-comparison*/ 11844 << Result); 11845 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11846 // What is it always going to evaluate to? 11847 unsigned Result; 11848 switch (Opc) { 11849 case BO_EQ: // e.g. array1 == array2 11850 Result = AlwaysFalse; 11851 break; 11852 case BO_NE: // e.g. array1 != array2 11853 Result = AlwaysTrue; 11854 break; 11855 default: // e.g. array1 <= array2 11856 // The best we can say is 'a constant' 11857 Result = AlwaysConstant; 11858 break; 11859 } 11860 S.DiagRuntimeBehavior(Loc, nullptr, 11861 S.PDiag(diag::warn_comparison_always) 11862 << 1 /*array comparison*/ 11863 << Result); 11864 } 11865 } 11866 11867 if (isa<CastExpr>(LHSStripped)) 11868 LHSStripped = LHSStripped->IgnoreParenCasts(); 11869 if (isa<CastExpr>(RHSStripped)) 11870 RHSStripped = RHSStripped->IgnoreParenCasts(); 11871 11872 // Warn about comparisons against a string constant (unless the other 11873 // operand is null); the user probably wants string comparison function. 11874 Expr *LiteralString = nullptr; 11875 Expr *LiteralStringStripped = nullptr; 11876 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11877 !RHSStripped->isNullPointerConstant(S.Context, 11878 Expr::NPC_ValueDependentIsNull)) { 11879 LiteralString = LHS; 11880 LiteralStringStripped = LHSStripped; 11881 } else if ((isa<StringLiteral>(RHSStripped) || 11882 isa<ObjCEncodeExpr>(RHSStripped)) && 11883 !LHSStripped->isNullPointerConstant(S.Context, 11884 Expr::NPC_ValueDependentIsNull)) { 11885 LiteralString = RHS; 11886 LiteralStringStripped = RHSStripped; 11887 } 11888 11889 if (LiteralString) { 11890 S.DiagRuntimeBehavior(Loc, nullptr, 11891 S.PDiag(diag::warn_stringcompare) 11892 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11893 << LiteralString->getSourceRange()); 11894 } 11895 } 11896 11897 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11898 switch (CK) { 11899 default: { 11900 #ifndef NDEBUG 11901 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11902 << "\n"; 11903 #endif 11904 llvm_unreachable("unhandled cast kind"); 11905 } 11906 case CK_UserDefinedConversion: 11907 return ICK_Identity; 11908 case CK_LValueToRValue: 11909 return ICK_Lvalue_To_Rvalue; 11910 case CK_ArrayToPointerDecay: 11911 return ICK_Array_To_Pointer; 11912 case CK_FunctionToPointerDecay: 11913 return ICK_Function_To_Pointer; 11914 case CK_IntegralCast: 11915 return ICK_Integral_Conversion; 11916 case CK_FloatingCast: 11917 return ICK_Floating_Conversion; 11918 case CK_IntegralToFloating: 11919 case CK_FloatingToIntegral: 11920 return ICK_Floating_Integral; 11921 case CK_IntegralComplexCast: 11922 case CK_FloatingComplexCast: 11923 case CK_FloatingComplexToIntegralComplex: 11924 case CK_IntegralComplexToFloatingComplex: 11925 return ICK_Complex_Conversion; 11926 case CK_FloatingComplexToReal: 11927 case CK_FloatingRealToComplex: 11928 case CK_IntegralComplexToReal: 11929 case CK_IntegralRealToComplex: 11930 return ICK_Complex_Real; 11931 } 11932 } 11933 11934 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11935 QualType FromType, 11936 SourceLocation Loc) { 11937 // Check for a narrowing implicit conversion. 11938 StandardConversionSequence SCS; 11939 SCS.setAsIdentityConversion(); 11940 SCS.setToType(0, FromType); 11941 SCS.setToType(1, ToType); 11942 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11943 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11944 11945 APValue PreNarrowingValue; 11946 QualType PreNarrowingType; 11947 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11948 PreNarrowingType, 11949 /*IgnoreFloatToIntegralConversion*/ true)) { 11950 case NK_Dependent_Narrowing: 11951 // Implicit conversion to a narrower type, but the expression is 11952 // value-dependent so we can't tell whether it's actually narrowing. 11953 case NK_Not_Narrowing: 11954 return false; 11955 11956 case NK_Constant_Narrowing: 11957 // Implicit conversion to a narrower type, and the value is not a constant 11958 // expression. 11959 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11960 << /*Constant*/ 1 11961 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11962 return true; 11963 11964 case NK_Variable_Narrowing: 11965 // Implicit conversion to a narrower type, and the value is not a constant 11966 // expression. 11967 case NK_Type_Narrowing: 11968 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11969 << /*Constant*/ 0 << FromType << ToType; 11970 // TODO: It's not a constant expression, but what if the user intended it 11971 // to be? Can we produce notes to help them figure out why it isn't? 11972 return true; 11973 } 11974 llvm_unreachable("unhandled case in switch"); 11975 } 11976 11977 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11978 ExprResult &LHS, 11979 ExprResult &RHS, 11980 SourceLocation Loc) { 11981 QualType LHSType = LHS.get()->getType(); 11982 QualType RHSType = RHS.get()->getType(); 11983 // Dig out the original argument type and expression before implicit casts 11984 // were applied. These are the types/expressions we need to check the 11985 // [expr.spaceship] requirements against. 11986 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11987 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11988 QualType LHSStrippedType = LHSStripped.get()->getType(); 11989 QualType RHSStrippedType = RHSStripped.get()->getType(); 11990 11991 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11992 // other is not, the program is ill-formed. 11993 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11994 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11995 return QualType(); 11996 } 11997 11998 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11999 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 12000 RHSStrippedType->isEnumeralType(); 12001 if (NumEnumArgs == 1) { 12002 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 12003 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 12004 if (OtherTy->hasFloatingRepresentation()) { 12005 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12006 return QualType(); 12007 } 12008 } 12009 if (NumEnumArgs == 2) { 12010 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 12011 // type E, the operator yields the result of converting the operands 12012 // to the underlying type of E and applying <=> to the converted operands. 12013 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 12014 S.InvalidOperands(Loc, LHS, RHS); 12015 return QualType(); 12016 } 12017 QualType IntType = 12018 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 12019 assert(IntType->isArithmeticType()); 12020 12021 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 12022 // promote the boolean type, and all other promotable integer types, to 12023 // avoid this. 12024 if (IntType->isPromotableIntegerType()) 12025 IntType = S.Context.getPromotedIntegerType(IntType); 12026 12027 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 12028 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 12029 LHSType = RHSType = IntType; 12030 } 12031 12032 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 12033 // usual arithmetic conversions are applied to the operands. 12034 QualType Type = 12035 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12036 if (LHS.isInvalid() || RHS.isInvalid()) 12037 return QualType(); 12038 if (Type.isNull()) 12039 return S.InvalidOperands(Loc, LHS, RHS); 12040 12041 Optional<ComparisonCategoryType> CCT = 12042 getComparisonCategoryForBuiltinCmp(Type); 12043 if (!CCT) 12044 return S.InvalidOperands(Loc, LHS, RHS); 12045 12046 bool HasNarrowing = checkThreeWayNarrowingConversion( 12047 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 12048 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 12049 RHS.get()->getBeginLoc()); 12050 if (HasNarrowing) 12051 return QualType(); 12052 12053 assert(!Type.isNull() && "composite type for <=> has not been set"); 12054 12055 return S.CheckComparisonCategoryType( 12056 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 12057 } 12058 12059 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 12060 ExprResult &RHS, 12061 SourceLocation Loc, 12062 BinaryOperatorKind Opc) { 12063 if (Opc == BO_Cmp) 12064 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 12065 12066 // C99 6.5.8p3 / C99 6.5.9p4 12067 QualType Type = 12068 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12069 if (LHS.isInvalid() || RHS.isInvalid()) 12070 return QualType(); 12071 if (Type.isNull()) 12072 return S.InvalidOperands(Loc, LHS, RHS); 12073 assert(Type->isArithmeticType() || Type->isEnumeralType()); 12074 12075 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 12076 return S.InvalidOperands(Loc, LHS, RHS); 12077 12078 // Check for comparisons of floating point operands using != and ==. 12079 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 12080 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12081 12082 // The result of comparisons is 'bool' in C++, 'int' in C. 12083 return S.Context.getLogicalOperationType(); 12084 } 12085 12086 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 12087 if (!NullE.get()->getType()->isAnyPointerType()) 12088 return; 12089 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 12090 if (!E.get()->getType()->isAnyPointerType() && 12091 E.get()->isNullPointerConstant(Context, 12092 Expr::NPC_ValueDependentIsNotNull) == 12093 Expr::NPCK_ZeroExpression) { 12094 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 12095 if (CL->getValue() == 0) 12096 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12097 << NullValue 12098 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12099 NullValue ? "NULL" : "(void *)0"); 12100 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 12101 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 12102 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 12103 if (T == Context.CharTy) 12104 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12105 << NullValue 12106 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12107 NullValue ? "NULL" : "(void *)0"); 12108 } 12109 } 12110 } 12111 12112 // C99 6.5.8, C++ [expr.rel] 12113 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 12114 SourceLocation Loc, 12115 BinaryOperatorKind Opc) { 12116 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 12117 bool IsThreeWay = Opc == BO_Cmp; 12118 bool IsOrdered = IsRelational || IsThreeWay; 12119 auto IsAnyPointerType = [](ExprResult E) { 12120 QualType Ty = E.get()->getType(); 12121 return Ty->isPointerType() || Ty->isMemberPointerType(); 12122 }; 12123 12124 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 12125 // type, array-to-pointer, ..., conversions are performed on both operands to 12126 // bring them to their composite type. 12127 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 12128 // any type-related checks. 12129 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 12130 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12131 if (LHS.isInvalid()) 12132 return QualType(); 12133 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12134 if (RHS.isInvalid()) 12135 return QualType(); 12136 } else { 12137 LHS = DefaultLvalueConversion(LHS.get()); 12138 if (LHS.isInvalid()) 12139 return QualType(); 12140 RHS = DefaultLvalueConversion(RHS.get()); 12141 if (RHS.isInvalid()) 12142 return QualType(); 12143 } 12144 12145 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 12146 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 12147 CheckPtrComparisonWithNullChar(LHS, RHS); 12148 CheckPtrComparisonWithNullChar(RHS, LHS); 12149 } 12150 12151 // Handle vector comparisons separately. 12152 if (LHS.get()->getType()->isVectorType() || 12153 RHS.get()->getType()->isVectorType()) 12154 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 12155 12156 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12157 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12158 12159 QualType LHSType = LHS.get()->getType(); 12160 QualType RHSType = RHS.get()->getType(); 12161 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 12162 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 12163 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 12164 12165 const Expr::NullPointerConstantKind LHSNullKind = 12166 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12167 const Expr::NullPointerConstantKind RHSNullKind = 12168 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12169 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 12170 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 12171 12172 auto computeResultTy = [&]() { 12173 if (Opc != BO_Cmp) 12174 return Context.getLogicalOperationType(); 12175 assert(getLangOpts().CPlusPlus); 12176 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 12177 12178 QualType CompositeTy = LHS.get()->getType(); 12179 assert(!CompositeTy->isReferenceType()); 12180 12181 Optional<ComparisonCategoryType> CCT = 12182 getComparisonCategoryForBuiltinCmp(CompositeTy); 12183 if (!CCT) 12184 return InvalidOperands(Loc, LHS, RHS); 12185 12186 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 12187 // P0946R0: Comparisons between a null pointer constant and an object 12188 // pointer result in std::strong_equality, which is ill-formed under 12189 // P1959R0. 12190 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 12191 << (LHSIsNull ? LHS.get()->getSourceRange() 12192 : RHS.get()->getSourceRange()); 12193 return QualType(); 12194 } 12195 12196 return CheckComparisonCategoryType( 12197 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 12198 }; 12199 12200 if (!IsOrdered && LHSIsNull != RHSIsNull) { 12201 bool IsEquality = Opc == BO_EQ; 12202 if (RHSIsNull) 12203 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 12204 RHS.get()->getSourceRange()); 12205 else 12206 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 12207 LHS.get()->getSourceRange()); 12208 } 12209 12210 if (IsOrdered && LHSType->isFunctionPointerType() && 12211 RHSType->isFunctionPointerType()) { 12212 // Valid unless a relational comparison of function pointers 12213 bool IsError = Opc == BO_Cmp; 12214 auto DiagID = 12215 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 12216 : getLangOpts().CPlusPlus 12217 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 12218 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 12219 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 12220 << RHS.get()->getSourceRange(); 12221 if (IsError) 12222 return QualType(); 12223 } 12224 12225 if ((LHSType->isIntegerType() && !LHSIsNull) || 12226 (RHSType->isIntegerType() && !RHSIsNull)) { 12227 // Skip normal pointer conversion checks in this case; we have better 12228 // diagnostics for this below. 12229 } else if (getLangOpts().CPlusPlus) { 12230 // Equality comparison of a function pointer to a void pointer is invalid, 12231 // but we allow it as an extension. 12232 // FIXME: If we really want to allow this, should it be part of composite 12233 // pointer type computation so it works in conditionals too? 12234 if (!IsOrdered && 12235 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 12236 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 12237 // This is a gcc extension compatibility comparison. 12238 // In a SFINAE context, we treat this as a hard error to maintain 12239 // conformance with the C++ standard. 12240 diagnoseFunctionPointerToVoidComparison( 12241 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 12242 12243 if (isSFINAEContext()) 12244 return QualType(); 12245 12246 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12247 return computeResultTy(); 12248 } 12249 12250 // C++ [expr.eq]p2: 12251 // If at least one operand is a pointer [...] bring them to their 12252 // composite pointer type. 12253 // C++ [expr.spaceship]p6 12254 // If at least one of the operands is of pointer type, [...] bring them 12255 // to their composite pointer type. 12256 // C++ [expr.rel]p2: 12257 // If both operands are pointers, [...] bring them to their composite 12258 // pointer type. 12259 // For <=>, the only valid non-pointer types are arrays and functions, and 12260 // we already decayed those, so this is really the same as the relational 12261 // comparison rule. 12262 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 12263 (IsOrdered ? 2 : 1) && 12264 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 12265 RHSType->isObjCObjectPointerType()))) { 12266 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12267 return QualType(); 12268 return computeResultTy(); 12269 } 12270 } else if (LHSType->isPointerType() && 12271 RHSType->isPointerType()) { // C99 6.5.8p2 12272 // All of the following pointer-related warnings are GCC extensions, except 12273 // when handling null pointer constants. 12274 QualType LCanPointeeTy = 12275 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12276 QualType RCanPointeeTy = 12277 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12278 12279 // C99 6.5.9p2 and C99 6.5.8p2 12280 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 12281 RCanPointeeTy.getUnqualifiedType())) { 12282 if (IsRelational) { 12283 // Pointers both need to point to complete or incomplete types 12284 if ((LCanPointeeTy->isIncompleteType() != 12285 RCanPointeeTy->isIncompleteType()) && 12286 !getLangOpts().C11) { 12287 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 12288 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 12289 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 12290 << RCanPointeeTy->isIncompleteType(); 12291 } 12292 } 12293 } else if (!IsRelational && 12294 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 12295 // Valid unless comparison between non-null pointer and function pointer 12296 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 12297 && !LHSIsNull && !RHSIsNull) 12298 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 12299 /*isError*/false); 12300 } else { 12301 // Invalid 12302 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 12303 } 12304 if (LCanPointeeTy != RCanPointeeTy) { 12305 // Treat NULL constant as a special case in OpenCL. 12306 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 12307 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 12308 Diag(Loc, 12309 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 12310 << LHSType << RHSType << 0 /* comparison */ 12311 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12312 } 12313 } 12314 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 12315 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12316 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12317 : CK_BitCast; 12318 if (LHSIsNull && !RHSIsNull) 12319 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12320 else 12321 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12322 } 12323 return computeResultTy(); 12324 } 12325 12326 if (getLangOpts().CPlusPlus) { 12327 // C++ [expr.eq]p4: 12328 // Two operands of type std::nullptr_t or one operand of type 12329 // std::nullptr_t and the other a null pointer constant compare equal. 12330 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12331 if (LHSType->isNullPtrType()) { 12332 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12333 return computeResultTy(); 12334 } 12335 if (RHSType->isNullPtrType()) { 12336 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12337 return computeResultTy(); 12338 } 12339 } 12340 12341 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12342 // These aren't covered by the composite pointer type rules. 12343 if (!IsOrdered && RHSType->isNullPtrType() && 12344 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12345 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12346 return computeResultTy(); 12347 } 12348 if (!IsOrdered && LHSType->isNullPtrType() && 12349 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12350 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12351 return computeResultTy(); 12352 } 12353 12354 if (IsRelational && 12355 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12356 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12357 // HACK: Relational comparison of nullptr_t against a pointer type is 12358 // invalid per DR583, but we allow it within std::less<> and friends, 12359 // since otherwise common uses of it break. 12360 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12361 // friends to have std::nullptr_t overload candidates. 12362 DeclContext *DC = CurContext; 12363 if (isa<FunctionDecl>(DC)) 12364 DC = DC->getParent(); 12365 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12366 if (CTSD->isInStdNamespace() && 12367 llvm::StringSwitch<bool>(CTSD->getName()) 12368 .Cases("less", "less_equal", "greater", "greater_equal", true) 12369 .Default(false)) { 12370 if (RHSType->isNullPtrType()) 12371 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12372 else 12373 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12374 return computeResultTy(); 12375 } 12376 } 12377 } 12378 12379 // C++ [expr.eq]p2: 12380 // If at least one operand is a pointer to member, [...] bring them to 12381 // their composite pointer type. 12382 if (!IsOrdered && 12383 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12384 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12385 return QualType(); 12386 else 12387 return computeResultTy(); 12388 } 12389 } 12390 12391 // Handle block pointer types. 12392 if (!IsOrdered && LHSType->isBlockPointerType() && 12393 RHSType->isBlockPointerType()) { 12394 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12395 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12396 12397 if (!LHSIsNull && !RHSIsNull && 12398 !Context.typesAreCompatible(lpointee, rpointee)) { 12399 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12400 << LHSType << RHSType << LHS.get()->getSourceRange() 12401 << RHS.get()->getSourceRange(); 12402 } 12403 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12404 return computeResultTy(); 12405 } 12406 12407 // Allow block pointers to be compared with null pointer constants. 12408 if (!IsOrdered 12409 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12410 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12411 if (!LHSIsNull && !RHSIsNull) { 12412 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12413 ->getPointeeType()->isVoidType()) 12414 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12415 ->getPointeeType()->isVoidType()))) 12416 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12417 << LHSType << RHSType << LHS.get()->getSourceRange() 12418 << RHS.get()->getSourceRange(); 12419 } 12420 if (LHSIsNull && !RHSIsNull) 12421 LHS = ImpCastExprToType(LHS.get(), RHSType, 12422 RHSType->isPointerType() ? CK_BitCast 12423 : CK_AnyPointerToBlockPointerCast); 12424 else 12425 RHS = ImpCastExprToType(RHS.get(), LHSType, 12426 LHSType->isPointerType() ? CK_BitCast 12427 : CK_AnyPointerToBlockPointerCast); 12428 return computeResultTy(); 12429 } 12430 12431 if (LHSType->isObjCObjectPointerType() || 12432 RHSType->isObjCObjectPointerType()) { 12433 const PointerType *LPT = LHSType->getAs<PointerType>(); 12434 const PointerType *RPT = RHSType->getAs<PointerType>(); 12435 if (LPT || RPT) { 12436 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12437 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12438 12439 if (!LPtrToVoid && !RPtrToVoid && 12440 !Context.typesAreCompatible(LHSType, RHSType)) { 12441 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12442 /*isError*/false); 12443 } 12444 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12445 // the RHS, but we have test coverage for this behavior. 12446 // FIXME: Consider using convertPointersToCompositeType in C++. 12447 if (LHSIsNull && !RHSIsNull) { 12448 Expr *E = LHS.get(); 12449 if (getLangOpts().ObjCAutoRefCount) 12450 CheckObjCConversion(SourceRange(), RHSType, E, 12451 CCK_ImplicitConversion); 12452 LHS = ImpCastExprToType(E, RHSType, 12453 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12454 } 12455 else { 12456 Expr *E = RHS.get(); 12457 if (getLangOpts().ObjCAutoRefCount) 12458 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12459 /*Diagnose=*/true, 12460 /*DiagnoseCFAudited=*/false, Opc); 12461 RHS = ImpCastExprToType(E, LHSType, 12462 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12463 } 12464 return computeResultTy(); 12465 } 12466 if (LHSType->isObjCObjectPointerType() && 12467 RHSType->isObjCObjectPointerType()) { 12468 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12469 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12470 /*isError*/false); 12471 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12472 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12473 12474 if (LHSIsNull && !RHSIsNull) 12475 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12476 else 12477 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12478 return computeResultTy(); 12479 } 12480 12481 if (!IsOrdered && LHSType->isBlockPointerType() && 12482 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12483 LHS = ImpCastExprToType(LHS.get(), RHSType, 12484 CK_BlockPointerToObjCPointerCast); 12485 return computeResultTy(); 12486 } else if (!IsOrdered && 12487 LHSType->isBlockCompatibleObjCPointerType(Context) && 12488 RHSType->isBlockPointerType()) { 12489 RHS = ImpCastExprToType(RHS.get(), LHSType, 12490 CK_BlockPointerToObjCPointerCast); 12491 return computeResultTy(); 12492 } 12493 } 12494 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12495 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12496 unsigned DiagID = 0; 12497 bool isError = false; 12498 if (LangOpts.DebuggerSupport) { 12499 // Under a debugger, allow the comparison of pointers to integers, 12500 // since users tend to want to compare addresses. 12501 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12502 (RHSIsNull && RHSType->isIntegerType())) { 12503 if (IsOrdered) { 12504 isError = getLangOpts().CPlusPlus; 12505 DiagID = 12506 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12507 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12508 } 12509 } else if (getLangOpts().CPlusPlus) { 12510 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12511 isError = true; 12512 } else if (IsOrdered) 12513 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12514 else 12515 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12516 12517 if (DiagID) { 12518 Diag(Loc, DiagID) 12519 << LHSType << RHSType << LHS.get()->getSourceRange() 12520 << RHS.get()->getSourceRange(); 12521 if (isError) 12522 return QualType(); 12523 } 12524 12525 if (LHSType->isIntegerType()) 12526 LHS = ImpCastExprToType(LHS.get(), RHSType, 12527 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12528 else 12529 RHS = ImpCastExprToType(RHS.get(), LHSType, 12530 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12531 return computeResultTy(); 12532 } 12533 12534 // Handle block pointers. 12535 if (!IsOrdered && RHSIsNull 12536 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12537 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12538 return computeResultTy(); 12539 } 12540 if (!IsOrdered && LHSIsNull 12541 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12542 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12543 return computeResultTy(); 12544 } 12545 12546 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12547 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12548 return computeResultTy(); 12549 } 12550 12551 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12552 return computeResultTy(); 12553 } 12554 12555 if (LHSIsNull && RHSType->isQueueT()) { 12556 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12557 return computeResultTy(); 12558 } 12559 12560 if (LHSType->isQueueT() && RHSIsNull) { 12561 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12562 return computeResultTy(); 12563 } 12564 } 12565 12566 return InvalidOperands(Loc, LHS, RHS); 12567 } 12568 12569 // Return a signed ext_vector_type that is of identical size and number of 12570 // elements. For floating point vectors, return an integer type of identical 12571 // size and number of elements. In the non ext_vector_type case, search from 12572 // the largest type to the smallest type to avoid cases where long long == long, 12573 // where long gets picked over long long. 12574 QualType Sema::GetSignedVectorType(QualType V) { 12575 const VectorType *VTy = V->castAs<VectorType>(); 12576 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12577 12578 if (isa<ExtVectorType>(VTy)) { 12579 if (VTy->isExtVectorBoolType()) 12580 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements()); 12581 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12582 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12583 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12584 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12585 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12586 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12587 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12588 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); 12589 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12590 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12591 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12592 "Unhandled vector element size in vector compare"); 12593 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12594 } 12595 12596 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12597 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), 12598 VectorType::GenericVector); 12599 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12600 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12601 VectorType::GenericVector); 12602 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12603 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12604 VectorType::GenericVector); 12605 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12606 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12607 VectorType::GenericVector); 12608 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12609 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12610 VectorType::GenericVector); 12611 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12612 "Unhandled vector element size in vector compare"); 12613 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12614 VectorType::GenericVector); 12615 } 12616 12617 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12618 /// operates on extended vector types. Instead of producing an IntTy result, 12619 /// like a scalar comparison, a vector comparison produces a vector of integer 12620 /// types. 12621 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12622 SourceLocation Loc, 12623 BinaryOperatorKind Opc) { 12624 if (Opc == BO_Cmp) { 12625 Diag(Loc, diag::err_three_way_vector_comparison); 12626 return QualType(); 12627 } 12628 12629 // Check to make sure we're operating on vectors of the same type and width, 12630 // Allowing one side to be a scalar of element type. 12631 QualType vType = 12632 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false, 12633 /*AllowBothBool*/ true, 12634 /*AllowBoolConversions*/ getLangOpts().ZVector, 12635 /*AllowBooleanOperation*/ true, 12636 /*ReportInvalid*/ true); 12637 if (vType.isNull()) 12638 return vType; 12639 12640 QualType LHSType = LHS.get()->getType(); 12641 12642 // Determine the return type of a vector compare. By default clang will return 12643 // a scalar for all vector compares except vector bool and vector pixel. 12644 // With the gcc compiler we will always return a vector type and with the xl 12645 // compiler we will always return a scalar type. This switch allows choosing 12646 // which behavior is prefered. 12647 if (getLangOpts().AltiVec) { 12648 switch (getLangOpts().getAltivecSrcCompat()) { 12649 case LangOptions::AltivecSrcCompatKind::Mixed: 12650 // If AltiVec, the comparison results in a numeric type, i.e. 12651 // bool for C++, int for C 12652 if (vType->castAs<VectorType>()->getVectorKind() == 12653 VectorType::AltiVecVector) 12654 return Context.getLogicalOperationType(); 12655 else 12656 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12657 break; 12658 case LangOptions::AltivecSrcCompatKind::GCC: 12659 // For GCC we always return the vector type. 12660 break; 12661 case LangOptions::AltivecSrcCompatKind::XL: 12662 return Context.getLogicalOperationType(); 12663 break; 12664 } 12665 } 12666 12667 // For non-floating point types, check for self-comparisons of the form 12668 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12669 // often indicate logic errors in the program. 12670 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12671 12672 // Check for comparisons of floating point operands using != and ==. 12673 if (BinaryOperator::isEqualityOp(Opc) && 12674 LHSType->hasFloatingRepresentation()) { 12675 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12676 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12677 } 12678 12679 // Return a signed type for the vector. 12680 return GetSignedVectorType(vType); 12681 } 12682 12683 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12684 const ExprResult &XorRHS, 12685 const SourceLocation Loc) { 12686 // Do not diagnose macros. 12687 if (Loc.isMacroID()) 12688 return; 12689 12690 // Do not diagnose if both LHS and RHS are macros. 12691 if (XorLHS.get()->getExprLoc().isMacroID() && 12692 XorRHS.get()->getExprLoc().isMacroID()) 12693 return; 12694 12695 bool Negative = false; 12696 bool ExplicitPlus = false; 12697 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12698 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12699 12700 if (!LHSInt) 12701 return; 12702 if (!RHSInt) { 12703 // Check negative literals. 12704 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12705 UnaryOperatorKind Opc = UO->getOpcode(); 12706 if (Opc != UO_Minus && Opc != UO_Plus) 12707 return; 12708 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12709 if (!RHSInt) 12710 return; 12711 Negative = (Opc == UO_Minus); 12712 ExplicitPlus = !Negative; 12713 } else { 12714 return; 12715 } 12716 } 12717 12718 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12719 llvm::APInt RightSideValue = RHSInt->getValue(); 12720 if (LeftSideValue != 2 && LeftSideValue != 10) 12721 return; 12722 12723 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12724 return; 12725 12726 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12727 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12728 llvm::StringRef ExprStr = 12729 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12730 12731 CharSourceRange XorRange = 12732 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12733 llvm::StringRef XorStr = 12734 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12735 // Do not diagnose if xor keyword/macro is used. 12736 if (XorStr == "xor") 12737 return; 12738 12739 std::string LHSStr = std::string(Lexer::getSourceText( 12740 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12741 S.getSourceManager(), S.getLangOpts())); 12742 std::string RHSStr = std::string(Lexer::getSourceText( 12743 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12744 S.getSourceManager(), S.getLangOpts())); 12745 12746 if (Negative) { 12747 RightSideValue = -RightSideValue; 12748 RHSStr = "-" + RHSStr; 12749 } else if (ExplicitPlus) { 12750 RHSStr = "+" + RHSStr; 12751 } 12752 12753 StringRef LHSStrRef = LHSStr; 12754 StringRef RHSStrRef = RHSStr; 12755 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12756 // literals. 12757 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12758 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12759 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12760 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12761 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12762 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12763 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12764 return; 12765 12766 bool SuggestXor = 12767 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12768 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12769 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12770 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12771 std::string SuggestedExpr = "1 << " + RHSStr; 12772 bool Overflow = false; 12773 llvm::APInt One = (LeftSideValue - 1); 12774 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12775 if (Overflow) { 12776 if (RightSideIntValue < 64) 12777 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12778 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12779 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12780 else if (RightSideIntValue == 64) 12781 S.Diag(Loc, diag::warn_xor_used_as_pow) 12782 << ExprStr << toString(XorValue, 10, true); 12783 else 12784 return; 12785 } else { 12786 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12787 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12788 << toString(PowValue, 10, true) 12789 << FixItHint::CreateReplacement( 12790 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12791 } 12792 12793 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12794 << ("0x2 ^ " + RHSStr) << SuggestXor; 12795 } else if (LeftSideValue == 10) { 12796 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12797 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12798 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12799 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12800 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12801 << ("0xA ^ " + RHSStr) << SuggestXor; 12802 } 12803 } 12804 12805 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12806 SourceLocation Loc) { 12807 // Ensure that either both operands are of the same vector type, or 12808 // one operand is of a vector type and the other is of its element type. 12809 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12810 /*AllowBothBool*/ true, 12811 /*AllowBoolConversions*/ false, 12812 /*AllowBooleanOperation*/ false, 12813 /*ReportInvalid*/ false); 12814 if (vType.isNull()) 12815 return InvalidOperands(Loc, LHS, RHS); 12816 if (getLangOpts().OpenCL && 12817 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12818 vType->hasFloatingRepresentation()) 12819 return InvalidOperands(Loc, LHS, RHS); 12820 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12821 // usage of the logical operators && and || with vectors in C. This 12822 // check could be notionally dropped. 12823 if (!getLangOpts().CPlusPlus && 12824 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12825 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12826 12827 return GetSignedVectorType(LHS.get()->getType()); 12828 } 12829 12830 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12831 SourceLocation Loc, 12832 bool IsCompAssign) { 12833 if (!IsCompAssign) { 12834 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12835 if (LHS.isInvalid()) 12836 return QualType(); 12837 } 12838 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12839 if (RHS.isInvalid()) 12840 return QualType(); 12841 12842 // For conversion purposes, we ignore any qualifiers. 12843 // For example, "const float" and "float" are equivalent. 12844 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12845 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12846 12847 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12848 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12849 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12850 12851 if (Context.hasSameType(LHSType, RHSType)) 12852 return LHSType; 12853 12854 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12855 // case we have to return InvalidOperands. 12856 ExprResult OriginalLHS = LHS; 12857 ExprResult OriginalRHS = RHS; 12858 if (LHSMatType && !RHSMatType) { 12859 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12860 if (!RHS.isInvalid()) 12861 return LHSType; 12862 12863 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12864 } 12865 12866 if (!LHSMatType && RHSMatType) { 12867 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12868 if (!LHS.isInvalid()) 12869 return RHSType; 12870 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12871 } 12872 12873 return InvalidOperands(Loc, LHS, RHS); 12874 } 12875 12876 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12877 SourceLocation Loc, 12878 bool IsCompAssign) { 12879 if (!IsCompAssign) { 12880 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12881 if (LHS.isInvalid()) 12882 return QualType(); 12883 } 12884 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12885 if (RHS.isInvalid()) 12886 return QualType(); 12887 12888 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12889 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12890 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12891 12892 if (LHSMatType && RHSMatType) { 12893 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12894 return InvalidOperands(Loc, LHS, RHS); 12895 12896 if (!Context.hasSameType(LHSMatType->getElementType(), 12897 RHSMatType->getElementType())) 12898 return InvalidOperands(Loc, LHS, RHS); 12899 12900 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12901 LHSMatType->getNumRows(), 12902 RHSMatType->getNumColumns()); 12903 } 12904 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12905 } 12906 12907 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { 12908 switch (Opc) { 12909 default: 12910 return false; 12911 case BO_And: 12912 case BO_AndAssign: 12913 case BO_Or: 12914 case BO_OrAssign: 12915 case BO_Xor: 12916 case BO_XorAssign: 12917 return true; 12918 } 12919 } 12920 12921 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12922 SourceLocation Loc, 12923 BinaryOperatorKind Opc) { 12924 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12925 12926 bool IsCompAssign = 12927 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12928 12929 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); 12930 12931 if (LHS.get()->getType()->isVectorType() || 12932 RHS.get()->getType()->isVectorType()) { 12933 if (LHS.get()->getType()->hasIntegerRepresentation() && 12934 RHS.get()->getType()->hasIntegerRepresentation()) 12935 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12936 /*AllowBothBool*/ true, 12937 /*AllowBoolConversions*/ getLangOpts().ZVector, 12938 /*AllowBooleanOperation*/ LegalBoolVecOperator, 12939 /*ReportInvalid*/ true); 12940 return InvalidOperands(Loc, LHS, RHS); 12941 } 12942 12943 if (LHS.get()->getType()->isVLSTBuiltinType() || 12944 RHS.get()->getType()->isVLSTBuiltinType()) { 12945 if (LHS.get()->getType()->hasIntegerRepresentation() && 12946 RHS.get()->getType()->hasIntegerRepresentation()) 12947 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 12948 ACK_BitwiseOp); 12949 return InvalidOperands(Loc, LHS, RHS); 12950 } 12951 12952 if (LHS.get()->getType()->isVLSTBuiltinType() || 12953 RHS.get()->getType()->isVLSTBuiltinType()) { 12954 if (LHS.get()->getType()->hasIntegerRepresentation() && 12955 RHS.get()->getType()->hasIntegerRepresentation()) 12956 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 12957 ACK_BitwiseOp); 12958 return InvalidOperands(Loc, LHS, RHS); 12959 } 12960 12961 if (Opc == BO_And) 12962 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12963 12964 if (LHS.get()->getType()->hasFloatingRepresentation() || 12965 RHS.get()->getType()->hasFloatingRepresentation()) 12966 return InvalidOperands(Loc, LHS, RHS); 12967 12968 ExprResult LHSResult = LHS, RHSResult = RHS; 12969 QualType compType = UsualArithmeticConversions( 12970 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12971 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12972 return QualType(); 12973 LHS = LHSResult.get(); 12974 RHS = RHSResult.get(); 12975 12976 if (Opc == BO_Xor) 12977 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12978 12979 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12980 return compType; 12981 return InvalidOperands(Loc, LHS, RHS); 12982 } 12983 12984 // C99 6.5.[13,14] 12985 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12986 SourceLocation Loc, 12987 BinaryOperatorKind Opc) { 12988 // Check vector operands differently. 12989 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12990 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12991 12992 bool EnumConstantInBoolContext = false; 12993 for (const ExprResult &HS : {LHS, RHS}) { 12994 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12995 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12996 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12997 EnumConstantInBoolContext = true; 12998 } 12999 } 13000 13001 if (EnumConstantInBoolContext) 13002 Diag(Loc, diag::warn_enum_constant_in_bool_context); 13003 13004 // Diagnose cases where the user write a logical and/or but probably meant a 13005 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 13006 // is a constant. 13007 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 13008 !LHS.get()->getType()->isBooleanType() && 13009 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 13010 // Don't warn in macros or template instantiations. 13011 !Loc.isMacroID() && !inTemplateInstantiation()) { 13012 // If the RHS can be constant folded, and if it constant folds to something 13013 // that isn't 0 or 1 (which indicate a potential logical operation that 13014 // happened to fold to true/false) then warn. 13015 // Parens on the RHS are ignored. 13016 Expr::EvalResult EVResult; 13017 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 13018 llvm::APSInt Result = EVResult.Val.getInt(); 13019 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 13020 !RHS.get()->getExprLoc().isMacroID()) || 13021 (Result != 0 && Result != 1)) { 13022 Diag(Loc, diag::warn_logical_instead_of_bitwise) 13023 << RHS.get()->getSourceRange() 13024 << (Opc == BO_LAnd ? "&&" : "||"); 13025 // Suggest replacing the logical operator with the bitwise version 13026 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 13027 << (Opc == BO_LAnd ? "&" : "|") 13028 << FixItHint::CreateReplacement(SourceRange( 13029 Loc, getLocForEndOfToken(Loc)), 13030 Opc == BO_LAnd ? "&" : "|"); 13031 if (Opc == BO_LAnd) 13032 // Suggest replacing "Foo() && kNonZero" with "Foo()" 13033 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 13034 << FixItHint::CreateRemoval( 13035 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 13036 RHS.get()->getEndLoc())); 13037 } 13038 } 13039 } 13040 13041 if (!Context.getLangOpts().CPlusPlus) { 13042 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 13043 // not operate on the built-in scalar and vector float types. 13044 if (Context.getLangOpts().OpenCL && 13045 Context.getLangOpts().OpenCLVersion < 120) { 13046 if (LHS.get()->getType()->isFloatingType() || 13047 RHS.get()->getType()->isFloatingType()) 13048 return InvalidOperands(Loc, LHS, RHS); 13049 } 13050 13051 LHS = UsualUnaryConversions(LHS.get()); 13052 if (LHS.isInvalid()) 13053 return QualType(); 13054 13055 RHS = UsualUnaryConversions(RHS.get()); 13056 if (RHS.isInvalid()) 13057 return QualType(); 13058 13059 if (!LHS.get()->getType()->isScalarType() || 13060 !RHS.get()->getType()->isScalarType()) 13061 return InvalidOperands(Loc, LHS, RHS); 13062 13063 return Context.IntTy; 13064 } 13065 13066 // The following is safe because we only use this method for 13067 // non-overloadable operands. 13068 13069 // C++ [expr.log.and]p1 13070 // C++ [expr.log.or]p1 13071 // The operands are both contextually converted to type bool. 13072 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 13073 if (LHSRes.isInvalid()) 13074 return InvalidOperands(Loc, LHS, RHS); 13075 LHS = LHSRes; 13076 13077 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 13078 if (RHSRes.isInvalid()) 13079 return InvalidOperands(Loc, LHS, RHS); 13080 RHS = RHSRes; 13081 13082 // C++ [expr.log.and]p2 13083 // C++ [expr.log.or]p2 13084 // The result is a bool. 13085 return Context.BoolTy; 13086 } 13087 13088 static bool IsReadonlyMessage(Expr *E, Sema &S) { 13089 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13090 if (!ME) return false; 13091 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 13092 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 13093 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 13094 if (!Base) return false; 13095 return Base->getMethodDecl() != nullptr; 13096 } 13097 13098 /// Is the given expression (which must be 'const') a reference to a 13099 /// variable which was originally non-const, but which has become 13100 /// 'const' due to being captured within a block? 13101 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 13102 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 13103 assert(E->isLValue() && E->getType().isConstQualified()); 13104 E = E->IgnoreParens(); 13105 13106 // Must be a reference to a declaration from an enclosing scope. 13107 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 13108 if (!DRE) return NCCK_None; 13109 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 13110 13111 // The declaration must be a variable which is not declared 'const'. 13112 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 13113 if (!var) return NCCK_None; 13114 if (var->getType().isConstQualified()) return NCCK_None; 13115 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 13116 13117 // Decide whether the first capture was for a block or a lambda. 13118 DeclContext *DC = S.CurContext, *Prev = nullptr; 13119 // Decide whether the first capture was for a block or a lambda. 13120 while (DC) { 13121 // For init-capture, it is possible that the variable belongs to the 13122 // template pattern of the current context. 13123 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 13124 if (var->isInitCapture() && 13125 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 13126 break; 13127 if (DC == var->getDeclContext()) 13128 break; 13129 Prev = DC; 13130 DC = DC->getParent(); 13131 } 13132 // Unless we have an init-capture, we've gone one step too far. 13133 if (!var->isInitCapture()) 13134 DC = Prev; 13135 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 13136 } 13137 13138 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 13139 Ty = Ty.getNonReferenceType(); 13140 if (IsDereference && Ty->isPointerType()) 13141 Ty = Ty->getPointeeType(); 13142 return !Ty.isConstQualified(); 13143 } 13144 13145 // Update err_typecheck_assign_const and note_typecheck_assign_const 13146 // when this enum is changed. 13147 enum { 13148 ConstFunction, 13149 ConstVariable, 13150 ConstMember, 13151 ConstMethod, 13152 NestedConstMember, 13153 ConstUnknown, // Keep as last element 13154 }; 13155 13156 /// Emit the "read-only variable not assignable" error and print notes to give 13157 /// more information about why the variable is not assignable, such as pointing 13158 /// to the declaration of a const variable, showing that a method is const, or 13159 /// that the function is returning a const reference. 13160 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 13161 SourceLocation Loc) { 13162 SourceRange ExprRange = E->getSourceRange(); 13163 13164 // Only emit one error on the first const found. All other consts will emit 13165 // a note to the error. 13166 bool DiagnosticEmitted = false; 13167 13168 // Track if the current expression is the result of a dereference, and if the 13169 // next checked expression is the result of a dereference. 13170 bool IsDereference = false; 13171 bool NextIsDereference = false; 13172 13173 // Loop to process MemberExpr chains. 13174 while (true) { 13175 IsDereference = NextIsDereference; 13176 13177 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 13178 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13179 NextIsDereference = ME->isArrow(); 13180 const ValueDecl *VD = ME->getMemberDecl(); 13181 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 13182 // Mutable fields can be modified even if the class is const. 13183 if (Field->isMutable()) { 13184 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 13185 break; 13186 } 13187 13188 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 13189 if (!DiagnosticEmitted) { 13190 S.Diag(Loc, diag::err_typecheck_assign_const) 13191 << ExprRange << ConstMember << false /*static*/ << Field 13192 << Field->getType(); 13193 DiagnosticEmitted = true; 13194 } 13195 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13196 << ConstMember << false /*static*/ << Field << Field->getType() 13197 << Field->getSourceRange(); 13198 } 13199 E = ME->getBase(); 13200 continue; 13201 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 13202 if (VDecl->getType().isConstQualified()) { 13203 if (!DiagnosticEmitted) { 13204 S.Diag(Loc, diag::err_typecheck_assign_const) 13205 << ExprRange << ConstMember << true /*static*/ << VDecl 13206 << VDecl->getType(); 13207 DiagnosticEmitted = true; 13208 } 13209 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13210 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 13211 << VDecl->getSourceRange(); 13212 } 13213 // Static fields do not inherit constness from parents. 13214 break; 13215 } 13216 break; // End MemberExpr 13217 } else if (const ArraySubscriptExpr *ASE = 13218 dyn_cast<ArraySubscriptExpr>(E)) { 13219 E = ASE->getBase()->IgnoreParenImpCasts(); 13220 continue; 13221 } else if (const ExtVectorElementExpr *EVE = 13222 dyn_cast<ExtVectorElementExpr>(E)) { 13223 E = EVE->getBase()->IgnoreParenImpCasts(); 13224 continue; 13225 } 13226 break; 13227 } 13228 13229 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 13230 // Function calls 13231 const FunctionDecl *FD = CE->getDirectCallee(); 13232 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 13233 if (!DiagnosticEmitted) { 13234 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13235 << ConstFunction << FD; 13236 DiagnosticEmitted = true; 13237 } 13238 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 13239 diag::note_typecheck_assign_const) 13240 << ConstFunction << FD << FD->getReturnType() 13241 << FD->getReturnTypeSourceRange(); 13242 } 13243 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13244 // Point to variable declaration. 13245 if (const ValueDecl *VD = DRE->getDecl()) { 13246 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 13247 if (!DiagnosticEmitted) { 13248 S.Diag(Loc, diag::err_typecheck_assign_const) 13249 << ExprRange << ConstVariable << VD << VD->getType(); 13250 DiagnosticEmitted = true; 13251 } 13252 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13253 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 13254 } 13255 } 13256 } else if (isa<CXXThisExpr>(E)) { 13257 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 13258 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 13259 if (MD->isConst()) { 13260 if (!DiagnosticEmitted) { 13261 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13262 << ConstMethod << MD; 13263 DiagnosticEmitted = true; 13264 } 13265 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 13266 << ConstMethod << MD << MD->getSourceRange(); 13267 } 13268 } 13269 } 13270 } 13271 13272 if (DiagnosticEmitted) 13273 return; 13274 13275 // Can't determine a more specific message, so display the generic error. 13276 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 13277 } 13278 13279 enum OriginalExprKind { 13280 OEK_Variable, 13281 OEK_Member, 13282 OEK_LValue 13283 }; 13284 13285 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 13286 const RecordType *Ty, 13287 SourceLocation Loc, SourceRange Range, 13288 OriginalExprKind OEK, 13289 bool &DiagnosticEmitted) { 13290 std::vector<const RecordType *> RecordTypeList; 13291 RecordTypeList.push_back(Ty); 13292 unsigned NextToCheckIndex = 0; 13293 // We walk the record hierarchy breadth-first to ensure that we print 13294 // diagnostics in field nesting order. 13295 while (RecordTypeList.size() > NextToCheckIndex) { 13296 bool IsNested = NextToCheckIndex > 0; 13297 for (const FieldDecl *Field : 13298 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 13299 // First, check every field for constness. 13300 QualType FieldTy = Field->getType(); 13301 if (FieldTy.isConstQualified()) { 13302 if (!DiagnosticEmitted) { 13303 S.Diag(Loc, diag::err_typecheck_assign_const) 13304 << Range << NestedConstMember << OEK << VD 13305 << IsNested << Field; 13306 DiagnosticEmitted = true; 13307 } 13308 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 13309 << NestedConstMember << IsNested << Field 13310 << FieldTy << Field->getSourceRange(); 13311 } 13312 13313 // Then we append it to the list to check next in order. 13314 FieldTy = FieldTy.getCanonicalType(); 13315 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 13316 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 13317 RecordTypeList.push_back(FieldRecTy); 13318 } 13319 } 13320 ++NextToCheckIndex; 13321 } 13322 } 13323 13324 /// Emit an error for the case where a record we are trying to assign to has a 13325 /// const-qualified field somewhere in its hierarchy. 13326 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 13327 SourceLocation Loc) { 13328 QualType Ty = E->getType(); 13329 assert(Ty->isRecordType() && "lvalue was not record?"); 13330 SourceRange Range = E->getSourceRange(); 13331 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 13332 bool DiagEmitted = false; 13333 13334 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 13335 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 13336 Range, OEK_Member, DiagEmitted); 13337 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13338 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 13339 Range, OEK_Variable, DiagEmitted); 13340 else 13341 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 13342 Range, OEK_LValue, DiagEmitted); 13343 if (!DiagEmitted) 13344 DiagnoseConstAssignment(S, E, Loc); 13345 } 13346 13347 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 13348 /// emit an error and return true. If so, return false. 13349 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 13350 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 13351 13352 S.CheckShadowingDeclModification(E, Loc); 13353 13354 SourceLocation OrigLoc = Loc; 13355 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 13356 &Loc); 13357 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 13358 IsLV = Expr::MLV_InvalidMessageExpression; 13359 if (IsLV == Expr::MLV_Valid) 13360 return false; 13361 13362 unsigned DiagID = 0; 13363 bool NeedType = false; 13364 switch (IsLV) { // C99 6.5.16p2 13365 case Expr::MLV_ConstQualified: 13366 // Use a specialized diagnostic when we're assigning to an object 13367 // from an enclosing function or block. 13368 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13369 if (NCCK == NCCK_Block) 13370 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13371 else 13372 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13373 break; 13374 } 13375 13376 // In ARC, use some specialized diagnostics for occasions where we 13377 // infer 'const'. These are always pseudo-strong variables. 13378 if (S.getLangOpts().ObjCAutoRefCount) { 13379 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13380 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13381 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13382 13383 // Use the normal diagnostic if it's pseudo-__strong but the 13384 // user actually wrote 'const'. 13385 if (var->isARCPseudoStrong() && 13386 (!var->getTypeSourceInfo() || 13387 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13388 // There are three pseudo-strong cases: 13389 // - self 13390 ObjCMethodDecl *method = S.getCurMethodDecl(); 13391 if (method && var == method->getSelfDecl()) { 13392 DiagID = method->isClassMethod() 13393 ? diag::err_typecheck_arc_assign_self_class_method 13394 : diag::err_typecheck_arc_assign_self; 13395 13396 // - Objective-C externally_retained attribute. 13397 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13398 isa<ParmVarDecl>(var)) { 13399 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13400 13401 // - fast enumeration variables 13402 } else { 13403 DiagID = diag::err_typecheck_arr_assign_enumeration; 13404 } 13405 13406 SourceRange Assign; 13407 if (Loc != OrigLoc) 13408 Assign = SourceRange(OrigLoc, OrigLoc); 13409 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13410 // We need to preserve the AST regardless, so migration tool 13411 // can do its job. 13412 return false; 13413 } 13414 } 13415 } 13416 13417 // If none of the special cases above are triggered, then this is a 13418 // simple const assignment. 13419 if (DiagID == 0) { 13420 DiagnoseConstAssignment(S, E, Loc); 13421 return true; 13422 } 13423 13424 break; 13425 case Expr::MLV_ConstAddrSpace: 13426 DiagnoseConstAssignment(S, E, Loc); 13427 return true; 13428 case Expr::MLV_ConstQualifiedField: 13429 DiagnoseRecursiveConstFields(S, E, Loc); 13430 return true; 13431 case Expr::MLV_ArrayType: 13432 case Expr::MLV_ArrayTemporary: 13433 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13434 NeedType = true; 13435 break; 13436 case Expr::MLV_NotObjectType: 13437 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13438 NeedType = true; 13439 break; 13440 case Expr::MLV_LValueCast: 13441 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13442 break; 13443 case Expr::MLV_Valid: 13444 llvm_unreachable("did not take early return for MLV_Valid"); 13445 case Expr::MLV_InvalidExpression: 13446 case Expr::MLV_MemberFunction: 13447 case Expr::MLV_ClassTemporary: 13448 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13449 break; 13450 case Expr::MLV_IncompleteType: 13451 case Expr::MLV_IncompleteVoidType: 13452 return S.RequireCompleteType(Loc, E->getType(), 13453 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13454 case Expr::MLV_DuplicateVectorComponents: 13455 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13456 break; 13457 case Expr::MLV_NoSetterProperty: 13458 llvm_unreachable("readonly properties should be processed differently"); 13459 case Expr::MLV_InvalidMessageExpression: 13460 DiagID = diag::err_readonly_message_assignment; 13461 break; 13462 case Expr::MLV_SubObjCPropertySetting: 13463 DiagID = diag::err_no_subobject_property_setting; 13464 break; 13465 } 13466 13467 SourceRange Assign; 13468 if (Loc != OrigLoc) 13469 Assign = SourceRange(OrigLoc, OrigLoc); 13470 if (NeedType) 13471 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13472 else 13473 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13474 return true; 13475 } 13476 13477 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13478 SourceLocation Loc, 13479 Sema &Sema) { 13480 if (Sema.inTemplateInstantiation()) 13481 return; 13482 if (Sema.isUnevaluatedContext()) 13483 return; 13484 if (Loc.isInvalid() || Loc.isMacroID()) 13485 return; 13486 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13487 return; 13488 13489 // C / C++ fields 13490 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13491 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13492 if (ML && MR) { 13493 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13494 return; 13495 const ValueDecl *LHSDecl = 13496 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13497 const ValueDecl *RHSDecl = 13498 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13499 if (LHSDecl != RHSDecl) 13500 return; 13501 if (LHSDecl->getType().isVolatileQualified()) 13502 return; 13503 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13504 if (RefTy->getPointeeType().isVolatileQualified()) 13505 return; 13506 13507 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13508 } 13509 13510 // Objective-C instance variables 13511 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13512 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13513 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13514 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13515 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13516 if (RL && RR && RL->getDecl() == RR->getDecl()) 13517 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13518 } 13519 } 13520 13521 // C99 6.5.16.1 13522 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13523 SourceLocation Loc, 13524 QualType CompoundType) { 13525 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13526 13527 // Verify that LHS is a modifiable lvalue, and emit error if not. 13528 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13529 return QualType(); 13530 13531 QualType LHSType = LHSExpr->getType(); 13532 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13533 CompoundType; 13534 // OpenCL v1.2 s6.1.1.1 p2: 13535 // The half data type can only be used to declare a pointer to a buffer that 13536 // contains half values 13537 if (getLangOpts().OpenCL && 13538 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13539 LHSType->isHalfType()) { 13540 Diag(Loc, diag::err_opencl_half_load_store) << 1 13541 << LHSType.getUnqualifiedType(); 13542 return QualType(); 13543 } 13544 13545 AssignConvertType ConvTy; 13546 if (CompoundType.isNull()) { 13547 Expr *RHSCheck = RHS.get(); 13548 13549 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13550 13551 QualType LHSTy(LHSType); 13552 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13553 if (RHS.isInvalid()) 13554 return QualType(); 13555 // Special case of NSObject attributes on c-style pointer types. 13556 if (ConvTy == IncompatiblePointer && 13557 ((Context.isObjCNSObjectType(LHSType) && 13558 RHSType->isObjCObjectPointerType()) || 13559 (Context.isObjCNSObjectType(RHSType) && 13560 LHSType->isObjCObjectPointerType()))) 13561 ConvTy = Compatible; 13562 13563 if (ConvTy == Compatible && 13564 LHSType->isObjCObjectType()) 13565 Diag(Loc, diag::err_objc_object_assignment) 13566 << LHSType; 13567 13568 // If the RHS is a unary plus or minus, check to see if they = and + are 13569 // right next to each other. If so, the user may have typo'd "x =+ 4" 13570 // instead of "x += 4". 13571 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13572 RHSCheck = ICE->getSubExpr(); 13573 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13574 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13575 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13576 // Only if the two operators are exactly adjacent. 13577 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13578 // And there is a space or other character before the subexpr of the 13579 // unary +/-. We don't want to warn on "x=-1". 13580 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13581 UO->getSubExpr()->getBeginLoc().isFileID()) { 13582 Diag(Loc, diag::warn_not_compound_assign) 13583 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13584 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13585 } 13586 } 13587 13588 if (ConvTy == Compatible) { 13589 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13590 // Warn about retain cycles where a block captures the LHS, but 13591 // not if the LHS is a simple variable into which the block is 13592 // being stored...unless that variable can be captured by reference! 13593 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13594 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13595 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13596 checkRetainCycles(LHSExpr, RHS.get()); 13597 } 13598 13599 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13600 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13601 // It is safe to assign a weak reference into a strong variable. 13602 // Although this code can still have problems: 13603 // id x = self.weakProp; 13604 // id y = self.weakProp; 13605 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13606 // paths through the function. This should be revisited if 13607 // -Wrepeated-use-of-weak is made flow-sensitive. 13608 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13609 // variable, which will be valid for the current autorelease scope. 13610 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13611 RHS.get()->getBeginLoc())) 13612 getCurFunction()->markSafeWeakUse(RHS.get()); 13613 13614 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13615 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13616 } 13617 } 13618 } else { 13619 // Compound assignment "x += y" 13620 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13621 } 13622 13623 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13624 RHS.get(), AA_Assigning)) 13625 return QualType(); 13626 13627 CheckForNullPointerDereference(*this, LHSExpr); 13628 13629 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13630 if (CompoundType.isNull()) { 13631 // C++2a [expr.ass]p5: 13632 // A simple-assignment whose left operand is of a volatile-qualified 13633 // type is deprecated unless the assignment is either a discarded-value 13634 // expression or an unevaluated operand 13635 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13636 } else { 13637 // C++2a [expr.ass]p6: 13638 // [Compound-assignment] expressions are deprecated if E1 has 13639 // volatile-qualified type 13640 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13641 } 13642 } 13643 13644 // C11 6.5.16p3: The type of an assignment expression is the type of the 13645 // left operand would have after lvalue conversion. 13646 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has 13647 // qualified type, the value has the unqualified version of the type of the 13648 // lvalue; additionally, if the lvalue has atomic type, the value has the 13649 // non-atomic version of the type of the lvalue. 13650 // C++ 5.17p1: the type of the assignment expression is that of its left 13651 // operand. 13652 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); 13653 } 13654 13655 // Only ignore explicit casts to void. 13656 static bool IgnoreCommaOperand(const Expr *E) { 13657 E = E->IgnoreParens(); 13658 13659 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13660 if (CE->getCastKind() == CK_ToVoid) { 13661 return true; 13662 } 13663 13664 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13665 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13666 CE->getSubExpr()->getType()->isDependentType()) { 13667 return true; 13668 } 13669 } 13670 13671 return false; 13672 } 13673 13674 // Look for instances where it is likely the comma operator is confused with 13675 // another operator. There is an explicit list of acceptable expressions for 13676 // the left hand side of the comma operator, otherwise emit a warning. 13677 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13678 // No warnings in macros 13679 if (Loc.isMacroID()) 13680 return; 13681 13682 // Don't warn in template instantiations. 13683 if (inTemplateInstantiation()) 13684 return; 13685 13686 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13687 // instead, skip more than needed, then call back into here with the 13688 // CommaVisitor in SemaStmt.cpp. 13689 // The listed locations are the initialization and increment portions 13690 // of a for loop. The additional checks are on the condition of 13691 // if statements, do/while loops, and for loops. 13692 // Differences in scope flags for C89 mode requires the extra logic. 13693 const unsigned ForIncrementFlags = 13694 getLangOpts().C99 || getLangOpts().CPlusPlus 13695 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13696 : Scope::ContinueScope | Scope::BreakScope; 13697 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13698 const unsigned ScopeFlags = getCurScope()->getFlags(); 13699 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13700 (ScopeFlags & ForInitFlags) == ForInitFlags) 13701 return; 13702 13703 // If there are multiple comma operators used together, get the RHS of the 13704 // of the comma operator as the LHS. 13705 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13706 if (BO->getOpcode() != BO_Comma) 13707 break; 13708 LHS = BO->getRHS(); 13709 } 13710 13711 // Only allow some expressions on LHS to not warn. 13712 if (IgnoreCommaOperand(LHS)) 13713 return; 13714 13715 Diag(Loc, diag::warn_comma_operator); 13716 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13717 << LHS->getSourceRange() 13718 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13719 LangOpts.CPlusPlus ? "static_cast<void>(" 13720 : "(void)(") 13721 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13722 ")"); 13723 } 13724 13725 // C99 6.5.17 13726 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13727 SourceLocation Loc) { 13728 LHS = S.CheckPlaceholderExpr(LHS.get()); 13729 RHS = S.CheckPlaceholderExpr(RHS.get()); 13730 if (LHS.isInvalid() || RHS.isInvalid()) 13731 return QualType(); 13732 13733 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13734 // operands, but not unary promotions. 13735 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13736 13737 // So we treat the LHS as a ignored value, and in C++ we allow the 13738 // containing site to determine what should be done with the RHS. 13739 LHS = S.IgnoredValueConversions(LHS.get()); 13740 if (LHS.isInvalid()) 13741 return QualType(); 13742 13743 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13744 13745 if (!S.getLangOpts().CPlusPlus) { 13746 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13747 if (RHS.isInvalid()) 13748 return QualType(); 13749 if (!RHS.get()->getType()->isVoidType()) 13750 S.RequireCompleteType(Loc, RHS.get()->getType(), 13751 diag::err_incomplete_type); 13752 } 13753 13754 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13755 S.DiagnoseCommaOperator(LHS.get(), Loc); 13756 13757 return RHS.get()->getType(); 13758 } 13759 13760 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13761 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13762 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13763 ExprValueKind &VK, 13764 ExprObjectKind &OK, 13765 SourceLocation OpLoc, 13766 bool IsInc, bool IsPrefix) { 13767 if (Op->isTypeDependent()) 13768 return S.Context.DependentTy; 13769 13770 QualType ResType = Op->getType(); 13771 // Atomic types can be used for increment / decrement where the non-atomic 13772 // versions can, so ignore the _Atomic() specifier for the purpose of 13773 // checking. 13774 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13775 ResType = ResAtomicType->getValueType(); 13776 13777 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13778 13779 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13780 // Decrement of bool is not allowed. 13781 if (!IsInc) { 13782 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13783 return QualType(); 13784 } 13785 // Increment of bool sets it to true, but is deprecated. 13786 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13787 : diag::warn_increment_bool) 13788 << Op->getSourceRange(); 13789 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13790 // Error on enum increments and decrements in C++ mode 13791 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13792 return QualType(); 13793 } else if (ResType->isRealType()) { 13794 // OK! 13795 } else if (ResType->isPointerType()) { 13796 // C99 6.5.2.4p2, 6.5.6p2 13797 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13798 return QualType(); 13799 } else if (ResType->isObjCObjectPointerType()) { 13800 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13801 // Otherwise, we just need a complete type. 13802 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13803 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13804 return QualType(); 13805 } else if (ResType->isAnyComplexType()) { 13806 // C99 does not support ++/-- on complex types, we allow as an extension. 13807 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13808 << ResType << Op->getSourceRange(); 13809 } else if (ResType->isPlaceholderType()) { 13810 ExprResult PR = S.CheckPlaceholderExpr(Op); 13811 if (PR.isInvalid()) return QualType(); 13812 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13813 IsInc, IsPrefix); 13814 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13815 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13816 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13817 (ResType->castAs<VectorType>()->getVectorKind() != 13818 VectorType::AltiVecBool)) { 13819 // The z vector extensions allow ++ and -- for non-bool vectors. 13820 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13821 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13822 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13823 } else { 13824 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13825 << ResType << int(IsInc) << Op->getSourceRange(); 13826 return QualType(); 13827 } 13828 // At this point, we know we have a real, complex or pointer type. 13829 // Now make sure the operand is a modifiable lvalue. 13830 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13831 return QualType(); 13832 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13833 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13834 // An operand with volatile-qualified type is deprecated 13835 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13836 << IsInc << ResType; 13837 } 13838 // In C++, a prefix increment is the same type as the operand. Otherwise 13839 // (in C or with postfix), the increment is the unqualified type of the 13840 // operand. 13841 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13842 VK = VK_LValue; 13843 OK = Op->getObjectKind(); 13844 return ResType; 13845 } else { 13846 VK = VK_PRValue; 13847 return ResType.getUnqualifiedType(); 13848 } 13849 } 13850 13851 13852 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13853 /// This routine allows us to typecheck complex/recursive expressions 13854 /// where the declaration is needed for type checking. We only need to 13855 /// handle cases when the expression references a function designator 13856 /// or is an lvalue. Here are some examples: 13857 /// - &(x) => x 13858 /// - &*****f => f for f a function designator. 13859 /// - &s.xx => s 13860 /// - &s.zz[1].yy -> s, if zz is an array 13861 /// - *(x + 1) -> x, if x is an array 13862 /// - &"123"[2] -> 0 13863 /// - & __real__ x -> x 13864 /// 13865 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13866 /// members. 13867 static ValueDecl *getPrimaryDecl(Expr *E) { 13868 switch (E->getStmtClass()) { 13869 case Stmt::DeclRefExprClass: 13870 return cast<DeclRefExpr>(E)->getDecl(); 13871 case Stmt::MemberExprClass: 13872 // If this is an arrow operator, the address is an offset from 13873 // the base's value, so the object the base refers to is 13874 // irrelevant. 13875 if (cast<MemberExpr>(E)->isArrow()) 13876 return nullptr; 13877 // Otherwise, the expression refers to a part of the base 13878 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13879 case Stmt::ArraySubscriptExprClass: { 13880 // FIXME: This code shouldn't be necessary! We should catch the implicit 13881 // promotion of register arrays earlier. 13882 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13883 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13884 if (ICE->getSubExpr()->getType()->isArrayType()) 13885 return getPrimaryDecl(ICE->getSubExpr()); 13886 } 13887 return nullptr; 13888 } 13889 case Stmt::UnaryOperatorClass: { 13890 UnaryOperator *UO = cast<UnaryOperator>(E); 13891 13892 switch(UO->getOpcode()) { 13893 case UO_Real: 13894 case UO_Imag: 13895 case UO_Extension: 13896 return getPrimaryDecl(UO->getSubExpr()); 13897 default: 13898 return nullptr; 13899 } 13900 } 13901 case Stmt::ParenExprClass: 13902 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13903 case Stmt::ImplicitCastExprClass: 13904 // If the result of an implicit cast is an l-value, we care about 13905 // the sub-expression; otherwise, the result here doesn't matter. 13906 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13907 case Stmt::CXXUuidofExprClass: 13908 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13909 default: 13910 return nullptr; 13911 } 13912 } 13913 13914 namespace { 13915 enum { 13916 AO_Bit_Field = 0, 13917 AO_Vector_Element = 1, 13918 AO_Property_Expansion = 2, 13919 AO_Register_Variable = 3, 13920 AO_Matrix_Element = 4, 13921 AO_No_Error = 5 13922 }; 13923 } 13924 /// Diagnose invalid operand for address of operations. 13925 /// 13926 /// \param Type The type of operand which cannot have its address taken. 13927 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13928 Expr *E, unsigned Type) { 13929 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13930 } 13931 13932 /// CheckAddressOfOperand - The operand of & must be either a function 13933 /// designator or an lvalue designating an object. If it is an lvalue, the 13934 /// object cannot be declared with storage class register or be a bit field. 13935 /// Note: The usual conversions are *not* applied to the operand of the & 13936 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13937 /// In C++, the operand might be an overloaded function name, in which case 13938 /// we allow the '&' but retain the overloaded-function type. 13939 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13940 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13941 if (PTy->getKind() == BuiltinType::Overload) { 13942 Expr *E = OrigOp.get()->IgnoreParens(); 13943 if (!isa<OverloadExpr>(E)) { 13944 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13945 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13946 << OrigOp.get()->getSourceRange(); 13947 return QualType(); 13948 } 13949 13950 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13951 if (isa<UnresolvedMemberExpr>(Ovl)) 13952 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13953 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13954 << OrigOp.get()->getSourceRange(); 13955 return QualType(); 13956 } 13957 13958 return Context.OverloadTy; 13959 } 13960 13961 if (PTy->getKind() == BuiltinType::UnknownAny) 13962 return Context.UnknownAnyTy; 13963 13964 if (PTy->getKind() == BuiltinType::BoundMember) { 13965 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13966 << OrigOp.get()->getSourceRange(); 13967 return QualType(); 13968 } 13969 13970 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13971 if (OrigOp.isInvalid()) return QualType(); 13972 } 13973 13974 if (OrigOp.get()->isTypeDependent()) 13975 return Context.DependentTy; 13976 13977 assert(!OrigOp.get()->hasPlaceholderType()); 13978 13979 // Make sure to ignore parentheses in subsequent checks 13980 Expr *op = OrigOp.get()->IgnoreParens(); 13981 13982 // In OpenCL captures for blocks called as lambda functions 13983 // are located in the private address space. Blocks used in 13984 // enqueue_kernel can be located in a different address space 13985 // depending on a vendor implementation. Thus preventing 13986 // taking an address of the capture to avoid invalid AS casts. 13987 if (LangOpts.OpenCL) { 13988 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13989 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13990 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13991 return QualType(); 13992 } 13993 } 13994 13995 if (getLangOpts().C99) { 13996 // Implement C99-only parts of addressof rules. 13997 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13998 if (uOp->getOpcode() == UO_Deref) 13999 // Per C99 6.5.3.2, the address of a deref always returns a valid result 14000 // (assuming the deref expression is valid). 14001 return uOp->getSubExpr()->getType(); 14002 } 14003 // Technically, there should be a check for array subscript 14004 // expressions here, but the result of one is always an lvalue anyway. 14005 } 14006 ValueDecl *dcl = getPrimaryDecl(op); 14007 14008 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 14009 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 14010 op->getBeginLoc())) 14011 return QualType(); 14012 14013 Expr::LValueClassification lval = op->ClassifyLValue(Context); 14014 unsigned AddressOfError = AO_No_Error; 14015 14016 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 14017 bool sfinae = (bool)isSFINAEContext(); 14018 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 14019 : diag::ext_typecheck_addrof_temporary) 14020 << op->getType() << op->getSourceRange(); 14021 if (sfinae) 14022 return QualType(); 14023 // Materialize the temporary as an lvalue so that we can take its address. 14024 OrigOp = op = 14025 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 14026 } else if (isa<ObjCSelectorExpr>(op)) { 14027 return Context.getPointerType(op->getType()); 14028 } else if (lval == Expr::LV_MemberFunction) { 14029 // If it's an instance method, make a member pointer. 14030 // The expression must have exactly the form &A::foo. 14031 14032 // If the underlying expression isn't a decl ref, give up. 14033 if (!isa<DeclRefExpr>(op)) { 14034 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14035 << OrigOp.get()->getSourceRange(); 14036 return QualType(); 14037 } 14038 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 14039 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 14040 14041 // The id-expression was parenthesized. 14042 if (OrigOp.get() != DRE) { 14043 Diag(OpLoc, diag::err_parens_pointer_member_function) 14044 << OrigOp.get()->getSourceRange(); 14045 14046 // The method was named without a qualifier. 14047 } else if (!DRE->getQualifier()) { 14048 if (MD->getParent()->getName().empty()) 14049 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14050 << op->getSourceRange(); 14051 else { 14052 SmallString<32> Str; 14053 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 14054 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14055 << op->getSourceRange() 14056 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 14057 } 14058 } 14059 14060 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 14061 if (isa<CXXDestructorDecl>(MD)) 14062 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 14063 14064 QualType MPTy = Context.getMemberPointerType( 14065 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 14066 // Under the MS ABI, lock down the inheritance model now. 14067 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14068 (void)isCompleteType(OpLoc, MPTy); 14069 return MPTy; 14070 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 14071 // C99 6.5.3.2p1 14072 // The operand must be either an l-value or a function designator 14073 if (!op->getType()->isFunctionType()) { 14074 // Use a special diagnostic for loads from property references. 14075 if (isa<PseudoObjectExpr>(op)) { 14076 AddressOfError = AO_Property_Expansion; 14077 } else { 14078 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 14079 << op->getType() << op->getSourceRange(); 14080 return QualType(); 14081 } 14082 } 14083 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 14084 // The operand cannot be a bit-field 14085 AddressOfError = AO_Bit_Field; 14086 } else if (op->getObjectKind() == OK_VectorComponent) { 14087 // The operand cannot be an element of a vector 14088 AddressOfError = AO_Vector_Element; 14089 } else if (op->getObjectKind() == OK_MatrixComponent) { 14090 // The operand cannot be an element of a matrix. 14091 AddressOfError = AO_Matrix_Element; 14092 } else if (dcl) { // C99 6.5.3.2p1 14093 // We have an lvalue with a decl. Make sure the decl is not declared 14094 // with the register storage-class specifier. 14095 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 14096 // in C++ it is not error to take address of a register 14097 // variable (c++03 7.1.1P3) 14098 if (vd->getStorageClass() == SC_Register && 14099 !getLangOpts().CPlusPlus) { 14100 AddressOfError = AO_Register_Variable; 14101 } 14102 } else if (isa<MSPropertyDecl>(dcl)) { 14103 AddressOfError = AO_Property_Expansion; 14104 } else if (isa<FunctionTemplateDecl>(dcl)) { 14105 return Context.OverloadTy; 14106 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 14107 // Okay: we can take the address of a field. 14108 // Could be a pointer to member, though, if there is an explicit 14109 // scope qualifier for the class. 14110 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 14111 DeclContext *Ctx = dcl->getDeclContext(); 14112 if (Ctx && Ctx->isRecord()) { 14113 if (dcl->getType()->isReferenceType()) { 14114 Diag(OpLoc, 14115 diag::err_cannot_form_pointer_to_member_of_reference_type) 14116 << dcl->getDeclName() << dcl->getType(); 14117 return QualType(); 14118 } 14119 14120 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 14121 Ctx = Ctx->getParent(); 14122 14123 QualType MPTy = Context.getMemberPointerType( 14124 op->getType(), 14125 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 14126 // Under the MS ABI, lock down the inheritance model now. 14127 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14128 (void)isCompleteType(OpLoc, MPTy); 14129 return MPTy; 14130 } 14131 } 14132 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, 14133 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl)) 14134 llvm_unreachable("Unknown/unexpected decl type"); 14135 } 14136 14137 if (AddressOfError != AO_No_Error) { 14138 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 14139 return QualType(); 14140 } 14141 14142 if (lval == Expr::LV_IncompleteVoidType) { 14143 // Taking the address of a void variable is technically illegal, but we 14144 // allow it in cases which are otherwise valid. 14145 // Example: "extern void x; void* y = &x;". 14146 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 14147 } 14148 14149 // If the operand has type "type", the result has type "pointer to type". 14150 if (op->getType()->isObjCObjectType()) 14151 return Context.getObjCObjectPointerType(op->getType()); 14152 14153 CheckAddressOfPackedMember(op); 14154 14155 return Context.getPointerType(op->getType()); 14156 } 14157 14158 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 14159 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 14160 if (!DRE) 14161 return; 14162 const Decl *D = DRE->getDecl(); 14163 if (!D) 14164 return; 14165 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 14166 if (!Param) 14167 return; 14168 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 14169 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 14170 return; 14171 if (FunctionScopeInfo *FD = S.getCurFunction()) 14172 if (!FD->ModifiedNonNullParams.count(Param)) 14173 FD->ModifiedNonNullParams.insert(Param); 14174 } 14175 14176 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 14177 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 14178 SourceLocation OpLoc) { 14179 if (Op->isTypeDependent()) 14180 return S.Context.DependentTy; 14181 14182 ExprResult ConvResult = S.UsualUnaryConversions(Op); 14183 if (ConvResult.isInvalid()) 14184 return QualType(); 14185 Op = ConvResult.get(); 14186 QualType OpTy = Op->getType(); 14187 QualType Result; 14188 14189 if (isa<CXXReinterpretCastExpr>(Op)) { 14190 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 14191 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 14192 Op->getSourceRange()); 14193 } 14194 14195 if (const PointerType *PT = OpTy->getAs<PointerType>()) 14196 { 14197 Result = PT->getPointeeType(); 14198 } 14199 else if (const ObjCObjectPointerType *OPT = 14200 OpTy->getAs<ObjCObjectPointerType>()) 14201 Result = OPT->getPointeeType(); 14202 else { 14203 ExprResult PR = S.CheckPlaceholderExpr(Op); 14204 if (PR.isInvalid()) return QualType(); 14205 if (PR.get() != Op) 14206 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 14207 } 14208 14209 if (Result.isNull()) { 14210 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 14211 << OpTy << Op->getSourceRange(); 14212 return QualType(); 14213 } 14214 14215 // Note that per both C89 and C99, indirection is always legal, even if Result 14216 // is an incomplete type or void. It would be possible to warn about 14217 // dereferencing a void pointer, but it's completely well-defined, and such a 14218 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 14219 // for pointers to 'void' but is fine for any other pointer type: 14220 // 14221 // C++ [expr.unary.op]p1: 14222 // [...] the expression to which [the unary * operator] is applied shall 14223 // be a pointer to an object type, or a pointer to a function type 14224 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 14225 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 14226 << OpTy << Op->getSourceRange(); 14227 14228 // Dereferences are usually l-values... 14229 VK = VK_LValue; 14230 14231 // ...except that certain expressions are never l-values in C. 14232 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 14233 VK = VK_PRValue; 14234 14235 return Result; 14236 } 14237 14238 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 14239 BinaryOperatorKind Opc; 14240 switch (Kind) { 14241 default: llvm_unreachable("Unknown binop!"); 14242 case tok::periodstar: Opc = BO_PtrMemD; break; 14243 case tok::arrowstar: Opc = BO_PtrMemI; break; 14244 case tok::star: Opc = BO_Mul; break; 14245 case tok::slash: Opc = BO_Div; break; 14246 case tok::percent: Opc = BO_Rem; break; 14247 case tok::plus: Opc = BO_Add; break; 14248 case tok::minus: Opc = BO_Sub; break; 14249 case tok::lessless: Opc = BO_Shl; break; 14250 case tok::greatergreater: Opc = BO_Shr; break; 14251 case tok::lessequal: Opc = BO_LE; break; 14252 case tok::less: Opc = BO_LT; break; 14253 case tok::greaterequal: Opc = BO_GE; break; 14254 case tok::greater: Opc = BO_GT; break; 14255 case tok::exclaimequal: Opc = BO_NE; break; 14256 case tok::equalequal: Opc = BO_EQ; break; 14257 case tok::spaceship: Opc = BO_Cmp; break; 14258 case tok::amp: Opc = BO_And; break; 14259 case tok::caret: Opc = BO_Xor; break; 14260 case tok::pipe: Opc = BO_Or; break; 14261 case tok::ampamp: Opc = BO_LAnd; break; 14262 case tok::pipepipe: Opc = BO_LOr; break; 14263 case tok::equal: Opc = BO_Assign; break; 14264 case tok::starequal: Opc = BO_MulAssign; break; 14265 case tok::slashequal: Opc = BO_DivAssign; break; 14266 case tok::percentequal: Opc = BO_RemAssign; break; 14267 case tok::plusequal: Opc = BO_AddAssign; break; 14268 case tok::minusequal: Opc = BO_SubAssign; break; 14269 case tok::lesslessequal: Opc = BO_ShlAssign; break; 14270 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 14271 case tok::ampequal: Opc = BO_AndAssign; break; 14272 case tok::caretequal: Opc = BO_XorAssign; break; 14273 case tok::pipeequal: Opc = BO_OrAssign; break; 14274 case tok::comma: Opc = BO_Comma; break; 14275 } 14276 return Opc; 14277 } 14278 14279 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 14280 tok::TokenKind Kind) { 14281 UnaryOperatorKind Opc; 14282 switch (Kind) { 14283 default: llvm_unreachable("Unknown unary op!"); 14284 case tok::plusplus: Opc = UO_PreInc; break; 14285 case tok::minusminus: Opc = UO_PreDec; break; 14286 case tok::amp: Opc = UO_AddrOf; break; 14287 case tok::star: Opc = UO_Deref; break; 14288 case tok::plus: Opc = UO_Plus; break; 14289 case tok::minus: Opc = UO_Minus; break; 14290 case tok::tilde: Opc = UO_Not; break; 14291 case tok::exclaim: Opc = UO_LNot; break; 14292 case tok::kw___real: Opc = UO_Real; break; 14293 case tok::kw___imag: Opc = UO_Imag; break; 14294 case tok::kw___extension__: Opc = UO_Extension; break; 14295 } 14296 return Opc; 14297 } 14298 14299 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 14300 /// This warning suppressed in the event of macro expansions. 14301 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 14302 SourceLocation OpLoc, bool IsBuiltin) { 14303 if (S.inTemplateInstantiation()) 14304 return; 14305 if (S.isUnevaluatedContext()) 14306 return; 14307 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 14308 return; 14309 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14310 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14311 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14312 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14313 if (!LHSDeclRef || !RHSDeclRef || 14314 LHSDeclRef->getLocation().isMacroID() || 14315 RHSDeclRef->getLocation().isMacroID()) 14316 return; 14317 const ValueDecl *LHSDecl = 14318 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 14319 const ValueDecl *RHSDecl = 14320 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 14321 if (LHSDecl != RHSDecl) 14322 return; 14323 if (LHSDecl->getType().isVolatileQualified()) 14324 return; 14325 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 14326 if (RefTy->getPointeeType().isVolatileQualified()) 14327 return; 14328 14329 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 14330 : diag::warn_self_assignment_overloaded) 14331 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 14332 << RHSExpr->getSourceRange(); 14333 } 14334 14335 /// Check if a bitwise-& is performed on an Objective-C pointer. This 14336 /// is usually indicative of introspection within the Objective-C pointer. 14337 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 14338 SourceLocation OpLoc) { 14339 if (!S.getLangOpts().ObjC) 14340 return; 14341 14342 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 14343 const Expr *LHS = L.get(); 14344 const Expr *RHS = R.get(); 14345 14346 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14347 ObjCPointerExpr = LHS; 14348 OtherExpr = RHS; 14349 } 14350 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14351 ObjCPointerExpr = RHS; 14352 OtherExpr = LHS; 14353 } 14354 14355 // This warning is deliberately made very specific to reduce false 14356 // positives with logic that uses '&' for hashing. This logic mainly 14357 // looks for code trying to introspect into tagged pointers, which 14358 // code should generally never do. 14359 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 14360 unsigned Diag = diag::warn_objc_pointer_masking; 14361 // Determine if we are introspecting the result of performSelectorXXX. 14362 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 14363 // Special case messages to -performSelector and friends, which 14364 // can return non-pointer values boxed in a pointer value. 14365 // Some clients may wish to silence warnings in this subcase. 14366 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14367 Selector S = ME->getSelector(); 14368 StringRef SelArg0 = S.getNameForSlot(0); 14369 if (SelArg0.startswith("performSelector")) 14370 Diag = diag::warn_objc_pointer_masking_performSelector; 14371 } 14372 14373 S.Diag(OpLoc, Diag) 14374 << ObjCPointerExpr->getSourceRange(); 14375 } 14376 } 14377 14378 static NamedDecl *getDeclFromExpr(Expr *E) { 14379 if (!E) 14380 return nullptr; 14381 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14382 return DRE->getDecl(); 14383 if (auto *ME = dyn_cast<MemberExpr>(E)) 14384 return ME->getMemberDecl(); 14385 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14386 return IRE->getDecl(); 14387 return nullptr; 14388 } 14389 14390 // This helper function promotes a binary operator's operands (which are of a 14391 // half vector type) to a vector of floats and then truncates the result to 14392 // a vector of either half or short. 14393 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14394 BinaryOperatorKind Opc, QualType ResultTy, 14395 ExprValueKind VK, ExprObjectKind OK, 14396 bool IsCompAssign, SourceLocation OpLoc, 14397 FPOptionsOverride FPFeatures) { 14398 auto &Context = S.getASTContext(); 14399 assert((isVector(ResultTy, Context.HalfTy) || 14400 isVector(ResultTy, Context.ShortTy)) && 14401 "Result must be a vector of half or short"); 14402 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14403 isVector(RHS.get()->getType(), Context.HalfTy) && 14404 "both operands expected to be a half vector"); 14405 14406 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14407 QualType BinOpResTy = RHS.get()->getType(); 14408 14409 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14410 // change BinOpResTy to a vector of ints. 14411 if (isVector(ResultTy, Context.ShortTy)) 14412 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14413 14414 if (IsCompAssign) 14415 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14416 ResultTy, VK, OK, OpLoc, FPFeatures, 14417 BinOpResTy, BinOpResTy); 14418 14419 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14420 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14421 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14422 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14423 } 14424 14425 static std::pair<ExprResult, ExprResult> 14426 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14427 Expr *RHSExpr) { 14428 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14429 if (!S.Context.isDependenceAllowed()) { 14430 // C cannot handle TypoExpr nodes on either side of a binop because it 14431 // doesn't handle dependent types properly, so make sure any TypoExprs have 14432 // been dealt with before checking the operands. 14433 LHS = S.CorrectDelayedTyposInExpr(LHS); 14434 RHS = S.CorrectDelayedTyposInExpr( 14435 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14436 [Opc, LHS](Expr *E) { 14437 if (Opc != BO_Assign) 14438 return ExprResult(E); 14439 // Avoid correcting the RHS to the same Expr as the LHS. 14440 Decl *D = getDeclFromExpr(E); 14441 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14442 }); 14443 } 14444 return std::make_pair(LHS, RHS); 14445 } 14446 14447 /// Returns true if conversion between vectors of halfs and vectors of floats 14448 /// is needed. 14449 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14450 Expr *E0, Expr *E1 = nullptr) { 14451 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14452 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14453 return false; 14454 14455 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14456 QualType Ty = E->IgnoreImplicit()->getType(); 14457 14458 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14459 // to vectors of floats. Although the element type of the vectors is __fp16, 14460 // the vectors shouldn't be treated as storage-only types. See the 14461 // discussion here: https://reviews.llvm.org/rG825235c140e7 14462 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14463 if (VT->getVectorKind() == VectorType::NeonVector) 14464 return false; 14465 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14466 } 14467 return false; 14468 }; 14469 14470 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14471 } 14472 14473 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14474 /// operator @p Opc at location @c TokLoc. This routine only supports 14475 /// built-in operations; ActOnBinOp handles overloaded operators. 14476 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14477 BinaryOperatorKind Opc, 14478 Expr *LHSExpr, Expr *RHSExpr) { 14479 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14480 // The syntax only allows initializer lists on the RHS of assignment, 14481 // so we don't need to worry about accepting invalid code for 14482 // non-assignment operators. 14483 // C++11 5.17p9: 14484 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14485 // of x = {} is x = T(). 14486 InitializationKind Kind = InitializationKind::CreateDirectList( 14487 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14488 InitializedEntity Entity = 14489 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14490 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14491 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14492 if (Init.isInvalid()) 14493 return Init; 14494 RHSExpr = Init.get(); 14495 } 14496 14497 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14498 QualType ResultTy; // Result type of the binary operator. 14499 // The following two variables are used for compound assignment operators 14500 QualType CompLHSTy; // Type of LHS after promotions for computation 14501 QualType CompResultTy; // Type of computation result 14502 ExprValueKind VK = VK_PRValue; 14503 ExprObjectKind OK = OK_Ordinary; 14504 bool ConvertHalfVec = false; 14505 14506 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14507 if (!LHS.isUsable() || !RHS.isUsable()) 14508 return ExprError(); 14509 14510 if (getLangOpts().OpenCL) { 14511 QualType LHSTy = LHSExpr->getType(); 14512 QualType RHSTy = RHSExpr->getType(); 14513 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14514 // the ATOMIC_VAR_INIT macro. 14515 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14516 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14517 if (BO_Assign == Opc) 14518 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14519 else 14520 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14521 return ExprError(); 14522 } 14523 14524 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14525 // only with a builtin functions and therefore should be disallowed here. 14526 if (LHSTy->isImageType() || RHSTy->isImageType() || 14527 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14528 LHSTy->isPipeType() || RHSTy->isPipeType() || 14529 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14530 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14531 return ExprError(); 14532 } 14533 } 14534 14535 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14536 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14537 14538 switch (Opc) { 14539 case BO_Assign: 14540 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14541 if (getLangOpts().CPlusPlus && 14542 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14543 VK = LHS.get()->getValueKind(); 14544 OK = LHS.get()->getObjectKind(); 14545 } 14546 if (!ResultTy.isNull()) { 14547 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14548 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14549 14550 // Avoid copying a block to the heap if the block is assigned to a local 14551 // auto variable that is declared in the same scope as the block. This 14552 // optimization is unsafe if the local variable is declared in an outer 14553 // scope. For example: 14554 // 14555 // BlockTy b; 14556 // { 14557 // b = ^{...}; 14558 // } 14559 // // It is unsafe to invoke the block here if it wasn't copied to the 14560 // // heap. 14561 // b(); 14562 14563 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14564 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14565 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14566 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14567 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14568 14569 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14570 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14571 NTCUC_Assignment, NTCUK_Copy); 14572 } 14573 RecordModifiableNonNullParam(*this, LHS.get()); 14574 break; 14575 case BO_PtrMemD: 14576 case BO_PtrMemI: 14577 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14578 Opc == BO_PtrMemI); 14579 break; 14580 case BO_Mul: 14581 case BO_Div: 14582 ConvertHalfVec = true; 14583 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14584 Opc == BO_Div); 14585 break; 14586 case BO_Rem: 14587 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14588 break; 14589 case BO_Add: 14590 ConvertHalfVec = true; 14591 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14592 break; 14593 case BO_Sub: 14594 ConvertHalfVec = true; 14595 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14596 break; 14597 case BO_Shl: 14598 case BO_Shr: 14599 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14600 break; 14601 case BO_LE: 14602 case BO_LT: 14603 case BO_GE: 14604 case BO_GT: 14605 ConvertHalfVec = true; 14606 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14607 break; 14608 case BO_EQ: 14609 case BO_NE: 14610 ConvertHalfVec = true; 14611 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14612 break; 14613 case BO_Cmp: 14614 ConvertHalfVec = true; 14615 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14616 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14617 break; 14618 case BO_And: 14619 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14620 LLVM_FALLTHROUGH; 14621 case BO_Xor: 14622 case BO_Or: 14623 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14624 break; 14625 case BO_LAnd: 14626 case BO_LOr: 14627 ConvertHalfVec = true; 14628 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14629 break; 14630 case BO_MulAssign: 14631 case BO_DivAssign: 14632 ConvertHalfVec = true; 14633 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14634 Opc == BO_DivAssign); 14635 CompLHSTy = CompResultTy; 14636 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14637 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14638 break; 14639 case BO_RemAssign: 14640 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14641 CompLHSTy = CompResultTy; 14642 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14643 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14644 break; 14645 case BO_AddAssign: 14646 ConvertHalfVec = true; 14647 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14648 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14649 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14650 break; 14651 case BO_SubAssign: 14652 ConvertHalfVec = true; 14653 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14654 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14655 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14656 break; 14657 case BO_ShlAssign: 14658 case BO_ShrAssign: 14659 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14660 CompLHSTy = CompResultTy; 14661 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14662 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14663 break; 14664 case BO_AndAssign: 14665 case BO_OrAssign: // fallthrough 14666 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14667 LLVM_FALLTHROUGH; 14668 case BO_XorAssign: 14669 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14670 CompLHSTy = CompResultTy; 14671 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14672 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14673 break; 14674 case BO_Comma: 14675 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14676 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14677 VK = RHS.get()->getValueKind(); 14678 OK = RHS.get()->getObjectKind(); 14679 } 14680 break; 14681 } 14682 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14683 return ExprError(); 14684 14685 // Some of the binary operations require promoting operands of half vector to 14686 // float vectors and truncating the result back to half vector. For now, we do 14687 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14688 // arm64). 14689 assert( 14690 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14691 isVector(LHS.get()->getType(), Context.HalfTy)) && 14692 "both sides are half vectors or neither sides are"); 14693 ConvertHalfVec = 14694 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14695 14696 // Check for array bounds violations for both sides of the BinaryOperator 14697 CheckArrayAccess(LHS.get()); 14698 CheckArrayAccess(RHS.get()); 14699 14700 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14701 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14702 &Context.Idents.get("object_setClass"), 14703 SourceLocation(), LookupOrdinaryName); 14704 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14705 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14706 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14707 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14708 "object_setClass(") 14709 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14710 ",") 14711 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14712 } 14713 else 14714 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14715 } 14716 else if (const ObjCIvarRefExpr *OIRE = 14717 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14718 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14719 14720 // Opc is not a compound assignment if CompResultTy is null. 14721 if (CompResultTy.isNull()) { 14722 if (ConvertHalfVec) 14723 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14724 OpLoc, CurFPFeatureOverrides()); 14725 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14726 VK, OK, OpLoc, CurFPFeatureOverrides()); 14727 } 14728 14729 // Handle compound assignments. 14730 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14731 OK_ObjCProperty) { 14732 VK = VK_LValue; 14733 OK = LHS.get()->getObjectKind(); 14734 } 14735 14736 // The LHS is not converted to the result type for fixed-point compound 14737 // assignment as the common type is computed on demand. Reset the CompLHSTy 14738 // to the LHS type we would have gotten after unary conversions. 14739 if (CompResultTy->isFixedPointType()) 14740 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14741 14742 if (ConvertHalfVec) 14743 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14744 OpLoc, CurFPFeatureOverrides()); 14745 14746 return CompoundAssignOperator::Create( 14747 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14748 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14749 } 14750 14751 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14752 /// operators are mixed in a way that suggests that the programmer forgot that 14753 /// comparison operators have higher precedence. The most typical example of 14754 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14755 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14756 SourceLocation OpLoc, Expr *LHSExpr, 14757 Expr *RHSExpr) { 14758 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14759 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14760 14761 // Check that one of the sides is a comparison operator and the other isn't. 14762 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14763 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14764 if (isLeftComp == isRightComp) 14765 return; 14766 14767 // Bitwise operations are sometimes used as eager logical ops. 14768 // Don't diagnose this. 14769 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14770 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14771 if (isLeftBitwise || isRightBitwise) 14772 return; 14773 14774 SourceRange DiagRange = isLeftComp 14775 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14776 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14777 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14778 SourceRange ParensRange = 14779 isLeftComp 14780 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14781 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14782 14783 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14784 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14785 SuggestParentheses(Self, OpLoc, 14786 Self.PDiag(diag::note_precedence_silence) << OpStr, 14787 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14788 SuggestParentheses(Self, OpLoc, 14789 Self.PDiag(diag::note_precedence_bitwise_first) 14790 << BinaryOperator::getOpcodeStr(Opc), 14791 ParensRange); 14792 } 14793 14794 /// It accepts a '&&' expr that is inside a '||' one. 14795 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14796 /// in parentheses. 14797 static void 14798 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14799 BinaryOperator *Bop) { 14800 assert(Bop->getOpcode() == BO_LAnd); 14801 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14802 << Bop->getSourceRange() << OpLoc; 14803 SuggestParentheses(Self, Bop->getOperatorLoc(), 14804 Self.PDiag(diag::note_precedence_silence) 14805 << Bop->getOpcodeStr(), 14806 Bop->getSourceRange()); 14807 } 14808 14809 /// Returns true if the given expression can be evaluated as a constant 14810 /// 'true'. 14811 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14812 bool Res; 14813 return !E->isValueDependent() && 14814 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14815 } 14816 14817 /// Returns true if the given expression can be evaluated as a constant 14818 /// 'false'. 14819 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14820 bool Res; 14821 return !E->isValueDependent() && 14822 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14823 } 14824 14825 /// Look for '&&' in the left hand of a '||' expr. 14826 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14827 Expr *LHSExpr, Expr *RHSExpr) { 14828 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14829 if (Bop->getOpcode() == BO_LAnd) { 14830 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14831 if (EvaluatesAsFalse(S, RHSExpr)) 14832 return; 14833 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14834 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14835 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14836 } else if (Bop->getOpcode() == BO_LOr) { 14837 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14838 // If it's "a || b && 1 || c" we didn't warn earlier for 14839 // "a || b && 1", but warn now. 14840 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14841 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14842 } 14843 } 14844 } 14845 } 14846 14847 /// Look for '&&' in the right hand of a '||' expr. 14848 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14849 Expr *LHSExpr, Expr *RHSExpr) { 14850 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14851 if (Bop->getOpcode() == BO_LAnd) { 14852 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14853 if (EvaluatesAsFalse(S, LHSExpr)) 14854 return; 14855 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14856 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14857 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14858 } 14859 } 14860 } 14861 14862 /// Look for bitwise op in the left or right hand of a bitwise op with 14863 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14864 /// the '&' expression in parentheses. 14865 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14866 SourceLocation OpLoc, Expr *SubExpr) { 14867 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14868 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14869 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14870 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14871 << Bop->getSourceRange() << OpLoc; 14872 SuggestParentheses(S, Bop->getOperatorLoc(), 14873 S.PDiag(diag::note_precedence_silence) 14874 << Bop->getOpcodeStr(), 14875 Bop->getSourceRange()); 14876 } 14877 } 14878 } 14879 14880 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14881 Expr *SubExpr, StringRef Shift) { 14882 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14883 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14884 StringRef Op = Bop->getOpcodeStr(); 14885 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14886 << Bop->getSourceRange() << OpLoc << Shift << Op; 14887 SuggestParentheses(S, Bop->getOperatorLoc(), 14888 S.PDiag(diag::note_precedence_silence) << Op, 14889 Bop->getSourceRange()); 14890 } 14891 } 14892 } 14893 14894 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14895 Expr *LHSExpr, Expr *RHSExpr) { 14896 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14897 if (!OCE) 14898 return; 14899 14900 FunctionDecl *FD = OCE->getDirectCallee(); 14901 if (!FD || !FD->isOverloadedOperator()) 14902 return; 14903 14904 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14905 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14906 return; 14907 14908 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14909 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14910 << (Kind == OO_LessLess); 14911 SuggestParentheses(S, OCE->getOperatorLoc(), 14912 S.PDiag(diag::note_precedence_silence) 14913 << (Kind == OO_LessLess ? "<<" : ">>"), 14914 OCE->getSourceRange()); 14915 SuggestParentheses( 14916 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14917 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14918 } 14919 14920 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14921 /// precedence. 14922 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14923 SourceLocation OpLoc, Expr *LHSExpr, 14924 Expr *RHSExpr){ 14925 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14926 if (BinaryOperator::isBitwiseOp(Opc)) 14927 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14928 14929 // Diagnose "arg1 & arg2 | arg3" 14930 if ((Opc == BO_Or || Opc == BO_Xor) && 14931 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14932 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14933 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14934 } 14935 14936 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14937 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14938 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14939 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14940 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14941 } 14942 14943 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14944 || Opc == BO_Shr) { 14945 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14946 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14947 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14948 } 14949 14950 // Warn on overloaded shift operators and comparisons, such as: 14951 // cout << 5 == 4; 14952 if (BinaryOperator::isComparisonOp(Opc)) 14953 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14954 } 14955 14956 // Binary Operators. 'Tok' is the token for the operator. 14957 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14958 tok::TokenKind Kind, 14959 Expr *LHSExpr, Expr *RHSExpr) { 14960 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14961 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14962 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14963 14964 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14965 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14966 14967 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14968 } 14969 14970 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14971 UnresolvedSetImpl &Functions) { 14972 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14973 if (OverOp != OO_None && OverOp != OO_Equal) 14974 LookupOverloadedOperatorName(OverOp, S, Functions); 14975 14976 // In C++20 onwards, we may have a second operator to look up. 14977 if (getLangOpts().CPlusPlus20) { 14978 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14979 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14980 } 14981 } 14982 14983 /// Build an overloaded binary operator expression in the given scope. 14984 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14985 BinaryOperatorKind Opc, 14986 Expr *LHS, Expr *RHS) { 14987 switch (Opc) { 14988 case BO_Assign: 14989 case BO_DivAssign: 14990 case BO_RemAssign: 14991 case BO_SubAssign: 14992 case BO_AndAssign: 14993 case BO_OrAssign: 14994 case BO_XorAssign: 14995 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14996 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14997 break; 14998 default: 14999 break; 15000 } 15001 15002 // Find all of the overloaded operators visible from this point. 15003 UnresolvedSet<16> Functions; 15004 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 15005 15006 // Build the (potentially-overloaded, potentially-dependent) 15007 // binary operation. 15008 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 15009 } 15010 15011 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 15012 BinaryOperatorKind Opc, 15013 Expr *LHSExpr, Expr *RHSExpr) { 15014 ExprResult LHS, RHS; 15015 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 15016 if (!LHS.isUsable() || !RHS.isUsable()) 15017 return ExprError(); 15018 LHSExpr = LHS.get(); 15019 RHSExpr = RHS.get(); 15020 15021 // We want to end up calling one of checkPseudoObjectAssignment 15022 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 15023 // both expressions are overloadable or either is type-dependent), 15024 // or CreateBuiltinBinOp (in any other case). We also want to get 15025 // any placeholder types out of the way. 15026 15027 // Handle pseudo-objects in the LHS. 15028 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 15029 // Assignments with a pseudo-object l-value need special analysis. 15030 if (pty->getKind() == BuiltinType::PseudoObject && 15031 BinaryOperator::isAssignmentOp(Opc)) 15032 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 15033 15034 // Don't resolve overloads if the other type is overloadable. 15035 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 15036 // We can't actually test that if we still have a placeholder, 15037 // though. Fortunately, none of the exceptions we see in that 15038 // code below are valid when the LHS is an overload set. Note 15039 // that an overload set can be dependently-typed, but it never 15040 // instantiates to having an overloadable type. 15041 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15042 if (resolvedRHS.isInvalid()) return ExprError(); 15043 RHSExpr = resolvedRHS.get(); 15044 15045 if (RHSExpr->isTypeDependent() || 15046 RHSExpr->getType()->isOverloadableType()) 15047 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15048 } 15049 15050 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 15051 // template, diagnose the missing 'template' keyword instead of diagnosing 15052 // an invalid use of a bound member function. 15053 // 15054 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 15055 // to C++1z [over.over]/1.4, but we already checked for that case above. 15056 if (Opc == BO_LT && inTemplateInstantiation() && 15057 (pty->getKind() == BuiltinType::BoundMember || 15058 pty->getKind() == BuiltinType::Overload)) { 15059 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 15060 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 15061 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 15062 return isa<FunctionTemplateDecl>(ND); 15063 })) { 15064 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 15065 : OE->getNameLoc(), 15066 diag::err_template_kw_missing) 15067 << OE->getName().getAsString() << ""; 15068 return ExprError(); 15069 } 15070 } 15071 15072 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 15073 if (LHS.isInvalid()) return ExprError(); 15074 LHSExpr = LHS.get(); 15075 } 15076 15077 // Handle pseudo-objects in the RHS. 15078 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 15079 // An overload in the RHS can potentially be resolved by the type 15080 // being assigned to. 15081 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 15082 if (getLangOpts().CPlusPlus && 15083 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 15084 LHSExpr->getType()->isOverloadableType())) 15085 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15086 15087 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15088 } 15089 15090 // Don't resolve overloads if the other type is overloadable. 15091 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 15092 LHSExpr->getType()->isOverloadableType()) 15093 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15094 15095 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15096 if (!resolvedRHS.isUsable()) return ExprError(); 15097 RHSExpr = resolvedRHS.get(); 15098 } 15099 15100 if (getLangOpts().CPlusPlus) { 15101 // If either expression is type-dependent, always build an 15102 // overloaded op. 15103 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 15104 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15105 15106 // Otherwise, build an overloaded op if either expression has an 15107 // overloadable type. 15108 if (LHSExpr->getType()->isOverloadableType() || 15109 RHSExpr->getType()->isOverloadableType()) 15110 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15111 } 15112 15113 if (getLangOpts().RecoveryAST && 15114 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 15115 assert(!getLangOpts().CPlusPlus); 15116 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 15117 "Should only occur in error-recovery path."); 15118 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 15119 // C [6.15.16] p3: 15120 // An assignment expression has the value of the left operand after the 15121 // assignment, but is not an lvalue. 15122 return CompoundAssignOperator::Create( 15123 Context, LHSExpr, RHSExpr, Opc, 15124 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 15125 OpLoc, CurFPFeatureOverrides()); 15126 QualType ResultType; 15127 switch (Opc) { 15128 case BO_Assign: 15129 ResultType = LHSExpr->getType().getUnqualifiedType(); 15130 break; 15131 case BO_LT: 15132 case BO_GT: 15133 case BO_LE: 15134 case BO_GE: 15135 case BO_EQ: 15136 case BO_NE: 15137 case BO_LAnd: 15138 case BO_LOr: 15139 // These operators have a fixed result type regardless of operands. 15140 ResultType = Context.IntTy; 15141 break; 15142 case BO_Comma: 15143 ResultType = RHSExpr->getType(); 15144 break; 15145 default: 15146 ResultType = Context.DependentTy; 15147 break; 15148 } 15149 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 15150 VK_PRValue, OK_Ordinary, OpLoc, 15151 CurFPFeatureOverrides()); 15152 } 15153 15154 // Build a built-in binary operation. 15155 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15156 } 15157 15158 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 15159 if (T.isNull() || T->isDependentType()) 15160 return false; 15161 15162 if (!T->isPromotableIntegerType()) 15163 return true; 15164 15165 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 15166 } 15167 15168 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 15169 UnaryOperatorKind Opc, 15170 Expr *InputExpr) { 15171 ExprResult Input = InputExpr; 15172 ExprValueKind VK = VK_PRValue; 15173 ExprObjectKind OK = OK_Ordinary; 15174 QualType resultType; 15175 bool CanOverflow = false; 15176 15177 bool ConvertHalfVec = false; 15178 if (getLangOpts().OpenCL) { 15179 QualType Ty = InputExpr->getType(); 15180 // The only legal unary operation for atomics is '&'. 15181 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 15182 // OpenCL special types - image, sampler, pipe, and blocks are to be used 15183 // only with a builtin functions and therefore should be disallowed here. 15184 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 15185 || Ty->isBlockPointerType())) { 15186 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15187 << InputExpr->getType() 15188 << Input.get()->getSourceRange()); 15189 } 15190 } 15191 15192 switch (Opc) { 15193 case UO_PreInc: 15194 case UO_PreDec: 15195 case UO_PostInc: 15196 case UO_PostDec: 15197 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 15198 OpLoc, 15199 Opc == UO_PreInc || 15200 Opc == UO_PostInc, 15201 Opc == UO_PreInc || 15202 Opc == UO_PreDec); 15203 CanOverflow = isOverflowingIntegerType(Context, resultType); 15204 break; 15205 case UO_AddrOf: 15206 resultType = CheckAddressOfOperand(Input, OpLoc); 15207 CheckAddressOfNoDeref(InputExpr); 15208 RecordModifiableNonNullParam(*this, InputExpr); 15209 break; 15210 case UO_Deref: { 15211 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15212 if (Input.isInvalid()) return ExprError(); 15213 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 15214 break; 15215 } 15216 case UO_Plus: 15217 case UO_Minus: 15218 CanOverflow = Opc == UO_Minus && 15219 isOverflowingIntegerType(Context, Input.get()->getType()); 15220 Input = UsualUnaryConversions(Input.get()); 15221 if (Input.isInvalid()) return ExprError(); 15222 // Unary plus and minus require promoting an operand of half vector to a 15223 // float vector and truncating the result back to a half vector. For now, we 15224 // do this only when HalfArgsAndReturns is set (that is, when the target is 15225 // arm or arm64). 15226 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 15227 15228 // If the operand is a half vector, promote it to a float vector. 15229 if (ConvertHalfVec) 15230 Input = convertVector(Input.get(), Context.FloatTy, *this); 15231 resultType = Input.get()->getType(); 15232 if (resultType->isDependentType()) 15233 break; 15234 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 15235 break; 15236 else if (resultType->isVectorType() && 15237 // The z vector extensions don't allow + or - with bool vectors. 15238 (!Context.getLangOpts().ZVector || 15239 resultType->castAs<VectorType>()->getVectorKind() != 15240 VectorType::AltiVecBool)) 15241 break; 15242 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 15243 Opc == UO_Plus && 15244 resultType->isPointerType()) 15245 break; 15246 15247 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15248 << resultType << Input.get()->getSourceRange()); 15249 15250 case UO_Not: // bitwise complement 15251 Input = UsualUnaryConversions(Input.get()); 15252 if (Input.isInvalid()) 15253 return ExprError(); 15254 resultType = Input.get()->getType(); 15255 if (resultType->isDependentType()) 15256 break; 15257 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 15258 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 15259 // C99 does not support '~' for complex conjugation. 15260 Diag(OpLoc, diag::ext_integer_complement_complex) 15261 << resultType << Input.get()->getSourceRange(); 15262 else if (resultType->hasIntegerRepresentation()) 15263 break; 15264 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 15265 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 15266 // on vector float types. 15267 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15268 if (!T->isIntegerType()) 15269 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15270 << resultType << Input.get()->getSourceRange()); 15271 } else { 15272 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15273 << resultType << Input.get()->getSourceRange()); 15274 } 15275 break; 15276 15277 case UO_LNot: // logical negation 15278 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 15279 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15280 if (Input.isInvalid()) return ExprError(); 15281 resultType = Input.get()->getType(); 15282 15283 // Though we still have to promote half FP to float... 15284 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 15285 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 15286 resultType = Context.FloatTy; 15287 } 15288 15289 if (resultType->isDependentType()) 15290 break; 15291 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 15292 // C99 6.5.3.3p1: ok, fallthrough; 15293 if (Context.getLangOpts().CPlusPlus) { 15294 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 15295 // operand contextually converted to bool. 15296 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 15297 ScalarTypeToBooleanCastKind(resultType)); 15298 } else if (Context.getLangOpts().OpenCL && 15299 Context.getLangOpts().OpenCLVersion < 120) { 15300 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15301 // operate on scalar float types. 15302 if (!resultType->isIntegerType() && !resultType->isPointerType()) 15303 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15304 << resultType << Input.get()->getSourceRange()); 15305 } 15306 } else if (resultType->isExtVectorType()) { 15307 if (Context.getLangOpts().OpenCL && 15308 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 15309 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15310 // operate on vector float types. 15311 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15312 if (!T->isIntegerType()) 15313 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15314 << resultType << Input.get()->getSourceRange()); 15315 } 15316 // Vector logical not returns the signed variant of the operand type. 15317 resultType = GetSignedVectorType(resultType); 15318 break; 15319 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 15320 const VectorType *VTy = resultType->castAs<VectorType>(); 15321 if (VTy->getVectorKind() != VectorType::GenericVector) 15322 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15323 << resultType << Input.get()->getSourceRange()); 15324 15325 // Vector logical not returns the signed variant of the operand type. 15326 resultType = GetSignedVectorType(resultType); 15327 break; 15328 } else { 15329 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15330 << resultType << Input.get()->getSourceRange()); 15331 } 15332 15333 // LNot always has type int. C99 6.5.3.3p5. 15334 // In C++, it's bool. C++ 5.3.1p8 15335 resultType = Context.getLogicalOperationType(); 15336 break; 15337 case UO_Real: 15338 case UO_Imag: 15339 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 15340 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 15341 // complex l-values to ordinary l-values and all other values to r-values. 15342 if (Input.isInvalid()) return ExprError(); 15343 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 15344 if (Input.get()->isGLValue() && 15345 Input.get()->getObjectKind() == OK_Ordinary) 15346 VK = Input.get()->getValueKind(); 15347 } else if (!getLangOpts().CPlusPlus) { 15348 // In C, a volatile scalar is read by __imag. In C++, it is not. 15349 Input = DefaultLvalueConversion(Input.get()); 15350 } 15351 break; 15352 case UO_Extension: 15353 resultType = Input.get()->getType(); 15354 VK = Input.get()->getValueKind(); 15355 OK = Input.get()->getObjectKind(); 15356 break; 15357 case UO_Coawait: 15358 // It's unnecessary to represent the pass-through operator co_await in the 15359 // AST; just return the input expression instead. 15360 assert(!Input.get()->getType()->isDependentType() && 15361 "the co_await expression must be non-dependant before " 15362 "building operator co_await"); 15363 return Input; 15364 } 15365 if (resultType.isNull() || Input.isInvalid()) 15366 return ExprError(); 15367 15368 // Check for array bounds violations in the operand of the UnaryOperator, 15369 // except for the '*' and '&' operators that have to be handled specially 15370 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15371 // that are explicitly defined as valid by the standard). 15372 if (Opc != UO_AddrOf && Opc != UO_Deref) 15373 CheckArrayAccess(Input.get()); 15374 15375 auto *UO = 15376 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15377 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15378 15379 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15380 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15381 !isUnevaluatedContext()) 15382 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15383 15384 // Convert the result back to a half vector. 15385 if (ConvertHalfVec) 15386 return convertVector(UO, Context.HalfTy, *this); 15387 return UO; 15388 } 15389 15390 /// Determine whether the given expression is a qualified member 15391 /// access expression, of a form that could be turned into a pointer to member 15392 /// with the address-of operator. 15393 bool Sema::isQualifiedMemberAccess(Expr *E) { 15394 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15395 if (!DRE->getQualifier()) 15396 return false; 15397 15398 ValueDecl *VD = DRE->getDecl(); 15399 if (!VD->isCXXClassMember()) 15400 return false; 15401 15402 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15403 return true; 15404 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15405 return Method->isInstance(); 15406 15407 return false; 15408 } 15409 15410 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15411 if (!ULE->getQualifier()) 15412 return false; 15413 15414 for (NamedDecl *D : ULE->decls()) { 15415 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15416 if (Method->isInstance()) 15417 return true; 15418 } else { 15419 // Overload set does not contain methods. 15420 break; 15421 } 15422 } 15423 15424 return false; 15425 } 15426 15427 return false; 15428 } 15429 15430 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15431 UnaryOperatorKind Opc, Expr *Input) { 15432 // First things first: handle placeholders so that the 15433 // overloaded-operator check considers the right type. 15434 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15435 // Increment and decrement of pseudo-object references. 15436 if (pty->getKind() == BuiltinType::PseudoObject && 15437 UnaryOperator::isIncrementDecrementOp(Opc)) 15438 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15439 15440 // extension is always a builtin operator. 15441 if (Opc == UO_Extension) 15442 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15443 15444 // & gets special logic for several kinds of placeholder. 15445 // The builtin code knows what to do. 15446 if (Opc == UO_AddrOf && 15447 (pty->getKind() == BuiltinType::Overload || 15448 pty->getKind() == BuiltinType::UnknownAny || 15449 pty->getKind() == BuiltinType::BoundMember)) 15450 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15451 15452 // Anything else needs to be handled now. 15453 ExprResult Result = CheckPlaceholderExpr(Input); 15454 if (Result.isInvalid()) return ExprError(); 15455 Input = Result.get(); 15456 } 15457 15458 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15459 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15460 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15461 // Find all of the overloaded operators visible from this point. 15462 UnresolvedSet<16> Functions; 15463 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15464 if (S && OverOp != OO_None) 15465 LookupOverloadedOperatorName(OverOp, S, Functions); 15466 15467 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15468 } 15469 15470 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15471 } 15472 15473 // Unary Operators. 'Tok' is the token for the operator. 15474 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15475 tok::TokenKind Op, Expr *Input) { 15476 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15477 } 15478 15479 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15480 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15481 LabelDecl *TheDecl) { 15482 TheDecl->markUsed(Context); 15483 // Create the AST node. The address of a label always has type 'void*'. 15484 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15485 Context.getPointerType(Context.VoidTy)); 15486 } 15487 15488 void Sema::ActOnStartStmtExpr() { 15489 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15490 } 15491 15492 void Sema::ActOnStmtExprError() { 15493 // Note that function is also called by TreeTransform when leaving a 15494 // StmtExpr scope without rebuilding anything. 15495 15496 DiscardCleanupsInEvaluationContext(); 15497 PopExpressionEvaluationContext(); 15498 } 15499 15500 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15501 SourceLocation RPLoc) { 15502 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15503 } 15504 15505 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15506 SourceLocation RPLoc, unsigned TemplateDepth) { 15507 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15508 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15509 15510 if (hasAnyUnrecoverableErrorsInThisFunction()) 15511 DiscardCleanupsInEvaluationContext(); 15512 assert(!Cleanup.exprNeedsCleanups() && 15513 "cleanups within StmtExpr not correctly bound!"); 15514 PopExpressionEvaluationContext(); 15515 15516 // FIXME: there are a variety of strange constraints to enforce here, for 15517 // example, it is not possible to goto into a stmt expression apparently. 15518 // More semantic analysis is needed. 15519 15520 // If there are sub-stmts in the compound stmt, take the type of the last one 15521 // as the type of the stmtexpr. 15522 QualType Ty = Context.VoidTy; 15523 bool StmtExprMayBindToTemp = false; 15524 if (!Compound->body_empty()) { 15525 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15526 if (const auto *LastStmt = 15527 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15528 if (const Expr *Value = LastStmt->getExprStmt()) { 15529 StmtExprMayBindToTemp = true; 15530 Ty = Value->getType(); 15531 } 15532 } 15533 } 15534 15535 // FIXME: Check that expression type is complete/non-abstract; statement 15536 // expressions are not lvalues. 15537 Expr *ResStmtExpr = 15538 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15539 if (StmtExprMayBindToTemp) 15540 return MaybeBindToTemporary(ResStmtExpr); 15541 return ResStmtExpr; 15542 } 15543 15544 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15545 if (ER.isInvalid()) 15546 return ExprError(); 15547 15548 // Do function/array conversion on the last expression, but not 15549 // lvalue-to-rvalue. However, initialize an unqualified type. 15550 ER = DefaultFunctionArrayConversion(ER.get()); 15551 if (ER.isInvalid()) 15552 return ExprError(); 15553 Expr *E = ER.get(); 15554 15555 if (E->isTypeDependent()) 15556 return E; 15557 15558 // In ARC, if the final expression ends in a consume, splice 15559 // the consume out and bind it later. In the alternate case 15560 // (when dealing with a retainable type), the result 15561 // initialization will create a produce. In both cases the 15562 // result will be +1, and we'll need to balance that out with 15563 // a bind. 15564 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15565 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15566 return Cast->getSubExpr(); 15567 15568 // FIXME: Provide a better location for the initialization. 15569 return PerformCopyInitialization( 15570 InitializedEntity::InitializeStmtExprResult( 15571 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15572 SourceLocation(), E); 15573 } 15574 15575 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15576 TypeSourceInfo *TInfo, 15577 ArrayRef<OffsetOfComponent> Components, 15578 SourceLocation RParenLoc) { 15579 QualType ArgTy = TInfo->getType(); 15580 bool Dependent = ArgTy->isDependentType(); 15581 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15582 15583 // We must have at least one component that refers to the type, and the first 15584 // one is known to be a field designator. Verify that the ArgTy represents 15585 // a struct/union/class. 15586 if (!Dependent && !ArgTy->isRecordType()) 15587 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15588 << ArgTy << TypeRange); 15589 15590 // Type must be complete per C99 7.17p3 because a declaring a variable 15591 // with an incomplete type would be ill-formed. 15592 if (!Dependent 15593 && RequireCompleteType(BuiltinLoc, ArgTy, 15594 diag::err_offsetof_incomplete_type, TypeRange)) 15595 return ExprError(); 15596 15597 bool DidWarnAboutNonPOD = false; 15598 QualType CurrentType = ArgTy; 15599 SmallVector<OffsetOfNode, 4> Comps; 15600 SmallVector<Expr*, 4> Exprs; 15601 for (const OffsetOfComponent &OC : Components) { 15602 if (OC.isBrackets) { 15603 // Offset of an array sub-field. TODO: Should we allow vector elements? 15604 if (!CurrentType->isDependentType()) { 15605 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15606 if(!AT) 15607 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15608 << CurrentType); 15609 CurrentType = AT->getElementType(); 15610 } else 15611 CurrentType = Context.DependentTy; 15612 15613 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15614 if (IdxRval.isInvalid()) 15615 return ExprError(); 15616 Expr *Idx = IdxRval.get(); 15617 15618 // The expression must be an integral expression. 15619 // FIXME: An integral constant expression? 15620 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15621 !Idx->getType()->isIntegerType()) 15622 return ExprError( 15623 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15624 << Idx->getSourceRange()); 15625 15626 // Record this array index. 15627 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15628 Exprs.push_back(Idx); 15629 continue; 15630 } 15631 15632 // Offset of a field. 15633 if (CurrentType->isDependentType()) { 15634 // We have the offset of a field, but we can't look into the dependent 15635 // type. Just record the identifier of the field. 15636 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15637 CurrentType = Context.DependentTy; 15638 continue; 15639 } 15640 15641 // We need to have a complete type to look into. 15642 if (RequireCompleteType(OC.LocStart, CurrentType, 15643 diag::err_offsetof_incomplete_type)) 15644 return ExprError(); 15645 15646 // Look for the designated field. 15647 const RecordType *RC = CurrentType->getAs<RecordType>(); 15648 if (!RC) 15649 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15650 << CurrentType); 15651 RecordDecl *RD = RC->getDecl(); 15652 15653 // C++ [lib.support.types]p5: 15654 // The macro offsetof accepts a restricted set of type arguments in this 15655 // International Standard. type shall be a POD structure or a POD union 15656 // (clause 9). 15657 // C++11 [support.types]p4: 15658 // If type is not a standard-layout class (Clause 9), the results are 15659 // undefined. 15660 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15661 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15662 unsigned DiagID = 15663 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15664 : diag::ext_offsetof_non_pod_type; 15665 15666 if (!IsSafe && !DidWarnAboutNonPOD && 15667 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15668 PDiag(DiagID) 15669 << SourceRange(Components[0].LocStart, OC.LocEnd) 15670 << CurrentType)) 15671 DidWarnAboutNonPOD = true; 15672 } 15673 15674 // Look for the field. 15675 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15676 LookupQualifiedName(R, RD); 15677 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15678 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15679 if (!MemberDecl) { 15680 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15681 MemberDecl = IndirectMemberDecl->getAnonField(); 15682 } 15683 15684 if (!MemberDecl) 15685 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15686 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15687 OC.LocEnd)); 15688 15689 // C99 7.17p3: 15690 // (If the specified member is a bit-field, the behavior is undefined.) 15691 // 15692 // We diagnose this as an error. 15693 if (MemberDecl->isBitField()) { 15694 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15695 << MemberDecl->getDeclName() 15696 << SourceRange(BuiltinLoc, RParenLoc); 15697 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15698 return ExprError(); 15699 } 15700 15701 RecordDecl *Parent = MemberDecl->getParent(); 15702 if (IndirectMemberDecl) 15703 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15704 15705 // If the member was found in a base class, introduce OffsetOfNodes for 15706 // the base class indirections. 15707 CXXBasePaths Paths; 15708 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15709 Paths)) { 15710 if (Paths.getDetectedVirtual()) { 15711 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15712 << MemberDecl->getDeclName() 15713 << SourceRange(BuiltinLoc, RParenLoc); 15714 return ExprError(); 15715 } 15716 15717 CXXBasePath &Path = Paths.front(); 15718 for (const CXXBasePathElement &B : Path) 15719 Comps.push_back(OffsetOfNode(B.Base)); 15720 } 15721 15722 if (IndirectMemberDecl) { 15723 for (auto *FI : IndirectMemberDecl->chain()) { 15724 assert(isa<FieldDecl>(FI)); 15725 Comps.push_back(OffsetOfNode(OC.LocStart, 15726 cast<FieldDecl>(FI), OC.LocEnd)); 15727 } 15728 } else 15729 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15730 15731 CurrentType = MemberDecl->getType().getNonReferenceType(); 15732 } 15733 15734 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15735 Comps, Exprs, RParenLoc); 15736 } 15737 15738 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15739 SourceLocation BuiltinLoc, 15740 SourceLocation TypeLoc, 15741 ParsedType ParsedArgTy, 15742 ArrayRef<OffsetOfComponent> Components, 15743 SourceLocation RParenLoc) { 15744 15745 TypeSourceInfo *ArgTInfo; 15746 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15747 if (ArgTy.isNull()) 15748 return ExprError(); 15749 15750 if (!ArgTInfo) 15751 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15752 15753 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15754 } 15755 15756 15757 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15758 Expr *CondExpr, 15759 Expr *LHSExpr, Expr *RHSExpr, 15760 SourceLocation RPLoc) { 15761 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15762 15763 ExprValueKind VK = VK_PRValue; 15764 ExprObjectKind OK = OK_Ordinary; 15765 QualType resType; 15766 bool CondIsTrue = false; 15767 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15768 resType = Context.DependentTy; 15769 } else { 15770 // The conditional expression is required to be a constant expression. 15771 llvm::APSInt condEval(32); 15772 ExprResult CondICE = VerifyIntegerConstantExpression( 15773 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15774 if (CondICE.isInvalid()) 15775 return ExprError(); 15776 CondExpr = CondICE.get(); 15777 CondIsTrue = condEval.getZExtValue(); 15778 15779 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15780 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15781 15782 resType = ActiveExpr->getType(); 15783 VK = ActiveExpr->getValueKind(); 15784 OK = ActiveExpr->getObjectKind(); 15785 } 15786 15787 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15788 resType, VK, OK, RPLoc, CondIsTrue); 15789 } 15790 15791 //===----------------------------------------------------------------------===// 15792 // Clang Extensions. 15793 //===----------------------------------------------------------------------===// 15794 15795 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15796 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15797 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15798 15799 if (LangOpts.CPlusPlus) { 15800 MangleNumberingContext *MCtx; 15801 Decl *ManglingContextDecl; 15802 std::tie(MCtx, ManglingContextDecl) = 15803 getCurrentMangleNumberContext(Block->getDeclContext()); 15804 if (MCtx) { 15805 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15806 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15807 } 15808 } 15809 15810 PushBlockScope(CurScope, Block); 15811 CurContext->addDecl(Block); 15812 if (CurScope) 15813 PushDeclContext(CurScope, Block); 15814 else 15815 CurContext = Block; 15816 15817 getCurBlock()->HasImplicitReturnType = true; 15818 15819 // Enter a new evaluation context to insulate the block from any 15820 // cleanups from the enclosing full-expression. 15821 PushExpressionEvaluationContext( 15822 ExpressionEvaluationContext::PotentiallyEvaluated); 15823 } 15824 15825 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15826 Scope *CurScope) { 15827 assert(ParamInfo.getIdentifier() == nullptr && 15828 "block-id should have no identifier!"); 15829 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15830 BlockScopeInfo *CurBlock = getCurBlock(); 15831 15832 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15833 QualType T = Sig->getType(); 15834 15835 // FIXME: We should allow unexpanded parameter packs here, but that would, 15836 // in turn, make the block expression contain unexpanded parameter packs. 15837 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15838 // Drop the parameters. 15839 FunctionProtoType::ExtProtoInfo EPI; 15840 EPI.HasTrailingReturn = false; 15841 EPI.TypeQuals.addConst(); 15842 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15843 Sig = Context.getTrivialTypeSourceInfo(T); 15844 } 15845 15846 // GetTypeForDeclarator always produces a function type for a block 15847 // literal signature. Furthermore, it is always a FunctionProtoType 15848 // unless the function was written with a typedef. 15849 assert(T->isFunctionType() && 15850 "GetTypeForDeclarator made a non-function block signature"); 15851 15852 // Look for an explicit signature in that function type. 15853 FunctionProtoTypeLoc ExplicitSignature; 15854 15855 if ((ExplicitSignature = Sig->getTypeLoc() 15856 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15857 15858 // Check whether that explicit signature was synthesized by 15859 // GetTypeForDeclarator. If so, don't save that as part of the 15860 // written signature. 15861 if (ExplicitSignature.getLocalRangeBegin() == 15862 ExplicitSignature.getLocalRangeEnd()) { 15863 // This would be much cheaper if we stored TypeLocs instead of 15864 // TypeSourceInfos. 15865 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15866 unsigned Size = Result.getFullDataSize(); 15867 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15868 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15869 15870 ExplicitSignature = FunctionProtoTypeLoc(); 15871 } 15872 } 15873 15874 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15875 CurBlock->FunctionType = T; 15876 15877 const auto *Fn = T->castAs<FunctionType>(); 15878 QualType RetTy = Fn->getReturnType(); 15879 bool isVariadic = 15880 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15881 15882 CurBlock->TheDecl->setIsVariadic(isVariadic); 15883 15884 // Context.DependentTy is used as a placeholder for a missing block 15885 // return type. TODO: what should we do with declarators like: 15886 // ^ * { ... } 15887 // If the answer is "apply template argument deduction".... 15888 if (RetTy != Context.DependentTy) { 15889 CurBlock->ReturnType = RetTy; 15890 CurBlock->TheDecl->setBlockMissingReturnType(false); 15891 CurBlock->HasImplicitReturnType = false; 15892 } 15893 15894 // Push block parameters from the declarator if we had them. 15895 SmallVector<ParmVarDecl*, 8> Params; 15896 if (ExplicitSignature) { 15897 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15898 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15899 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15900 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15901 // Diagnose this as an extension in C17 and earlier. 15902 if (!getLangOpts().C2x) 15903 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15904 } 15905 Params.push_back(Param); 15906 } 15907 15908 // Fake up parameter variables if we have a typedef, like 15909 // ^ fntype { ... } 15910 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15911 for (const auto &I : Fn->param_types()) { 15912 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15913 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15914 Params.push_back(Param); 15915 } 15916 } 15917 15918 // Set the parameters on the block decl. 15919 if (!Params.empty()) { 15920 CurBlock->TheDecl->setParams(Params); 15921 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15922 /*CheckParameterNames=*/false); 15923 } 15924 15925 // Finally we can process decl attributes. 15926 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15927 15928 // Put the parameter variables in scope. 15929 for (auto AI : CurBlock->TheDecl->parameters()) { 15930 AI->setOwningFunction(CurBlock->TheDecl); 15931 15932 // If this has an identifier, add it to the scope stack. 15933 if (AI->getIdentifier()) { 15934 CheckShadow(CurBlock->TheScope, AI); 15935 15936 PushOnScopeChains(AI, CurBlock->TheScope); 15937 } 15938 } 15939 } 15940 15941 /// ActOnBlockError - If there is an error parsing a block, this callback 15942 /// is invoked to pop the information about the block from the action impl. 15943 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15944 // Leave the expression-evaluation context. 15945 DiscardCleanupsInEvaluationContext(); 15946 PopExpressionEvaluationContext(); 15947 15948 // Pop off CurBlock, handle nested blocks. 15949 PopDeclContext(); 15950 PopFunctionScopeInfo(); 15951 } 15952 15953 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15954 /// literal was successfully completed. ^(int x){...} 15955 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15956 Stmt *Body, Scope *CurScope) { 15957 // If blocks are disabled, emit an error. 15958 if (!LangOpts.Blocks) 15959 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15960 15961 // Leave the expression-evaluation context. 15962 if (hasAnyUnrecoverableErrorsInThisFunction()) 15963 DiscardCleanupsInEvaluationContext(); 15964 assert(!Cleanup.exprNeedsCleanups() && 15965 "cleanups within block not correctly bound!"); 15966 PopExpressionEvaluationContext(); 15967 15968 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15969 BlockDecl *BD = BSI->TheDecl; 15970 15971 if (BSI->HasImplicitReturnType) 15972 deduceClosureReturnType(*BSI); 15973 15974 QualType RetTy = Context.VoidTy; 15975 if (!BSI->ReturnType.isNull()) 15976 RetTy = BSI->ReturnType; 15977 15978 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15979 QualType BlockTy; 15980 15981 // If the user wrote a function type in some form, try to use that. 15982 if (!BSI->FunctionType.isNull()) { 15983 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15984 15985 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15986 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15987 15988 // Turn protoless block types into nullary block types. 15989 if (isa<FunctionNoProtoType>(FTy)) { 15990 FunctionProtoType::ExtProtoInfo EPI; 15991 EPI.ExtInfo = Ext; 15992 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15993 15994 // Otherwise, if we don't need to change anything about the function type, 15995 // preserve its sugar structure. 15996 } else if (FTy->getReturnType() == RetTy && 15997 (!NoReturn || FTy->getNoReturnAttr())) { 15998 BlockTy = BSI->FunctionType; 15999 16000 // Otherwise, make the minimal modifications to the function type. 16001 } else { 16002 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 16003 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 16004 EPI.TypeQuals = Qualifiers(); 16005 EPI.ExtInfo = Ext; 16006 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 16007 } 16008 16009 // If we don't have a function type, just build one from nothing. 16010 } else { 16011 FunctionProtoType::ExtProtoInfo EPI; 16012 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 16013 BlockTy = Context.getFunctionType(RetTy, None, EPI); 16014 } 16015 16016 DiagnoseUnusedParameters(BD->parameters()); 16017 BlockTy = Context.getBlockPointerType(BlockTy); 16018 16019 // If needed, diagnose invalid gotos and switches in the block. 16020 if (getCurFunction()->NeedsScopeChecking() && 16021 !PP.isCodeCompletionEnabled()) 16022 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 16023 16024 BD->setBody(cast<CompoundStmt>(Body)); 16025 16026 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 16027 DiagnoseUnguardedAvailabilityViolations(BD); 16028 16029 // Try to apply the named return value optimization. We have to check again 16030 // if we can do this, though, because blocks keep return statements around 16031 // to deduce an implicit return type. 16032 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 16033 !BD->isDependentContext()) 16034 computeNRVO(Body, BSI); 16035 16036 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 16037 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 16038 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 16039 NTCUK_Destruct|NTCUK_Copy); 16040 16041 PopDeclContext(); 16042 16043 // Set the captured variables on the block. 16044 SmallVector<BlockDecl::Capture, 4> Captures; 16045 for (Capture &Cap : BSI->Captures) { 16046 if (Cap.isInvalid() || Cap.isThisCapture()) 16047 continue; 16048 16049 VarDecl *Var = Cap.getVariable(); 16050 Expr *CopyExpr = nullptr; 16051 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 16052 if (const RecordType *Record = 16053 Cap.getCaptureType()->getAs<RecordType>()) { 16054 // The capture logic needs the destructor, so make sure we mark it. 16055 // Usually this is unnecessary because most local variables have 16056 // their destructors marked at declaration time, but parameters are 16057 // an exception because it's technically only the call site that 16058 // actually requires the destructor. 16059 if (isa<ParmVarDecl>(Var)) 16060 FinalizeVarWithDestructor(Var, Record); 16061 16062 // Enter a separate potentially-evaluated context while building block 16063 // initializers to isolate their cleanups from those of the block 16064 // itself. 16065 // FIXME: Is this appropriate even when the block itself occurs in an 16066 // unevaluated operand? 16067 EnterExpressionEvaluationContext EvalContext( 16068 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16069 16070 SourceLocation Loc = Cap.getLocation(); 16071 16072 ExprResult Result = BuildDeclarationNameExpr( 16073 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 16074 16075 // According to the blocks spec, the capture of a variable from 16076 // the stack requires a const copy constructor. This is not true 16077 // of the copy/move done to move a __block variable to the heap. 16078 if (!Result.isInvalid() && 16079 !Result.get()->getType().isConstQualified()) { 16080 Result = ImpCastExprToType(Result.get(), 16081 Result.get()->getType().withConst(), 16082 CK_NoOp, VK_LValue); 16083 } 16084 16085 if (!Result.isInvalid()) { 16086 Result = PerformCopyInitialization( 16087 InitializedEntity::InitializeBlock(Var->getLocation(), 16088 Cap.getCaptureType()), 16089 Loc, Result.get()); 16090 } 16091 16092 // Build a full-expression copy expression if initialization 16093 // succeeded and used a non-trivial constructor. Recover from 16094 // errors by pretending that the copy isn't necessary. 16095 if (!Result.isInvalid() && 16096 !cast<CXXConstructExpr>(Result.get())->getConstructor() 16097 ->isTrivial()) { 16098 Result = MaybeCreateExprWithCleanups(Result); 16099 CopyExpr = Result.get(); 16100 } 16101 } 16102 } 16103 16104 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 16105 CopyExpr); 16106 Captures.push_back(NewCap); 16107 } 16108 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 16109 16110 // Pop the block scope now but keep it alive to the end of this function. 16111 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 16112 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 16113 16114 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 16115 16116 // If the block isn't obviously global, i.e. it captures anything at 16117 // all, then we need to do a few things in the surrounding context: 16118 if (Result->getBlockDecl()->hasCaptures()) { 16119 // First, this expression has a new cleanup object. 16120 ExprCleanupObjects.push_back(Result->getBlockDecl()); 16121 Cleanup.setExprNeedsCleanups(true); 16122 16123 // It also gets a branch-protected scope if any of the captured 16124 // variables needs destruction. 16125 for (const auto &CI : Result->getBlockDecl()->captures()) { 16126 const VarDecl *var = CI.getVariable(); 16127 if (var->getType().isDestructedType() != QualType::DK_none) { 16128 setFunctionHasBranchProtectedScope(); 16129 break; 16130 } 16131 } 16132 } 16133 16134 if (getCurFunction()) 16135 getCurFunction()->addBlock(BD); 16136 16137 return Result; 16138 } 16139 16140 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 16141 SourceLocation RPLoc) { 16142 TypeSourceInfo *TInfo; 16143 GetTypeFromParser(Ty, &TInfo); 16144 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 16145 } 16146 16147 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 16148 Expr *E, TypeSourceInfo *TInfo, 16149 SourceLocation RPLoc) { 16150 Expr *OrigExpr = E; 16151 bool IsMS = false; 16152 16153 // CUDA device code does not support varargs. 16154 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 16155 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 16156 CUDAFunctionTarget T = IdentifyCUDATarget(F); 16157 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 16158 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 16159 } 16160 } 16161 16162 // NVPTX does not support va_arg expression. 16163 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 16164 Context.getTargetInfo().getTriple().isNVPTX()) 16165 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 16166 16167 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 16168 // as Microsoft ABI on an actual Microsoft platform, where 16169 // __builtin_ms_va_list and __builtin_va_list are the same.) 16170 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 16171 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 16172 QualType MSVaListType = Context.getBuiltinMSVaListType(); 16173 if (Context.hasSameType(MSVaListType, E->getType())) { 16174 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16175 return ExprError(); 16176 IsMS = true; 16177 } 16178 } 16179 16180 // Get the va_list type 16181 QualType VaListType = Context.getBuiltinVaListType(); 16182 if (!IsMS) { 16183 if (VaListType->isArrayType()) { 16184 // Deal with implicit array decay; for example, on x86-64, 16185 // va_list is an array, but it's supposed to decay to 16186 // a pointer for va_arg. 16187 VaListType = Context.getArrayDecayedType(VaListType); 16188 // Make sure the input expression also decays appropriately. 16189 ExprResult Result = UsualUnaryConversions(E); 16190 if (Result.isInvalid()) 16191 return ExprError(); 16192 E = Result.get(); 16193 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 16194 // If va_list is a record type and we are compiling in C++ mode, 16195 // check the argument using reference binding. 16196 InitializedEntity Entity = InitializedEntity::InitializeParameter( 16197 Context, Context.getLValueReferenceType(VaListType), false); 16198 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 16199 if (Init.isInvalid()) 16200 return ExprError(); 16201 E = Init.getAs<Expr>(); 16202 } else { 16203 // Otherwise, the va_list argument must be an l-value because 16204 // it is modified by va_arg. 16205 if (!E->isTypeDependent() && 16206 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16207 return ExprError(); 16208 } 16209 } 16210 16211 if (!IsMS && !E->isTypeDependent() && 16212 !Context.hasSameType(VaListType, E->getType())) 16213 return ExprError( 16214 Diag(E->getBeginLoc(), 16215 diag::err_first_argument_to_va_arg_not_of_type_va_list) 16216 << OrigExpr->getType() << E->getSourceRange()); 16217 16218 if (!TInfo->getType()->isDependentType()) { 16219 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 16220 diag::err_second_parameter_to_va_arg_incomplete, 16221 TInfo->getTypeLoc())) 16222 return ExprError(); 16223 16224 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 16225 TInfo->getType(), 16226 diag::err_second_parameter_to_va_arg_abstract, 16227 TInfo->getTypeLoc())) 16228 return ExprError(); 16229 16230 if (!TInfo->getType().isPODType(Context)) { 16231 Diag(TInfo->getTypeLoc().getBeginLoc(), 16232 TInfo->getType()->isObjCLifetimeType() 16233 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 16234 : diag::warn_second_parameter_to_va_arg_not_pod) 16235 << TInfo->getType() 16236 << TInfo->getTypeLoc().getSourceRange(); 16237 } 16238 16239 // Check for va_arg where arguments of the given type will be promoted 16240 // (i.e. this va_arg is guaranteed to have undefined behavior). 16241 QualType PromoteType; 16242 if (TInfo->getType()->isPromotableIntegerType()) { 16243 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 16244 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 16245 // and C2x 7.16.1.1p2 says, in part: 16246 // If type is not compatible with the type of the actual next argument 16247 // (as promoted according to the default argument promotions), the 16248 // behavior is undefined, except for the following cases: 16249 // - both types are pointers to qualified or unqualified versions of 16250 // compatible types; 16251 // - one type is a signed integer type, the other type is the 16252 // corresponding unsigned integer type, and the value is 16253 // representable in both types; 16254 // - one type is pointer to qualified or unqualified void and the 16255 // other is a pointer to a qualified or unqualified character type. 16256 // Given that type compatibility is the primary requirement (ignoring 16257 // qualifications), you would think we could call typesAreCompatible() 16258 // directly to test this. However, in C++, that checks for *same type*, 16259 // which causes false positives when passing an enumeration type to 16260 // va_arg. Instead, get the underlying type of the enumeration and pass 16261 // that. 16262 QualType UnderlyingType = TInfo->getType(); 16263 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 16264 UnderlyingType = ET->getDecl()->getIntegerType(); 16265 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16266 /*CompareUnqualified*/ true)) 16267 PromoteType = QualType(); 16268 16269 // If the types are still not compatible, we need to test whether the 16270 // promoted type and the underlying type are the same except for 16271 // signedness. Ask the AST for the correctly corresponding type and see 16272 // if that's compatible. 16273 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && 16274 PromoteType->isUnsignedIntegerType() != 16275 UnderlyingType->isUnsignedIntegerType()) { 16276 UnderlyingType = 16277 UnderlyingType->isUnsignedIntegerType() 16278 ? Context.getCorrespondingSignedType(UnderlyingType) 16279 : Context.getCorrespondingUnsignedType(UnderlyingType); 16280 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16281 /*CompareUnqualified*/ true)) 16282 PromoteType = QualType(); 16283 } 16284 } 16285 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 16286 PromoteType = Context.DoubleTy; 16287 if (!PromoteType.isNull()) 16288 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 16289 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 16290 << TInfo->getType() 16291 << PromoteType 16292 << TInfo->getTypeLoc().getSourceRange()); 16293 } 16294 16295 QualType T = TInfo->getType().getNonLValueExprType(Context); 16296 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 16297 } 16298 16299 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 16300 // The type of __null will be int or long, depending on the size of 16301 // pointers on the target. 16302 QualType Ty; 16303 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 16304 if (pw == Context.getTargetInfo().getIntWidth()) 16305 Ty = Context.IntTy; 16306 else if (pw == Context.getTargetInfo().getLongWidth()) 16307 Ty = Context.LongTy; 16308 else if (pw == Context.getTargetInfo().getLongLongWidth()) 16309 Ty = Context.LongLongTy; 16310 else { 16311 llvm_unreachable("I don't know size of pointer!"); 16312 } 16313 16314 return new (Context) GNUNullExpr(Ty, TokenLoc); 16315 } 16316 16317 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { 16318 CXXRecordDecl *ImplDecl = nullptr; 16319 16320 // Fetch the std::source_location::__impl decl. 16321 if (NamespaceDecl *Std = S.getStdNamespace()) { 16322 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"), 16323 Loc, Sema::LookupOrdinaryName); 16324 if (S.LookupQualifiedName(ResultSL, Std)) { 16325 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { 16326 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"), 16327 Loc, Sema::LookupOrdinaryName); 16328 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && 16329 S.LookupQualifiedName(ResultImpl, SLDecl)) { 16330 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); 16331 } 16332 } 16333 } 16334 } 16335 16336 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { 16337 S.Diag(Loc, diag::err_std_source_location_impl_not_found); 16338 return nullptr; 16339 } 16340 16341 // Verify that __impl is a trivial struct type, with no base classes, and with 16342 // only the four expected fields. 16343 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || 16344 ImplDecl->getNumBases() != 0) { 16345 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 16346 return nullptr; 16347 } 16348 16349 unsigned Count = 0; 16350 for (FieldDecl *F : ImplDecl->fields()) { 16351 StringRef Name = F->getName(); 16352 16353 if (Name == "_M_file_name") { 16354 if (F->getType() != 16355 S.Context.getPointerType(S.Context.CharTy.withConst())) 16356 break; 16357 Count++; 16358 } else if (Name == "_M_function_name") { 16359 if (F->getType() != 16360 S.Context.getPointerType(S.Context.CharTy.withConst())) 16361 break; 16362 Count++; 16363 } else if (Name == "_M_line") { 16364 if (!F->getType()->isIntegerType()) 16365 break; 16366 Count++; 16367 } else if (Name == "_M_column") { 16368 if (!F->getType()->isIntegerType()) 16369 break; 16370 Count++; 16371 } else { 16372 Count = 100; // invalid 16373 break; 16374 } 16375 } 16376 if (Count != 4) { 16377 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 16378 return nullptr; 16379 } 16380 16381 return ImplDecl; 16382 } 16383 16384 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 16385 SourceLocation BuiltinLoc, 16386 SourceLocation RPLoc) { 16387 QualType ResultTy; 16388 switch (Kind) { 16389 case SourceLocExpr::File: 16390 case SourceLocExpr::Function: { 16391 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0); 16392 ResultTy = 16393 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType()); 16394 break; 16395 } 16396 case SourceLocExpr::Line: 16397 case SourceLocExpr::Column: 16398 ResultTy = Context.UnsignedIntTy; 16399 break; 16400 case SourceLocExpr::SourceLocStruct: 16401 if (!StdSourceLocationImplDecl) { 16402 StdSourceLocationImplDecl = 16403 LookupStdSourceLocationImpl(*this, BuiltinLoc); 16404 if (!StdSourceLocationImplDecl) 16405 return ExprError(); 16406 } 16407 ResultTy = Context.getPointerType( 16408 Context.getRecordType(StdSourceLocationImplDecl).withConst()); 16409 break; 16410 } 16411 16412 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext); 16413 } 16414 16415 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 16416 QualType ResultTy, 16417 SourceLocation BuiltinLoc, 16418 SourceLocation RPLoc, 16419 DeclContext *ParentContext) { 16420 return new (Context) 16421 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); 16422 } 16423 16424 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 16425 bool Diagnose) { 16426 if (!getLangOpts().ObjC) 16427 return false; 16428 16429 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 16430 if (!PT) 16431 return false; 16432 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 16433 16434 // Ignore any parens, implicit casts (should only be 16435 // array-to-pointer decays), and not-so-opaque values. The last is 16436 // important for making this trigger for property assignments. 16437 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 16438 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 16439 if (OV->getSourceExpr()) 16440 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 16441 16442 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 16443 if (!PT->isObjCIdType() && 16444 !(ID && ID->getIdentifier()->isStr("NSString"))) 16445 return false; 16446 if (!SL->isAscii()) 16447 return false; 16448 16449 if (Diagnose) { 16450 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 16451 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 16452 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 16453 } 16454 return true; 16455 } 16456 16457 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16458 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16459 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16460 !SrcExpr->isNullPointerConstant( 16461 getASTContext(), Expr::NPC_NeverValueDependent)) { 16462 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16463 return false; 16464 if (Diagnose) { 16465 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16466 << /*number*/1 16467 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16468 Expr *NumLit = 16469 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16470 if (NumLit) 16471 Exp = NumLit; 16472 } 16473 return true; 16474 } 16475 16476 return false; 16477 } 16478 16479 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16480 const Expr *SrcExpr) { 16481 if (!DstType->isFunctionPointerType() || 16482 !SrcExpr->getType()->isFunctionType()) 16483 return false; 16484 16485 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16486 if (!DRE) 16487 return false; 16488 16489 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16490 if (!FD) 16491 return false; 16492 16493 return !S.checkAddressOfFunctionIsAvailable(FD, 16494 /*Complain=*/true, 16495 SrcExpr->getBeginLoc()); 16496 } 16497 16498 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16499 SourceLocation Loc, 16500 QualType DstType, QualType SrcType, 16501 Expr *SrcExpr, AssignmentAction Action, 16502 bool *Complained) { 16503 if (Complained) 16504 *Complained = false; 16505 16506 // Decode the result (notice that AST's are still created for extensions). 16507 bool CheckInferredResultType = false; 16508 bool isInvalid = false; 16509 unsigned DiagKind = 0; 16510 ConversionFixItGenerator ConvHints; 16511 bool MayHaveConvFixit = false; 16512 bool MayHaveFunctionDiff = false; 16513 const ObjCInterfaceDecl *IFace = nullptr; 16514 const ObjCProtocolDecl *PDecl = nullptr; 16515 16516 switch (ConvTy) { 16517 case Compatible: 16518 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16519 return false; 16520 16521 case PointerToInt: 16522 if (getLangOpts().CPlusPlus) { 16523 DiagKind = diag::err_typecheck_convert_pointer_int; 16524 isInvalid = true; 16525 } else { 16526 DiagKind = diag::ext_typecheck_convert_pointer_int; 16527 } 16528 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16529 MayHaveConvFixit = true; 16530 break; 16531 case IntToPointer: 16532 if (getLangOpts().CPlusPlus) { 16533 DiagKind = diag::err_typecheck_convert_int_pointer; 16534 isInvalid = true; 16535 } else { 16536 DiagKind = diag::ext_typecheck_convert_int_pointer; 16537 } 16538 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16539 MayHaveConvFixit = true; 16540 break; 16541 case IncompatibleFunctionPointer: 16542 if (getLangOpts().CPlusPlus) { 16543 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16544 isInvalid = true; 16545 } else { 16546 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16547 } 16548 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16549 MayHaveConvFixit = true; 16550 break; 16551 case IncompatiblePointer: 16552 if (Action == AA_Passing_CFAudited) { 16553 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16554 } else if (getLangOpts().CPlusPlus) { 16555 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16556 isInvalid = true; 16557 } else { 16558 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16559 } 16560 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16561 SrcType->isObjCObjectPointerType(); 16562 if (!CheckInferredResultType) { 16563 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16564 } else if (CheckInferredResultType) { 16565 SrcType = SrcType.getUnqualifiedType(); 16566 DstType = DstType.getUnqualifiedType(); 16567 } 16568 MayHaveConvFixit = true; 16569 break; 16570 case IncompatiblePointerSign: 16571 if (getLangOpts().CPlusPlus) { 16572 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16573 isInvalid = true; 16574 } else { 16575 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16576 } 16577 break; 16578 case FunctionVoidPointer: 16579 if (getLangOpts().CPlusPlus) { 16580 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16581 isInvalid = true; 16582 } else { 16583 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16584 } 16585 break; 16586 case IncompatiblePointerDiscardsQualifiers: { 16587 // Perform array-to-pointer decay if necessary. 16588 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16589 16590 isInvalid = true; 16591 16592 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16593 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16594 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16595 DiagKind = diag::err_typecheck_incompatible_address_space; 16596 break; 16597 16598 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16599 DiagKind = diag::err_typecheck_incompatible_ownership; 16600 break; 16601 } 16602 16603 llvm_unreachable("unknown error case for discarding qualifiers!"); 16604 // fallthrough 16605 } 16606 case CompatiblePointerDiscardsQualifiers: 16607 // If the qualifiers lost were because we were applying the 16608 // (deprecated) C++ conversion from a string literal to a char* 16609 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16610 // Ideally, this check would be performed in 16611 // checkPointerTypesForAssignment. However, that would require a 16612 // bit of refactoring (so that the second argument is an 16613 // expression, rather than a type), which should be done as part 16614 // of a larger effort to fix checkPointerTypesForAssignment for 16615 // C++ semantics. 16616 if (getLangOpts().CPlusPlus && 16617 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16618 return false; 16619 if (getLangOpts().CPlusPlus) { 16620 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16621 isInvalid = true; 16622 } else { 16623 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16624 } 16625 16626 break; 16627 case IncompatibleNestedPointerQualifiers: 16628 if (getLangOpts().CPlusPlus) { 16629 isInvalid = true; 16630 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16631 } else { 16632 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16633 } 16634 break; 16635 case IncompatibleNestedPointerAddressSpaceMismatch: 16636 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16637 isInvalid = true; 16638 break; 16639 case IntToBlockPointer: 16640 DiagKind = diag::err_int_to_block_pointer; 16641 isInvalid = true; 16642 break; 16643 case IncompatibleBlockPointer: 16644 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16645 isInvalid = true; 16646 break; 16647 case IncompatibleObjCQualifiedId: { 16648 if (SrcType->isObjCQualifiedIdType()) { 16649 const ObjCObjectPointerType *srcOPT = 16650 SrcType->castAs<ObjCObjectPointerType>(); 16651 for (auto *srcProto : srcOPT->quals()) { 16652 PDecl = srcProto; 16653 break; 16654 } 16655 if (const ObjCInterfaceType *IFaceT = 16656 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16657 IFace = IFaceT->getDecl(); 16658 } 16659 else if (DstType->isObjCQualifiedIdType()) { 16660 const ObjCObjectPointerType *dstOPT = 16661 DstType->castAs<ObjCObjectPointerType>(); 16662 for (auto *dstProto : dstOPT->quals()) { 16663 PDecl = dstProto; 16664 break; 16665 } 16666 if (const ObjCInterfaceType *IFaceT = 16667 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16668 IFace = IFaceT->getDecl(); 16669 } 16670 if (getLangOpts().CPlusPlus) { 16671 DiagKind = diag::err_incompatible_qualified_id; 16672 isInvalid = true; 16673 } else { 16674 DiagKind = diag::warn_incompatible_qualified_id; 16675 } 16676 break; 16677 } 16678 case IncompatibleVectors: 16679 if (getLangOpts().CPlusPlus) { 16680 DiagKind = diag::err_incompatible_vectors; 16681 isInvalid = true; 16682 } else { 16683 DiagKind = diag::warn_incompatible_vectors; 16684 } 16685 break; 16686 case IncompatibleObjCWeakRef: 16687 DiagKind = diag::err_arc_weak_unavailable_assign; 16688 isInvalid = true; 16689 break; 16690 case Incompatible: 16691 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16692 if (Complained) 16693 *Complained = true; 16694 return true; 16695 } 16696 16697 DiagKind = diag::err_typecheck_convert_incompatible; 16698 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16699 MayHaveConvFixit = true; 16700 isInvalid = true; 16701 MayHaveFunctionDiff = true; 16702 break; 16703 } 16704 16705 QualType FirstType, SecondType; 16706 switch (Action) { 16707 case AA_Assigning: 16708 case AA_Initializing: 16709 // The destination type comes first. 16710 FirstType = DstType; 16711 SecondType = SrcType; 16712 break; 16713 16714 case AA_Returning: 16715 case AA_Passing: 16716 case AA_Passing_CFAudited: 16717 case AA_Converting: 16718 case AA_Sending: 16719 case AA_Casting: 16720 // The source type comes first. 16721 FirstType = SrcType; 16722 SecondType = DstType; 16723 break; 16724 } 16725 16726 PartialDiagnostic FDiag = PDiag(DiagKind); 16727 if (Action == AA_Passing_CFAudited) 16728 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16729 else 16730 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16731 16732 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16733 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16734 auto isPlainChar = [](const clang::Type *Type) { 16735 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16736 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16737 }; 16738 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16739 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16740 } 16741 16742 // If we can fix the conversion, suggest the FixIts. 16743 if (!ConvHints.isNull()) { 16744 for (FixItHint &H : ConvHints.Hints) 16745 FDiag << H; 16746 } 16747 16748 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16749 16750 if (MayHaveFunctionDiff) 16751 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16752 16753 Diag(Loc, FDiag); 16754 if ((DiagKind == diag::warn_incompatible_qualified_id || 16755 DiagKind == diag::err_incompatible_qualified_id) && 16756 PDecl && IFace && !IFace->hasDefinition()) 16757 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16758 << IFace << PDecl; 16759 16760 if (SecondType == Context.OverloadTy) 16761 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16762 FirstType, /*TakingAddress=*/true); 16763 16764 if (CheckInferredResultType) 16765 EmitRelatedResultTypeNote(SrcExpr); 16766 16767 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16768 EmitRelatedResultTypeNoteForReturn(DstType); 16769 16770 if (Complained) 16771 *Complained = true; 16772 return isInvalid; 16773 } 16774 16775 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16776 llvm::APSInt *Result, 16777 AllowFoldKind CanFold) { 16778 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16779 public: 16780 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16781 QualType T) override { 16782 return S.Diag(Loc, diag::err_ice_not_integral) 16783 << T << S.LangOpts.CPlusPlus; 16784 } 16785 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16786 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16787 } 16788 } Diagnoser; 16789 16790 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16791 } 16792 16793 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16794 llvm::APSInt *Result, 16795 unsigned DiagID, 16796 AllowFoldKind CanFold) { 16797 class IDDiagnoser : public VerifyICEDiagnoser { 16798 unsigned DiagID; 16799 16800 public: 16801 IDDiagnoser(unsigned DiagID) 16802 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16803 16804 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16805 return S.Diag(Loc, DiagID); 16806 } 16807 } Diagnoser(DiagID); 16808 16809 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16810 } 16811 16812 Sema::SemaDiagnosticBuilder 16813 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16814 QualType T) { 16815 return diagnoseNotICE(S, Loc); 16816 } 16817 16818 Sema::SemaDiagnosticBuilder 16819 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16820 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16821 } 16822 16823 ExprResult 16824 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16825 VerifyICEDiagnoser &Diagnoser, 16826 AllowFoldKind CanFold) { 16827 SourceLocation DiagLoc = E->getBeginLoc(); 16828 16829 if (getLangOpts().CPlusPlus11) { 16830 // C++11 [expr.const]p5: 16831 // If an expression of literal class type is used in a context where an 16832 // integral constant expression is required, then that class type shall 16833 // have a single non-explicit conversion function to an integral or 16834 // unscoped enumeration type 16835 ExprResult Converted; 16836 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16837 VerifyICEDiagnoser &BaseDiagnoser; 16838 public: 16839 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16840 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16841 BaseDiagnoser.Suppress, true), 16842 BaseDiagnoser(BaseDiagnoser) {} 16843 16844 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16845 QualType T) override { 16846 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16847 } 16848 16849 SemaDiagnosticBuilder diagnoseIncomplete( 16850 Sema &S, SourceLocation Loc, QualType T) override { 16851 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16852 } 16853 16854 SemaDiagnosticBuilder diagnoseExplicitConv( 16855 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16856 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16857 } 16858 16859 SemaDiagnosticBuilder noteExplicitConv( 16860 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16861 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16862 << ConvTy->isEnumeralType() << ConvTy; 16863 } 16864 16865 SemaDiagnosticBuilder diagnoseAmbiguous( 16866 Sema &S, SourceLocation Loc, QualType T) override { 16867 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16868 } 16869 16870 SemaDiagnosticBuilder noteAmbiguous( 16871 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16872 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16873 << ConvTy->isEnumeralType() << ConvTy; 16874 } 16875 16876 SemaDiagnosticBuilder diagnoseConversion( 16877 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16878 llvm_unreachable("conversion functions are permitted"); 16879 } 16880 } ConvertDiagnoser(Diagnoser); 16881 16882 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16883 ConvertDiagnoser); 16884 if (Converted.isInvalid()) 16885 return Converted; 16886 E = Converted.get(); 16887 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16888 return ExprError(); 16889 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16890 // An ICE must be of integral or unscoped enumeration type. 16891 if (!Diagnoser.Suppress) 16892 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16893 << E->getSourceRange(); 16894 return ExprError(); 16895 } 16896 16897 ExprResult RValueExpr = DefaultLvalueConversion(E); 16898 if (RValueExpr.isInvalid()) 16899 return ExprError(); 16900 16901 E = RValueExpr.get(); 16902 16903 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16904 // in the non-ICE case. 16905 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16906 if (Result) 16907 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16908 if (!isa<ConstantExpr>(E)) 16909 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16910 : ConstantExpr::Create(Context, E); 16911 return E; 16912 } 16913 16914 Expr::EvalResult EvalResult; 16915 SmallVector<PartialDiagnosticAt, 8> Notes; 16916 EvalResult.Diag = &Notes; 16917 16918 // Try to evaluate the expression, and produce diagnostics explaining why it's 16919 // not a constant expression as a side-effect. 16920 bool Folded = 16921 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16922 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16923 16924 if (!isa<ConstantExpr>(E)) 16925 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16926 16927 // In C++11, we can rely on diagnostics being produced for any expression 16928 // which is not a constant expression. If no diagnostics were produced, then 16929 // this is a constant expression. 16930 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16931 if (Result) 16932 *Result = EvalResult.Val.getInt(); 16933 return E; 16934 } 16935 16936 // If our only note is the usual "invalid subexpression" note, just point 16937 // the caret at its location rather than producing an essentially 16938 // redundant note. 16939 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16940 diag::note_invalid_subexpr_in_const_expr) { 16941 DiagLoc = Notes[0].first; 16942 Notes.clear(); 16943 } 16944 16945 if (!Folded || !CanFold) { 16946 if (!Diagnoser.Suppress) { 16947 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16948 for (const PartialDiagnosticAt &Note : Notes) 16949 Diag(Note.first, Note.second); 16950 } 16951 16952 return ExprError(); 16953 } 16954 16955 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16956 for (const PartialDiagnosticAt &Note : Notes) 16957 Diag(Note.first, Note.second); 16958 16959 if (Result) 16960 *Result = EvalResult.Val.getInt(); 16961 return E; 16962 } 16963 16964 namespace { 16965 // Handle the case where we conclude a expression which we speculatively 16966 // considered to be unevaluated is actually evaluated. 16967 class TransformToPE : public TreeTransform<TransformToPE> { 16968 typedef TreeTransform<TransformToPE> BaseTransform; 16969 16970 public: 16971 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16972 16973 // Make sure we redo semantic analysis 16974 bool AlwaysRebuild() { return true; } 16975 bool ReplacingOriginal() { return true; } 16976 16977 // We need to special-case DeclRefExprs referring to FieldDecls which 16978 // are not part of a member pointer formation; normal TreeTransforming 16979 // doesn't catch this case because of the way we represent them in the AST. 16980 // FIXME: This is a bit ugly; is it really the best way to handle this 16981 // case? 16982 // 16983 // Error on DeclRefExprs referring to FieldDecls. 16984 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16985 if (isa<FieldDecl>(E->getDecl()) && 16986 !SemaRef.isUnevaluatedContext()) 16987 return SemaRef.Diag(E->getLocation(), 16988 diag::err_invalid_non_static_member_use) 16989 << E->getDecl() << E->getSourceRange(); 16990 16991 return BaseTransform::TransformDeclRefExpr(E); 16992 } 16993 16994 // Exception: filter out member pointer formation 16995 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16996 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16997 return E; 16998 16999 return BaseTransform::TransformUnaryOperator(E); 17000 } 17001 17002 // The body of a lambda-expression is in a separate expression evaluation 17003 // context so never needs to be transformed. 17004 // FIXME: Ideally we wouldn't transform the closure type either, and would 17005 // just recreate the capture expressions and lambda expression. 17006 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 17007 return SkipLambdaBody(E, Body); 17008 } 17009 }; 17010 } 17011 17012 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 17013 assert(isUnevaluatedContext() && 17014 "Should only transform unevaluated expressions"); 17015 ExprEvalContexts.back().Context = 17016 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 17017 if (isUnevaluatedContext()) 17018 return E; 17019 return TransformToPE(*this).TransformExpr(E); 17020 } 17021 17022 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { 17023 assert(isUnevaluatedContext() && 17024 "Should only transform unevaluated expressions"); 17025 ExprEvalContexts.back().Context = 17026 ExprEvalContexts[ExprEvalContexts.size() - 2].Context; 17027 if (isUnevaluatedContext()) 17028 return TInfo; 17029 return TransformToPE(*this).TransformType(TInfo); 17030 } 17031 17032 void 17033 Sema::PushExpressionEvaluationContext( 17034 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 17035 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17036 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 17037 LambdaContextDecl, ExprContext); 17038 17039 // Discarded statements and immediate contexts nested in other 17040 // discarded statements or immediate context are themselves 17041 // a discarded statement or an immediate context, respectively. 17042 ExprEvalContexts.back().InDiscardedStatement = 17043 ExprEvalContexts[ExprEvalContexts.size() - 2] 17044 .isDiscardedStatementContext(); 17045 ExprEvalContexts.back().InImmediateFunctionContext = 17046 ExprEvalContexts[ExprEvalContexts.size() - 2] 17047 .isImmediateFunctionContext(); 17048 17049 Cleanup.reset(); 17050 if (!MaybeODRUseExprs.empty()) 17051 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 17052 } 17053 17054 void 17055 Sema::PushExpressionEvaluationContext( 17056 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 17057 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17058 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 17059 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 17060 } 17061 17062 namespace { 17063 17064 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 17065 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 17066 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 17067 if (E->getOpcode() == UO_Deref) 17068 return CheckPossibleDeref(S, E->getSubExpr()); 17069 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 17070 return CheckPossibleDeref(S, E->getBase()); 17071 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 17072 return CheckPossibleDeref(S, E->getBase()); 17073 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 17074 QualType Inner; 17075 QualType Ty = E->getType(); 17076 if (const auto *Ptr = Ty->getAs<PointerType>()) 17077 Inner = Ptr->getPointeeType(); 17078 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 17079 Inner = Arr->getElementType(); 17080 else 17081 return nullptr; 17082 17083 if (Inner->hasAttr(attr::NoDeref)) 17084 return E; 17085 } 17086 return nullptr; 17087 } 17088 17089 } // namespace 17090 17091 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 17092 for (const Expr *E : Rec.PossibleDerefs) { 17093 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 17094 if (DeclRef) { 17095 const ValueDecl *Decl = DeclRef->getDecl(); 17096 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 17097 << Decl->getName() << E->getSourceRange(); 17098 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 17099 } else { 17100 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 17101 << E->getSourceRange(); 17102 } 17103 } 17104 Rec.PossibleDerefs.clear(); 17105 } 17106 17107 /// Check whether E, which is either a discarded-value expression or an 17108 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 17109 /// and if so, remove it from the list of volatile-qualified assignments that 17110 /// we are going to warn are deprecated. 17111 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 17112 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 17113 return; 17114 17115 // Note: ignoring parens here is not justified by the standard rules, but 17116 // ignoring parentheses seems like a more reasonable approach, and this only 17117 // drives a deprecation warning so doesn't affect conformance. 17118 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 17119 if (BO->getOpcode() == BO_Assign) { 17120 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 17121 llvm::erase_value(LHSs, BO->getLHS()); 17122 } 17123 } 17124 } 17125 17126 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 17127 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 17128 !Decl->isConsteval() || isConstantEvaluated() || 17129 RebuildingImmediateInvocation || isImmediateFunctionContext()) 17130 return E; 17131 17132 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 17133 /// It's OK if this fails; we'll also remove this in 17134 /// HandleImmediateInvocations, but catching it here allows us to avoid 17135 /// walking the AST looking for it in simple cases. 17136 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 17137 if (auto *DeclRef = 17138 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 17139 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 17140 17141 E = MaybeCreateExprWithCleanups(E); 17142 17143 ConstantExpr *Res = ConstantExpr::Create( 17144 getASTContext(), E.get(), 17145 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 17146 getASTContext()), 17147 /*IsImmediateInvocation*/ true); 17148 /// Value-dependent constant expressions should not be immediately 17149 /// evaluated until they are instantiated. 17150 if (!Res->isValueDependent()) 17151 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 17152 return Res; 17153 } 17154 17155 static void EvaluateAndDiagnoseImmediateInvocation( 17156 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 17157 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 17158 Expr::EvalResult Eval; 17159 Eval.Diag = &Notes; 17160 ConstantExpr *CE = Candidate.getPointer(); 17161 bool Result = CE->EvaluateAsConstantExpr( 17162 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 17163 if (!Result || !Notes.empty()) { 17164 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 17165 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 17166 InnerExpr = FunctionalCast->getSubExpr(); 17167 FunctionDecl *FD = nullptr; 17168 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 17169 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 17170 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 17171 FD = Call->getConstructor(); 17172 else 17173 llvm_unreachable("unhandled decl kind"); 17174 assert(FD->isConsteval()); 17175 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 17176 for (auto &Note : Notes) 17177 SemaRef.Diag(Note.first, Note.second); 17178 return; 17179 } 17180 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 17181 } 17182 17183 static void RemoveNestedImmediateInvocation( 17184 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 17185 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 17186 struct ComplexRemove : TreeTransform<ComplexRemove> { 17187 using Base = TreeTransform<ComplexRemove>; 17188 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17189 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 17190 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 17191 CurrentII; 17192 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 17193 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 17194 SmallVector<Sema::ImmediateInvocationCandidate, 17195 4>::reverse_iterator Current) 17196 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 17197 void RemoveImmediateInvocation(ConstantExpr* E) { 17198 auto It = std::find_if(CurrentII, IISet.rend(), 17199 [E](Sema::ImmediateInvocationCandidate Elem) { 17200 return Elem.getPointer() == E; 17201 }); 17202 assert(It != IISet.rend() && 17203 "ConstantExpr marked IsImmediateInvocation should " 17204 "be present"); 17205 It->setInt(1); // Mark as deleted 17206 } 17207 ExprResult TransformConstantExpr(ConstantExpr *E) { 17208 if (!E->isImmediateInvocation()) 17209 return Base::TransformConstantExpr(E); 17210 RemoveImmediateInvocation(E); 17211 return Base::TransformExpr(E->getSubExpr()); 17212 } 17213 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 17214 /// we need to remove its DeclRefExpr from the DRSet. 17215 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 17216 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 17217 return Base::TransformCXXOperatorCallExpr(E); 17218 } 17219 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 17220 /// here. 17221 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 17222 if (!Init) 17223 return Init; 17224 /// ConstantExpr are the first layer of implicit node to be removed so if 17225 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 17226 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 17227 if (CE->isImmediateInvocation()) 17228 RemoveImmediateInvocation(CE); 17229 return Base::TransformInitializer(Init, NotCopyInit); 17230 } 17231 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 17232 DRSet.erase(E); 17233 return E; 17234 } 17235 bool AlwaysRebuild() { return false; } 17236 bool ReplacingOriginal() { return true; } 17237 bool AllowSkippingCXXConstructExpr() { 17238 bool Res = AllowSkippingFirstCXXConstructExpr; 17239 AllowSkippingFirstCXXConstructExpr = true; 17240 return Res; 17241 } 17242 bool AllowSkippingFirstCXXConstructExpr = true; 17243 } Transformer(SemaRef, Rec.ReferenceToConsteval, 17244 Rec.ImmediateInvocationCandidates, It); 17245 17246 /// CXXConstructExpr with a single argument are getting skipped by 17247 /// TreeTransform in some situtation because they could be implicit. This 17248 /// can only occur for the top-level CXXConstructExpr because it is used 17249 /// nowhere in the expression being transformed therefore will not be rebuilt. 17250 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 17251 /// skipping the first CXXConstructExpr. 17252 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 17253 Transformer.AllowSkippingFirstCXXConstructExpr = false; 17254 17255 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 17256 assert(Res.isUsable()); 17257 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 17258 It->getPointer()->setSubExpr(Res.get()); 17259 } 17260 17261 static void 17262 HandleImmediateInvocations(Sema &SemaRef, 17263 Sema::ExpressionEvaluationContextRecord &Rec) { 17264 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 17265 Rec.ReferenceToConsteval.size() == 0) || 17266 SemaRef.RebuildingImmediateInvocation) 17267 return; 17268 17269 /// When we have more then 1 ImmediateInvocationCandidates we need to check 17270 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 17271 /// need to remove ReferenceToConsteval in the immediate invocation. 17272 if (Rec.ImmediateInvocationCandidates.size() > 1) { 17273 17274 /// Prevent sema calls during the tree transform from adding pointers that 17275 /// are already in the sets. 17276 llvm::SaveAndRestore<bool> DisableIITracking( 17277 SemaRef.RebuildingImmediateInvocation, true); 17278 17279 /// Prevent diagnostic during tree transfrom as they are duplicates 17280 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 17281 17282 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 17283 It != Rec.ImmediateInvocationCandidates.rend(); It++) 17284 if (!It->getInt()) 17285 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 17286 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 17287 Rec.ReferenceToConsteval.size()) { 17288 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 17289 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17290 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 17291 bool VisitDeclRefExpr(DeclRefExpr *E) { 17292 DRSet.erase(E); 17293 return DRSet.size(); 17294 } 17295 } Visitor(Rec.ReferenceToConsteval); 17296 Visitor.TraverseStmt( 17297 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 17298 } 17299 for (auto CE : Rec.ImmediateInvocationCandidates) 17300 if (!CE.getInt()) 17301 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 17302 for (auto DR : Rec.ReferenceToConsteval) { 17303 auto *FD = cast<FunctionDecl>(DR->getDecl()); 17304 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 17305 << FD; 17306 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 17307 } 17308 } 17309 17310 void Sema::PopExpressionEvaluationContext() { 17311 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 17312 unsigned NumTypos = Rec.NumTypos; 17313 17314 if (!Rec.Lambdas.empty()) { 17315 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 17316 if (!getLangOpts().CPlusPlus20 && 17317 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 17318 Rec.isUnevaluated() || 17319 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 17320 unsigned D; 17321 if (Rec.isUnevaluated()) { 17322 // C++11 [expr.prim.lambda]p2: 17323 // A lambda-expression shall not appear in an unevaluated operand 17324 // (Clause 5). 17325 D = diag::err_lambda_unevaluated_operand; 17326 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 17327 // C++1y [expr.const]p2: 17328 // A conditional-expression e is a core constant expression unless the 17329 // evaluation of e, following the rules of the abstract machine, would 17330 // evaluate [...] a lambda-expression. 17331 D = diag::err_lambda_in_constant_expression; 17332 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 17333 // C++17 [expr.prim.lamda]p2: 17334 // A lambda-expression shall not appear [...] in a template-argument. 17335 D = diag::err_lambda_in_invalid_context; 17336 } else 17337 llvm_unreachable("Couldn't infer lambda error message."); 17338 17339 for (const auto *L : Rec.Lambdas) 17340 Diag(L->getBeginLoc(), D); 17341 } 17342 } 17343 17344 WarnOnPendingNoDerefs(Rec); 17345 HandleImmediateInvocations(*this, Rec); 17346 17347 // Warn on any volatile-qualified simple-assignments that are not discarded- 17348 // value expressions nor unevaluated operands (those cases get removed from 17349 // this list by CheckUnusedVolatileAssignment). 17350 for (auto *BO : Rec.VolatileAssignmentLHSs) 17351 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 17352 << BO->getType(); 17353 17354 // When are coming out of an unevaluated context, clear out any 17355 // temporaries that we may have created as part of the evaluation of 17356 // the expression in that context: they aren't relevant because they 17357 // will never be constructed. 17358 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 17359 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 17360 ExprCleanupObjects.end()); 17361 Cleanup = Rec.ParentCleanup; 17362 CleanupVarDeclMarking(); 17363 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 17364 // Otherwise, merge the contexts together. 17365 } else { 17366 Cleanup.mergeFrom(Rec.ParentCleanup); 17367 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 17368 Rec.SavedMaybeODRUseExprs.end()); 17369 } 17370 17371 // Pop the current expression evaluation context off the stack. 17372 ExprEvalContexts.pop_back(); 17373 17374 // The global expression evaluation context record is never popped. 17375 ExprEvalContexts.back().NumTypos += NumTypos; 17376 } 17377 17378 void Sema::DiscardCleanupsInEvaluationContext() { 17379 ExprCleanupObjects.erase( 17380 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 17381 ExprCleanupObjects.end()); 17382 Cleanup.reset(); 17383 MaybeODRUseExprs.clear(); 17384 } 17385 17386 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 17387 ExprResult Result = CheckPlaceholderExpr(E); 17388 if (Result.isInvalid()) 17389 return ExprError(); 17390 E = Result.get(); 17391 if (!E->getType()->isVariablyModifiedType()) 17392 return E; 17393 return TransformToPotentiallyEvaluated(E); 17394 } 17395 17396 /// Are we in a context that is potentially constant evaluated per C++20 17397 /// [expr.const]p12? 17398 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 17399 /// C++2a [expr.const]p12: 17400 // An expression or conversion is potentially constant evaluated if it is 17401 switch (SemaRef.ExprEvalContexts.back().Context) { 17402 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17403 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17404 17405 // -- a manifestly constant-evaluated expression, 17406 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17407 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17408 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17409 // -- a potentially-evaluated expression, 17410 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17411 // -- an immediate subexpression of a braced-init-list, 17412 17413 // -- [FIXME] an expression of the form & cast-expression that occurs 17414 // within a templated entity 17415 // -- a subexpression of one of the above that is not a subexpression of 17416 // a nested unevaluated operand. 17417 return true; 17418 17419 case Sema::ExpressionEvaluationContext::Unevaluated: 17420 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17421 // Expressions in this context are never evaluated. 17422 return false; 17423 } 17424 llvm_unreachable("Invalid context"); 17425 } 17426 17427 /// Return true if this function has a calling convention that requires mangling 17428 /// in the size of the parameter pack. 17429 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 17430 // These manglings don't do anything on non-Windows or non-x86 platforms, so 17431 // we don't need parameter type sizes. 17432 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 17433 if (!TT.isOSWindows() || !TT.isX86()) 17434 return false; 17435 17436 // If this is C++ and this isn't an extern "C" function, parameters do not 17437 // need to be complete. In this case, C++ mangling will apply, which doesn't 17438 // use the size of the parameters. 17439 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 17440 return false; 17441 17442 // Stdcall, fastcall, and vectorcall need this special treatment. 17443 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17444 switch (CC) { 17445 case CC_X86StdCall: 17446 case CC_X86FastCall: 17447 case CC_X86VectorCall: 17448 return true; 17449 default: 17450 break; 17451 } 17452 return false; 17453 } 17454 17455 /// Require that all of the parameter types of function be complete. Normally, 17456 /// parameter types are only required to be complete when a function is called 17457 /// or defined, but to mangle functions with certain calling conventions, the 17458 /// mangler needs to know the size of the parameter list. In this situation, 17459 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 17460 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 17461 /// result in a linker error. Clang doesn't implement this behavior, and instead 17462 /// attempts to error at compile time. 17463 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 17464 SourceLocation Loc) { 17465 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 17466 FunctionDecl *FD; 17467 ParmVarDecl *Param; 17468 17469 public: 17470 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 17471 : FD(FD), Param(Param) {} 17472 17473 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17474 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17475 StringRef CCName; 17476 switch (CC) { 17477 case CC_X86StdCall: 17478 CCName = "stdcall"; 17479 break; 17480 case CC_X86FastCall: 17481 CCName = "fastcall"; 17482 break; 17483 case CC_X86VectorCall: 17484 CCName = "vectorcall"; 17485 break; 17486 default: 17487 llvm_unreachable("CC does not need mangling"); 17488 } 17489 17490 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17491 << Param->getDeclName() << FD->getDeclName() << CCName; 17492 } 17493 }; 17494 17495 for (ParmVarDecl *Param : FD->parameters()) { 17496 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17497 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17498 } 17499 } 17500 17501 namespace { 17502 enum class OdrUseContext { 17503 /// Declarations in this context are not odr-used. 17504 None, 17505 /// Declarations in this context are formally odr-used, but this is a 17506 /// dependent context. 17507 Dependent, 17508 /// Declarations in this context are odr-used but not actually used (yet). 17509 FormallyOdrUsed, 17510 /// Declarations in this context are used. 17511 Used 17512 }; 17513 } 17514 17515 /// Are we within a context in which references to resolved functions or to 17516 /// variables result in odr-use? 17517 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17518 OdrUseContext Result; 17519 17520 switch (SemaRef.ExprEvalContexts.back().Context) { 17521 case Sema::ExpressionEvaluationContext::Unevaluated: 17522 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17523 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17524 return OdrUseContext::None; 17525 17526 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17527 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17528 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17529 Result = OdrUseContext::Used; 17530 break; 17531 17532 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17533 Result = OdrUseContext::FormallyOdrUsed; 17534 break; 17535 17536 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17537 // A default argument formally results in odr-use, but doesn't actually 17538 // result in a use in any real sense until it itself is used. 17539 Result = OdrUseContext::FormallyOdrUsed; 17540 break; 17541 } 17542 17543 if (SemaRef.CurContext->isDependentContext()) 17544 return OdrUseContext::Dependent; 17545 17546 return Result; 17547 } 17548 17549 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17550 if (!Func->isConstexpr()) 17551 return false; 17552 17553 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17554 return true; 17555 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17556 return CCD && CCD->getInheritedConstructor(); 17557 } 17558 17559 /// Mark a function referenced, and check whether it is odr-used 17560 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17561 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17562 bool MightBeOdrUse) { 17563 assert(Func && "No function?"); 17564 17565 Func->setReferenced(); 17566 17567 // Recursive functions aren't really used until they're used from some other 17568 // context. 17569 bool IsRecursiveCall = CurContext == Func; 17570 17571 // C++11 [basic.def.odr]p3: 17572 // A function whose name appears as a potentially-evaluated expression is 17573 // odr-used if it is the unique lookup result or the selected member of a 17574 // set of overloaded functions [...]. 17575 // 17576 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17577 // can just check that here. 17578 OdrUseContext OdrUse = 17579 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17580 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17581 OdrUse = OdrUseContext::FormallyOdrUsed; 17582 17583 // Trivial default constructors and destructors are never actually used. 17584 // FIXME: What about other special members? 17585 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17586 OdrUse == OdrUseContext::Used) { 17587 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17588 if (Constructor->isDefaultConstructor()) 17589 OdrUse = OdrUseContext::FormallyOdrUsed; 17590 if (isa<CXXDestructorDecl>(Func)) 17591 OdrUse = OdrUseContext::FormallyOdrUsed; 17592 } 17593 17594 // C++20 [expr.const]p12: 17595 // A function [...] is needed for constant evaluation if it is [...] a 17596 // constexpr function that is named by an expression that is potentially 17597 // constant evaluated 17598 bool NeededForConstantEvaluation = 17599 isPotentiallyConstantEvaluatedContext(*this) && 17600 isImplicitlyDefinableConstexprFunction(Func); 17601 17602 // Determine whether we require a function definition to exist, per 17603 // C++11 [temp.inst]p3: 17604 // Unless a function template specialization has been explicitly 17605 // instantiated or explicitly specialized, the function template 17606 // specialization is implicitly instantiated when the specialization is 17607 // referenced in a context that requires a function definition to exist. 17608 // C++20 [temp.inst]p7: 17609 // The existence of a definition of a [...] function is considered to 17610 // affect the semantics of the program if the [...] function is needed for 17611 // constant evaluation by an expression 17612 // C++20 [basic.def.odr]p10: 17613 // Every program shall contain exactly one definition of every non-inline 17614 // function or variable that is odr-used in that program outside of a 17615 // discarded statement 17616 // C++20 [special]p1: 17617 // The implementation will implicitly define [defaulted special members] 17618 // if they are odr-used or needed for constant evaluation. 17619 // 17620 // Note that we skip the implicit instantiation of templates that are only 17621 // used in unused default arguments or by recursive calls to themselves. 17622 // This is formally non-conforming, but seems reasonable in practice. 17623 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17624 NeededForConstantEvaluation); 17625 17626 // C++14 [temp.expl.spec]p6: 17627 // If a template [...] is explicitly specialized then that specialization 17628 // shall be declared before the first use of that specialization that would 17629 // cause an implicit instantiation to take place, in every translation unit 17630 // in which such a use occurs 17631 if (NeedDefinition && 17632 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17633 Func->getMemberSpecializationInfo())) 17634 checkSpecializationVisibility(Loc, Func); 17635 17636 if (getLangOpts().CUDA) 17637 CheckCUDACall(Loc, Func); 17638 17639 if (getLangOpts().SYCLIsDevice) 17640 checkSYCLDeviceFunction(Loc, Func); 17641 17642 // If we need a definition, try to create one. 17643 if (NeedDefinition && !Func->getBody()) { 17644 runWithSufficientStackSpace(Loc, [&] { 17645 if (CXXConstructorDecl *Constructor = 17646 dyn_cast<CXXConstructorDecl>(Func)) { 17647 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17648 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17649 if (Constructor->isDefaultConstructor()) { 17650 if (Constructor->isTrivial() && 17651 !Constructor->hasAttr<DLLExportAttr>()) 17652 return; 17653 DefineImplicitDefaultConstructor(Loc, Constructor); 17654 } else if (Constructor->isCopyConstructor()) { 17655 DefineImplicitCopyConstructor(Loc, Constructor); 17656 } else if (Constructor->isMoveConstructor()) { 17657 DefineImplicitMoveConstructor(Loc, Constructor); 17658 } 17659 } else if (Constructor->getInheritedConstructor()) { 17660 DefineInheritingConstructor(Loc, Constructor); 17661 } 17662 } else if (CXXDestructorDecl *Destructor = 17663 dyn_cast<CXXDestructorDecl>(Func)) { 17664 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17665 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17666 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17667 return; 17668 DefineImplicitDestructor(Loc, Destructor); 17669 } 17670 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17671 MarkVTableUsed(Loc, Destructor->getParent()); 17672 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17673 if (MethodDecl->isOverloadedOperator() && 17674 MethodDecl->getOverloadedOperator() == OO_Equal) { 17675 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17676 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17677 if (MethodDecl->isCopyAssignmentOperator()) 17678 DefineImplicitCopyAssignment(Loc, MethodDecl); 17679 else if (MethodDecl->isMoveAssignmentOperator()) 17680 DefineImplicitMoveAssignment(Loc, MethodDecl); 17681 } 17682 } else if (isa<CXXConversionDecl>(MethodDecl) && 17683 MethodDecl->getParent()->isLambda()) { 17684 CXXConversionDecl *Conversion = 17685 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17686 if (Conversion->isLambdaToBlockPointerConversion()) 17687 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17688 else 17689 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17690 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17691 MarkVTableUsed(Loc, MethodDecl->getParent()); 17692 } 17693 17694 if (Func->isDefaulted() && !Func->isDeleted()) { 17695 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17696 if (DCK != DefaultedComparisonKind::None) 17697 DefineDefaultedComparison(Loc, Func, DCK); 17698 } 17699 17700 // Implicit instantiation of function templates and member functions of 17701 // class templates. 17702 if (Func->isImplicitlyInstantiable()) { 17703 TemplateSpecializationKind TSK = 17704 Func->getTemplateSpecializationKindForInstantiation(); 17705 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17706 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17707 if (FirstInstantiation) { 17708 PointOfInstantiation = Loc; 17709 if (auto *MSI = Func->getMemberSpecializationInfo()) 17710 MSI->setPointOfInstantiation(Loc); 17711 // FIXME: Notify listener. 17712 else 17713 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17714 } else if (TSK != TSK_ImplicitInstantiation) { 17715 // Use the point of use as the point of instantiation, instead of the 17716 // point of explicit instantiation (which we track as the actual point 17717 // of instantiation). This gives better backtraces in diagnostics. 17718 PointOfInstantiation = Loc; 17719 } 17720 17721 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17722 Func->isConstexpr()) { 17723 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17724 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17725 CodeSynthesisContexts.size()) 17726 PendingLocalImplicitInstantiations.push_back( 17727 std::make_pair(Func, PointOfInstantiation)); 17728 else if (Func->isConstexpr()) 17729 // Do not defer instantiations of constexpr functions, to avoid the 17730 // expression evaluator needing to call back into Sema if it sees a 17731 // call to such a function. 17732 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17733 else { 17734 Func->setInstantiationIsPending(true); 17735 PendingInstantiations.push_back( 17736 std::make_pair(Func, PointOfInstantiation)); 17737 // Notify the consumer that a function was implicitly instantiated. 17738 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17739 } 17740 } 17741 } else { 17742 // Walk redefinitions, as some of them may be instantiable. 17743 for (auto i : Func->redecls()) { 17744 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17745 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17746 } 17747 } 17748 }); 17749 } 17750 17751 // C++14 [except.spec]p17: 17752 // An exception-specification is considered to be needed when: 17753 // - the function is odr-used or, if it appears in an unevaluated operand, 17754 // would be odr-used if the expression were potentially-evaluated; 17755 // 17756 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17757 // function is a pure virtual function we're calling, and in that case the 17758 // function was selected by overload resolution and we need to resolve its 17759 // exception specification for a different reason. 17760 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17761 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17762 ResolveExceptionSpec(Loc, FPT); 17763 17764 // If this is the first "real" use, act on that. 17765 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17766 // Keep track of used but undefined functions. 17767 if (!Func->isDefined()) { 17768 if (mightHaveNonExternalLinkage(Func)) 17769 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17770 else if (Func->getMostRecentDecl()->isInlined() && 17771 !LangOpts.GNUInline && 17772 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17773 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17774 else if (isExternalWithNoLinkageType(Func)) 17775 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17776 } 17777 17778 // Some x86 Windows calling conventions mangle the size of the parameter 17779 // pack into the name. Computing the size of the parameters requires the 17780 // parameter types to be complete. Check that now. 17781 if (funcHasParameterSizeMangling(*this, Func)) 17782 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17783 17784 // In the MS C++ ABI, the compiler emits destructor variants where they are 17785 // used. If the destructor is used here but defined elsewhere, mark the 17786 // virtual base destructors referenced. If those virtual base destructors 17787 // are inline, this will ensure they are defined when emitting the complete 17788 // destructor variant. This checking may be redundant if the destructor is 17789 // provided later in this TU. 17790 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17791 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17792 CXXRecordDecl *Parent = Dtor->getParent(); 17793 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17794 CheckCompleteDestructorVariant(Loc, Dtor); 17795 } 17796 } 17797 17798 Func->markUsed(Context); 17799 } 17800 } 17801 17802 /// Directly mark a variable odr-used. Given a choice, prefer to use 17803 /// MarkVariableReferenced since it does additional checks and then 17804 /// calls MarkVarDeclODRUsed. 17805 /// If the variable must be captured: 17806 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17807 /// - else capture it in the DeclContext that maps to the 17808 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17809 static void 17810 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17811 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17812 // Keep track of used but undefined variables. 17813 // FIXME: We shouldn't suppress this warning for static data members. 17814 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17815 (!Var->isExternallyVisible() || Var->isInline() || 17816 SemaRef.isExternalWithNoLinkageType(Var)) && 17817 !(Var->isStaticDataMember() && Var->hasInit())) { 17818 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17819 if (old.isInvalid()) 17820 old = Loc; 17821 } 17822 QualType CaptureType, DeclRefType; 17823 if (SemaRef.LangOpts.OpenMP) 17824 SemaRef.tryCaptureOpenMPLambdas(Var); 17825 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17826 /*EllipsisLoc*/ SourceLocation(), 17827 /*BuildAndDiagnose*/ true, 17828 CaptureType, DeclRefType, 17829 FunctionScopeIndexToStopAt); 17830 17831 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { 17832 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17833 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17834 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17835 if (VarTarget == Sema::CVT_Host && 17836 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17837 UserTarget == Sema::CFT_Global)) { 17838 // Diagnose ODR-use of host global variables in device functions. 17839 // Reference of device global variables in host functions is allowed 17840 // through shadow variables therefore it is not diagnosed. 17841 if (SemaRef.LangOpts.CUDAIsDevice) { 17842 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17843 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17844 SemaRef.targetDiag(Var->getLocation(), 17845 Var->getType().isConstQualified() 17846 ? diag::note_cuda_const_var_unpromoted 17847 : diag::note_cuda_host_var); 17848 } 17849 } else if (VarTarget == Sema::CVT_Device && 17850 (UserTarget == Sema::CFT_Host || 17851 UserTarget == Sema::CFT_HostDevice) && 17852 !Var->hasExternalStorage()) { 17853 // Record a CUDA/HIP device side variable if it is ODR-used 17854 // by host code. This is done conservatively, when the variable is 17855 // referenced in any of the following contexts: 17856 // - a non-function context 17857 // - a host function 17858 // - a host device function 17859 // This makes the ODR-use of the device side variable by host code to 17860 // be visible in the device compilation for the compiler to be able to 17861 // emit template variables instantiated by host code only and to 17862 // externalize the static device side variable ODR-used by host code. 17863 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17864 } 17865 } 17866 17867 Var->markUsed(SemaRef.Context); 17868 } 17869 17870 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17871 SourceLocation Loc, 17872 unsigned CapturingScopeIndex) { 17873 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17874 } 17875 17876 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17877 ValueDecl *var) { 17878 DeclContext *VarDC = var->getDeclContext(); 17879 17880 // If the parameter still belongs to the translation unit, then 17881 // we're actually just using one parameter in the declaration of 17882 // the next. 17883 if (isa<ParmVarDecl>(var) && 17884 isa<TranslationUnitDecl>(VarDC)) 17885 return; 17886 17887 // For C code, don't diagnose about capture if we're not actually in code 17888 // right now; it's impossible to write a non-constant expression outside of 17889 // function context, so we'll get other (more useful) diagnostics later. 17890 // 17891 // For C++, things get a bit more nasty... it would be nice to suppress this 17892 // diagnostic for certain cases like using a local variable in an array bound 17893 // for a member of a local class, but the correct predicate is not obvious. 17894 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17895 return; 17896 17897 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17898 unsigned ContextKind = 3; // unknown 17899 if (isa<CXXMethodDecl>(VarDC) && 17900 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17901 ContextKind = 2; 17902 } else if (isa<FunctionDecl>(VarDC)) { 17903 ContextKind = 0; 17904 } else if (isa<BlockDecl>(VarDC)) { 17905 ContextKind = 1; 17906 } 17907 17908 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17909 << var << ValueKind << ContextKind << VarDC; 17910 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17911 << var; 17912 17913 // FIXME: Add additional diagnostic info about class etc. which prevents 17914 // capture. 17915 } 17916 17917 17918 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17919 bool &SubCapturesAreNested, 17920 QualType &CaptureType, 17921 QualType &DeclRefType) { 17922 // Check whether we've already captured it. 17923 if (CSI->CaptureMap.count(Var)) { 17924 // If we found a capture, any subcaptures are nested. 17925 SubCapturesAreNested = true; 17926 17927 // Retrieve the capture type for this variable. 17928 CaptureType = CSI->getCapture(Var).getCaptureType(); 17929 17930 // Compute the type of an expression that refers to this variable. 17931 DeclRefType = CaptureType.getNonReferenceType(); 17932 17933 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17934 // are mutable in the sense that user can change their value - they are 17935 // private instances of the captured declarations. 17936 const Capture &Cap = CSI->getCapture(Var); 17937 if (Cap.isCopyCapture() && 17938 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17939 !(isa<CapturedRegionScopeInfo>(CSI) && 17940 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17941 DeclRefType.addConst(); 17942 return true; 17943 } 17944 return false; 17945 } 17946 17947 // Only block literals, captured statements, and lambda expressions can 17948 // capture; other scopes don't work. 17949 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17950 SourceLocation Loc, 17951 const bool Diagnose, Sema &S) { 17952 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17953 return getLambdaAwareParentOfDeclContext(DC); 17954 else if (Var->hasLocalStorage()) { 17955 if (Diagnose) 17956 diagnoseUncapturableValueReference(S, Loc, Var); 17957 } 17958 return nullptr; 17959 } 17960 17961 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17962 // certain types of variables (unnamed, variably modified types etc.) 17963 // so check for eligibility. 17964 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17965 SourceLocation Loc, 17966 const bool Diagnose, Sema &S) { 17967 17968 bool IsBlock = isa<BlockScopeInfo>(CSI); 17969 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17970 17971 // Lambdas are not allowed to capture unnamed variables 17972 // (e.g. anonymous unions). 17973 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17974 // assuming that's the intent. 17975 if (IsLambda && !Var->getDeclName()) { 17976 if (Diagnose) { 17977 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17978 S.Diag(Var->getLocation(), diag::note_declared_at); 17979 } 17980 return false; 17981 } 17982 17983 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17984 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17985 if (Diagnose) { 17986 S.Diag(Loc, diag::err_ref_vm_type); 17987 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17988 } 17989 return false; 17990 } 17991 // Prohibit structs with flexible array members too. 17992 // We cannot capture what is in the tail end of the struct. 17993 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17994 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17995 if (Diagnose) { 17996 if (IsBlock) 17997 S.Diag(Loc, diag::err_ref_flexarray_type); 17998 else 17999 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 18000 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18001 } 18002 return false; 18003 } 18004 } 18005 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18006 // Lambdas and captured statements are not allowed to capture __block 18007 // variables; they don't support the expected semantics. 18008 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 18009 if (Diagnose) { 18010 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 18011 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18012 } 18013 return false; 18014 } 18015 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 18016 if (S.getLangOpts().OpenCL && IsBlock && 18017 Var->getType()->isBlockPointerType()) { 18018 if (Diagnose) 18019 S.Diag(Loc, diag::err_opencl_block_ref_block); 18020 return false; 18021 } 18022 18023 return true; 18024 } 18025 18026 // Returns true if the capture by block was successful. 18027 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 18028 SourceLocation Loc, 18029 const bool BuildAndDiagnose, 18030 QualType &CaptureType, 18031 QualType &DeclRefType, 18032 const bool Nested, 18033 Sema &S, bool Invalid) { 18034 bool ByRef = false; 18035 18036 // Blocks are not allowed to capture arrays, excepting OpenCL. 18037 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 18038 // (decayed to pointers). 18039 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 18040 if (BuildAndDiagnose) { 18041 S.Diag(Loc, diag::err_ref_array_type); 18042 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18043 Invalid = true; 18044 } else { 18045 return false; 18046 } 18047 } 18048 18049 // Forbid the block-capture of autoreleasing variables. 18050 if (!Invalid && 18051 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18052 if (BuildAndDiagnose) { 18053 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 18054 << /*block*/ 0; 18055 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18056 Invalid = true; 18057 } else { 18058 return false; 18059 } 18060 } 18061 18062 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 18063 if (const auto *PT = CaptureType->getAs<PointerType>()) { 18064 QualType PointeeTy = PT->getPointeeType(); 18065 18066 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 18067 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 18068 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 18069 if (BuildAndDiagnose) { 18070 SourceLocation VarLoc = Var->getLocation(); 18071 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 18072 S.Diag(VarLoc, diag::note_declare_parameter_strong); 18073 } 18074 } 18075 } 18076 18077 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18078 if (HasBlocksAttr || CaptureType->isReferenceType() || 18079 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 18080 // Block capture by reference does not change the capture or 18081 // declaration reference types. 18082 ByRef = true; 18083 } else { 18084 // Block capture by copy introduces 'const'. 18085 CaptureType = CaptureType.getNonReferenceType().withConst(); 18086 DeclRefType = CaptureType; 18087 } 18088 18089 // Actually capture the variable. 18090 if (BuildAndDiagnose) 18091 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 18092 CaptureType, Invalid); 18093 18094 return !Invalid; 18095 } 18096 18097 18098 /// Capture the given variable in the captured region. 18099 static bool captureInCapturedRegion( 18100 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 18101 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 18102 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 18103 bool IsTopScope, Sema &S, bool Invalid) { 18104 // By default, capture variables by reference. 18105 bool ByRef = true; 18106 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18107 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18108 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 18109 // Using an LValue reference type is consistent with Lambdas (see below). 18110 if (S.isOpenMPCapturedDecl(Var)) { 18111 bool HasConst = DeclRefType.isConstQualified(); 18112 DeclRefType = DeclRefType.getUnqualifiedType(); 18113 // Don't lose diagnostics about assignments to const. 18114 if (HasConst) 18115 DeclRefType.addConst(); 18116 } 18117 // Do not capture firstprivates in tasks. 18118 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 18119 OMPC_unknown) 18120 return true; 18121 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 18122 RSI->OpenMPCaptureLevel); 18123 } 18124 18125 if (ByRef) 18126 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18127 else 18128 CaptureType = DeclRefType; 18129 18130 // Actually capture the variable. 18131 if (BuildAndDiagnose) 18132 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 18133 Loc, SourceLocation(), CaptureType, Invalid); 18134 18135 return !Invalid; 18136 } 18137 18138 /// Capture the given variable in the lambda. 18139 static bool captureInLambda(LambdaScopeInfo *LSI, 18140 VarDecl *Var, 18141 SourceLocation Loc, 18142 const bool BuildAndDiagnose, 18143 QualType &CaptureType, 18144 QualType &DeclRefType, 18145 const bool RefersToCapturedVariable, 18146 const Sema::TryCaptureKind Kind, 18147 SourceLocation EllipsisLoc, 18148 const bool IsTopScope, 18149 Sema &S, bool Invalid) { 18150 // Determine whether we are capturing by reference or by value. 18151 bool ByRef = false; 18152 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18153 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18154 } else { 18155 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 18156 } 18157 18158 // Compute the type of the field that will capture this variable. 18159 if (ByRef) { 18160 // C++11 [expr.prim.lambda]p15: 18161 // An entity is captured by reference if it is implicitly or 18162 // explicitly captured but not captured by copy. It is 18163 // unspecified whether additional unnamed non-static data 18164 // members are declared in the closure type for entities 18165 // captured by reference. 18166 // 18167 // FIXME: It is not clear whether we want to build an lvalue reference 18168 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 18169 // to do the former, while EDG does the latter. Core issue 1249 will 18170 // clarify, but for now we follow GCC because it's a more permissive and 18171 // easily defensible position. 18172 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18173 } else { 18174 // C++11 [expr.prim.lambda]p14: 18175 // For each entity captured by copy, an unnamed non-static 18176 // data member is declared in the closure type. The 18177 // declaration order of these members is unspecified. The type 18178 // of such a data member is the type of the corresponding 18179 // captured entity if the entity is not a reference to an 18180 // object, or the referenced type otherwise. [Note: If the 18181 // captured entity is a reference to a function, the 18182 // corresponding data member is also a reference to a 18183 // function. - end note ] 18184 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 18185 if (!RefType->getPointeeType()->isFunctionType()) 18186 CaptureType = RefType->getPointeeType(); 18187 } 18188 18189 // Forbid the lambda copy-capture of autoreleasing variables. 18190 if (!Invalid && 18191 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18192 if (BuildAndDiagnose) { 18193 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 18194 S.Diag(Var->getLocation(), diag::note_previous_decl) 18195 << Var->getDeclName(); 18196 Invalid = true; 18197 } else { 18198 return false; 18199 } 18200 } 18201 18202 // Make sure that by-copy captures are of a complete and non-abstract type. 18203 if (!Invalid && BuildAndDiagnose) { 18204 if (!CaptureType->isDependentType() && 18205 S.RequireCompleteSizedType( 18206 Loc, CaptureType, 18207 diag::err_capture_of_incomplete_or_sizeless_type, 18208 Var->getDeclName())) 18209 Invalid = true; 18210 else if (S.RequireNonAbstractType(Loc, CaptureType, 18211 diag::err_capture_of_abstract_type)) 18212 Invalid = true; 18213 } 18214 } 18215 18216 // Compute the type of a reference to this captured variable. 18217 if (ByRef) 18218 DeclRefType = CaptureType.getNonReferenceType(); 18219 else { 18220 // C++ [expr.prim.lambda]p5: 18221 // The closure type for a lambda-expression has a public inline 18222 // function call operator [...]. This function call operator is 18223 // declared const (9.3.1) if and only if the lambda-expression's 18224 // parameter-declaration-clause is not followed by mutable. 18225 DeclRefType = CaptureType.getNonReferenceType(); 18226 if (!LSI->Mutable && !CaptureType->isReferenceType()) 18227 DeclRefType.addConst(); 18228 } 18229 18230 // Add the capture. 18231 if (BuildAndDiagnose) 18232 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 18233 Loc, EllipsisLoc, CaptureType, Invalid); 18234 18235 return !Invalid; 18236 } 18237 18238 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 18239 // Offer a Copy fix even if the type is dependent. 18240 if (Var->getType()->isDependentType()) 18241 return true; 18242 QualType T = Var->getType().getNonReferenceType(); 18243 if (T.isTriviallyCopyableType(Context)) 18244 return true; 18245 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 18246 18247 if (!(RD = RD->getDefinition())) 18248 return false; 18249 if (RD->hasSimpleCopyConstructor()) 18250 return true; 18251 if (RD->hasUserDeclaredCopyConstructor()) 18252 for (CXXConstructorDecl *Ctor : RD->ctors()) 18253 if (Ctor->isCopyConstructor()) 18254 return !Ctor->isDeleted(); 18255 } 18256 return false; 18257 } 18258 18259 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 18260 /// default capture. Fixes may be omitted if they aren't allowed by the 18261 /// standard, for example we can't emit a default copy capture fix-it if we 18262 /// already explicitly copy capture capture another variable. 18263 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 18264 VarDecl *Var) { 18265 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 18266 // Don't offer Capture by copy of default capture by copy fixes if Var is 18267 // known not to be copy constructible. 18268 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 18269 18270 SmallString<32> FixBuffer; 18271 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 18272 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 18273 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 18274 if (ShouldOfferCopyFix) { 18275 // Offer fixes to insert an explicit capture for the variable. 18276 // [] -> [VarName] 18277 // [OtherCapture] -> [OtherCapture, VarName] 18278 FixBuffer.assign({Separator, Var->getName()}); 18279 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18280 << Var << /*value*/ 0 18281 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18282 } 18283 // As above but capture by reference. 18284 FixBuffer.assign({Separator, "&", Var->getName()}); 18285 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18286 << Var << /*reference*/ 1 18287 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18288 } 18289 18290 // Only try to offer default capture if there are no captures excluding this 18291 // and init captures. 18292 // [this]: OK. 18293 // [X = Y]: OK. 18294 // [&A, &B]: Don't offer. 18295 // [A, B]: Don't offer. 18296 if (llvm::any_of(LSI->Captures, [](Capture &C) { 18297 return !C.isThisCapture() && !C.isInitCapture(); 18298 })) 18299 return; 18300 18301 // The default capture specifiers, '=' or '&', must appear first in the 18302 // capture body. 18303 SourceLocation DefaultInsertLoc = 18304 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 18305 18306 if (ShouldOfferCopyFix) { 18307 bool CanDefaultCopyCapture = true; 18308 // [=, *this] OK since c++17 18309 // [=, this] OK since c++20 18310 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 18311 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 18312 ? LSI->getCXXThisCapture().isCopyCapture() 18313 : false; 18314 // We can't use default capture by copy if any captures already specified 18315 // capture by copy. 18316 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 18317 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 18318 })) { 18319 FixBuffer.assign({"=", Separator}); 18320 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 18321 << /*value*/ 0 18322 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 18323 } 18324 } 18325 18326 // We can't use default capture by reference if any captures already specified 18327 // capture by reference. 18328 if (llvm::none_of(LSI->Captures, [](Capture &C) { 18329 return !C.isInitCapture() && C.isReferenceCapture() && 18330 !C.isThisCapture(); 18331 })) { 18332 FixBuffer.assign({"&", Separator}); 18333 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 18334 << /*reference*/ 1 18335 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 18336 } 18337 } 18338 18339 bool Sema::tryCaptureVariable( 18340 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 18341 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 18342 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 18343 // An init-capture is notionally from the context surrounding its 18344 // declaration, but its parent DC is the lambda class. 18345 DeclContext *VarDC = Var->getDeclContext(); 18346 if (Var->isInitCapture()) 18347 VarDC = VarDC->getParent(); 18348 18349 DeclContext *DC = CurContext; 18350 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 18351 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 18352 // We need to sync up the Declaration Context with the 18353 // FunctionScopeIndexToStopAt 18354 if (FunctionScopeIndexToStopAt) { 18355 unsigned FSIndex = FunctionScopes.size() - 1; 18356 while (FSIndex != MaxFunctionScopesIndex) { 18357 DC = getLambdaAwareParentOfDeclContext(DC); 18358 --FSIndex; 18359 } 18360 } 18361 18362 18363 // If the variable is declared in the current context, there is no need to 18364 // capture it. 18365 if (VarDC == DC) return true; 18366 18367 // Capture global variables if it is required to use private copy of this 18368 // variable. 18369 bool IsGlobal = !Var->hasLocalStorage(); 18370 if (IsGlobal && 18371 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 18372 MaxFunctionScopesIndex))) 18373 return true; 18374 Var = Var->getCanonicalDecl(); 18375 18376 // Walk up the stack to determine whether we can capture the variable, 18377 // performing the "simple" checks that don't depend on type. We stop when 18378 // we've either hit the declared scope of the variable or find an existing 18379 // capture of that variable. We start from the innermost capturing-entity 18380 // (the DC) and ensure that all intervening capturing-entities 18381 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 18382 // declcontext can either capture the variable or have already captured 18383 // the variable. 18384 CaptureType = Var->getType(); 18385 DeclRefType = CaptureType.getNonReferenceType(); 18386 bool Nested = false; 18387 bool Explicit = (Kind != TryCapture_Implicit); 18388 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 18389 do { 18390 // Only block literals, captured statements, and lambda expressions can 18391 // capture; other scopes don't work. 18392 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 18393 ExprLoc, 18394 BuildAndDiagnose, 18395 *this); 18396 // We need to check for the parent *first* because, if we *have* 18397 // private-captured a global variable, we need to recursively capture it in 18398 // intermediate blocks, lambdas, etc. 18399 if (!ParentDC) { 18400 if (IsGlobal) { 18401 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 18402 break; 18403 } 18404 return true; 18405 } 18406 18407 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 18408 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 18409 18410 18411 // Check whether we've already captured it. 18412 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 18413 DeclRefType)) { 18414 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 18415 break; 18416 } 18417 // If we are instantiating a generic lambda call operator body, 18418 // we do not want to capture new variables. What was captured 18419 // during either a lambdas transformation or initial parsing 18420 // should be used. 18421 if (isGenericLambdaCallOperatorSpecialization(DC)) { 18422 if (BuildAndDiagnose) { 18423 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18424 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 18425 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18426 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18427 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18428 buildLambdaCaptureFixit(*this, LSI, Var); 18429 } else 18430 diagnoseUncapturableValueReference(*this, ExprLoc, Var); 18431 } 18432 return true; 18433 } 18434 18435 // Try to capture variable-length arrays types. 18436 if (Var->getType()->isVariablyModifiedType()) { 18437 // We're going to walk down into the type and look for VLA 18438 // expressions. 18439 QualType QTy = Var->getType(); 18440 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18441 QTy = PVD->getOriginalType(); 18442 captureVariablyModifiedType(Context, QTy, CSI); 18443 } 18444 18445 if (getLangOpts().OpenMP) { 18446 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18447 // OpenMP private variables should not be captured in outer scope, so 18448 // just break here. Similarly, global variables that are captured in a 18449 // target region should not be captured outside the scope of the region. 18450 if (RSI->CapRegionKind == CR_OpenMP) { 18451 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 18452 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 18453 // If the variable is private (i.e. not captured) and has variably 18454 // modified type, we still need to capture the type for correct 18455 // codegen in all regions, associated with the construct. Currently, 18456 // it is captured in the innermost captured region only. 18457 if (IsOpenMPPrivateDecl != OMPC_unknown && 18458 Var->getType()->isVariablyModifiedType()) { 18459 QualType QTy = Var->getType(); 18460 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18461 QTy = PVD->getOriginalType(); 18462 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 18463 I < E; ++I) { 18464 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 18465 FunctionScopes[FunctionScopesIndex - I]); 18466 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 18467 "Wrong number of captured regions associated with the " 18468 "OpenMP construct."); 18469 captureVariablyModifiedType(Context, QTy, OuterRSI); 18470 } 18471 } 18472 bool IsTargetCap = 18473 IsOpenMPPrivateDecl != OMPC_private && 18474 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 18475 RSI->OpenMPCaptureLevel); 18476 // Do not capture global if it is not privatized in outer regions. 18477 bool IsGlobalCap = 18478 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 18479 RSI->OpenMPCaptureLevel); 18480 18481 // When we detect target captures we are looking from inside the 18482 // target region, therefore we need to propagate the capture from the 18483 // enclosing region. Therefore, the capture is not initially nested. 18484 if (IsTargetCap) 18485 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18486 18487 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18488 (IsGlobal && !IsGlobalCap)) { 18489 Nested = !IsTargetCap; 18490 bool HasConst = DeclRefType.isConstQualified(); 18491 DeclRefType = DeclRefType.getUnqualifiedType(); 18492 // Don't lose diagnostics about assignments to const. 18493 if (HasConst) 18494 DeclRefType.addConst(); 18495 CaptureType = Context.getLValueReferenceType(DeclRefType); 18496 break; 18497 } 18498 } 18499 } 18500 } 18501 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18502 // No capture-default, and this is not an explicit capture 18503 // so cannot capture this variable. 18504 if (BuildAndDiagnose) { 18505 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18506 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18507 auto *LSI = cast<LambdaScopeInfo>(CSI); 18508 if (LSI->Lambda) { 18509 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18510 buildLambdaCaptureFixit(*this, LSI, Var); 18511 } 18512 // FIXME: If we error out because an outer lambda can not implicitly 18513 // capture a variable that an inner lambda explicitly captures, we 18514 // should have the inner lambda do the explicit capture - because 18515 // it makes for cleaner diagnostics later. This would purely be done 18516 // so that the diagnostic does not misleadingly claim that a variable 18517 // can not be captured by a lambda implicitly even though it is captured 18518 // explicitly. Suggestion: 18519 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18520 // at the function head 18521 // - cache the StartingDeclContext - this must be a lambda 18522 // - captureInLambda in the innermost lambda the variable. 18523 } 18524 return true; 18525 } 18526 18527 FunctionScopesIndex--; 18528 DC = ParentDC; 18529 Explicit = false; 18530 } while (!VarDC->Equals(DC)); 18531 18532 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18533 // computing the type of the capture at each step, checking type-specific 18534 // requirements, and adding captures if requested. 18535 // If the variable had already been captured previously, we start capturing 18536 // at the lambda nested within that one. 18537 bool Invalid = false; 18538 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18539 ++I) { 18540 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18541 18542 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18543 // certain types of variables (unnamed, variably modified types etc.) 18544 // so check for eligibility. 18545 if (!Invalid) 18546 Invalid = 18547 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18548 18549 // After encountering an error, if we're actually supposed to capture, keep 18550 // capturing in nested contexts to suppress any follow-on diagnostics. 18551 if (Invalid && !BuildAndDiagnose) 18552 return true; 18553 18554 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18555 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18556 DeclRefType, Nested, *this, Invalid); 18557 Nested = true; 18558 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18559 Invalid = !captureInCapturedRegion( 18560 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18561 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18562 Nested = true; 18563 } else { 18564 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18565 Invalid = 18566 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18567 DeclRefType, Nested, Kind, EllipsisLoc, 18568 /*IsTopScope*/ I == N - 1, *this, Invalid); 18569 Nested = true; 18570 } 18571 18572 if (Invalid && !BuildAndDiagnose) 18573 return true; 18574 } 18575 return Invalid; 18576 } 18577 18578 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18579 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18580 QualType CaptureType; 18581 QualType DeclRefType; 18582 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18583 /*BuildAndDiagnose=*/true, CaptureType, 18584 DeclRefType, nullptr); 18585 } 18586 18587 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18588 QualType CaptureType; 18589 QualType DeclRefType; 18590 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18591 /*BuildAndDiagnose=*/false, CaptureType, 18592 DeclRefType, nullptr); 18593 } 18594 18595 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18596 QualType CaptureType; 18597 QualType DeclRefType; 18598 18599 // Determine whether we can capture this variable. 18600 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18601 /*BuildAndDiagnose=*/false, CaptureType, 18602 DeclRefType, nullptr)) 18603 return QualType(); 18604 18605 return DeclRefType; 18606 } 18607 18608 namespace { 18609 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18610 // The produced TemplateArgumentListInfo* points to data stored within this 18611 // object, so should only be used in contexts where the pointer will not be 18612 // used after the CopiedTemplateArgs object is destroyed. 18613 class CopiedTemplateArgs { 18614 bool HasArgs; 18615 TemplateArgumentListInfo TemplateArgStorage; 18616 public: 18617 template<typename RefExpr> 18618 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18619 if (HasArgs) 18620 E->copyTemplateArgumentsInto(TemplateArgStorage); 18621 } 18622 operator TemplateArgumentListInfo*() 18623 #ifdef __has_cpp_attribute 18624 #if __has_cpp_attribute(clang::lifetimebound) 18625 [[clang::lifetimebound]] 18626 #endif 18627 #endif 18628 { 18629 return HasArgs ? &TemplateArgStorage : nullptr; 18630 } 18631 }; 18632 } 18633 18634 /// Walk the set of potential results of an expression and mark them all as 18635 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18636 /// 18637 /// \return A new expression if we found any potential results, ExprEmpty() if 18638 /// not, and ExprError() if we diagnosed an error. 18639 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18640 NonOdrUseReason NOUR) { 18641 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18642 // an object that satisfies the requirements for appearing in a 18643 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18644 // is immediately applied." This function handles the lvalue-to-rvalue 18645 // conversion part. 18646 // 18647 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18648 // transform it into the relevant kind of non-odr-use node and rebuild the 18649 // tree of nodes leading to it. 18650 // 18651 // This is a mini-TreeTransform that only transforms a restricted subset of 18652 // nodes (and only certain operands of them). 18653 18654 // Rebuild a subexpression. 18655 auto Rebuild = [&](Expr *Sub) { 18656 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18657 }; 18658 18659 // Check whether a potential result satisfies the requirements of NOUR. 18660 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18661 // Any entity other than a VarDecl is always odr-used whenever it's named 18662 // in a potentially-evaluated expression. 18663 auto *VD = dyn_cast<VarDecl>(D); 18664 if (!VD) 18665 return true; 18666 18667 // C++2a [basic.def.odr]p4: 18668 // A variable x whose name appears as a potentially-evalauted expression 18669 // e is odr-used by e unless 18670 // -- x is a reference that is usable in constant expressions, or 18671 // -- x is a variable of non-reference type that is usable in constant 18672 // expressions and has no mutable subobjects, and e is an element of 18673 // the set of potential results of an expression of 18674 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18675 // conversion is applied, or 18676 // -- x is a variable of non-reference type, and e is an element of the 18677 // set of potential results of a discarded-value expression to which 18678 // the lvalue-to-rvalue conversion is not applied 18679 // 18680 // We check the first bullet and the "potentially-evaluated" condition in 18681 // BuildDeclRefExpr. We check the type requirements in the second bullet 18682 // in CheckLValueToRValueConversionOperand below. 18683 switch (NOUR) { 18684 case NOUR_None: 18685 case NOUR_Unevaluated: 18686 llvm_unreachable("unexpected non-odr-use-reason"); 18687 18688 case NOUR_Constant: 18689 // Constant references were handled when they were built. 18690 if (VD->getType()->isReferenceType()) 18691 return true; 18692 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18693 if (RD->hasMutableFields()) 18694 return true; 18695 if (!VD->isUsableInConstantExpressions(S.Context)) 18696 return true; 18697 break; 18698 18699 case NOUR_Discarded: 18700 if (VD->getType()->isReferenceType()) 18701 return true; 18702 break; 18703 } 18704 return false; 18705 }; 18706 18707 // Mark that this expression does not constitute an odr-use. 18708 auto MarkNotOdrUsed = [&] { 18709 S.MaybeODRUseExprs.remove(E); 18710 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18711 LSI->markVariableExprAsNonODRUsed(E); 18712 }; 18713 18714 // C++2a [basic.def.odr]p2: 18715 // The set of potential results of an expression e is defined as follows: 18716 switch (E->getStmtClass()) { 18717 // -- If e is an id-expression, ... 18718 case Expr::DeclRefExprClass: { 18719 auto *DRE = cast<DeclRefExpr>(E); 18720 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18721 break; 18722 18723 // Rebuild as a non-odr-use DeclRefExpr. 18724 MarkNotOdrUsed(); 18725 return DeclRefExpr::Create( 18726 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18727 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18728 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18729 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18730 } 18731 18732 case Expr::FunctionParmPackExprClass: { 18733 auto *FPPE = cast<FunctionParmPackExpr>(E); 18734 // If any of the declarations in the pack is odr-used, then the expression 18735 // as a whole constitutes an odr-use. 18736 for (VarDecl *D : *FPPE) 18737 if (IsPotentialResultOdrUsed(D)) 18738 return ExprEmpty(); 18739 18740 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18741 // nothing cares about whether we marked this as an odr-use, but it might 18742 // be useful for non-compiler tools. 18743 MarkNotOdrUsed(); 18744 break; 18745 } 18746 18747 // -- If e is a subscripting operation with an array operand... 18748 case Expr::ArraySubscriptExprClass: { 18749 auto *ASE = cast<ArraySubscriptExpr>(E); 18750 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18751 if (!OldBase->getType()->isArrayType()) 18752 break; 18753 ExprResult Base = Rebuild(OldBase); 18754 if (!Base.isUsable()) 18755 return Base; 18756 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18757 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18758 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18759 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18760 ASE->getRBracketLoc()); 18761 } 18762 18763 case Expr::MemberExprClass: { 18764 auto *ME = cast<MemberExpr>(E); 18765 // -- If e is a class member access expression [...] naming a non-static 18766 // data member... 18767 if (isa<FieldDecl>(ME->getMemberDecl())) { 18768 ExprResult Base = Rebuild(ME->getBase()); 18769 if (!Base.isUsable()) 18770 return Base; 18771 return MemberExpr::Create( 18772 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18773 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18774 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18775 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18776 ME->getObjectKind(), ME->isNonOdrUse()); 18777 } 18778 18779 if (ME->getMemberDecl()->isCXXInstanceMember()) 18780 break; 18781 18782 // -- If e is a class member access expression naming a static data member, 18783 // ... 18784 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18785 break; 18786 18787 // Rebuild as a non-odr-use MemberExpr. 18788 MarkNotOdrUsed(); 18789 return MemberExpr::Create( 18790 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18791 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18792 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18793 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18794 } 18795 18796 case Expr::BinaryOperatorClass: { 18797 auto *BO = cast<BinaryOperator>(E); 18798 Expr *LHS = BO->getLHS(); 18799 Expr *RHS = BO->getRHS(); 18800 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18801 if (BO->getOpcode() == BO_PtrMemD) { 18802 ExprResult Sub = Rebuild(LHS); 18803 if (!Sub.isUsable()) 18804 return Sub; 18805 LHS = Sub.get(); 18806 // -- If e is a comma expression, ... 18807 } else if (BO->getOpcode() == BO_Comma) { 18808 ExprResult Sub = Rebuild(RHS); 18809 if (!Sub.isUsable()) 18810 return Sub; 18811 RHS = Sub.get(); 18812 } else { 18813 break; 18814 } 18815 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18816 LHS, RHS); 18817 } 18818 18819 // -- If e has the form (e1)... 18820 case Expr::ParenExprClass: { 18821 auto *PE = cast<ParenExpr>(E); 18822 ExprResult Sub = Rebuild(PE->getSubExpr()); 18823 if (!Sub.isUsable()) 18824 return Sub; 18825 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18826 } 18827 18828 // -- If e is a glvalue conditional expression, ... 18829 // We don't apply this to a binary conditional operator. FIXME: Should we? 18830 case Expr::ConditionalOperatorClass: { 18831 auto *CO = cast<ConditionalOperator>(E); 18832 ExprResult LHS = Rebuild(CO->getLHS()); 18833 if (LHS.isInvalid()) 18834 return ExprError(); 18835 ExprResult RHS = Rebuild(CO->getRHS()); 18836 if (RHS.isInvalid()) 18837 return ExprError(); 18838 if (!LHS.isUsable() && !RHS.isUsable()) 18839 return ExprEmpty(); 18840 if (!LHS.isUsable()) 18841 LHS = CO->getLHS(); 18842 if (!RHS.isUsable()) 18843 RHS = CO->getRHS(); 18844 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18845 CO->getCond(), LHS.get(), RHS.get()); 18846 } 18847 18848 // [Clang extension] 18849 // -- If e has the form __extension__ e1... 18850 case Expr::UnaryOperatorClass: { 18851 auto *UO = cast<UnaryOperator>(E); 18852 if (UO->getOpcode() != UO_Extension) 18853 break; 18854 ExprResult Sub = Rebuild(UO->getSubExpr()); 18855 if (!Sub.isUsable()) 18856 return Sub; 18857 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18858 Sub.get()); 18859 } 18860 18861 // [Clang extension] 18862 // -- If e has the form _Generic(...), the set of potential results is the 18863 // union of the sets of potential results of the associated expressions. 18864 case Expr::GenericSelectionExprClass: { 18865 auto *GSE = cast<GenericSelectionExpr>(E); 18866 18867 SmallVector<Expr *, 4> AssocExprs; 18868 bool AnyChanged = false; 18869 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18870 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18871 if (AssocExpr.isInvalid()) 18872 return ExprError(); 18873 if (AssocExpr.isUsable()) { 18874 AssocExprs.push_back(AssocExpr.get()); 18875 AnyChanged = true; 18876 } else { 18877 AssocExprs.push_back(OrigAssocExpr); 18878 } 18879 } 18880 18881 return AnyChanged ? S.CreateGenericSelectionExpr( 18882 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18883 GSE->getRParenLoc(), GSE->getControllingExpr(), 18884 GSE->getAssocTypeSourceInfos(), AssocExprs) 18885 : ExprEmpty(); 18886 } 18887 18888 // [Clang extension] 18889 // -- If e has the form __builtin_choose_expr(...), the set of potential 18890 // results is the union of the sets of potential results of the 18891 // second and third subexpressions. 18892 case Expr::ChooseExprClass: { 18893 auto *CE = cast<ChooseExpr>(E); 18894 18895 ExprResult LHS = Rebuild(CE->getLHS()); 18896 if (LHS.isInvalid()) 18897 return ExprError(); 18898 18899 ExprResult RHS = Rebuild(CE->getLHS()); 18900 if (RHS.isInvalid()) 18901 return ExprError(); 18902 18903 if (!LHS.get() && !RHS.get()) 18904 return ExprEmpty(); 18905 if (!LHS.isUsable()) 18906 LHS = CE->getLHS(); 18907 if (!RHS.isUsable()) 18908 RHS = CE->getRHS(); 18909 18910 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18911 RHS.get(), CE->getRParenLoc()); 18912 } 18913 18914 // Step through non-syntactic nodes. 18915 case Expr::ConstantExprClass: { 18916 auto *CE = cast<ConstantExpr>(E); 18917 ExprResult Sub = Rebuild(CE->getSubExpr()); 18918 if (!Sub.isUsable()) 18919 return Sub; 18920 return ConstantExpr::Create(S.Context, Sub.get()); 18921 } 18922 18923 // We could mostly rely on the recursive rebuilding to rebuild implicit 18924 // casts, but not at the top level, so rebuild them here. 18925 case Expr::ImplicitCastExprClass: { 18926 auto *ICE = cast<ImplicitCastExpr>(E); 18927 // Only step through the narrow set of cast kinds we expect to encounter. 18928 // Anything else suggests we've left the region in which potential results 18929 // can be found. 18930 switch (ICE->getCastKind()) { 18931 case CK_NoOp: 18932 case CK_DerivedToBase: 18933 case CK_UncheckedDerivedToBase: { 18934 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18935 if (!Sub.isUsable()) 18936 return Sub; 18937 CXXCastPath Path(ICE->path()); 18938 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18939 ICE->getValueKind(), &Path); 18940 } 18941 18942 default: 18943 break; 18944 } 18945 break; 18946 } 18947 18948 default: 18949 break; 18950 } 18951 18952 // Can't traverse through this node. Nothing to do. 18953 return ExprEmpty(); 18954 } 18955 18956 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18957 // Check whether the operand is or contains an object of non-trivial C union 18958 // type. 18959 if (E->getType().isVolatileQualified() && 18960 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18961 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18962 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18963 Sema::NTCUC_LValueToRValueVolatile, 18964 NTCUK_Destruct|NTCUK_Copy); 18965 18966 // C++2a [basic.def.odr]p4: 18967 // [...] an expression of non-volatile-qualified non-class type to which 18968 // the lvalue-to-rvalue conversion is applied [...] 18969 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18970 return E; 18971 18972 ExprResult Result = 18973 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18974 if (Result.isInvalid()) 18975 return ExprError(); 18976 return Result.get() ? Result : E; 18977 } 18978 18979 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18980 Res = CorrectDelayedTyposInExpr(Res); 18981 18982 if (!Res.isUsable()) 18983 return Res; 18984 18985 // If a constant-expression is a reference to a variable where we delay 18986 // deciding whether it is an odr-use, just assume we will apply the 18987 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18988 // (a non-type template argument), we have special handling anyway. 18989 return CheckLValueToRValueConversionOperand(Res.get()); 18990 } 18991 18992 void Sema::CleanupVarDeclMarking() { 18993 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18994 // call. 18995 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18996 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18997 18998 for (Expr *E : LocalMaybeODRUseExprs) { 18999 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 19000 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 19001 DRE->getLocation(), *this); 19002 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 19003 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 19004 *this); 19005 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 19006 for (VarDecl *VD : *FP) 19007 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 19008 } else { 19009 llvm_unreachable("Unexpected expression"); 19010 } 19011 } 19012 19013 assert(MaybeODRUseExprs.empty() && 19014 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 19015 } 19016 19017 static void DoMarkVarDeclReferenced( 19018 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 19019 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19020 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 19021 isa<FunctionParmPackExpr>(E)) && 19022 "Invalid Expr argument to DoMarkVarDeclReferenced"); 19023 Var->setReferenced(); 19024 19025 if (Var->isInvalidDecl()) 19026 return; 19027 19028 auto *MSI = Var->getMemberSpecializationInfo(); 19029 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 19030 : Var->getTemplateSpecializationKind(); 19031 19032 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 19033 bool UsableInConstantExpr = 19034 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 19035 19036 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 19037 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 19038 } 19039 19040 // C++20 [expr.const]p12: 19041 // A variable [...] is needed for constant evaluation if it is [...] a 19042 // variable whose name appears as a potentially constant evaluated 19043 // expression that is either a contexpr variable or is of non-volatile 19044 // const-qualified integral type or of reference type 19045 bool NeededForConstantEvaluation = 19046 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 19047 19048 bool NeedDefinition = 19049 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 19050 19051 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 19052 "Can't instantiate a partial template specialization."); 19053 19054 // If this might be a member specialization of a static data member, check 19055 // the specialization is visible. We already did the checks for variable 19056 // template specializations when we created them. 19057 if (NeedDefinition && TSK != TSK_Undeclared && 19058 !isa<VarTemplateSpecializationDecl>(Var)) 19059 SemaRef.checkSpecializationVisibility(Loc, Var); 19060 19061 // Perform implicit instantiation of static data members, static data member 19062 // templates of class templates, and variable template specializations. Delay 19063 // instantiations of variable templates, except for those that could be used 19064 // in a constant expression. 19065 if (NeedDefinition && isTemplateInstantiation(TSK)) { 19066 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 19067 // instantiation declaration if a variable is usable in a constant 19068 // expression (among other cases). 19069 bool TryInstantiating = 19070 TSK == TSK_ImplicitInstantiation || 19071 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 19072 19073 if (TryInstantiating) { 19074 SourceLocation PointOfInstantiation = 19075 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 19076 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 19077 if (FirstInstantiation) { 19078 PointOfInstantiation = Loc; 19079 if (MSI) 19080 MSI->setPointOfInstantiation(PointOfInstantiation); 19081 // FIXME: Notify listener. 19082 else 19083 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 19084 } 19085 19086 if (UsableInConstantExpr) { 19087 // Do not defer instantiations of variables that could be used in a 19088 // constant expression. 19089 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 19090 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 19091 }); 19092 19093 // Re-set the member to trigger a recomputation of the dependence bits 19094 // for the expression. 19095 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19096 DRE->setDecl(DRE->getDecl()); 19097 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 19098 ME->setMemberDecl(ME->getMemberDecl()); 19099 } else if (FirstInstantiation || 19100 isa<VarTemplateSpecializationDecl>(Var)) { 19101 // FIXME: For a specialization of a variable template, we don't 19102 // distinguish between "declaration and type implicitly instantiated" 19103 // and "implicit instantiation of definition requested", so we have 19104 // no direct way to avoid enqueueing the pending instantiation 19105 // multiple times. 19106 SemaRef.PendingInstantiations 19107 .push_back(std::make_pair(Var, PointOfInstantiation)); 19108 } 19109 } 19110 } 19111 19112 // C++2a [basic.def.odr]p4: 19113 // A variable x whose name appears as a potentially-evaluated expression e 19114 // is odr-used by e unless 19115 // -- x is a reference that is usable in constant expressions 19116 // -- x is a variable of non-reference type that is usable in constant 19117 // expressions and has no mutable subobjects [FIXME], and e is an 19118 // element of the set of potential results of an expression of 19119 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 19120 // conversion is applied 19121 // -- x is a variable of non-reference type, and e is an element of the set 19122 // of potential results of a discarded-value expression to which the 19123 // lvalue-to-rvalue conversion is not applied [FIXME] 19124 // 19125 // We check the first part of the second bullet here, and 19126 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 19127 // FIXME: To get the third bullet right, we need to delay this even for 19128 // variables that are not usable in constant expressions. 19129 19130 // If we already know this isn't an odr-use, there's nothing more to do. 19131 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19132 if (DRE->isNonOdrUse()) 19133 return; 19134 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 19135 if (ME->isNonOdrUse()) 19136 return; 19137 19138 switch (OdrUse) { 19139 case OdrUseContext::None: 19140 assert((!E || isa<FunctionParmPackExpr>(E)) && 19141 "missing non-odr-use marking for unevaluated decl ref"); 19142 break; 19143 19144 case OdrUseContext::FormallyOdrUsed: 19145 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 19146 // behavior. 19147 break; 19148 19149 case OdrUseContext::Used: 19150 // If we might later find that this expression isn't actually an odr-use, 19151 // delay the marking. 19152 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 19153 SemaRef.MaybeODRUseExprs.insert(E); 19154 else 19155 MarkVarDeclODRUsed(Var, Loc, SemaRef); 19156 break; 19157 19158 case OdrUseContext::Dependent: 19159 // If this is a dependent context, we don't need to mark variables as 19160 // odr-used, but we may still need to track them for lambda capture. 19161 // FIXME: Do we also need to do this inside dependent typeid expressions 19162 // (which are modeled as unevaluated at this point)? 19163 const bool RefersToEnclosingScope = 19164 (SemaRef.CurContext != Var->getDeclContext() && 19165 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 19166 if (RefersToEnclosingScope) { 19167 LambdaScopeInfo *const LSI = 19168 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 19169 if (LSI && (!LSI->CallOperator || 19170 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 19171 // If a variable could potentially be odr-used, defer marking it so 19172 // until we finish analyzing the full expression for any 19173 // lvalue-to-rvalue 19174 // or discarded value conversions that would obviate odr-use. 19175 // Add it to the list of potential captures that will be analyzed 19176 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 19177 // unless the variable is a reference that was initialized by a constant 19178 // expression (this will never need to be captured or odr-used). 19179 // 19180 // FIXME: We can simplify this a lot after implementing P0588R1. 19181 assert(E && "Capture variable should be used in an expression."); 19182 if (!Var->getType()->isReferenceType() || 19183 !Var->isUsableInConstantExpressions(SemaRef.Context)) 19184 LSI->addPotentialCapture(E->IgnoreParens()); 19185 } 19186 } 19187 break; 19188 } 19189 } 19190 19191 /// Mark a variable referenced, and check whether it is odr-used 19192 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 19193 /// used directly for normal expressions referring to VarDecl. 19194 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 19195 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 19196 } 19197 19198 static void 19199 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 19200 bool MightBeOdrUse, 19201 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19202 if (SemaRef.isInOpenMPDeclareTargetContext()) 19203 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 19204 19205 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 19206 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 19207 return; 19208 } 19209 19210 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 19211 19212 // If this is a call to a method via a cast, also mark the method in the 19213 // derived class used in case codegen can devirtualize the call. 19214 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 19215 if (!ME) 19216 return; 19217 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 19218 if (!MD) 19219 return; 19220 // Only attempt to devirtualize if this is truly a virtual call. 19221 bool IsVirtualCall = MD->isVirtual() && 19222 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 19223 if (!IsVirtualCall) 19224 return; 19225 19226 // If it's possible to devirtualize the call, mark the called function 19227 // referenced. 19228 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 19229 ME->getBase(), SemaRef.getLangOpts().AppleKext); 19230 if (DM) 19231 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 19232 } 19233 19234 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 19235 /// 19236 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 19237 /// handled with care if the DeclRefExpr is not newly-created. 19238 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 19239 // TODO: update this with DR# once a defect report is filed. 19240 // C++11 defect. The address of a pure member should not be an ODR use, even 19241 // if it's a qualified reference. 19242 bool OdrUse = true; 19243 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 19244 if (Method->isVirtual() && 19245 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 19246 OdrUse = false; 19247 19248 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 19249 if (!isUnevaluatedContext() && !isConstantEvaluated() && 19250 FD->isConsteval() && !RebuildingImmediateInvocation) 19251 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 19252 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 19253 RefsMinusAssignments); 19254 } 19255 19256 /// Perform reference-marking and odr-use handling for a MemberExpr. 19257 void Sema::MarkMemberReferenced(MemberExpr *E) { 19258 // C++11 [basic.def.odr]p2: 19259 // A non-overloaded function whose name appears as a potentially-evaluated 19260 // expression or a member of a set of candidate functions, if selected by 19261 // overload resolution when referred to from a potentially-evaluated 19262 // expression, is odr-used, unless it is a pure virtual function and its 19263 // name is not explicitly qualified. 19264 bool MightBeOdrUse = true; 19265 if (E->performsVirtualDispatch(getLangOpts())) { 19266 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 19267 if (Method->isPure()) 19268 MightBeOdrUse = false; 19269 } 19270 SourceLocation Loc = 19271 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 19272 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 19273 RefsMinusAssignments); 19274 } 19275 19276 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 19277 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 19278 for (VarDecl *VD : *E) 19279 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 19280 RefsMinusAssignments); 19281 } 19282 19283 /// Perform marking for a reference to an arbitrary declaration. It 19284 /// marks the declaration referenced, and performs odr-use checking for 19285 /// functions and variables. This method should not be used when building a 19286 /// normal expression which refers to a variable. 19287 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 19288 bool MightBeOdrUse) { 19289 if (MightBeOdrUse) { 19290 if (auto *VD = dyn_cast<VarDecl>(D)) { 19291 MarkVariableReferenced(Loc, VD); 19292 return; 19293 } 19294 } 19295 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 19296 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 19297 return; 19298 } 19299 D->setReferenced(); 19300 } 19301 19302 namespace { 19303 // Mark all of the declarations used by a type as referenced. 19304 // FIXME: Not fully implemented yet! We need to have a better understanding 19305 // of when we're entering a context we should not recurse into. 19306 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 19307 // TreeTransforms rebuilding the type in a new context. Rather than 19308 // duplicating the TreeTransform logic, we should consider reusing it here. 19309 // Currently that causes problems when rebuilding LambdaExprs. 19310 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 19311 Sema &S; 19312 SourceLocation Loc; 19313 19314 public: 19315 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 19316 19317 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 19318 19319 bool TraverseTemplateArgument(const TemplateArgument &Arg); 19320 }; 19321 } 19322 19323 bool MarkReferencedDecls::TraverseTemplateArgument( 19324 const TemplateArgument &Arg) { 19325 { 19326 // A non-type template argument is a constant-evaluated context. 19327 EnterExpressionEvaluationContext Evaluated( 19328 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 19329 if (Arg.getKind() == TemplateArgument::Declaration) { 19330 if (Decl *D = Arg.getAsDecl()) 19331 S.MarkAnyDeclReferenced(Loc, D, true); 19332 } else if (Arg.getKind() == TemplateArgument::Expression) { 19333 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 19334 } 19335 } 19336 19337 return Inherited::TraverseTemplateArgument(Arg); 19338 } 19339 19340 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 19341 MarkReferencedDecls Marker(*this, Loc); 19342 Marker.TraverseType(T); 19343 } 19344 19345 namespace { 19346 /// Helper class that marks all of the declarations referenced by 19347 /// potentially-evaluated subexpressions as "referenced". 19348 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 19349 public: 19350 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 19351 bool SkipLocalVariables; 19352 ArrayRef<const Expr *> StopAt; 19353 19354 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 19355 ArrayRef<const Expr *> StopAt) 19356 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 19357 19358 void visitUsedDecl(SourceLocation Loc, Decl *D) { 19359 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 19360 } 19361 19362 void Visit(Expr *E) { 19363 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end()) 19364 return; 19365 Inherited::Visit(E); 19366 } 19367 19368 void VisitDeclRefExpr(DeclRefExpr *E) { 19369 // If we were asked not to visit local variables, don't. 19370 if (SkipLocalVariables) { 19371 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 19372 if (VD->hasLocalStorage()) 19373 return; 19374 } 19375 19376 // FIXME: This can trigger the instantiation of the initializer of a 19377 // variable, which can cause the expression to become value-dependent 19378 // or error-dependent. Do we need to propagate the new dependence bits? 19379 S.MarkDeclRefReferenced(E); 19380 } 19381 19382 void VisitMemberExpr(MemberExpr *E) { 19383 S.MarkMemberReferenced(E); 19384 Visit(E->getBase()); 19385 } 19386 }; 19387 } // namespace 19388 19389 /// Mark any declarations that appear within this expression or any 19390 /// potentially-evaluated subexpressions as "referenced". 19391 /// 19392 /// \param SkipLocalVariables If true, don't mark local variables as 19393 /// 'referenced'. 19394 /// \param StopAt Subexpressions that we shouldn't recurse into. 19395 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 19396 bool SkipLocalVariables, 19397 ArrayRef<const Expr*> StopAt) { 19398 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 19399 } 19400 19401 /// Emit a diagnostic when statements are reachable. 19402 /// FIXME: check for reachability even in expressions for which we don't build a 19403 /// CFG (eg, in the initializer of a global or in a constant expression). 19404 /// For example, 19405 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 19406 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 19407 const PartialDiagnostic &PD) { 19408 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 19409 if (!FunctionScopes.empty()) 19410 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 19411 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 19412 return true; 19413 } 19414 19415 // The initializer of a constexpr variable or of the first declaration of a 19416 // static data member is not syntactically a constant evaluated constant, 19417 // but nonetheless is always required to be a constant expression, so we 19418 // can skip diagnosing. 19419 // FIXME: Using the mangling context here is a hack. 19420 if (auto *VD = dyn_cast_or_null<VarDecl>( 19421 ExprEvalContexts.back().ManglingContextDecl)) { 19422 if (VD->isConstexpr() || 19423 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 19424 return false; 19425 // FIXME: For any other kind of variable, we should build a CFG for its 19426 // initializer and check whether the context in question is reachable. 19427 } 19428 19429 Diag(Loc, PD); 19430 return true; 19431 } 19432 19433 /// Emit a diagnostic that describes an effect on the run-time behavior 19434 /// of the program being compiled. 19435 /// 19436 /// This routine emits the given diagnostic when the code currently being 19437 /// type-checked is "potentially evaluated", meaning that there is a 19438 /// possibility that the code will actually be executable. Code in sizeof() 19439 /// expressions, code used only during overload resolution, etc., are not 19440 /// potentially evaluated. This routine will suppress such diagnostics or, 19441 /// in the absolutely nutty case of potentially potentially evaluated 19442 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 19443 /// later. 19444 /// 19445 /// This routine should be used for all diagnostics that describe the run-time 19446 /// behavior of a program, such as passing a non-POD value through an ellipsis. 19447 /// Failure to do so will likely result in spurious diagnostics or failures 19448 /// during overload resolution or within sizeof/alignof/typeof/typeid. 19449 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 19450 const PartialDiagnostic &PD) { 19451 19452 if (ExprEvalContexts.back().isDiscardedStatementContext()) 19453 return false; 19454 19455 switch (ExprEvalContexts.back().Context) { 19456 case ExpressionEvaluationContext::Unevaluated: 19457 case ExpressionEvaluationContext::UnevaluatedList: 19458 case ExpressionEvaluationContext::UnevaluatedAbstract: 19459 case ExpressionEvaluationContext::DiscardedStatement: 19460 // The argument will never be evaluated, so don't complain. 19461 break; 19462 19463 case ExpressionEvaluationContext::ConstantEvaluated: 19464 case ExpressionEvaluationContext::ImmediateFunctionContext: 19465 // Relevant diagnostics should be produced by constant evaluation. 19466 break; 19467 19468 case ExpressionEvaluationContext::PotentiallyEvaluated: 19469 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 19470 return DiagIfReachable(Loc, Stmts, PD); 19471 } 19472 19473 return false; 19474 } 19475 19476 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 19477 const PartialDiagnostic &PD) { 19478 return DiagRuntimeBehavior( 19479 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 19480 } 19481 19482 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 19483 CallExpr *CE, FunctionDecl *FD) { 19484 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 19485 return false; 19486 19487 // If we're inside a decltype's expression, don't check for a valid return 19488 // type or construct temporaries until we know whether this is the last call. 19489 if (ExprEvalContexts.back().ExprContext == 19490 ExpressionEvaluationContextRecord::EK_Decltype) { 19491 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 19492 return false; 19493 } 19494 19495 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19496 FunctionDecl *FD; 19497 CallExpr *CE; 19498 19499 public: 19500 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19501 : FD(FD), CE(CE) { } 19502 19503 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19504 if (!FD) { 19505 S.Diag(Loc, diag::err_call_incomplete_return) 19506 << T << CE->getSourceRange(); 19507 return; 19508 } 19509 19510 S.Diag(Loc, diag::err_call_function_incomplete_return) 19511 << CE->getSourceRange() << FD << T; 19512 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19513 << FD->getDeclName(); 19514 } 19515 } Diagnoser(FD, CE); 19516 19517 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19518 return true; 19519 19520 return false; 19521 } 19522 19523 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19524 // will prevent this condition from triggering, which is what we want. 19525 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19526 SourceLocation Loc; 19527 19528 unsigned diagnostic = diag::warn_condition_is_assignment; 19529 bool IsOrAssign = false; 19530 19531 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19532 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19533 return; 19534 19535 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19536 19537 // Greylist some idioms by putting them into a warning subcategory. 19538 if (ObjCMessageExpr *ME 19539 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19540 Selector Sel = ME->getSelector(); 19541 19542 // self = [<foo> init...] 19543 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19544 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19545 19546 // <foo> = [<bar> nextObject] 19547 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19548 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19549 } 19550 19551 Loc = Op->getOperatorLoc(); 19552 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19553 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19554 return; 19555 19556 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19557 Loc = Op->getOperatorLoc(); 19558 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19559 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19560 else { 19561 // Not an assignment. 19562 return; 19563 } 19564 19565 Diag(Loc, diagnostic) << E->getSourceRange(); 19566 19567 SourceLocation Open = E->getBeginLoc(); 19568 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19569 Diag(Loc, diag::note_condition_assign_silence) 19570 << FixItHint::CreateInsertion(Open, "(") 19571 << FixItHint::CreateInsertion(Close, ")"); 19572 19573 if (IsOrAssign) 19574 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19575 << FixItHint::CreateReplacement(Loc, "!="); 19576 else 19577 Diag(Loc, diag::note_condition_assign_to_comparison) 19578 << FixItHint::CreateReplacement(Loc, "=="); 19579 } 19580 19581 /// Redundant parentheses over an equality comparison can indicate 19582 /// that the user intended an assignment used as condition. 19583 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19584 // Don't warn if the parens came from a macro. 19585 SourceLocation parenLoc = ParenE->getBeginLoc(); 19586 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19587 return; 19588 // Don't warn for dependent expressions. 19589 if (ParenE->isTypeDependent()) 19590 return; 19591 19592 Expr *E = ParenE->IgnoreParens(); 19593 19594 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19595 if (opE->getOpcode() == BO_EQ && 19596 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19597 == Expr::MLV_Valid) { 19598 SourceLocation Loc = opE->getOperatorLoc(); 19599 19600 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19601 SourceRange ParenERange = ParenE->getSourceRange(); 19602 Diag(Loc, diag::note_equality_comparison_silence) 19603 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19604 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19605 Diag(Loc, diag::note_equality_comparison_to_assign) 19606 << FixItHint::CreateReplacement(Loc, "="); 19607 } 19608 } 19609 19610 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19611 bool IsConstexpr) { 19612 DiagnoseAssignmentAsCondition(E); 19613 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19614 DiagnoseEqualityWithExtraParens(parenE); 19615 19616 ExprResult result = CheckPlaceholderExpr(E); 19617 if (result.isInvalid()) return ExprError(); 19618 E = result.get(); 19619 19620 if (!E->isTypeDependent()) { 19621 if (getLangOpts().CPlusPlus) 19622 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19623 19624 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19625 if (ERes.isInvalid()) 19626 return ExprError(); 19627 E = ERes.get(); 19628 19629 QualType T = E->getType(); 19630 if (!T->isScalarType()) { // C99 6.8.4.1p1 19631 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19632 << T << E->getSourceRange(); 19633 return ExprError(); 19634 } 19635 CheckBoolLikeConversion(E, Loc); 19636 } 19637 19638 return E; 19639 } 19640 19641 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19642 Expr *SubExpr, ConditionKind CK, 19643 bool MissingOK) { 19644 // MissingOK indicates whether having no condition expression is valid 19645 // (for loop) or invalid (e.g. while loop). 19646 if (!SubExpr) 19647 return MissingOK ? ConditionResult() : ConditionError(); 19648 19649 ExprResult Cond; 19650 switch (CK) { 19651 case ConditionKind::Boolean: 19652 Cond = CheckBooleanCondition(Loc, SubExpr); 19653 break; 19654 19655 case ConditionKind::ConstexprIf: 19656 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19657 break; 19658 19659 case ConditionKind::Switch: 19660 Cond = CheckSwitchCondition(Loc, SubExpr); 19661 break; 19662 } 19663 if (Cond.isInvalid()) { 19664 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19665 {SubExpr}, PreferredConditionType(CK)); 19666 if (!Cond.get()) 19667 return ConditionError(); 19668 } 19669 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19670 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19671 if (!FullExpr.get()) 19672 return ConditionError(); 19673 19674 return ConditionResult(*this, nullptr, FullExpr, 19675 CK == ConditionKind::ConstexprIf); 19676 } 19677 19678 namespace { 19679 /// A visitor for rebuilding a call to an __unknown_any expression 19680 /// to have an appropriate type. 19681 struct RebuildUnknownAnyFunction 19682 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19683 19684 Sema &S; 19685 19686 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19687 19688 ExprResult VisitStmt(Stmt *S) { 19689 llvm_unreachable("unexpected statement!"); 19690 } 19691 19692 ExprResult VisitExpr(Expr *E) { 19693 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19694 << E->getSourceRange(); 19695 return ExprError(); 19696 } 19697 19698 /// Rebuild an expression which simply semantically wraps another 19699 /// expression which it shares the type and value kind of. 19700 template <class T> ExprResult rebuildSugarExpr(T *E) { 19701 ExprResult SubResult = Visit(E->getSubExpr()); 19702 if (SubResult.isInvalid()) return ExprError(); 19703 19704 Expr *SubExpr = SubResult.get(); 19705 E->setSubExpr(SubExpr); 19706 E->setType(SubExpr->getType()); 19707 E->setValueKind(SubExpr->getValueKind()); 19708 assert(E->getObjectKind() == OK_Ordinary); 19709 return E; 19710 } 19711 19712 ExprResult VisitParenExpr(ParenExpr *E) { 19713 return rebuildSugarExpr(E); 19714 } 19715 19716 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19717 return rebuildSugarExpr(E); 19718 } 19719 19720 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19721 ExprResult SubResult = Visit(E->getSubExpr()); 19722 if (SubResult.isInvalid()) return ExprError(); 19723 19724 Expr *SubExpr = SubResult.get(); 19725 E->setSubExpr(SubExpr); 19726 E->setType(S.Context.getPointerType(SubExpr->getType())); 19727 assert(E->isPRValue()); 19728 assert(E->getObjectKind() == OK_Ordinary); 19729 return E; 19730 } 19731 19732 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19733 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19734 19735 E->setType(VD->getType()); 19736 19737 assert(E->isPRValue()); 19738 if (S.getLangOpts().CPlusPlus && 19739 !(isa<CXXMethodDecl>(VD) && 19740 cast<CXXMethodDecl>(VD)->isInstance())) 19741 E->setValueKind(VK_LValue); 19742 19743 return E; 19744 } 19745 19746 ExprResult VisitMemberExpr(MemberExpr *E) { 19747 return resolveDecl(E, E->getMemberDecl()); 19748 } 19749 19750 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19751 return resolveDecl(E, E->getDecl()); 19752 } 19753 }; 19754 } 19755 19756 /// Given a function expression of unknown-any type, try to rebuild it 19757 /// to have a function type. 19758 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19759 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19760 if (Result.isInvalid()) return ExprError(); 19761 return S.DefaultFunctionArrayConversion(Result.get()); 19762 } 19763 19764 namespace { 19765 /// A visitor for rebuilding an expression of type __unknown_anytype 19766 /// into one which resolves the type directly on the referring 19767 /// expression. Strict preservation of the original source 19768 /// structure is not a goal. 19769 struct RebuildUnknownAnyExpr 19770 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19771 19772 Sema &S; 19773 19774 /// The current destination type. 19775 QualType DestType; 19776 19777 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19778 : S(S), DestType(CastType) {} 19779 19780 ExprResult VisitStmt(Stmt *S) { 19781 llvm_unreachable("unexpected statement!"); 19782 } 19783 19784 ExprResult VisitExpr(Expr *E) { 19785 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19786 << E->getSourceRange(); 19787 return ExprError(); 19788 } 19789 19790 ExprResult VisitCallExpr(CallExpr *E); 19791 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19792 19793 /// Rebuild an expression which simply semantically wraps another 19794 /// expression which it shares the type and value kind of. 19795 template <class T> ExprResult rebuildSugarExpr(T *E) { 19796 ExprResult SubResult = Visit(E->getSubExpr()); 19797 if (SubResult.isInvalid()) return ExprError(); 19798 Expr *SubExpr = SubResult.get(); 19799 E->setSubExpr(SubExpr); 19800 E->setType(SubExpr->getType()); 19801 E->setValueKind(SubExpr->getValueKind()); 19802 assert(E->getObjectKind() == OK_Ordinary); 19803 return E; 19804 } 19805 19806 ExprResult VisitParenExpr(ParenExpr *E) { 19807 return rebuildSugarExpr(E); 19808 } 19809 19810 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19811 return rebuildSugarExpr(E); 19812 } 19813 19814 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19815 const PointerType *Ptr = DestType->getAs<PointerType>(); 19816 if (!Ptr) { 19817 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19818 << E->getSourceRange(); 19819 return ExprError(); 19820 } 19821 19822 if (isa<CallExpr>(E->getSubExpr())) { 19823 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19824 << E->getSourceRange(); 19825 return ExprError(); 19826 } 19827 19828 assert(E->isPRValue()); 19829 assert(E->getObjectKind() == OK_Ordinary); 19830 E->setType(DestType); 19831 19832 // Build the sub-expression as if it were an object of the pointee type. 19833 DestType = Ptr->getPointeeType(); 19834 ExprResult SubResult = Visit(E->getSubExpr()); 19835 if (SubResult.isInvalid()) return ExprError(); 19836 E->setSubExpr(SubResult.get()); 19837 return E; 19838 } 19839 19840 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19841 19842 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19843 19844 ExprResult VisitMemberExpr(MemberExpr *E) { 19845 return resolveDecl(E, E->getMemberDecl()); 19846 } 19847 19848 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19849 return resolveDecl(E, E->getDecl()); 19850 } 19851 }; 19852 } 19853 19854 /// Rebuilds a call expression which yielded __unknown_anytype. 19855 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19856 Expr *CalleeExpr = E->getCallee(); 19857 19858 enum FnKind { 19859 FK_MemberFunction, 19860 FK_FunctionPointer, 19861 FK_BlockPointer 19862 }; 19863 19864 FnKind Kind; 19865 QualType CalleeType = CalleeExpr->getType(); 19866 if (CalleeType == S.Context.BoundMemberTy) { 19867 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19868 Kind = FK_MemberFunction; 19869 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19870 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19871 CalleeType = Ptr->getPointeeType(); 19872 Kind = FK_FunctionPointer; 19873 } else { 19874 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19875 Kind = FK_BlockPointer; 19876 } 19877 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19878 19879 // Verify that this is a legal result type of a function. 19880 if (DestType->isArrayType() || DestType->isFunctionType()) { 19881 unsigned diagID = diag::err_func_returning_array_function; 19882 if (Kind == FK_BlockPointer) 19883 diagID = diag::err_block_returning_array_function; 19884 19885 S.Diag(E->getExprLoc(), diagID) 19886 << DestType->isFunctionType() << DestType; 19887 return ExprError(); 19888 } 19889 19890 // Otherwise, go ahead and set DestType as the call's result. 19891 E->setType(DestType.getNonLValueExprType(S.Context)); 19892 E->setValueKind(Expr::getValueKindForType(DestType)); 19893 assert(E->getObjectKind() == OK_Ordinary); 19894 19895 // Rebuild the function type, replacing the result type with DestType. 19896 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19897 if (Proto) { 19898 // __unknown_anytype(...) is a special case used by the debugger when 19899 // it has no idea what a function's signature is. 19900 // 19901 // We want to build this call essentially under the K&R 19902 // unprototyped rules, but making a FunctionNoProtoType in C++ 19903 // would foul up all sorts of assumptions. However, we cannot 19904 // simply pass all arguments as variadic arguments, nor can we 19905 // portably just call the function under a non-variadic type; see 19906 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19907 // However, it turns out that in practice it is generally safe to 19908 // call a function declared as "A foo(B,C,D);" under the prototype 19909 // "A foo(B,C,D,...);". The only known exception is with the 19910 // Windows ABI, where any variadic function is implicitly cdecl 19911 // regardless of its normal CC. Therefore we change the parameter 19912 // types to match the types of the arguments. 19913 // 19914 // This is a hack, but it is far superior to moving the 19915 // corresponding target-specific code from IR-gen to Sema/AST. 19916 19917 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19918 SmallVector<QualType, 8> ArgTypes; 19919 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19920 ArgTypes.reserve(E->getNumArgs()); 19921 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19922 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19923 } 19924 ParamTypes = ArgTypes; 19925 } 19926 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19927 Proto->getExtProtoInfo()); 19928 } else { 19929 DestType = S.Context.getFunctionNoProtoType(DestType, 19930 FnType->getExtInfo()); 19931 } 19932 19933 // Rebuild the appropriate pointer-to-function type. 19934 switch (Kind) { 19935 case FK_MemberFunction: 19936 // Nothing to do. 19937 break; 19938 19939 case FK_FunctionPointer: 19940 DestType = S.Context.getPointerType(DestType); 19941 break; 19942 19943 case FK_BlockPointer: 19944 DestType = S.Context.getBlockPointerType(DestType); 19945 break; 19946 } 19947 19948 // Finally, we can recurse. 19949 ExprResult CalleeResult = Visit(CalleeExpr); 19950 if (!CalleeResult.isUsable()) return ExprError(); 19951 E->setCallee(CalleeResult.get()); 19952 19953 // Bind a temporary if necessary. 19954 return S.MaybeBindToTemporary(E); 19955 } 19956 19957 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19958 // Verify that this is a legal result type of a call. 19959 if (DestType->isArrayType() || DestType->isFunctionType()) { 19960 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19961 << DestType->isFunctionType() << DestType; 19962 return ExprError(); 19963 } 19964 19965 // Rewrite the method result type if available. 19966 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19967 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19968 Method->setReturnType(DestType); 19969 } 19970 19971 // Change the type of the message. 19972 E->setType(DestType.getNonReferenceType()); 19973 E->setValueKind(Expr::getValueKindForType(DestType)); 19974 19975 return S.MaybeBindToTemporary(E); 19976 } 19977 19978 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19979 // The only case we should ever see here is a function-to-pointer decay. 19980 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19981 assert(E->isPRValue()); 19982 assert(E->getObjectKind() == OK_Ordinary); 19983 19984 E->setType(DestType); 19985 19986 // Rebuild the sub-expression as the pointee (function) type. 19987 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19988 19989 ExprResult Result = Visit(E->getSubExpr()); 19990 if (!Result.isUsable()) return ExprError(); 19991 19992 E->setSubExpr(Result.get()); 19993 return E; 19994 } else if (E->getCastKind() == CK_LValueToRValue) { 19995 assert(E->isPRValue()); 19996 assert(E->getObjectKind() == OK_Ordinary); 19997 19998 assert(isa<BlockPointerType>(E->getType())); 19999 20000 E->setType(DestType); 20001 20002 // The sub-expression has to be a lvalue reference, so rebuild it as such. 20003 DestType = S.Context.getLValueReferenceType(DestType); 20004 20005 ExprResult Result = Visit(E->getSubExpr()); 20006 if (!Result.isUsable()) return ExprError(); 20007 20008 E->setSubExpr(Result.get()); 20009 return E; 20010 } else { 20011 llvm_unreachable("Unhandled cast type!"); 20012 } 20013 } 20014 20015 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 20016 ExprValueKind ValueKind = VK_LValue; 20017 QualType Type = DestType; 20018 20019 // We know how to make this work for certain kinds of decls: 20020 20021 // - functions 20022 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 20023 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 20024 DestType = Ptr->getPointeeType(); 20025 ExprResult Result = resolveDecl(E, VD); 20026 if (Result.isInvalid()) return ExprError(); 20027 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 20028 VK_PRValue); 20029 } 20030 20031 if (!Type->isFunctionType()) { 20032 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 20033 << VD << E->getSourceRange(); 20034 return ExprError(); 20035 } 20036 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 20037 // We must match the FunctionDecl's type to the hack introduced in 20038 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 20039 // type. See the lengthy commentary in that routine. 20040 QualType FDT = FD->getType(); 20041 const FunctionType *FnType = FDT->castAs<FunctionType>(); 20042 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 20043 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 20044 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 20045 SourceLocation Loc = FD->getLocation(); 20046 FunctionDecl *NewFD = FunctionDecl::Create( 20047 S.Context, FD->getDeclContext(), Loc, Loc, 20048 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 20049 SC_None, S.getCurFPFeatures().isFPConstrained(), 20050 false /*isInlineSpecified*/, FD->hasPrototype(), 20051 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 20052 20053 if (FD->getQualifier()) 20054 NewFD->setQualifierInfo(FD->getQualifierLoc()); 20055 20056 SmallVector<ParmVarDecl*, 16> Params; 20057 for (const auto &AI : FT->param_types()) { 20058 ParmVarDecl *Param = 20059 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 20060 Param->setScopeInfo(0, Params.size()); 20061 Params.push_back(Param); 20062 } 20063 NewFD->setParams(Params); 20064 DRE->setDecl(NewFD); 20065 VD = DRE->getDecl(); 20066 } 20067 } 20068 20069 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 20070 if (MD->isInstance()) { 20071 ValueKind = VK_PRValue; 20072 Type = S.Context.BoundMemberTy; 20073 } 20074 20075 // Function references aren't l-values in C. 20076 if (!S.getLangOpts().CPlusPlus) 20077 ValueKind = VK_PRValue; 20078 20079 // - variables 20080 } else if (isa<VarDecl>(VD)) { 20081 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 20082 Type = RefTy->getPointeeType(); 20083 } else if (Type->isFunctionType()) { 20084 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 20085 << VD << E->getSourceRange(); 20086 return ExprError(); 20087 } 20088 20089 // - nothing else 20090 } else { 20091 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 20092 << VD << E->getSourceRange(); 20093 return ExprError(); 20094 } 20095 20096 // Modifying the declaration like this is friendly to IR-gen but 20097 // also really dangerous. 20098 VD->setType(DestType); 20099 E->setType(Type); 20100 E->setValueKind(ValueKind); 20101 return E; 20102 } 20103 20104 /// Check a cast of an unknown-any type. We intentionally only 20105 /// trigger this for C-style casts. 20106 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 20107 Expr *CastExpr, CastKind &CastKind, 20108 ExprValueKind &VK, CXXCastPath &Path) { 20109 // The type we're casting to must be either void or complete. 20110 if (!CastType->isVoidType() && 20111 RequireCompleteType(TypeRange.getBegin(), CastType, 20112 diag::err_typecheck_cast_to_incomplete)) 20113 return ExprError(); 20114 20115 // Rewrite the casted expression from scratch. 20116 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 20117 if (!result.isUsable()) return ExprError(); 20118 20119 CastExpr = result.get(); 20120 VK = CastExpr->getValueKind(); 20121 CastKind = CK_NoOp; 20122 20123 return CastExpr; 20124 } 20125 20126 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 20127 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 20128 } 20129 20130 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 20131 Expr *arg, QualType ¶mType) { 20132 // If the syntactic form of the argument is not an explicit cast of 20133 // any sort, just do default argument promotion. 20134 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 20135 if (!castArg) { 20136 ExprResult result = DefaultArgumentPromotion(arg); 20137 if (result.isInvalid()) return ExprError(); 20138 paramType = result.get()->getType(); 20139 return result; 20140 } 20141 20142 // Otherwise, use the type that was written in the explicit cast. 20143 assert(!arg->hasPlaceholderType()); 20144 paramType = castArg->getTypeAsWritten(); 20145 20146 // Copy-initialize a parameter of that type. 20147 InitializedEntity entity = 20148 InitializedEntity::InitializeParameter(Context, paramType, 20149 /*consumed*/ false); 20150 return PerformCopyInitialization(entity, callLoc, arg); 20151 } 20152 20153 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 20154 Expr *orig = E; 20155 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 20156 while (true) { 20157 E = E->IgnoreParenImpCasts(); 20158 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 20159 E = call->getCallee(); 20160 diagID = diag::err_uncasted_call_of_unknown_any; 20161 } else { 20162 break; 20163 } 20164 } 20165 20166 SourceLocation loc; 20167 NamedDecl *d; 20168 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 20169 loc = ref->getLocation(); 20170 d = ref->getDecl(); 20171 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 20172 loc = mem->getMemberLoc(); 20173 d = mem->getMemberDecl(); 20174 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 20175 diagID = diag::err_uncasted_call_of_unknown_any; 20176 loc = msg->getSelectorStartLoc(); 20177 d = msg->getMethodDecl(); 20178 if (!d) { 20179 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 20180 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 20181 << orig->getSourceRange(); 20182 return ExprError(); 20183 } 20184 } else { 20185 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 20186 << E->getSourceRange(); 20187 return ExprError(); 20188 } 20189 20190 S.Diag(loc, diagID) << d << orig->getSourceRange(); 20191 20192 // Never recoverable. 20193 return ExprError(); 20194 } 20195 20196 /// Check for operands with placeholder types and complain if found. 20197 /// Returns ExprError() if there was an error and no recovery was possible. 20198 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 20199 if (!Context.isDependenceAllowed()) { 20200 // C cannot handle TypoExpr nodes on either side of a binop because it 20201 // doesn't handle dependent types properly, so make sure any TypoExprs have 20202 // been dealt with before checking the operands. 20203 ExprResult Result = CorrectDelayedTyposInExpr(E); 20204 if (!Result.isUsable()) return ExprError(); 20205 E = Result.get(); 20206 } 20207 20208 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 20209 if (!placeholderType) return E; 20210 20211 switch (placeholderType->getKind()) { 20212 20213 // Overloaded expressions. 20214 case BuiltinType::Overload: { 20215 // Try to resolve a single function template specialization. 20216 // This is obligatory. 20217 ExprResult Result = E; 20218 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 20219 return Result; 20220 20221 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 20222 // leaves Result unchanged on failure. 20223 Result = E; 20224 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 20225 return Result; 20226 20227 // If that failed, try to recover with a call. 20228 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 20229 /*complain*/ true); 20230 return Result; 20231 } 20232 20233 // Bound member functions. 20234 case BuiltinType::BoundMember: { 20235 ExprResult result = E; 20236 const Expr *BME = E->IgnoreParens(); 20237 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 20238 // Try to give a nicer diagnostic if it is a bound member that we recognize. 20239 if (isa<CXXPseudoDestructorExpr>(BME)) { 20240 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 20241 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 20242 if (ME->getMemberNameInfo().getName().getNameKind() == 20243 DeclarationName::CXXDestructorName) 20244 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 20245 } 20246 tryToRecoverWithCall(result, PD, 20247 /*complain*/ true); 20248 return result; 20249 } 20250 20251 // ARC unbridged casts. 20252 case BuiltinType::ARCUnbridgedCast: { 20253 Expr *realCast = stripARCUnbridgedCast(E); 20254 diagnoseARCUnbridgedCast(realCast); 20255 return realCast; 20256 } 20257 20258 // Expressions of unknown type. 20259 case BuiltinType::UnknownAny: 20260 return diagnoseUnknownAnyExpr(*this, E); 20261 20262 // Pseudo-objects. 20263 case BuiltinType::PseudoObject: 20264 return checkPseudoObjectRValue(E); 20265 20266 case BuiltinType::BuiltinFn: { 20267 // Accept __noop without parens by implicitly converting it to a call expr. 20268 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 20269 if (DRE) { 20270 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 20271 if (FD->getBuiltinID() == Builtin::BI__noop) { 20272 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 20273 CK_BuiltinFnToFnPtr) 20274 .get(); 20275 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 20276 VK_PRValue, SourceLocation(), 20277 FPOptionsOverride()); 20278 } 20279 } 20280 20281 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 20282 return ExprError(); 20283 } 20284 20285 case BuiltinType::IncompleteMatrixIdx: 20286 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 20287 ->getRowIdx() 20288 ->getBeginLoc(), 20289 diag::err_matrix_incomplete_index); 20290 return ExprError(); 20291 20292 // Expressions of unknown type. 20293 case BuiltinType::OMPArraySection: 20294 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 20295 return ExprError(); 20296 20297 // Expressions of unknown type. 20298 case BuiltinType::OMPArrayShaping: 20299 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 20300 20301 case BuiltinType::OMPIterator: 20302 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 20303 20304 // Everything else should be impossible. 20305 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 20306 case BuiltinType::Id: 20307 #include "clang/Basic/OpenCLImageTypes.def" 20308 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 20309 case BuiltinType::Id: 20310 #include "clang/Basic/OpenCLExtensionTypes.def" 20311 #define SVE_TYPE(Name, Id, SingletonId) \ 20312 case BuiltinType::Id: 20313 #include "clang/Basic/AArch64SVEACLETypes.def" 20314 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 20315 case BuiltinType::Id: 20316 #include "clang/Basic/PPCTypes.def" 20317 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 20318 #include "clang/Basic/RISCVVTypes.def" 20319 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 20320 #define PLACEHOLDER_TYPE(Id, SingletonId) 20321 #include "clang/AST/BuiltinTypes.def" 20322 break; 20323 } 20324 20325 llvm_unreachable("invalid placeholder type!"); 20326 } 20327 20328 bool Sema::CheckCaseExpression(Expr *E) { 20329 if (E->isTypeDependent()) 20330 return true; 20331 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 20332 return E->getType()->isIntegralOrEnumerationType(); 20333 return false; 20334 } 20335 20336 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 20337 ExprResult 20338 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 20339 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 20340 "Unknown Objective-C Boolean value!"); 20341 QualType BoolT = Context.ObjCBuiltinBoolTy; 20342 if (!Context.getBOOLDecl()) { 20343 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 20344 Sema::LookupOrdinaryName); 20345 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 20346 NamedDecl *ND = Result.getFoundDecl(); 20347 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 20348 Context.setBOOLDecl(TD); 20349 } 20350 } 20351 if (Context.getBOOLDecl()) 20352 BoolT = Context.getBOOLType(); 20353 return new (Context) 20354 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 20355 } 20356 20357 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 20358 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 20359 SourceLocation RParen) { 20360 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 20361 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20362 return Spec.getPlatform() == Platform; 20363 }); 20364 // Transcribe the "ios" availability check to "maccatalyst" when compiling 20365 // for "maccatalyst" if "maccatalyst" is not specified. 20366 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 20367 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 20368 return Spec.getPlatform() == "ios"; 20369 }); 20370 } 20371 if (Spec == AvailSpecs.end()) 20372 return None; 20373 return Spec->getVersion(); 20374 }; 20375 20376 VersionTuple Version; 20377 if (auto MaybeVersion = 20378 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 20379 Version = *MaybeVersion; 20380 20381 // The use of `@available` in the enclosing context should be analyzed to 20382 // warn when it's used inappropriately (i.e. not if(@available)). 20383 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 20384 Context->HasPotentialAvailabilityViolations = true; 20385 20386 return new (Context) 20387 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 20388 } 20389 20390 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 20391 ArrayRef<Expr *> SubExprs, QualType T) { 20392 if (!Context.getLangOpts().RecoveryAST) 20393 return ExprError(); 20394 20395 if (isSFINAEContext()) 20396 return ExprError(); 20397 20398 if (T.isNull() || T->isUndeducedType() || 20399 !Context.getLangOpts().RecoveryASTType) 20400 // We don't know the concrete type, fallback to dependent type. 20401 T = Context.DependentTy; 20402 20403 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 20404 } 20405