1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/OperationKinds.h" 28 #include "clang/AST/ParentMapContext.h" 29 #include "clang/AST/RecursiveASTVisitor.h" 30 #include "clang/AST/TypeLoc.h" 31 #include "clang/Basic/Builtins.h" 32 #include "clang/Basic/DiagnosticSema.h" 33 #include "clang/Basic/PartialDiagnostic.h" 34 #include "clang/Basic/SourceManager.h" 35 #include "clang/Basic/TargetInfo.h" 36 #include "clang/Lex/LiteralSupport.h" 37 #include "clang/Lex/Preprocessor.h" 38 #include "clang/Sema/AnalysisBasedWarnings.h" 39 #include "clang/Sema/DeclSpec.h" 40 #include "clang/Sema/DelayedDiagnostic.h" 41 #include "clang/Sema/Designator.h" 42 #include "clang/Sema/Initialization.h" 43 #include "clang/Sema/Lookup.h" 44 #include "clang/Sema/Overload.h" 45 #include "clang/Sema/ParsedTemplate.h" 46 #include "clang/Sema/Scope.h" 47 #include "clang/Sema/ScopeInfo.h" 48 #include "clang/Sema/SemaFixItUtils.h" 49 #include "clang/Sema/SemaInternal.h" 50 #include "clang/Sema/Template.h" 51 #include "llvm/ADT/STLExtras.h" 52 #include "llvm/ADT/StringExtras.h" 53 #include "llvm/Support/ConvertUTF.h" 54 #include "llvm/Support/SaveAndRestore.h" 55 56 using namespace clang; 57 using namespace sema; 58 using llvm::RoundingMode; 59 60 /// Determine whether the use of this declaration is valid, without 61 /// emitting diagnostics. 62 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 63 // See if this is an auto-typed variable whose initializer we are parsing. 64 if (ParsingInitForAutoVars.count(D)) 65 return false; 66 67 // See if this is a deleted function. 68 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 69 if (FD->isDeleted()) 70 return false; 71 72 // If the function has a deduced return type, and we can't deduce it, 73 // then we can't use it either. 74 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 75 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 76 return false; 77 78 // See if this is an aligned allocation/deallocation function that is 79 // unavailable. 80 if (TreatUnavailableAsInvalid && 81 isUnavailableAlignedAllocationFunction(*FD)) 82 return false; 83 } 84 85 // See if this function is unavailable. 86 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 87 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 88 return false; 89 90 if (isa<UnresolvedUsingIfExistsDecl>(D)) 91 return false; 92 93 return true; 94 } 95 96 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 97 // Warn if this is used but marked unused. 98 if (const auto *A = D->getAttr<UnusedAttr>()) { 99 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 100 // should diagnose them. 101 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 102 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 103 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 104 if (DC && !DC->hasAttr<UnusedAttr>()) 105 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 106 } 107 } 108 } 109 110 /// Emit a note explaining that this function is deleted. 111 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 112 assert(Decl && Decl->isDeleted()); 113 114 if (Decl->isDefaulted()) { 115 // If the method was explicitly defaulted, point at that declaration. 116 if (!Decl->isImplicit()) 117 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 118 119 // Try to diagnose why this special member function was implicitly 120 // deleted. This might fail, if that reason no longer applies. 121 DiagnoseDeletedDefaultedFunction(Decl); 122 return; 123 } 124 125 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 126 if (Ctor && Ctor->isInheritingConstructor()) 127 return NoteDeletedInheritingConstructor(Ctor); 128 129 Diag(Decl->getLocation(), diag::note_availability_specified_here) 130 << Decl << 1; 131 } 132 133 /// Determine whether a FunctionDecl was ever declared with an 134 /// explicit storage class. 135 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 136 for (auto I : D->redecls()) { 137 if (I->getStorageClass() != SC_None) 138 return true; 139 } 140 return false; 141 } 142 143 /// Check whether we're in an extern inline function and referring to a 144 /// variable or function with internal linkage (C11 6.7.4p3). 145 /// 146 /// This is only a warning because we used to silently accept this code, but 147 /// in many cases it will not behave correctly. This is not enabled in C++ mode 148 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 149 /// and so while there may still be user mistakes, most of the time we can't 150 /// prove that there are errors. 151 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 152 const NamedDecl *D, 153 SourceLocation Loc) { 154 // This is disabled under C++; there are too many ways for this to fire in 155 // contexts where the warning is a false positive, or where it is technically 156 // correct but benign. 157 if (S.getLangOpts().CPlusPlus) 158 return; 159 160 // Check if this is an inlined function or method. 161 FunctionDecl *Current = S.getCurFunctionDecl(); 162 if (!Current) 163 return; 164 if (!Current->isInlined()) 165 return; 166 if (!Current->isExternallyVisible()) 167 return; 168 169 // Check if the decl has internal linkage. 170 if (D->getFormalLinkage() != InternalLinkage) 171 return; 172 173 // Downgrade from ExtWarn to Extension if 174 // (1) the supposedly external inline function is in the main file, 175 // and probably won't be included anywhere else. 176 // (2) the thing we're referencing is a pure function. 177 // (3) the thing we're referencing is another inline function. 178 // This last can give us false negatives, but it's better than warning on 179 // wrappers for simple C library functions. 180 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 181 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 182 if (!DowngradeWarning && UsedFn) 183 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 184 185 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 186 : diag::ext_internal_in_extern_inline) 187 << /*IsVar=*/!UsedFn << D; 188 189 S.MaybeSuggestAddingStaticToDecl(Current); 190 191 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 192 << D; 193 } 194 195 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 196 const FunctionDecl *First = Cur->getFirstDecl(); 197 198 // Suggest "static" on the function, if possible. 199 if (!hasAnyExplicitStorageClass(First)) { 200 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 201 Diag(DeclBegin, diag::note_convert_inline_to_static) 202 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 203 } 204 } 205 206 /// Determine whether the use of this declaration is valid, and 207 /// emit any corresponding diagnostics. 208 /// 209 /// This routine diagnoses various problems with referencing 210 /// declarations that can occur when using a declaration. For example, 211 /// it might warn if a deprecated or unavailable declaration is being 212 /// used, or produce an error (and return true) if a C++0x deleted 213 /// function is being used. 214 /// 215 /// \returns true if there was an error (this declaration cannot be 216 /// referenced), false otherwise. 217 /// 218 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 219 const ObjCInterfaceDecl *UnknownObjCClass, 220 bool ObjCPropertyAccess, 221 bool AvoidPartialAvailabilityChecks, 222 ObjCInterfaceDecl *ClassReceiver) { 223 SourceLocation Loc = Locs.front(); 224 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 225 // If there were any diagnostics suppressed by template argument deduction, 226 // emit them now. 227 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 228 if (Pos != SuppressedDiagnostics.end()) { 229 for (const PartialDiagnosticAt &Suppressed : Pos->second) 230 Diag(Suppressed.first, Suppressed.second); 231 232 // Clear out the list of suppressed diagnostics, so that we don't emit 233 // them again for this specialization. However, we don't obsolete this 234 // entry from the table, because we want to avoid ever emitting these 235 // diagnostics again. 236 Pos->second.clear(); 237 } 238 239 // C++ [basic.start.main]p3: 240 // The function 'main' shall not be used within a program. 241 if (cast<FunctionDecl>(D)->isMain()) 242 Diag(Loc, diag::ext_main_used); 243 244 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 245 } 246 247 // See if this is an auto-typed variable whose initializer we are parsing. 248 if (ParsingInitForAutoVars.count(D)) { 249 if (isa<BindingDecl>(D)) { 250 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 251 << D->getDeclName(); 252 } else { 253 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 254 << D->getDeclName() << cast<VarDecl>(D)->getType(); 255 } 256 return true; 257 } 258 259 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 260 // See if this is a deleted function. 261 if (FD->isDeleted()) { 262 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 263 if (Ctor && Ctor->isInheritingConstructor()) 264 Diag(Loc, diag::err_deleted_inherited_ctor_use) 265 << Ctor->getParent() 266 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 267 else 268 Diag(Loc, diag::err_deleted_function_use); 269 NoteDeletedFunction(FD); 270 return true; 271 } 272 273 // [expr.prim.id]p4 274 // A program that refers explicitly or implicitly to a function with a 275 // trailing requires-clause whose constraint-expression is not satisfied, 276 // other than to declare it, is ill-formed. [...] 277 // 278 // See if this is a function with constraints that need to be satisfied. 279 // Check this before deducing the return type, as it might instantiate the 280 // definition. 281 if (FD->getTrailingRequiresClause()) { 282 ConstraintSatisfaction Satisfaction; 283 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 284 // A diagnostic will have already been generated (non-constant 285 // constraint expression, for example) 286 return true; 287 if (!Satisfaction.IsSatisfied) { 288 Diag(Loc, 289 diag::err_reference_to_function_with_unsatisfied_constraints) 290 << D; 291 DiagnoseUnsatisfiedConstraint(Satisfaction); 292 return true; 293 } 294 } 295 296 // If the function has a deduced return type, and we can't deduce it, 297 // then we can't use it either. 298 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 299 DeduceReturnType(FD, Loc)) 300 return true; 301 302 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 303 return true; 304 305 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 306 return true; 307 } 308 309 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 310 // Lambdas are only default-constructible or assignable in C++2a onwards. 311 if (MD->getParent()->isLambda() && 312 ((isa<CXXConstructorDecl>(MD) && 313 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 314 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 315 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 316 << !isa<CXXConstructorDecl>(MD); 317 } 318 } 319 320 auto getReferencedObjCProp = [](const NamedDecl *D) -> 321 const ObjCPropertyDecl * { 322 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 323 return MD->findPropertyDecl(); 324 return nullptr; 325 }; 326 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 327 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 328 return true; 329 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 330 return true; 331 } 332 333 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 334 // Only the variables omp_in and omp_out are allowed in the combiner. 335 // Only the variables omp_priv and omp_orig are allowed in the 336 // initializer-clause. 337 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 338 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 339 isa<VarDecl>(D)) { 340 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 341 << getCurFunction()->HasOMPDeclareReductionCombiner; 342 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 343 return true; 344 } 345 346 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 347 // List-items in map clauses on this construct may only refer to the declared 348 // variable var and entities that could be referenced by a procedure defined 349 // at the same location 350 if (LangOpts.OpenMP && isa<VarDecl>(D) && 351 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 352 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 353 << getOpenMPDeclareMapperVarName(); 354 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 355 return true; 356 } 357 358 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 359 Diag(Loc, diag::err_use_of_empty_using_if_exists); 360 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 361 return true; 362 } 363 364 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 365 AvoidPartialAvailabilityChecks, ClassReceiver); 366 367 DiagnoseUnusedOfDecl(*this, D, Loc); 368 369 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 370 371 if (auto *VD = dyn_cast<ValueDecl>(D)) 372 checkTypeSupport(VD->getType(), Loc, VD); 373 374 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 375 if (!Context.getTargetInfo().isTLSSupported()) 376 if (const auto *VD = dyn_cast<VarDecl>(D)) 377 if (VD->getTLSKind() != VarDecl::TLS_None) 378 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 379 } 380 381 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 382 !isUnevaluatedContext()) { 383 // C++ [expr.prim.req.nested] p3 384 // A local parameter shall only appear as an unevaluated operand 385 // (Clause 8) within the constraint-expression. 386 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 387 << D; 388 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 389 return true; 390 } 391 392 return false; 393 } 394 395 /// DiagnoseSentinelCalls - This routine checks whether a call or 396 /// message-send is to a declaration with the sentinel attribute, and 397 /// if so, it checks that the requirements of the sentinel are 398 /// satisfied. 399 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 400 ArrayRef<Expr *> Args) { 401 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 402 if (!attr) 403 return; 404 405 // The number of formal parameters of the declaration. 406 unsigned numFormalParams; 407 408 // The kind of declaration. This is also an index into a %select in 409 // the diagnostic. 410 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 411 412 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 413 numFormalParams = MD->param_size(); 414 calleeType = CT_Method; 415 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 416 numFormalParams = FD->param_size(); 417 calleeType = CT_Function; 418 } else if (isa<VarDecl>(D)) { 419 QualType type = cast<ValueDecl>(D)->getType(); 420 const FunctionType *fn = nullptr; 421 if (const PointerType *ptr = type->getAs<PointerType>()) { 422 fn = ptr->getPointeeType()->getAs<FunctionType>(); 423 if (!fn) return; 424 calleeType = CT_Function; 425 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 426 fn = ptr->getPointeeType()->castAs<FunctionType>(); 427 calleeType = CT_Block; 428 } else { 429 return; 430 } 431 432 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 433 numFormalParams = proto->getNumParams(); 434 } else { 435 numFormalParams = 0; 436 } 437 } else { 438 return; 439 } 440 441 // "nullPos" is the number of formal parameters at the end which 442 // effectively count as part of the variadic arguments. This is 443 // useful if you would prefer to not have *any* formal parameters, 444 // but the language forces you to have at least one. 445 unsigned nullPos = attr->getNullPos(); 446 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 447 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 448 449 // The number of arguments which should follow the sentinel. 450 unsigned numArgsAfterSentinel = attr->getSentinel(); 451 452 // If there aren't enough arguments for all the formal parameters, 453 // the sentinel, and the args after the sentinel, complain. 454 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 455 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 456 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 457 return; 458 } 459 460 // Otherwise, find the sentinel expression. 461 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 462 if (!sentinelExpr) return; 463 if (sentinelExpr->isValueDependent()) return; 464 if (Context.isSentinelNullExpr(sentinelExpr)) return; 465 466 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 467 // or 'NULL' if those are actually defined in the context. Only use 468 // 'nil' for ObjC methods, where it's much more likely that the 469 // variadic arguments form a list of object pointers. 470 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 471 std::string NullValue; 472 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 473 NullValue = "nil"; 474 else if (getLangOpts().CPlusPlus11) 475 NullValue = "nullptr"; 476 else if (PP.isMacroDefined("NULL")) 477 NullValue = "NULL"; 478 else 479 NullValue = "(void*) 0"; 480 481 if (MissingNilLoc.isInvalid()) 482 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 483 else 484 Diag(MissingNilLoc, diag::warn_missing_sentinel) 485 << int(calleeType) 486 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 487 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 488 } 489 490 SourceRange Sema::getExprRange(Expr *E) const { 491 return E ? E->getSourceRange() : SourceRange(); 492 } 493 494 //===----------------------------------------------------------------------===// 495 // Standard Promotions and Conversions 496 //===----------------------------------------------------------------------===// 497 498 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 499 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 500 // Handle any placeholder expressions which made it here. 501 if (E->getType()->isPlaceholderType()) { 502 ExprResult result = CheckPlaceholderExpr(E); 503 if (result.isInvalid()) return ExprError(); 504 E = result.get(); 505 } 506 507 QualType Ty = E->getType(); 508 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 509 510 if (Ty->isFunctionType()) { 511 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 512 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 513 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 514 return ExprError(); 515 516 E = ImpCastExprToType(E, Context.getPointerType(Ty), 517 CK_FunctionToPointerDecay).get(); 518 } else if (Ty->isArrayType()) { 519 // In C90 mode, arrays only promote to pointers if the array expression is 520 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 521 // type 'array of type' is converted to an expression that has type 'pointer 522 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 523 // that has type 'array of type' ...". The relevant change is "an lvalue" 524 // (C90) to "an expression" (C99). 525 // 526 // C++ 4.2p1: 527 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 528 // T" can be converted to an rvalue of type "pointer to T". 529 // 530 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 531 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 532 CK_ArrayToPointerDecay); 533 if (Res.isInvalid()) 534 return ExprError(); 535 E = Res.get(); 536 } 537 } 538 return E; 539 } 540 541 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 542 // Check to see if we are dereferencing a null pointer. If so, 543 // and if not volatile-qualified, this is undefined behavior that the 544 // optimizer will delete, so warn about it. People sometimes try to use this 545 // to get a deterministic trap and are surprised by clang's behavior. This 546 // only handles the pattern "*null", which is a very syntactic check. 547 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 548 if (UO && UO->getOpcode() == UO_Deref && 549 UO->getSubExpr()->getType()->isPointerType()) { 550 const LangAS AS = 551 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 552 if ((!isTargetAddressSpace(AS) || 553 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 554 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 555 S.Context, Expr::NPC_ValueDependentIsNotNull) && 556 !UO->getType().isVolatileQualified()) { 557 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 558 S.PDiag(diag::warn_indirection_through_null) 559 << UO->getSubExpr()->getSourceRange()); 560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 561 S.PDiag(diag::note_indirection_through_null)); 562 } 563 } 564 } 565 566 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 567 SourceLocation AssignLoc, 568 const Expr* RHS) { 569 const ObjCIvarDecl *IV = OIRE->getDecl(); 570 if (!IV) 571 return; 572 573 DeclarationName MemberName = IV->getDeclName(); 574 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 575 if (!Member || !Member->isStr("isa")) 576 return; 577 578 const Expr *Base = OIRE->getBase(); 579 QualType BaseType = Base->getType(); 580 if (OIRE->isArrow()) 581 BaseType = BaseType->getPointeeType(); 582 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 583 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 584 ObjCInterfaceDecl *ClassDeclared = nullptr; 585 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 586 if (!ClassDeclared->getSuperClass() 587 && (*ClassDeclared->ivar_begin()) == IV) { 588 if (RHS) { 589 NamedDecl *ObjectSetClass = 590 S.LookupSingleName(S.TUScope, 591 &S.Context.Idents.get("object_setClass"), 592 SourceLocation(), S.LookupOrdinaryName); 593 if (ObjectSetClass) { 594 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 595 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 596 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 597 "object_setClass(") 598 << FixItHint::CreateReplacement( 599 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 600 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 601 } 602 else 603 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 604 } else { 605 NamedDecl *ObjectGetClass = 606 S.LookupSingleName(S.TUScope, 607 &S.Context.Idents.get("object_getClass"), 608 SourceLocation(), S.LookupOrdinaryName); 609 if (ObjectGetClass) 610 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 611 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 612 "object_getClass(") 613 << FixItHint::CreateReplacement( 614 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 615 else 616 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 617 } 618 S.Diag(IV->getLocation(), diag::note_ivar_decl); 619 } 620 } 621 } 622 623 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 624 // Handle any placeholder expressions which made it here. 625 if (E->getType()->isPlaceholderType()) { 626 ExprResult result = CheckPlaceholderExpr(E); 627 if (result.isInvalid()) return ExprError(); 628 E = result.get(); 629 } 630 631 // C++ [conv.lval]p1: 632 // A glvalue of a non-function, non-array type T can be 633 // converted to a prvalue. 634 if (!E->isGLValue()) return E; 635 636 QualType T = E->getType(); 637 assert(!T.isNull() && "r-value conversion on typeless expression?"); 638 639 // lvalue-to-rvalue conversion cannot be applied to function or array types. 640 if (T->isFunctionType() || T->isArrayType()) 641 return E; 642 643 // We don't want to throw lvalue-to-rvalue casts on top of 644 // expressions of certain types in C++. 645 if (getLangOpts().CPlusPlus && 646 (E->getType() == Context.OverloadTy || 647 T->isDependentType() || 648 T->isRecordType())) 649 return E; 650 651 // The C standard is actually really unclear on this point, and 652 // DR106 tells us what the result should be but not why. It's 653 // generally best to say that void types just doesn't undergo 654 // lvalue-to-rvalue at all. Note that expressions of unqualified 655 // 'void' type are never l-values, but qualified void can be. 656 if (T->isVoidType()) 657 return E; 658 659 // OpenCL usually rejects direct accesses to values of 'half' type. 660 if (getLangOpts().OpenCL && 661 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 662 T->isHalfType()) { 663 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 664 << 0 << T; 665 return ExprError(); 666 } 667 668 CheckForNullPointerDereference(*this, E); 669 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 670 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 671 &Context.Idents.get("object_getClass"), 672 SourceLocation(), LookupOrdinaryName); 673 if (ObjectGetClass) 674 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 675 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 676 << FixItHint::CreateReplacement( 677 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 678 else 679 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 680 } 681 else if (const ObjCIvarRefExpr *OIRE = 682 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 683 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 684 685 // C++ [conv.lval]p1: 686 // [...] If T is a non-class type, the type of the prvalue is the 687 // cv-unqualified version of T. Otherwise, the type of the 688 // rvalue is T. 689 // 690 // C99 6.3.2.1p2: 691 // If the lvalue has qualified type, the value has the unqualified 692 // version of the type of the lvalue; otherwise, the value has the 693 // type of the lvalue. 694 if (T.hasQualifiers()) 695 T = T.getUnqualifiedType(); 696 697 // Under the MS ABI, lock down the inheritance model now. 698 if (T->isMemberPointerType() && 699 Context.getTargetInfo().getCXXABI().isMicrosoft()) 700 (void)isCompleteType(E->getExprLoc(), T); 701 702 ExprResult Res = CheckLValueToRValueConversionOperand(E); 703 if (Res.isInvalid()) 704 return Res; 705 E = Res.get(); 706 707 // Loading a __weak object implicitly retains the value, so we need a cleanup to 708 // balance that. 709 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 710 Cleanup.setExprNeedsCleanups(true); 711 712 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 713 Cleanup.setExprNeedsCleanups(true); 714 715 // C++ [conv.lval]p3: 716 // If T is cv std::nullptr_t, the result is a null pointer constant. 717 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 718 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 719 CurFPFeatureOverrides()); 720 721 // C11 6.3.2.1p2: 722 // ... if the lvalue has atomic type, the value has the non-atomic version 723 // of the type of the lvalue ... 724 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 725 T = Atomic->getValueType().getUnqualifiedType(); 726 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 727 nullptr, VK_PRValue, FPOptionsOverride()); 728 } 729 730 return Res; 731 } 732 733 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 734 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 735 if (Res.isInvalid()) 736 return ExprError(); 737 Res = DefaultLvalueConversion(Res.get()); 738 if (Res.isInvalid()) 739 return ExprError(); 740 return Res; 741 } 742 743 /// CallExprUnaryConversions - a special case of an unary conversion 744 /// performed on a function designator of a call expression. 745 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 746 QualType Ty = E->getType(); 747 ExprResult Res = E; 748 // Only do implicit cast for a function type, but not for a pointer 749 // to function type. 750 if (Ty->isFunctionType()) { 751 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 752 CK_FunctionToPointerDecay); 753 if (Res.isInvalid()) 754 return ExprError(); 755 } 756 Res = DefaultLvalueConversion(Res.get()); 757 if (Res.isInvalid()) 758 return ExprError(); 759 return Res.get(); 760 } 761 762 /// UsualUnaryConversions - Performs various conversions that are common to most 763 /// operators (C99 6.3). The conversions of array and function types are 764 /// sometimes suppressed. For example, the array->pointer conversion doesn't 765 /// apply if the array is an argument to the sizeof or address (&) operators. 766 /// In these instances, this routine should *not* be called. 767 ExprResult Sema::UsualUnaryConversions(Expr *E) { 768 // First, convert to an r-value. 769 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 770 if (Res.isInvalid()) 771 return ExprError(); 772 E = Res.get(); 773 774 QualType Ty = E->getType(); 775 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 776 777 // Half FP have to be promoted to float unless it is natively supported 778 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 779 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 780 781 // Try to perform integral promotions if the object has a theoretically 782 // promotable type. 783 if (Ty->isIntegralOrUnscopedEnumerationType()) { 784 // C99 6.3.1.1p2: 785 // 786 // The following may be used in an expression wherever an int or 787 // unsigned int may be used: 788 // - an object or expression with an integer type whose integer 789 // conversion rank is less than or equal to the rank of int 790 // and unsigned int. 791 // - A bit-field of type _Bool, int, signed int, or unsigned int. 792 // 793 // If an int can represent all values of the original type, the 794 // value is converted to an int; otherwise, it is converted to an 795 // unsigned int. These are called the integer promotions. All 796 // other types are unchanged by the integer promotions. 797 798 QualType PTy = Context.isPromotableBitField(E); 799 if (!PTy.isNull()) { 800 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 801 return E; 802 } 803 if (Ty->isPromotableIntegerType()) { 804 QualType PT = Context.getPromotedIntegerType(Ty); 805 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 806 return E; 807 } 808 } 809 return E; 810 } 811 812 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 813 /// do not have a prototype. Arguments that have type float or __fp16 814 /// are promoted to double. All other argument types are converted by 815 /// UsualUnaryConversions(). 816 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 817 QualType Ty = E->getType(); 818 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 819 820 ExprResult Res = UsualUnaryConversions(E); 821 if (Res.isInvalid()) 822 return ExprError(); 823 E = Res.get(); 824 825 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 826 // promote to double. 827 // Note that default argument promotion applies only to float (and 828 // half/fp16); it does not apply to _Float16. 829 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 830 if (BTy && (BTy->getKind() == BuiltinType::Half || 831 BTy->getKind() == BuiltinType::Float)) { 832 if (getLangOpts().OpenCL && 833 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 834 if (BTy->getKind() == BuiltinType::Half) { 835 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 836 } 837 } else { 838 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 839 } 840 } 841 if (BTy && 842 getLangOpts().getExtendIntArgs() == 843 LangOptions::ExtendArgsKind::ExtendTo64 && 844 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 845 Context.getTypeSizeInChars(BTy) < 846 Context.getTypeSizeInChars(Context.LongLongTy)) { 847 E = (Ty->isUnsignedIntegerType()) 848 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 849 .get() 850 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 851 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 852 "Unexpected typesize for LongLongTy"); 853 } 854 855 // C++ performs lvalue-to-rvalue conversion as a default argument 856 // promotion, even on class types, but note: 857 // C++11 [conv.lval]p2: 858 // When an lvalue-to-rvalue conversion occurs in an unevaluated 859 // operand or a subexpression thereof the value contained in the 860 // referenced object is not accessed. Otherwise, if the glvalue 861 // has a class type, the conversion copy-initializes a temporary 862 // of type T from the glvalue and the result of the conversion 863 // is a prvalue for the temporary. 864 // FIXME: add some way to gate this entire thing for correctness in 865 // potentially potentially evaluated contexts. 866 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 867 ExprResult Temp = PerformCopyInitialization( 868 InitializedEntity::InitializeTemporary(E->getType()), 869 E->getExprLoc(), E); 870 if (Temp.isInvalid()) 871 return ExprError(); 872 E = Temp.get(); 873 } 874 875 return E; 876 } 877 878 /// Determine the degree of POD-ness for an expression. 879 /// Incomplete types are considered POD, since this check can be performed 880 /// when we're in an unevaluated context. 881 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 882 if (Ty->isIncompleteType()) { 883 // C++11 [expr.call]p7: 884 // After these conversions, if the argument does not have arithmetic, 885 // enumeration, pointer, pointer to member, or class type, the program 886 // is ill-formed. 887 // 888 // Since we've already performed array-to-pointer and function-to-pointer 889 // decay, the only such type in C++ is cv void. This also handles 890 // initializer lists as variadic arguments. 891 if (Ty->isVoidType()) 892 return VAK_Invalid; 893 894 if (Ty->isObjCObjectType()) 895 return VAK_Invalid; 896 return VAK_Valid; 897 } 898 899 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 900 return VAK_Invalid; 901 902 if (Ty.isCXX98PODType(Context)) 903 return VAK_Valid; 904 905 // C++11 [expr.call]p7: 906 // Passing a potentially-evaluated argument of class type (Clause 9) 907 // having a non-trivial copy constructor, a non-trivial move constructor, 908 // or a non-trivial destructor, with no corresponding parameter, 909 // is conditionally-supported with implementation-defined semantics. 910 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 911 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 912 if (!Record->hasNonTrivialCopyConstructor() && 913 !Record->hasNonTrivialMoveConstructor() && 914 !Record->hasNonTrivialDestructor()) 915 return VAK_ValidInCXX11; 916 917 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 918 return VAK_Valid; 919 920 if (Ty->isObjCObjectType()) 921 return VAK_Invalid; 922 923 if (getLangOpts().MSVCCompat) 924 return VAK_MSVCUndefined; 925 926 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 927 // permitted to reject them. We should consider doing so. 928 return VAK_Undefined; 929 } 930 931 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 932 // Don't allow one to pass an Objective-C interface to a vararg. 933 const QualType &Ty = E->getType(); 934 VarArgKind VAK = isValidVarArgType(Ty); 935 936 // Complain about passing non-POD types through varargs. 937 switch (VAK) { 938 case VAK_ValidInCXX11: 939 DiagRuntimeBehavior( 940 E->getBeginLoc(), nullptr, 941 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 942 LLVM_FALLTHROUGH; 943 case VAK_Valid: 944 if (Ty->isRecordType()) { 945 // This is unlikely to be what the user intended. If the class has a 946 // 'c_str' member function, the user probably meant to call that. 947 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 948 PDiag(diag::warn_pass_class_arg_to_vararg) 949 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 950 } 951 break; 952 953 case VAK_Undefined: 954 case VAK_MSVCUndefined: 955 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 956 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 957 << getLangOpts().CPlusPlus11 << Ty << CT); 958 break; 959 960 case VAK_Invalid: 961 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 962 Diag(E->getBeginLoc(), 963 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 964 << Ty << CT; 965 else if (Ty->isObjCObjectType()) 966 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 967 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 968 << Ty << CT); 969 else 970 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 971 << isa<InitListExpr>(E) << Ty << CT; 972 break; 973 } 974 } 975 976 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 977 /// will create a trap if the resulting type is not a POD type. 978 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 979 FunctionDecl *FDecl) { 980 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 981 // Strip the unbridged-cast placeholder expression off, if applicable. 982 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 983 (CT == VariadicMethod || 984 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 985 E = stripARCUnbridgedCast(E); 986 987 // Otherwise, do normal placeholder checking. 988 } else { 989 ExprResult ExprRes = CheckPlaceholderExpr(E); 990 if (ExprRes.isInvalid()) 991 return ExprError(); 992 E = ExprRes.get(); 993 } 994 } 995 996 ExprResult ExprRes = DefaultArgumentPromotion(E); 997 if (ExprRes.isInvalid()) 998 return ExprError(); 999 1000 // Copy blocks to the heap. 1001 if (ExprRes.get()->getType()->isBlockPointerType()) 1002 maybeExtendBlockObject(ExprRes); 1003 1004 E = ExprRes.get(); 1005 1006 // Diagnostics regarding non-POD argument types are 1007 // emitted along with format string checking in Sema::CheckFunctionCall(). 1008 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1009 // Turn this into a trap. 1010 CXXScopeSpec SS; 1011 SourceLocation TemplateKWLoc; 1012 UnqualifiedId Name; 1013 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1014 E->getBeginLoc()); 1015 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1016 /*HasTrailingLParen=*/true, 1017 /*IsAddressOfOperand=*/false); 1018 if (TrapFn.isInvalid()) 1019 return ExprError(); 1020 1021 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1022 None, E->getEndLoc()); 1023 if (Call.isInvalid()) 1024 return ExprError(); 1025 1026 ExprResult Comma = 1027 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1028 if (Comma.isInvalid()) 1029 return ExprError(); 1030 return Comma.get(); 1031 } 1032 1033 if (!getLangOpts().CPlusPlus && 1034 RequireCompleteType(E->getExprLoc(), E->getType(), 1035 diag::err_call_incomplete_argument)) 1036 return ExprError(); 1037 1038 return E; 1039 } 1040 1041 /// Converts an integer to complex float type. Helper function of 1042 /// UsualArithmeticConversions() 1043 /// 1044 /// \return false if the integer expression is an integer type and is 1045 /// successfully converted to the complex type. 1046 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1047 ExprResult &ComplexExpr, 1048 QualType IntTy, 1049 QualType ComplexTy, 1050 bool SkipCast) { 1051 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1052 if (SkipCast) return false; 1053 if (IntTy->isIntegerType()) { 1054 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1055 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1056 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1057 CK_FloatingRealToComplex); 1058 } else { 1059 assert(IntTy->isComplexIntegerType()); 1060 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1061 CK_IntegralComplexToFloatingComplex); 1062 } 1063 return false; 1064 } 1065 1066 /// Handle arithmetic conversion with complex types. Helper function of 1067 /// UsualArithmeticConversions() 1068 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1069 ExprResult &RHS, QualType LHSType, 1070 QualType RHSType, 1071 bool IsCompAssign) { 1072 // if we have an integer operand, the result is the complex type. 1073 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1074 /*skipCast*/false)) 1075 return LHSType; 1076 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1077 /*skipCast*/IsCompAssign)) 1078 return RHSType; 1079 1080 // This handles complex/complex, complex/float, or float/complex. 1081 // When both operands are complex, the shorter operand is converted to the 1082 // type of the longer, and that is the type of the result. This corresponds 1083 // to what is done when combining two real floating-point operands. 1084 // The fun begins when size promotion occur across type domains. 1085 // From H&S 6.3.4: When one operand is complex and the other is a real 1086 // floating-point type, the less precise type is converted, within it's 1087 // real or complex domain, to the precision of the other type. For example, 1088 // when combining a "long double" with a "double _Complex", the 1089 // "double _Complex" is promoted to "long double _Complex". 1090 1091 // Compute the rank of the two types, regardless of whether they are complex. 1092 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1093 1094 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1095 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1096 QualType LHSElementType = 1097 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1098 QualType RHSElementType = 1099 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1100 1101 QualType ResultType = S.Context.getComplexType(LHSElementType); 1102 if (Order < 0) { 1103 // Promote the precision of the LHS if not an assignment. 1104 ResultType = S.Context.getComplexType(RHSElementType); 1105 if (!IsCompAssign) { 1106 if (LHSComplexType) 1107 LHS = 1108 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1109 else 1110 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1111 } 1112 } else if (Order > 0) { 1113 // Promote the precision of the RHS. 1114 if (RHSComplexType) 1115 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1116 else 1117 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1118 } 1119 return ResultType; 1120 } 1121 1122 /// Handle arithmetic conversion from integer to float. Helper function 1123 /// of UsualArithmeticConversions() 1124 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1125 ExprResult &IntExpr, 1126 QualType FloatTy, QualType IntTy, 1127 bool ConvertFloat, bool ConvertInt) { 1128 if (IntTy->isIntegerType()) { 1129 if (ConvertInt) 1130 // Convert intExpr to the lhs floating point type. 1131 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1132 CK_IntegralToFloating); 1133 return FloatTy; 1134 } 1135 1136 // Convert both sides to the appropriate complex float. 1137 assert(IntTy->isComplexIntegerType()); 1138 QualType result = S.Context.getComplexType(FloatTy); 1139 1140 // _Complex int -> _Complex float 1141 if (ConvertInt) 1142 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1143 CK_IntegralComplexToFloatingComplex); 1144 1145 // float -> _Complex float 1146 if (ConvertFloat) 1147 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1148 CK_FloatingRealToComplex); 1149 1150 return result; 1151 } 1152 1153 /// Handle arithmethic conversion with floating point types. Helper 1154 /// function of UsualArithmeticConversions() 1155 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1156 ExprResult &RHS, QualType LHSType, 1157 QualType RHSType, bool IsCompAssign) { 1158 bool LHSFloat = LHSType->isRealFloatingType(); 1159 bool RHSFloat = RHSType->isRealFloatingType(); 1160 1161 // N1169 4.1.4: If one of the operands has a floating type and the other 1162 // operand has a fixed-point type, the fixed-point operand 1163 // is converted to the floating type [...] 1164 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1165 if (LHSFloat) 1166 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1167 else if (!IsCompAssign) 1168 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1169 return LHSFloat ? LHSType : RHSType; 1170 } 1171 1172 // If we have two real floating types, convert the smaller operand 1173 // to the bigger result. 1174 if (LHSFloat && RHSFloat) { 1175 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1176 if (order > 0) { 1177 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1178 return LHSType; 1179 } 1180 1181 assert(order < 0 && "illegal float comparison"); 1182 if (!IsCompAssign) 1183 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1184 return RHSType; 1185 } 1186 1187 if (LHSFloat) { 1188 // Half FP has to be promoted to float unless it is natively supported 1189 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1190 LHSType = S.Context.FloatTy; 1191 1192 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1193 /*ConvertFloat=*/!IsCompAssign, 1194 /*ConvertInt=*/ true); 1195 } 1196 assert(RHSFloat); 1197 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1198 /*ConvertFloat=*/ true, 1199 /*ConvertInt=*/!IsCompAssign); 1200 } 1201 1202 /// Diagnose attempts to convert between __float128, __ibm128 and 1203 /// long double if there is no support for such conversion. 1204 /// Helper function of UsualArithmeticConversions(). 1205 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1206 QualType RHSType) { 1207 // No issue if either is not a floating point type. 1208 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1209 return false; 1210 1211 // No issue if both have the same 128-bit float semantics. 1212 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1213 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1214 1215 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1216 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1217 1218 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1219 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1220 1221 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1222 &RHSSem != &llvm::APFloat::IEEEquad()) && 1223 (&LHSSem != &llvm::APFloat::IEEEquad() || 1224 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1225 return false; 1226 1227 return true; 1228 } 1229 1230 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1231 1232 namespace { 1233 /// These helper callbacks are placed in an anonymous namespace to 1234 /// permit their use as function template parameters. 1235 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1236 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1237 } 1238 1239 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1240 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1241 CK_IntegralComplexCast); 1242 } 1243 } 1244 1245 /// Handle integer arithmetic conversions. Helper function of 1246 /// UsualArithmeticConversions() 1247 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1248 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1249 ExprResult &RHS, QualType LHSType, 1250 QualType RHSType, bool IsCompAssign) { 1251 // The rules for this case are in C99 6.3.1.8 1252 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1253 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1254 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1255 if (LHSSigned == RHSSigned) { 1256 // Same signedness; use the higher-ranked type 1257 if (order >= 0) { 1258 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1259 return LHSType; 1260 } else if (!IsCompAssign) 1261 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1262 return RHSType; 1263 } else if (order != (LHSSigned ? 1 : -1)) { 1264 // The unsigned type has greater than or equal rank to the 1265 // signed type, so use the unsigned type 1266 if (RHSSigned) { 1267 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1268 return LHSType; 1269 } else if (!IsCompAssign) 1270 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1271 return RHSType; 1272 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1273 // The two types are different widths; if we are here, that 1274 // means the signed type is larger than the unsigned type, so 1275 // use the signed type. 1276 if (LHSSigned) { 1277 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1278 return LHSType; 1279 } else if (!IsCompAssign) 1280 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1281 return RHSType; 1282 } else { 1283 // The signed type is higher-ranked than the unsigned type, 1284 // but isn't actually any bigger (like unsigned int and long 1285 // on most 32-bit systems). Use the unsigned type corresponding 1286 // to the signed type. 1287 QualType result = 1288 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1289 RHS = (*doRHSCast)(S, RHS.get(), result); 1290 if (!IsCompAssign) 1291 LHS = (*doLHSCast)(S, LHS.get(), result); 1292 return result; 1293 } 1294 } 1295 1296 /// Handle conversions with GCC complex int extension. Helper function 1297 /// of UsualArithmeticConversions() 1298 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1299 ExprResult &RHS, QualType LHSType, 1300 QualType RHSType, 1301 bool IsCompAssign) { 1302 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1303 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1304 1305 if (LHSComplexInt && RHSComplexInt) { 1306 QualType LHSEltType = LHSComplexInt->getElementType(); 1307 QualType RHSEltType = RHSComplexInt->getElementType(); 1308 QualType ScalarType = 1309 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1310 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1311 1312 return S.Context.getComplexType(ScalarType); 1313 } 1314 1315 if (LHSComplexInt) { 1316 QualType LHSEltType = LHSComplexInt->getElementType(); 1317 QualType ScalarType = 1318 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1319 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1320 QualType ComplexType = S.Context.getComplexType(ScalarType); 1321 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1322 CK_IntegralRealToComplex); 1323 1324 return ComplexType; 1325 } 1326 1327 assert(RHSComplexInt); 1328 1329 QualType RHSEltType = RHSComplexInt->getElementType(); 1330 QualType ScalarType = 1331 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1332 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1333 QualType ComplexType = S.Context.getComplexType(ScalarType); 1334 1335 if (!IsCompAssign) 1336 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1337 CK_IntegralRealToComplex); 1338 return ComplexType; 1339 } 1340 1341 /// Return the rank of a given fixed point or integer type. The value itself 1342 /// doesn't matter, but the values must be increasing with proper increasing 1343 /// rank as described in N1169 4.1.1. 1344 static unsigned GetFixedPointRank(QualType Ty) { 1345 const auto *BTy = Ty->getAs<BuiltinType>(); 1346 assert(BTy && "Expected a builtin type."); 1347 1348 switch (BTy->getKind()) { 1349 case BuiltinType::ShortFract: 1350 case BuiltinType::UShortFract: 1351 case BuiltinType::SatShortFract: 1352 case BuiltinType::SatUShortFract: 1353 return 1; 1354 case BuiltinType::Fract: 1355 case BuiltinType::UFract: 1356 case BuiltinType::SatFract: 1357 case BuiltinType::SatUFract: 1358 return 2; 1359 case BuiltinType::LongFract: 1360 case BuiltinType::ULongFract: 1361 case BuiltinType::SatLongFract: 1362 case BuiltinType::SatULongFract: 1363 return 3; 1364 case BuiltinType::ShortAccum: 1365 case BuiltinType::UShortAccum: 1366 case BuiltinType::SatShortAccum: 1367 case BuiltinType::SatUShortAccum: 1368 return 4; 1369 case BuiltinType::Accum: 1370 case BuiltinType::UAccum: 1371 case BuiltinType::SatAccum: 1372 case BuiltinType::SatUAccum: 1373 return 5; 1374 case BuiltinType::LongAccum: 1375 case BuiltinType::ULongAccum: 1376 case BuiltinType::SatLongAccum: 1377 case BuiltinType::SatULongAccum: 1378 return 6; 1379 default: 1380 if (BTy->isInteger()) 1381 return 0; 1382 llvm_unreachable("Unexpected fixed point or integer type"); 1383 } 1384 } 1385 1386 /// handleFixedPointConversion - Fixed point operations between fixed 1387 /// point types and integers or other fixed point types do not fall under 1388 /// usual arithmetic conversion since these conversions could result in loss 1389 /// of precsision (N1169 4.1.4). These operations should be calculated with 1390 /// the full precision of their result type (N1169 4.1.6.2.1). 1391 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1392 QualType RHSTy) { 1393 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1394 "Expected at least one of the operands to be a fixed point type"); 1395 assert((LHSTy->isFixedPointOrIntegerType() || 1396 RHSTy->isFixedPointOrIntegerType()) && 1397 "Special fixed point arithmetic operation conversions are only " 1398 "applied to ints or other fixed point types"); 1399 1400 // If one operand has signed fixed-point type and the other operand has 1401 // unsigned fixed-point type, then the unsigned fixed-point operand is 1402 // converted to its corresponding signed fixed-point type and the resulting 1403 // type is the type of the converted operand. 1404 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1405 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1406 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1407 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1408 1409 // The result type is the type with the highest rank, whereby a fixed-point 1410 // conversion rank is always greater than an integer conversion rank; if the 1411 // type of either of the operands is a saturating fixedpoint type, the result 1412 // type shall be the saturating fixed-point type corresponding to the type 1413 // with the highest rank; the resulting value is converted (taking into 1414 // account rounding and overflow) to the precision of the resulting type. 1415 // Same ranks between signed and unsigned types are resolved earlier, so both 1416 // types are either signed or both unsigned at this point. 1417 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1418 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1419 1420 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1421 1422 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1423 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1424 1425 return ResultTy; 1426 } 1427 1428 /// Check that the usual arithmetic conversions can be performed on this pair of 1429 /// expressions that might be of enumeration type. 1430 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1431 SourceLocation Loc, 1432 Sema::ArithConvKind ACK) { 1433 // C++2a [expr.arith.conv]p1: 1434 // If one operand is of enumeration type and the other operand is of a 1435 // different enumeration type or a floating-point type, this behavior is 1436 // deprecated ([depr.arith.conv.enum]). 1437 // 1438 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1439 // Eventually we will presumably reject these cases (in C++23 onwards?). 1440 QualType L = LHS->getType(), R = RHS->getType(); 1441 bool LEnum = L->isUnscopedEnumerationType(), 1442 REnum = R->isUnscopedEnumerationType(); 1443 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1444 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1445 (REnum && L->isFloatingType())) { 1446 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1447 ? diag::warn_arith_conv_enum_float_cxx20 1448 : diag::warn_arith_conv_enum_float) 1449 << LHS->getSourceRange() << RHS->getSourceRange() 1450 << (int)ACK << LEnum << L << R; 1451 } else if (!IsCompAssign && LEnum && REnum && 1452 !S.Context.hasSameUnqualifiedType(L, R)) { 1453 unsigned DiagID; 1454 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1455 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1456 // If either enumeration type is unnamed, it's less likely that the 1457 // user cares about this, but this situation is still deprecated in 1458 // C++2a. Use a different warning group. 1459 DiagID = S.getLangOpts().CPlusPlus20 1460 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1461 : diag::warn_arith_conv_mixed_anon_enum_types; 1462 } else if (ACK == Sema::ACK_Conditional) { 1463 // Conditional expressions are separated out because they have 1464 // historically had a different warning flag. 1465 DiagID = S.getLangOpts().CPlusPlus20 1466 ? diag::warn_conditional_mixed_enum_types_cxx20 1467 : diag::warn_conditional_mixed_enum_types; 1468 } else if (ACK == Sema::ACK_Comparison) { 1469 // Comparison expressions are separated out because they have 1470 // historically had a different warning flag. 1471 DiagID = S.getLangOpts().CPlusPlus20 1472 ? diag::warn_comparison_mixed_enum_types_cxx20 1473 : diag::warn_comparison_mixed_enum_types; 1474 } else { 1475 DiagID = S.getLangOpts().CPlusPlus20 1476 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1477 : diag::warn_arith_conv_mixed_enum_types; 1478 } 1479 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1480 << (int)ACK << L << R; 1481 } 1482 } 1483 1484 /// UsualArithmeticConversions - Performs various conversions that are common to 1485 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1486 /// routine returns the first non-arithmetic type found. The client is 1487 /// responsible for emitting appropriate error diagnostics. 1488 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1489 SourceLocation Loc, 1490 ArithConvKind ACK) { 1491 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1492 1493 if (ACK != ACK_CompAssign) { 1494 LHS = UsualUnaryConversions(LHS.get()); 1495 if (LHS.isInvalid()) 1496 return QualType(); 1497 } 1498 1499 RHS = UsualUnaryConversions(RHS.get()); 1500 if (RHS.isInvalid()) 1501 return QualType(); 1502 1503 // For conversion purposes, we ignore any qualifiers. 1504 // For example, "const float" and "float" are equivalent. 1505 QualType LHSType = 1506 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1507 QualType RHSType = 1508 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1509 1510 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1511 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1512 LHSType = AtomicLHS->getValueType(); 1513 1514 // If both types are identical, no conversion is needed. 1515 if (LHSType == RHSType) 1516 return LHSType; 1517 1518 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1519 // The caller can deal with this (e.g. pointer + int). 1520 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1521 return QualType(); 1522 1523 // Apply unary and bitfield promotions to the LHS's type. 1524 QualType LHSUnpromotedType = LHSType; 1525 if (LHSType->isPromotableIntegerType()) 1526 LHSType = Context.getPromotedIntegerType(LHSType); 1527 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1528 if (!LHSBitfieldPromoteTy.isNull()) 1529 LHSType = LHSBitfieldPromoteTy; 1530 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1531 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1532 1533 // If both types are identical, no conversion is needed. 1534 if (LHSType == RHSType) 1535 return LHSType; 1536 1537 // At this point, we have two different arithmetic types. 1538 1539 // Diagnose attempts to convert between __ibm128, __float128 and long double 1540 // where such conversions currently can't be handled. 1541 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1542 return QualType(); 1543 1544 // Handle complex types first (C99 6.3.1.8p1). 1545 if (LHSType->isComplexType() || RHSType->isComplexType()) 1546 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1547 ACK == ACK_CompAssign); 1548 1549 // Now handle "real" floating types (i.e. float, double, long double). 1550 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1551 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1552 ACK == ACK_CompAssign); 1553 1554 // Handle GCC complex int extension. 1555 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1556 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1557 ACK == ACK_CompAssign); 1558 1559 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1560 return handleFixedPointConversion(*this, LHSType, RHSType); 1561 1562 // Finally, we have two differing integer types. 1563 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1564 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1565 } 1566 1567 //===----------------------------------------------------------------------===// 1568 // Semantic Analysis for various Expression Types 1569 //===----------------------------------------------------------------------===// 1570 1571 1572 ExprResult 1573 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1574 SourceLocation DefaultLoc, 1575 SourceLocation RParenLoc, 1576 Expr *ControllingExpr, 1577 ArrayRef<ParsedType> ArgTypes, 1578 ArrayRef<Expr *> ArgExprs) { 1579 unsigned NumAssocs = ArgTypes.size(); 1580 assert(NumAssocs == ArgExprs.size()); 1581 1582 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1583 for (unsigned i = 0; i < NumAssocs; ++i) { 1584 if (ArgTypes[i]) 1585 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1586 else 1587 Types[i] = nullptr; 1588 } 1589 1590 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1591 ControllingExpr, 1592 llvm::makeArrayRef(Types, NumAssocs), 1593 ArgExprs); 1594 delete [] Types; 1595 return ER; 1596 } 1597 1598 ExprResult 1599 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1600 SourceLocation DefaultLoc, 1601 SourceLocation RParenLoc, 1602 Expr *ControllingExpr, 1603 ArrayRef<TypeSourceInfo *> Types, 1604 ArrayRef<Expr *> Exprs) { 1605 unsigned NumAssocs = Types.size(); 1606 assert(NumAssocs == Exprs.size()); 1607 1608 // Decay and strip qualifiers for the controlling expression type, and handle 1609 // placeholder type replacement. See committee discussion from WG14 DR423. 1610 { 1611 EnterExpressionEvaluationContext Unevaluated( 1612 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1613 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1614 if (R.isInvalid()) 1615 return ExprError(); 1616 ControllingExpr = R.get(); 1617 } 1618 1619 // The controlling expression is an unevaluated operand, so side effects are 1620 // likely unintended. 1621 if (!inTemplateInstantiation() && 1622 ControllingExpr->HasSideEffects(Context, false)) 1623 Diag(ControllingExpr->getExprLoc(), 1624 diag::warn_side_effects_unevaluated_context); 1625 1626 bool TypeErrorFound = false, 1627 IsResultDependent = ControllingExpr->isTypeDependent(), 1628 ContainsUnexpandedParameterPack 1629 = ControllingExpr->containsUnexpandedParameterPack(); 1630 1631 for (unsigned i = 0; i < NumAssocs; ++i) { 1632 if (Exprs[i]->containsUnexpandedParameterPack()) 1633 ContainsUnexpandedParameterPack = true; 1634 1635 if (Types[i]) { 1636 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1637 ContainsUnexpandedParameterPack = true; 1638 1639 if (Types[i]->getType()->isDependentType()) { 1640 IsResultDependent = true; 1641 } else { 1642 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1643 // complete object type other than a variably modified type." 1644 unsigned D = 0; 1645 if (Types[i]->getType()->isIncompleteType()) 1646 D = diag::err_assoc_type_incomplete; 1647 else if (!Types[i]->getType()->isObjectType()) 1648 D = diag::err_assoc_type_nonobject; 1649 else if (Types[i]->getType()->isVariablyModifiedType()) 1650 D = diag::err_assoc_type_variably_modified; 1651 1652 if (D != 0) { 1653 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1654 << Types[i]->getTypeLoc().getSourceRange() 1655 << Types[i]->getType(); 1656 TypeErrorFound = true; 1657 } 1658 1659 // C11 6.5.1.1p2 "No two generic associations in the same generic 1660 // selection shall specify compatible types." 1661 for (unsigned j = i+1; j < NumAssocs; ++j) 1662 if (Types[j] && !Types[j]->getType()->isDependentType() && 1663 Context.typesAreCompatible(Types[i]->getType(), 1664 Types[j]->getType())) { 1665 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1666 diag::err_assoc_compatible_types) 1667 << Types[j]->getTypeLoc().getSourceRange() 1668 << Types[j]->getType() 1669 << Types[i]->getType(); 1670 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1671 diag::note_compat_assoc) 1672 << Types[i]->getTypeLoc().getSourceRange() 1673 << Types[i]->getType(); 1674 TypeErrorFound = true; 1675 } 1676 } 1677 } 1678 } 1679 if (TypeErrorFound) 1680 return ExprError(); 1681 1682 // If we determined that the generic selection is result-dependent, don't 1683 // try to compute the result expression. 1684 if (IsResultDependent) 1685 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1686 Exprs, DefaultLoc, RParenLoc, 1687 ContainsUnexpandedParameterPack); 1688 1689 SmallVector<unsigned, 1> CompatIndices; 1690 unsigned DefaultIndex = -1U; 1691 for (unsigned i = 0; i < NumAssocs; ++i) { 1692 if (!Types[i]) 1693 DefaultIndex = i; 1694 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1695 Types[i]->getType())) 1696 CompatIndices.push_back(i); 1697 } 1698 1699 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1700 // type compatible with at most one of the types named in its generic 1701 // association list." 1702 if (CompatIndices.size() > 1) { 1703 // We strip parens here because the controlling expression is typically 1704 // parenthesized in macro definitions. 1705 ControllingExpr = ControllingExpr->IgnoreParens(); 1706 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1707 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1708 << (unsigned)CompatIndices.size(); 1709 for (unsigned I : CompatIndices) { 1710 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1711 diag::note_compat_assoc) 1712 << Types[I]->getTypeLoc().getSourceRange() 1713 << Types[I]->getType(); 1714 } 1715 return ExprError(); 1716 } 1717 1718 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1719 // its controlling expression shall have type compatible with exactly one of 1720 // the types named in its generic association list." 1721 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1722 // We strip parens here because the controlling expression is typically 1723 // parenthesized in macro definitions. 1724 ControllingExpr = ControllingExpr->IgnoreParens(); 1725 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1726 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1727 return ExprError(); 1728 } 1729 1730 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1731 // type name that is compatible with the type of the controlling expression, 1732 // then the result expression of the generic selection is the expression 1733 // in that generic association. Otherwise, the result expression of the 1734 // generic selection is the expression in the default generic association." 1735 unsigned ResultIndex = 1736 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1737 1738 return GenericSelectionExpr::Create( 1739 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1740 ContainsUnexpandedParameterPack, ResultIndex); 1741 } 1742 1743 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1744 /// location of the token and the offset of the ud-suffix within it. 1745 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1746 unsigned Offset) { 1747 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1748 S.getLangOpts()); 1749 } 1750 1751 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1752 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1753 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1754 IdentifierInfo *UDSuffix, 1755 SourceLocation UDSuffixLoc, 1756 ArrayRef<Expr*> Args, 1757 SourceLocation LitEndLoc) { 1758 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1759 1760 QualType ArgTy[2]; 1761 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1762 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1763 if (ArgTy[ArgIdx]->isArrayType()) 1764 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1765 } 1766 1767 DeclarationName OpName = 1768 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1769 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1770 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1771 1772 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1773 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1774 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1775 /*AllowStringTemplatePack*/ false, 1776 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1777 return ExprError(); 1778 1779 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1780 } 1781 1782 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1783 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1784 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1785 /// multiple tokens. However, the common case is that StringToks points to one 1786 /// string. 1787 /// 1788 ExprResult 1789 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1790 assert(!StringToks.empty() && "Must have at least one string!"); 1791 1792 StringLiteralParser Literal(StringToks, PP); 1793 if (Literal.hadError) 1794 return ExprError(); 1795 1796 SmallVector<SourceLocation, 4> StringTokLocs; 1797 for (const Token &Tok : StringToks) 1798 StringTokLocs.push_back(Tok.getLocation()); 1799 1800 QualType CharTy = Context.CharTy; 1801 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1802 if (Literal.isWide()) { 1803 CharTy = Context.getWideCharType(); 1804 Kind = StringLiteral::Wide; 1805 } else if (Literal.isUTF8()) { 1806 if (getLangOpts().Char8) 1807 CharTy = Context.Char8Ty; 1808 Kind = StringLiteral::UTF8; 1809 } else if (Literal.isUTF16()) { 1810 CharTy = Context.Char16Ty; 1811 Kind = StringLiteral::UTF16; 1812 } else if (Literal.isUTF32()) { 1813 CharTy = Context.Char32Ty; 1814 Kind = StringLiteral::UTF32; 1815 } else if (Literal.isPascal()) { 1816 CharTy = Context.UnsignedCharTy; 1817 } 1818 1819 // Warn on initializing an array of char from a u8 string literal; this 1820 // becomes ill-formed in C++2a. 1821 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1822 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1823 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1824 1825 // Create removals for all 'u8' prefixes in the string literal(s). This 1826 // ensures C++2a compatibility (but may change the program behavior when 1827 // built by non-Clang compilers for which the execution character set is 1828 // not always UTF-8). 1829 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1830 SourceLocation RemovalDiagLoc; 1831 for (const Token &Tok : StringToks) { 1832 if (Tok.getKind() == tok::utf8_string_literal) { 1833 if (RemovalDiagLoc.isInvalid()) 1834 RemovalDiagLoc = Tok.getLocation(); 1835 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1836 Tok.getLocation(), 1837 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1838 getSourceManager(), getLangOpts()))); 1839 } 1840 } 1841 Diag(RemovalDiagLoc, RemovalDiag); 1842 } 1843 1844 QualType StrTy = 1845 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1846 1847 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1848 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1849 Kind, Literal.Pascal, StrTy, 1850 &StringTokLocs[0], 1851 StringTokLocs.size()); 1852 if (Literal.getUDSuffix().empty()) 1853 return Lit; 1854 1855 // We're building a user-defined literal. 1856 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1857 SourceLocation UDSuffixLoc = 1858 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1859 Literal.getUDSuffixOffset()); 1860 1861 // Make sure we're allowed user-defined literals here. 1862 if (!UDLScope) 1863 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1864 1865 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1866 // operator "" X (str, len) 1867 QualType SizeType = Context.getSizeType(); 1868 1869 DeclarationName OpName = 1870 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1871 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1872 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1873 1874 QualType ArgTy[] = { 1875 Context.getArrayDecayedType(StrTy), SizeType 1876 }; 1877 1878 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1879 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1880 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1881 /*AllowStringTemplatePack*/ true, 1882 /*DiagnoseMissing*/ true, Lit)) { 1883 1884 case LOLR_Cooked: { 1885 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1886 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1887 StringTokLocs[0]); 1888 Expr *Args[] = { Lit, LenArg }; 1889 1890 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1891 } 1892 1893 case LOLR_Template: { 1894 TemplateArgumentListInfo ExplicitArgs; 1895 TemplateArgument Arg(Lit); 1896 TemplateArgumentLocInfo ArgInfo(Lit); 1897 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1898 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1899 &ExplicitArgs); 1900 } 1901 1902 case LOLR_StringTemplatePack: { 1903 TemplateArgumentListInfo ExplicitArgs; 1904 1905 unsigned CharBits = Context.getIntWidth(CharTy); 1906 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1907 llvm::APSInt Value(CharBits, CharIsUnsigned); 1908 1909 TemplateArgument TypeArg(CharTy); 1910 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1911 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1912 1913 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1914 Value = Lit->getCodeUnit(I); 1915 TemplateArgument Arg(Context, Value, CharTy); 1916 TemplateArgumentLocInfo ArgInfo; 1917 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1918 } 1919 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1920 &ExplicitArgs); 1921 } 1922 case LOLR_Raw: 1923 case LOLR_ErrorNoDiagnostic: 1924 llvm_unreachable("unexpected literal operator lookup result"); 1925 case LOLR_Error: 1926 return ExprError(); 1927 } 1928 llvm_unreachable("unexpected literal operator lookup result"); 1929 } 1930 1931 DeclRefExpr * 1932 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1933 SourceLocation Loc, 1934 const CXXScopeSpec *SS) { 1935 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1936 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1937 } 1938 1939 DeclRefExpr * 1940 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1941 const DeclarationNameInfo &NameInfo, 1942 const CXXScopeSpec *SS, NamedDecl *FoundD, 1943 SourceLocation TemplateKWLoc, 1944 const TemplateArgumentListInfo *TemplateArgs) { 1945 NestedNameSpecifierLoc NNS = 1946 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1947 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1948 TemplateArgs); 1949 } 1950 1951 // CUDA/HIP: Check whether a captured reference variable is referencing a 1952 // host variable in a device or host device lambda. 1953 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1954 VarDecl *VD) { 1955 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1956 return false; 1957 assert(VD->getType()->isReferenceType()); 1958 1959 // Check whether the reference variable is referencing a host variable. 1960 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1961 if (!DRE) 1962 return false; 1963 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1964 if (!Referee || !Referee->hasGlobalStorage() || 1965 Referee->hasAttr<CUDADeviceAttr>()) 1966 return false; 1967 1968 // Check whether the current function is a device or host device lambda. 1969 // Check whether the reference variable is a capture by getDeclContext() 1970 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1971 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1972 if (MD && MD->getParent()->isLambda() && 1973 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1974 VD->getDeclContext() != MD) 1975 return true; 1976 1977 return false; 1978 } 1979 1980 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1981 // A declaration named in an unevaluated operand never constitutes an odr-use. 1982 if (isUnevaluatedContext()) 1983 return NOUR_Unevaluated; 1984 1985 // C++2a [basic.def.odr]p4: 1986 // A variable x whose name appears as a potentially-evaluated expression e 1987 // is odr-used by e unless [...] x is a reference that is usable in 1988 // constant expressions. 1989 // CUDA/HIP: 1990 // If a reference variable referencing a host variable is captured in a 1991 // device or host device lambda, the value of the referee must be copied 1992 // to the capture and the reference variable must be treated as odr-use 1993 // since the value of the referee is not known at compile time and must 1994 // be loaded from the captured. 1995 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1996 if (VD->getType()->isReferenceType() && 1997 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1998 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 1999 VD->isUsableInConstantExpressions(Context)) 2000 return NOUR_Constant; 2001 } 2002 2003 // All remaining non-variable cases constitute an odr-use. For variables, we 2004 // need to wait and see how the expression is used. 2005 return NOUR_None; 2006 } 2007 2008 /// BuildDeclRefExpr - Build an expression that references a 2009 /// declaration that does not require a closure capture. 2010 DeclRefExpr * 2011 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2012 const DeclarationNameInfo &NameInfo, 2013 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2014 SourceLocation TemplateKWLoc, 2015 const TemplateArgumentListInfo *TemplateArgs) { 2016 bool RefersToCapturedVariable = 2017 isa<VarDecl>(D) && 2018 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2019 2020 DeclRefExpr *E = DeclRefExpr::Create( 2021 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2022 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2023 MarkDeclRefReferenced(E); 2024 2025 // C++ [except.spec]p17: 2026 // An exception-specification is considered to be needed when: 2027 // - in an expression, the function is the unique lookup result or 2028 // the selected member of a set of overloaded functions. 2029 // 2030 // We delay doing this until after we've built the function reference and 2031 // marked it as used so that: 2032 // a) if the function is defaulted, we get errors from defining it before / 2033 // instead of errors from computing its exception specification, and 2034 // b) if the function is a defaulted comparison, we can use the body we 2035 // build when defining it as input to the exception specification 2036 // computation rather than computing a new body. 2037 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2038 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2039 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2040 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2041 } 2042 } 2043 2044 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2045 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2046 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2047 getCurFunction()->recordUseOfWeak(E); 2048 2049 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2050 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2051 FD = IFD->getAnonField(); 2052 if (FD) { 2053 UnusedPrivateFields.remove(FD); 2054 // Just in case we're building an illegal pointer-to-member. 2055 if (FD->isBitField()) 2056 E->setObjectKind(OK_BitField); 2057 } 2058 2059 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2060 // designates a bit-field. 2061 if (auto *BD = dyn_cast<BindingDecl>(D)) 2062 if (auto *BE = BD->getBinding()) 2063 E->setObjectKind(BE->getObjectKind()); 2064 2065 return E; 2066 } 2067 2068 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2069 /// possibly a list of template arguments. 2070 /// 2071 /// If this produces template arguments, it is permitted to call 2072 /// DecomposeTemplateName. 2073 /// 2074 /// This actually loses a lot of source location information for 2075 /// non-standard name kinds; we should consider preserving that in 2076 /// some way. 2077 void 2078 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2079 TemplateArgumentListInfo &Buffer, 2080 DeclarationNameInfo &NameInfo, 2081 const TemplateArgumentListInfo *&TemplateArgs) { 2082 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2083 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2084 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2085 2086 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2087 Id.TemplateId->NumArgs); 2088 translateTemplateArguments(TemplateArgsPtr, Buffer); 2089 2090 TemplateName TName = Id.TemplateId->Template.get(); 2091 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2092 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2093 TemplateArgs = &Buffer; 2094 } else { 2095 NameInfo = GetNameFromUnqualifiedId(Id); 2096 TemplateArgs = nullptr; 2097 } 2098 } 2099 2100 static void emitEmptyLookupTypoDiagnostic( 2101 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2102 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2103 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2104 DeclContext *Ctx = 2105 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2106 if (!TC) { 2107 // Emit a special diagnostic for failed member lookups. 2108 // FIXME: computing the declaration context might fail here (?) 2109 if (Ctx) 2110 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2111 << SS.getRange(); 2112 else 2113 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2114 return; 2115 } 2116 2117 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2118 bool DroppedSpecifier = 2119 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2120 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2121 ? diag::note_implicit_param_decl 2122 : diag::note_previous_decl; 2123 if (!Ctx) 2124 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2125 SemaRef.PDiag(NoteID)); 2126 else 2127 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2128 << Typo << Ctx << DroppedSpecifier 2129 << SS.getRange(), 2130 SemaRef.PDiag(NoteID)); 2131 } 2132 2133 /// Diagnose a lookup that found results in an enclosing class during error 2134 /// recovery. This usually indicates that the results were found in a dependent 2135 /// base class that could not be searched as part of a template definition. 2136 /// Always issues a diagnostic (though this may be only a warning in MS 2137 /// compatibility mode). 2138 /// 2139 /// Return \c true if the error is unrecoverable, or \c false if the caller 2140 /// should attempt to recover using these lookup results. 2141 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2142 // During a default argument instantiation the CurContext points 2143 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2144 // function parameter list, hence add an explicit check. 2145 bool isDefaultArgument = 2146 !CodeSynthesisContexts.empty() && 2147 CodeSynthesisContexts.back().Kind == 2148 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2149 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2150 bool isInstance = CurMethod && CurMethod->isInstance() && 2151 R.getNamingClass() == CurMethod->getParent() && 2152 !isDefaultArgument; 2153 2154 // There are two ways we can find a class-scope declaration during template 2155 // instantiation that we did not find in the template definition: if it is a 2156 // member of a dependent base class, or if it is declared after the point of 2157 // use in the same class. Distinguish these by comparing the class in which 2158 // the member was found to the naming class of the lookup. 2159 unsigned DiagID = diag::err_found_in_dependent_base; 2160 unsigned NoteID = diag::note_member_declared_at; 2161 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2162 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2163 : diag::err_found_later_in_class; 2164 } else if (getLangOpts().MSVCCompat) { 2165 DiagID = diag::ext_found_in_dependent_base; 2166 NoteID = diag::note_dependent_member_use; 2167 } 2168 2169 if (isInstance) { 2170 // Give a code modification hint to insert 'this->'. 2171 Diag(R.getNameLoc(), DiagID) 2172 << R.getLookupName() 2173 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2174 CheckCXXThisCapture(R.getNameLoc()); 2175 } else { 2176 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2177 // they're not shadowed). 2178 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2179 } 2180 2181 for (NamedDecl *D : R) 2182 Diag(D->getLocation(), NoteID); 2183 2184 // Return true if we are inside a default argument instantiation 2185 // and the found name refers to an instance member function, otherwise 2186 // the caller will try to create an implicit member call and this is wrong 2187 // for default arguments. 2188 // 2189 // FIXME: Is this special case necessary? We could allow the caller to 2190 // diagnose this. 2191 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2192 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2193 return true; 2194 } 2195 2196 // Tell the callee to try to recover. 2197 return false; 2198 } 2199 2200 /// Diagnose an empty lookup. 2201 /// 2202 /// \return false if new lookup candidates were found 2203 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2204 CorrectionCandidateCallback &CCC, 2205 TemplateArgumentListInfo *ExplicitTemplateArgs, 2206 ArrayRef<Expr *> Args, TypoExpr **Out) { 2207 DeclarationName Name = R.getLookupName(); 2208 2209 unsigned diagnostic = diag::err_undeclared_var_use; 2210 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2211 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2212 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2213 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2214 diagnostic = diag::err_undeclared_use; 2215 diagnostic_suggest = diag::err_undeclared_use_suggest; 2216 } 2217 2218 // If the original lookup was an unqualified lookup, fake an 2219 // unqualified lookup. This is useful when (for example) the 2220 // original lookup would not have found something because it was a 2221 // dependent name. 2222 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2223 while (DC) { 2224 if (isa<CXXRecordDecl>(DC)) { 2225 LookupQualifiedName(R, DC); 2226 2227 if (!R.empty()) { 2228 // Don't give errors about ambiguities in this lookup. 2229 R.suppressDiagnostics(); 2230 2231 // If there's a best viable function among the results, only mention 2232 // that one in the notes. 2233 OverloadCandidateSet Candidates(R.getNameLoc(), 2234 OverloadCandidateSet::CSK_Normal); 2235 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2236 OverloadCandidateSet::iterator Best; 2237 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2238 OR_Success) { 2239 R.clear(); 2240 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2241 R.resolveKind(); 2242 } 2243 2244 return DiagnoseDependentMemberLookup(R); 2245 } 2246 2247 R.clear(); 2248 } 2249 2250 DC = DC->getLookupParent(); 2251 } 2252 2253 // We didn't find anything, so try to correct for a typo. 2254 TypoCorrection Corrected; 2255 if (S && Out) { 2256 SourceLocation TypoLoc = R.getNameLoc(); 2257 assert(!ExplicitTemplateArgs && 2258 "Diagnosing an empty lookup with explicit template args!"); 2259 *Out = CorrectTypoDelayed( 2260 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2261 [=](const TypoCorrection &TC) { 2262 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2263 diagnostic, diagnostic_suggest); 2264 }, 2265 nullptr, CTK_ErrorRecovery); 2266 if (*Out) 2267 return true; 2268 } else if (S && 2269 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2270 S, &SS, CCC, CTK_ErrorRecovery))) { 2271 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2272 bool DroppedSpecifier = 2273 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2274 R.setLookupName(Corrected.getCorrection()); 2275 2276 bool AcceptableWithRecovery = false; 2277 bool AcceptableWithoutRecovery = false; 2278 NamedDecl *ND = Corrected.getFoundDecl(); 2279 if (ND) { 2280 if (Corrected.isOverloaded()) { 2281 OverloadCandidateSet OCS(R.getNameLoc(), 2282 OverloadCandidateSet::CSK_Normal); 2283 OverloadCandidateSet::iterator Best; 2284 for (NamedDecl *CD : Corrected) { 2285 if (FunctionTemplateDecl *FTD = 2286 dyn_cast<FunctionTemplateDecl>(CD)) 2287 AddTemplateOverloadCandidate( 2288 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2289 Args, OCS); 2290 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2291 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2292 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2293 Args, OCS); 2294 } 2295 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2296 case OR_Success: 2297 ND = Best->FoundDecl; 2298 Corrected.setCorrectionDecl(ND); 2299 break; 2300 default: 2301 // FIXME: Arbitrarily pick the first declaration for the note. 2302 Corrected.setCorrectionDecl(ND); 2303 break; 2304 } 2305 } 2306 R.addDecl(ND); 2307 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2308 CXXRecordDecl *Record = nullptr; 2309 if (Corrected.getCorrectionSpecifier()) { 2310 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2311 Record = Ty->getAsCXXRecordDecl(); 2312 } 2313 if (!Record) 2314 Record = cast<CXXRecordDecl>( 2315 ND->getDeclContext()->getRedeclContext()); 2316 R.setNamingClass(Record); 2317 } 2318 2319 auto *UnderlyingND = ND->getUnderlyingDecl(); 2320 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2321 isa<FunctionTemplateDecl>(UnderlyingND); 2322 // FIXME: If we ended up with a typo for a type name or 2323 // Objective-C class name, we're in trouble because the parser 2324 // is in the wrong place to recover. Suggest the typo 2325 // correction, but don't make it a fix-it since we're not going 2326 // to recover well anyway. 2327 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2328 getAsTypeTemplateDecl(UnderlyingND) || 2329 isa<ObjCInterfaceDecl>(UnderlyingND); 2330 } else { 2331 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2332 // because we aren't able to recover. 2333 AcceptableWithoutRecovery = true; 2334 } 2335 2336 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2337 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2338 ? diag::note_implicit_param_decl 2339 : diag::note_previous_decl; 2340 if (SS.isEmpty()) 2341 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2342 PDiag(NoteID), AcceptableWithRecovery); 2343 else 2344 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2345 << Name << computeDeclContext(SS, false) 2346 << DroppedSpecifier << SS.getRange(), 2347 PDiag(NoteID), AcceptableWithRecovery); 2348 2349 // Tell the callee whether to try to recover. 2350 return !AcceptableWithRecovery; 2351 } 2352 } 2353 R.clear(); 2354 2355 // Emit a special diagnostic for failed member lookups. 2356 // FIXME: computing the declaration context might fail here (?) 2357 if (!SS.isEmpty()) { 2358 Diag(R.getNameLoc(), diag::err_no_member) 2359 << Name << computeDeclContext(SS, false) 2360 << SS.getRange(); 2361 return true; 2362 } 2363 2364 // Give up, we can't recover. 2365 Diag(R.getNameLoc(), diagnostic) << Name; 2366 return true; 2367 } 2368 2369 /// In Microsoft mode, if we are inside a template class whose parent class has 2370 /// dependent base classes, and we can't resolve an unqualified identifier, then 2371 /// assume the identifier is a member of a dependent base class. We can only 2372 /// recover successfully in static methods, instance methods, and other contexts 2373 /// where 'this' is available. This doesn't precisely match MSVC's 2374 /// instantiation model, but it's close enough. 2375 static Expr * 2376 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2377 DeclarationNameInfo &NameInfo, 2378 SourceLocation TemplateKWLoc, 2379 const TemplateArgumentListInfo *TemplateArgs) { 2380 // Only try to recover from lookup into dependent bases in static methods or 2381 // contexts where 'this' is available. 2382 QualType ThisType = S.getCurrentThisType(); 2383 const CXXRecordDecl *RD = nullptr; 2384 if (!ThisType.isNull()) 2385 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2386 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2387 RD = MD->getParent(); 2388 if (!RD || !RD->hasAnyDependentBases()) 2389 return nullptr; 2390 2391 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2392 // is available, suggest inserting 'this->' as a fixit. 2393 SourceLocation Loc = NameInfo.getLoc(); 2394 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2395 DB << NameInfo.getName() << RD; 2396 2397 if (!ThisType.isNull()) { 2398 DB << FixItHint::CreateInsertion(Loc, "this->"); 2399 return CXXDependentScopeMemberExpr::Create( 2400 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2401 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2402 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2403 } 2404 2405 // Synthesize a fake NNS that points to the derived class. This will 2406 // perform name lookup during template instantiation. 2407 CXXScopeSpec SS; 2408 auto *NNS = 2409 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2410 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2411 return DependentScopeDeclRefExpr::Create( 2412 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2413 TemplateArgs); 2414 } 2415 2416 ExprResult 2417 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2418 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2419 bool HasTrailingLParen, bool IsAddressOfOperand, 2420 CorrectionCandidateCallback *CCC, 2421 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2422 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2423 "cannot be direct & operand and have a trailing lparen"); 2424 if (SS.isInvalid()) 2425 return ExprError(); 2426 2427 TemplateArgumentListInfo TemplateArgsBuffer; 2428 2429 // Decompose the UnqualifiedId into the following data. 2430 DeclarationNameInfo NameInfo; 2431 const TemplateArgumentListInfo *TemplateArgs; 2432 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2433 2434 DeclarationName Name = NameInfo.getName(); 2435 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2436 SourceLocation NameLoc = NameInfo.getLoc(); 2437 2438 if (II && II->isEditorPlaceholder()) { 2439 // FIXME: When typed placeholders are supported we can create a typed 2440 // placeholder expression node. 2441 return ExprError(); 2442 } 2443 2444 // C++ [temp.dep.expr]p3: 2445 // An id-expression is type-dependent if it contains: 2446 // -- an identifier that was declared with a dependent type, 2447 // (note: handled after lookup) 2448 // -- a template-id that is dependent, 2449 // (note: handled in BuildTemplateIdExpr) 2450 // -- a conversion-function-id that specifies a dependent type, 2451 // -- a nested-name-specifier that contains a class-name that 2452 // names a dependent type. 2453 // Determine whether this is a member of an unknown specialization; 2454 // we need to handle these differently. 2455 bool DependentID = false; 2456 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2457 Name.getCXXNameType()->isDependentType()) { 2458 DependentID = true; 2459 } else if (SS.isSet()) { 2460 if (DeclContext *DC = computeDeclContext(SS, false)) { 2461 if (RequireCompleteDeclContext(SS, DC)) 2462 return ExprError(); 2463 } else { 2464 DependentID = true; 2465 } 2466 } 2467 2468 if (DependentID) 2469 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2470 IsAddressOfOperand, TemplateArgs); 2471 2472 // Perform the required lookup. 2473 LookupResult R(*this, NameInfo, 2474 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2475 ? LookupObjCImplicitSelfParam 2476 : LookupOrdinaryName); 2477 if (TemplateKWLoc.isValid() || TemplateArgs) { 2478 // Lookup the template name again to correctly establish the context in 2479 // which it was found. This is really unfortunate as we already did the 2480 // lookup to determine that it was a template name in the first place. If 2481 // this becomes a performance hit, we can work harder to preserve those 2482 // results until we get here but it's likely not worth it. 2483 bool MemberOfUnknownSpecialization; 2484 AssumedTemplateKind AssumedTemplate; 2485 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2486 MemberOfUnknownSpecialization, TemplateKWLoc, 2487 &AssumedTemplate)) 2488 return ExprError(); 2489 2490 if (MemberOfUnknownSpecialization || 2491 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2492 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2493 IsAddressOfOperand, TemplateArgs); 2494 } else { 2495 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2496 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2497 2498 // If the result might be in a dependent base class, this is a dependent 2499 // id-expression. 2500 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2501 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2502 IsAddressOfOperand, TemplateArgs); 2503 2504 // If this reference is in an Objective-C method, then we need to do 2505 // some special Objective-C lookup, too. 2506 if (IvarLookupFollowUp) { 2507 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2508 if (E.isInvalid()) 2509 return ExprError(); 2510 2511 if (Expr *Ex = E.getAs<Expr>()) 2512 return Ex; 2513 } 2514 } 2515 2516 if (R.isAmbiguous()) 2517 return ExprError(); 2518 2519 // This could be an implicitly declared function reference (legal in C90, 2520 // extension in C99, forbidden in C++). 2521 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2522 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2523 if (D) R.addDecl(D); 2524 } 2525 2526 // Determine whether this name might be a candidate for 2527 // argument-dependent lookup. 2528 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2529 2530 if (R.empty() && !ADL) { 2531 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2532 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2533 TemplateKWLoc, TemplateArgs)) 2534 return E; 2535 } 2536 2537 // Don't diagnose an empty lookup for inline assembly. 2538 if (IsInlineAsmIdentifier) 2539 return ExprError(); 2540 2541 // If this name wasn't predeclared and if this is not a function 2542 // call, diagnose the problem. 2543 TypoExpr *TE = nullptr; 2544 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2545 : nullptr); 2546 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2547 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2548 "Typo correction callback misconfigured"); 2549 if (CCC) { 2550 // Make sure the callback knows what the typo being diagnosed is. 2551 CCC->setTypoName(II); 2552 if (SS.isValid()) 2553 CCC->setTypoNNS(SS.getScopeRep()); 2554 } 2555 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2556 // a template name, but we happen to have always already looked up the name 2557 // before we get here if it must be a template name. 2558 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2559 None, &TE)) { 2560 if (TE && KeywordReplacement) { 2561 auto &State = getTypoExprState(TE); 2562 auto BestTC = State.Consumer->getNextCorrection(); 2563 if (BestTC.isKeyword()) { 2564 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2565 if (State.DiagHandler) 2566 State.DiagHandler(BestTC); 2567 KeywordReplacement->startToken(); 2568 KeywordReplacement->setKind(II->getTokenID()); 2569 KeywordReplacement->setIdentifierInfo(II); 2570 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2571 // Clean up the state associated with the TypoExpr, since it has 2572 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2573 clearDelayedTypo(TE); 2574 // Signal that a correction to a keyword was performed by returning a 2575 // valid-but-null ExprResult. 2576 return (Expr*)nullptr; 2577 } 2578 State.Consumer->resetCorrectionStream(); 2579 } 2580 return TE ? TE : ExprError(); 2581 } 2582 2583 assert(!R.empty() && 2584 "DiagnoseEmptyLookup returned false but added no results"); 2585 2586 // If we found an Objective-C instance variable, let 2587 // LookupInObjCMethod build the appropriate expression to 2588 // reference the ivar. 2589 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2590 R.clear(); 2591 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2592 // In a hopelessly buggy code, Objective-C instance variable 2593 // lookup fails and no expression will be built to reference it. 2594 if (!E.isInvalid() && !E.get()) 2595 return ExprError(); 2596 return E; 2597 } 2598 } 2599 2600 // This is guaranteed from this point on. 2601 assert(!R.empty() || ADL); 2602 2603 // Check whether this might be a C++ implicit instance member access. 2604 // C++ [class.mfct.non-static]p3: 2605 // When an id-expression that is not part of a class member access 2606 // syntax and not used to form a pointer to member is used in the 2607 // body of a non-static member function of class X, if name lookup 2608 // resolves the name in the id-expression to a non-static non-type 2609 // member of some class C, the id-expression is transformed into a 2610 // class member access expression using (*this) as the 2611 // postfix-expression to the left of the . operator. 2612 // 2613 // But we don't actually need to do this for '&' operands if R 2614 // resolved to a function or overloaded function set, because the 2615 // expression is ill-formed if it actually works out to be a 2616 // non-static member function: 2617 // 2618 // C++ [expr.ref]p4: 2619 // Otherwise, if E1.E2 refers to a non-static member function. . . 2620 // [t]he expression can be used only as the left-hand operand of a 2621 // member function call. 2622 // 2623 // There are other safeguards against such uses, but it's important 2624 // to get this right here so that we don't end up making a 2625 // spuriously dependent expression if we're inside a dependent 2626 // instance method. 2627 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2628 bool MightBeImplicitMember; 2629 if (!IsAddressOfOperand) 2630 MightBeImplicitMember = true; 2631 else if (!SS.isEmpty()) 2632 MightBeImplicitMember = false; 2633 else if (R.isOverloadedResult()) 2634 MightBeImplicitMember = false; 2635 else if (R.isUnresolvableResult()) 2636 MightBeImplicitMember = true; 2637 else 2638 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2639 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2640 isa<MSPropertyDecl>(R.getFoundDecl()); 2641 2642 if (MightBeImplicitMember) 2643 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2644 R, TemplateArgs, S); 2645 } 2646 2647 if (TemplateArgs || TemplateKWLoc.isValid()) { 2648 2649 // In C++1y, if this is a variable template id, then check it 2650 // in BuildTemplateIdExpr(). 2651 // The single lookup result must be a variable template declaration. 2652 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2653 Id.TemplateId->Kind == TNK_Var_template) { 2654 assert(R.getAsSingle<VarTemplateDecl>() && 2655 "There should only be one declaration found."); 2656 } 2657 2658 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2659 } 2660 2661 return BuildDeclarationNameExpr(SS, R, ADL); 2662 } 2663 2664 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2665 /// declaration name, generally during template instantiation. 2666 /// There's a large number of things which don't need to be done along 2667 /// this path. 2668 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2669 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2670 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2671 DeclContext *DC = computeDeclContext(SS, false); 2672 if (!DC) 2673 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2674 NameInfo, /*TemplateArgs=*/nullptr); 2675 2676 if (RequireCompleteDeclContext(SS, DC)) 2677 return ExprError(); 2678 2679 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2680 LookupQualifiedName(R, DC); 2681 2682 if (R.isAmbiguous()) 2683 return ExprError(); 2684 2685 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2686 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2687 NameInfo, /*TemplateArgs=*/nullptr); 2688 2689 if (R.empty()) { 2690 // Don't diagnose problems with invalid record decl, the secondary no_member 2691 // diagnostic during template instantiation is likely bogus, e.g. if a class 2692 // is invalid because it's derived from an invalid base class, then missing 2693 // members were likely supposed to be inherited. 2694 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2695 if (CD->isInvalidDecl()) 2696 return ExprError(); 2697 Diag(NameInfo.getLoc(), diag::err_no_member) 2698 << NameInfo.getName() << DC << SS.getRange(); 2699 return ExprError(); 2700 } 2701 2702 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2703 // Diagnose a missing typename if this resolved unambiguously to a type in 2704 // a dependent context. If we can recover with a type, downgrade this to 2705 // a warning in Microsoft compatibility mode. 2706 unsigned DiagID = diag::err_typename_missing; 2707 if (RecoveryTSI && getLangOpts().MSVCCompat) 2708 DiagID = diag::ext_typename_missing; 2709 SourceLocation Loc = SS.getBeginLoc(); 2710 auto D = Diag(Loc, DiagID); 2711 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2712 << SourceRange(Loc, NameInfo.getEndLoc()); 2713 2714 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2715 // context. 2716 if (!RecoveryTSI) 2717 return ExprError(); 2718 2719 // Only issue the fixit if we're prepared to recover. 2720 D << FixItHint::CreateInsertion(Loc, "typename "); 2721 2722 // Recover by pretending this was an elaborated type. 2723 QualType Ty = Context.getTypeDeclType(TD); 2724 TypeLocBuilder TLB; 2725 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2726 2727 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2728 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2729 QTL.setElaboratedKeywordLoc(SourceLocation()); 2730 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2731 2732 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2733 2734 return ExprEmpty(); 2735 } 2736 2737 // Defend against this resolving to an implicit member access. We usually 2738 // won't get here if this might be a legitimate a class member (we end up in 2739 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2740 // a pointer-to-member or in an unevaluated context in C++11. 2741 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2742 return BuildPossibleImplicitMemberExpr(SS, 2743 /*TemplateKWLoc=*/SourceLocation(), 2744 R, /*TemplateArgs=*/nullptr, S); 2745 2746 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2747 } 2748 2749 /// The parser has read a name in, and Sema has detected that we're currently 2750 /// inside an ObjC method. Perform some additional checks and determine if we 2751 /// should form a reference to an ivar. 2752 /// 2753 /// Ideally, most of this would be done by lookup, but there's 2754 /// actually quite a lot of extra work involved. 2755 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2756 IdentifierInfo *II) { 2757 SourceLocation Loc = Lookup.getNameLoc(); 2758 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2759 2760 // Check for error condition which is already reported. 2761 if (!CurMethod) 2762 return DeclResult(true); 2763 2764 // There are two cases to handle here. 1) scoped lookup could have failed, 2765 // in which case we should look for an ivar. 2) scoped lookup could have 2766 // found a decl, but that decl is outside the current instance method (i.e. 2767 // a global variable). In these two cases, we do a lookup for an ivar with 2768 // this name, if the lookup sucedes, we replace it our current decl. 2769 2770 // If we're in a class method, we don't normally want to look for 2771 // ivars. But if we don't find anything else, and there's an 2772 // ivar, that's an error. 2773 bool IsClassMethod = CurMethod->isClassMethod(); 2774 2775 bool LookForIvars; 2776 if (Lookup.empty()) 2777 LookForIvars = true; 2778 else if (IsClassMethod) 2779 LookForIvars = false; 2780 else 2781 LookForIvars = (Lookup.isSingleResult() && 2782 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2783 ObjCInterfaceDecl *IFace = nullptr; 2784 if (LookForIvars) { 2785 IFace = CurMethod->getClassInterface(); 2786 ObjCInterfaceDecl *ClassDeclared; 2787 ObjCIvarDecl *IV = nullptr; 2788 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2789 // Diagnose using an ivar in a class method. 2790 if (IsClassMethod) { 2791 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2792 return DeclResult(true); 2793 } 2794 2795 // Diagnose the use of an ivar outside of the declaring class. 2796 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2797 !declaresSameEntity(ClassDeclared, IFace) && 2798 !getLangOpts().DebuggerSupport) 2799 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2800 2801 // Success. 2802 return IV; 2803 } 2804 } else if (CurMethod->isInstanceMethod()) { 2805 // We should warn if a local variable hides an ivar. 2806 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2807 ObjCInterfaceDecl *ClassDeclared; 2808 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2809 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2810 declaresSameEntity(IFace, ClassDeclared)) 2811 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2812 } 2813 } 2814 } else if (Lookup.isSingleResult() && 2815 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2816 // If accessing a stand-alone ivar in a class method, this is an error. 2817 if (const ObjCIvarDecl *IV = 2818 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2819 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2820 return DeclResult(true); 2821 } 2822 } 2823 2824 // Didn't encounter an error, didn't find an ivar. 2825 return DeclResult(false); 2826 } 2827 2828 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2829 ObjCIvarDecl *IV) { 2830 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2831 assert(CurMethod && CurMethod->isInstanceMethod() && 2832 "should not reference ivar from this context"); 2833 2834 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2835 assert(IFace && "should not reference ivar from this context"); 2836 2837 // If we're referencing an invalid decl, just return this as a silent 2838 // error node. The error diagnostic was already emitted on the decl. 2839 if (IV->isInvalidDecl()) 2840 return ExprError(); 2841 2842 // Check if referencing a field with __attribute__((deprecated)). 2843 if (DiagnoseUseOfDecl(IV, Loc)) 2844 return ExprError(); 2845 2846 // FIXME: This should use a new expr for a direct reference, don't 2847 // turn this into Self->ivar, just return a BareIVarExpr or something. 2848 IdentifierInfo &II = Context.Idents.get("self"); 2849 UnqualifiedId SelfName; 2850 SelfName.setImplicitSelfParam(&II); 2851 CXXScopeSpec SelfScopeSpec; 2852 SourceLocation TemplateKWLoc; 2853 ExprResult SelfExpr = 2854 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2855 /*HasTrailingLParen=*/false, 2856 /*IsAddressOfOperand=*/false); 2857 if (SelfExpr.isInvalid()) 2858 return ExprError(); 2859 2860 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2861 if (SelfExpr.isInvalid()) 2862 return ExprError(); 2863 2864 MarkAnyDeclReferenced(Loc, IV, true); 2865 2866 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2867 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2868 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2869 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2870 2871 ObjCIvarRefExpr *Result = new (Context) 2872 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2873 IV->getLocation(), SelfExpr.get(), true, true); 2874 2875 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2876 if (!isUnevaluatedContext() && 2877 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2878 getCurFunction()->recordUseOfWeak(Result); 2879 } 2880 if (getLangOpts().ObjCAutoRefCount) 2881 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2882 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2883 2884 return Result; 2885 } 2886 2887 /// The parser has read a name in, and Sema has detected that we're currently 2888 /// inside an ObjC method. Perform some additional checks and determine if we 2889 /// should form a reference to an ivar. If so, build an expression referencing 2890 /// that ivar. 2891 ExprResult 2892 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2893 IdentifierInfo *II, bool AllowBuiltinCreation) { 2894 // FIXME: Integrate this lookup step into LookupParsedName. 2895 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2896 if (Ivar.isInvalid()) 2897 return ExprError(); 2898 if (Ivar.isUsable()) 2899 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2900 cast<ObjCIvarDecl>(Ivar.get())); 2901 2902 if (Lookup.empty() && II && AllowBuiltinCreation) 2903 LookupBuiltin(Lookup); 2904 2905 // Sentinel value saying that we didn't do anything special. 2906 return ExprResult(false); 2907 } 2908 2909 /// Cast a base object to a member's actual type. 2910 /// 2911 /// There are two relevant checks: 2912 /// 2913 /// C++ [class.access.base]p7: 2914 /// 2915 /// If a class member access operator [...] is used to access a non-static 2916 /// data member or non-static member function, the reference is ill-formed if 2917 /// the left operand [...] cannot be implicitly converted to a pointer to the 2918 /// naming class of the right operand. 2919 /// 2920 /// C++ [expr.ref]p7: 2921 /// 2922 /// If E2 is a non-static data member or a non-static member function, the 2923 /// program is ill-formed if the class of which E2 is directly a member is an 2924 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2925 /// 2926 /// Note that the latter check does not consider access; the access of the 2927 /// "real" base class is checked as appropriate when checking the access of the 2928 /// member name. 2929 ExprResult 2930 Sema::PerformObjectMemberConversion(Expr *From, 2931 NestedNameSpecifier *Qualifier, 2932 NamedDecl *FoundDecl, 2933 NamedDecl *Member) { 2934 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2935 if (!RD) 2936 return From; 2937 2938 QualType DestRecordType; 2939 QualType DestType; 2940 QualType FromRecordType; 2941 QualType FromType = From->getType(); 2942 bool PointerConversions = false; 2943 if (isa<FieldDecl>(Member)) { 2944 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2945 auto FromPtrType = FromType->getAs<PointerType>(); 2946 DestRecordType = Context.getAddrSpaceQualType( 2947 DestRecordType, FromPtrType 2948 ? FromType->getPointeeType().getAddressSpace() 2949 : FromType.getAddressSpace()); 2950 2951 if (FromPtrType) { 2952 DestType = Context.getPointerType(DestRecordType); 2953 FromRecordType = FromPtrType->getPointeeType(); 2954 PointerConversions = true; 2955 } else { 2956 DestType = DestRecordType; 2957 FromRecordType = FromType; 2958 } 2959 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2960 if (Method->isStatic()) 2961 return From; 2962 2963 DestType = Method->getThisType(); 2964 DestRecordType = DestType->getPointeeType(); 2965 2966 if (FromType->getAs<PointerType>()) { 2967 FromRecordType = FromType->getPointeeType(); 2968 PointerConversions = true; 2969 } else { 2970 FromRecordType = FromType; 2971 DestType = DestRecordType; 2972 } 2973 2974 LangAS FromAS = FromRecordType.getAddressSpace(); 2975 LangAS DestAS = DestRecordType.getAddressSpace(); 2976 if (FromAS != DestAS) { 2977 QualType FromRecordTypeWithoutAS = 2978 Context.removeAddrSpaceQualType(FromRecordType); 2979 QualType FromTypeWithDestAS = 2980 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2981 if (PointerConversions) 2982 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2983 From = ImpCastExprToType(From, FromTypeWithDestAS, 2984 CK_AddressSpaceConversion, From->getValueKind()) 2985 .get(); 2986 } 2987 } else { 2988 // No conversion necessary. 2989 return From; 2990 } 2991 2992 if (DestType->isDependentType() || FromType->isDependentType()) 2993 return From; 2994 2995 // If the unqualified types are the same, no conversion is necessary. 2996 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2997 return From; 2998 2999 SourceRange FromRange = From->getSourceRange(); 3000 SourceLocation FromLoc = FromRange.getBegin(); 3001 3002 ExprValueKind VK = From->getValueKind(); 3003 3004 // C++ [class.member.lookup]p8: 3005 // [...] Ambiguities can often be resolved by qualifying a name with its 3006 // class name. 3007 // 3008 // If the member was a qualified name and the qualified referred to a 3009 // specific base subobject type, we'll cast to that intermediate type 3010 // first and then to the object in which the member is declared. That allows 3011 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3012 // 3013 // class Base { public: int x; }; 3014 // class Derived1 : public Base { }; 3015 // class Derived2 : public Base { }; 3016 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3017 // 3018 // void VeryDerived::f() { 3019 // x = 17; // error: ambiguous base subobjects 3020 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3021 // } 3022 if (Qualifier && Qualifier->getAsType()) { 3023 QualType QType = QualType(Qualifier->getAsType(), 0); 3024 assert(QType->isRecordType() && "lookup done with non-record type"); 3025 3026 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3027 3028 // In C++98, the qualifier type doesn't actually have to be a base 3029 // type of the object type, in which case we just ignore it. 3030 // Otherwise build the appropriate casts. 3031 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3032 CXXCastPath BasePath; 3033 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3034 FromLoc, FromRange, &BasePath)) 3035 return ExprError(); 3036 3037 if (PointerConversions) 3038 QType = Context.getPointerType(QType); 3039 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3040 VK, &BasePath).get(); 3041 3042 FromType = QType; 3043 FromRecordType = QRecordType; 3044 3045 // If the qualifier type was the same as the destination type, 3046 // we're done. 3047 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3048 return From; 3049 } 3050 } 3051 3052 CXXCastPath BasePath; 3053 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3054 FromLoc, FromRange, &BasePath, 3055 /*IgnoreAccess=*/true)) 3056 return ExprError(); 3057 3058 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3059 VK, &BasePath); 3060 } 3061 3062 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3063 const LookupResult &R, 3064 bool HasTrailingLParen) { 3065 // Only when used directly as the postfix-expression of a call. 3066 if (!HasTrailingLParen) 3067 return false; 3068 3069 // Never if a scope specifier was provided. 3070 if (SS.isSet()) 3071 return false; 3072 3073 // Only in C++ or ObjC++. 3074 if (!getLangOpts().CPlusPlus) 3075 return false; 3076 3077 // Turn off ADL when we find certain kinds of declarations during 3078 // normal lookup: 3079 for (NamedDecl *D : R) { 3080 // C++0x [basic.lookup.argdep]p3: 3081 // -- a declaration of a class member 3082 // Since using decls preserve this property, we check this on the 3083 // original decl. 3084 if (D->isCXXClassMember()) 3085 return false; 3086 3087 // C++0x [basic.lookup.argdep]p3: 3088 // -- a block-scope function declaration that is not a 3089 // using-declaration 3090 // NOTE: we also trigger this for function templates (in fact, we 3091 // don't check the decl type at all, since all other decl types 3092 // turn off ADL anyway). 3093 if (isa<UsingShadowDecl>(D)) 3094 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3095 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3096 return false; 3097 3098 // C++0x [basic.lookup.argdep]p3: 3099 // -- a declaration that is neither a function or a function 3100 // template 3101 // And also for builtin functions. 3102 if (isa<FunctionDecl>(D)) { 3103 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3104 3105 // But also builtin functions. 3106 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3107 return false; 3108 } else if (!isa<FunctionTemplateDecl>(D)) 3109 return false; 3110 } 3111 3112 return true; 3113 } 3114 3115 3116 /// Diagnoses obvious problems with the use of the given declaration 3117 /// as an expression. This is only actually called for lookups that 3118 /// were not overloaded, and it doesn't promise that the declaration 3119 /// will in fact be used. 3120 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3121 if (D->isInvalidDecl()) 3122 return true; 3123 3124 if (isa<TypedefNameDecl>(D)) { 3125 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3126 return true; 3127 } 3128 3129 if (isa<ObjCInterfaceDecl>(D)) { 3130 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3131 return true; 3132 } 3133 3134 if (isa<NamespaceDecl>(D)) { 3135 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3136 return true; 3137 } 3138 3139 return false; 3140 } 3141 3142 // Certain multiversion types should be treated as overloaded even when there is 3143 // only one result. 3144 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3145 assert(R.isSingleResult() && "Expected only a single result"); 3146 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3147 return FD && 3148 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3149 } 3150 3151 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3152 LookupResult &R, bool NeedsADL, 3153 bool AcceptInvalidDecl) { 3154 // If this is a single, fully-resolved result and we don't need ADL, 3155 // just build an ordinary singleton decl ref. 3156 if (!NeedsADL && R.isSingleResult() && 3157 !R.getAsSingle<FunctionTemplateDecl>() && 3158 !ShouldLookupResultBeMultiVersionOverload(R)) 3159 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3160 R.getRepresentativeDecl(), nullptr, 3161 AcceptInvalidDecl); 3162 3163 // We only need to check the declaration if there's exactly one 3164 // result, because in the overloaded case the results can only be 3165 // functions and function templates. 3166 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3167 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3168 return ExprError(); 3169 3170 // Otherwise, just build an unresolved lookup expression. Suppress 3171 // any lookup-related diagnostics; we'll hash these out later, when 3172 // we've picked a target. 3173 R.suppressDiagnostics(); 3174 3175 UnresolvedLookupExpr *ULE 3176 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3177 SS.getWithLocInContext(Context), 3178 R.getLookupNameInfo(), 3179 NeedsADL, R.isOverloadedResult(), 3180 R.begin(), R.end()); 3181 3182 return ULE; 3183 } 3184 3185 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3186 ValueDecl *var); 3187 3188 /// Complete semantic analysis for a reference to the given declaration. 3189 ExprResult Sema::BuildDeclarationNameExpr( 3190 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3191 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3192 bool AcceptInvalidDecl) { 3193 assert(D && "Cannot refer to a NULL declaration"); 3194 assert(!isa<FunctionTemplateDecl>(D) && 3195 "Cannot refer unambiguously to a function template"); 3196 3197 SourceLocation Loc = NameInfo.getLoc(); 3198 if (CheckDeclInExpr(*this, Loc, D)) 3199 return ExprError(); 3200 3201 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3202 // Specifically diagnose references to class templates that are missing 3203 // a template argument list. 3204 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3205 return ExprError(); 3206 } 3207 3208 // Make sure that we're referring to a value. 3209 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3210 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3211 Diag(D->getLocation(), diag::note_declared_at); 3212 return ExprError(); 3213 } 3214 3215 // Check whether this declaration can be used. Note that we suppress 3216 // this check when we're going to perform argument-dependent lookup 3217 // on this function name, because this might not be the function 3218 // that overload resolution actually selects. 3219 if (DiagnoseUseOfDecl(D, Loc)) 3220 return ExprError(); 3221 3222 auto *VD = cast<ValueDecl>(D); 3223 3224 // Only create DeclRefExpr's for valid Decl's. 3225 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3226 return ExprError(); 3227 3228 // Handle members of anonymous structs and unions. If we got here, 3229 // and the reference is to a class member indirect field, then this 3230 // must be the subject of a pointer-to-member expression. 3231 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3232 if (!indirectField->isCXXClassMember()) 3233 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3234 indirectField); 3235 3236 QualType type = VD->getType(); 3237 if (type.isNull()) 3238 return ExprError(); 3239 ExprValueKind valueKind = VK_PRValue; 3240 3241 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3242 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3243 // is expanded by some outer '...' in the context of the use. 3244 type = type.getNonPackExpansionType(); 3245 3246 switch (D->getKind()) { 3247 // Ignore all the non-ValueDecl kinds. 3248 #define ABSTRACT_DECL(kind) 3249 #define VALUE(type, base) 3250 #define DECL(type, base) case Decl::type: 3251 #include "clang/AST/DeclNodes.inc" 3252 llvm_unreachable("invalid value decl kind"); 3253 3254 // These shouldn't make it here. 3255 case Decl::ObjCAtDefsField: 3256 llvm_unreachable("forming non-member reference to ivar?"); 3257 3258 // Enum constants are always r-values and never references. 3259 // Unresolved using declarations are dependent. 3260 case Decl::EnumConstant: 3261 case Decl::UnresolvedUsingValue: 3262 case Decl::OMPDeclareReduction: 3263 case Decl::OMPDeclareMapper: 3264 valueKind = VK_PRValue; 3265 break; 3266 3267 // Fields and indirect fields that got here must be for 3268 // pointer-to-member expressions; we just call them l-values for 3269 // internal consistency, because this subexpression doesn't really 3270 // exist in the high-level semantics. 3271 case Decl::Field: 3272 case Decl::IndirectField: 3273 case Decl::ObjCIvar: 3274 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3275 3276 // These can't have reference type in well-formed programs, but 3277 // for internal consistency we do this anyway. 3278 type = type.getNonReferenceType(); 3279 valueKind = VK_LValue; 3280 break; 3281 3282 // Non-type template parameters are either l-values or r-values 3283 // depending on the type. 3284 case Decl::NonTypeTemplateParm: { 3285 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3286 type = reftype->getPointeeType(); 3287 valueKind = VK_LValue; // even if the parameter is an r-value reference 3288 break; 3289 } 3290 3291 // [expr.prim.id.unqual]p2: 3292 // If the entity is a template parameter object for a template 3293 // parameter of type T, the type of the expression is const T. 3294 // [...] The expression is an lvalue if the entity is a [...] template 3295 // parameter object. 3296 if (type->isRecordType()) { 3297 type = type.getUnqualifiedType().withConst(); 3298 valueKind = VK_LValue; 3299 break; 3300 } 3301 3302 // For non-references, we need to strip qualifiers just in case 3303 // the template parameter was declared as 'const int' or whatever. 3304 valueKind = VK_PRValue; 3305 type = type.getUnqualifiedType(); 3306 break; 3307 } 3308 3309 case Decl::Var: 3310 case Decl::VarTemplateSpecialization: 3311 case Decl::VarTemplatePartialSpecialization: 3312 case Decl::Decomposition: 3313 case Decl::OMPCapturedExpr: 3314 // In C, "extern void blah;" is valid and is an r-value. 3315 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3316 type->isVoidType()) { 3317 valueKind = VK_PRValue; 3318 break; 3319 } 3320 LLVM_FALLTHROUGH; 3321 3322 case Decl::ImplicitParam: 3323 case Decl::ParmVar: { 3324 // These are always l-values. 3325 valueKind = VK_LValue; 3326 type = type.getNonReferenceType(); 3327 3328 // FIXME: Does the addition of const really only apply in 3329 // potentially-evaluated contexts? Since the variable isn't actually 3330 // captured in an unevaluated context, it seems that the answer is no. 3331 if (!isUnevaluatedContext()) { 3332 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3333 if (!CapturedType.isNull()) 3334 type = CapturedType; 3335 } 3336 3337 break; 3338 } 3339 3340 case Decl::Binding: { 3341 // These are always lvalues. 3342 valueKind = VK_LValue; 3343 type = type.getNonReferenceType(); 3344 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3345 // decides how that's supposed to work. 3346 auto *BD = cast<BindingDecl>(VD); 3347 if (BD->getDeclContext() != CurContext) { 3348 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3349 if (DD && DD->hasLocalStorage()) 3350 diagnoseUncapturableValueReference(*this, Loc, BD); 3351 } 3352 break; 3353 } 3354 3355 case Decl::Function: { 3356 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3357 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3358 type = Context.BuiltinFnTy; 3359 valueKind = VK_PRValue; 3360 break; 3361 } 3362 } 3363 3364 const FunctionType *fty = type->castAs<FunctionType>(); 3365 3366 // If we're referring to a function with an __unknown_anytype 3367 // result type, make the entire expression __unknown_anytype. 3368 if (fty->getReturnType() == Context.UnknownAnyTy) { 3369 type = Context.UnknownAnyTy; 3370 valueKind = VK_PRValue; 3371 break; 3372 } 3373 3374 // Functions are l-values in C++. 3375 if (getLangOpts().CPlusPlus) { 3376 valueKind = VK_LValue; 3377 break; 3378 } 3379 3380 // C99 DR 316 says that, if a function type comes from a 3381 // function definition (without a prototype), that type is only 3382 // used for checking compatibility. Therefore, when referencing 3383 // the function, we pretend that we don't have the full function 3384 // type. 3385 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3386 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3387 fty->getExtInfo()); 3388 3389 // Functions are r-values in C. 3390 valueKind = VK_PRValue; 3391 break; 3392 } 3393 3394 case Decl::CXXDeductionGuide: 3395 llvm_unreachable("building reference to deduction guide"); 3396 3397 case Decl::MSProperty: 3398 case Decl::MSGuid: 3399 case Decl::TemplateParamObject: 3400 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3401 // capture in OpenMP, or duplicated between host and device? 3402 valueKind = VK_LValue; 3403 break; 3404 3405 case Decl::CXXMethod: 3406 // If we're referring to a method with an __unknown_anytype 3407 // result type, make the entire expression __unknown_anytype. 3408 // This should only be possible with a type written directly. 3409 if (const FunctionProtoType *proto = 3410 dyn_cast<FunctionProtoType>(VD->getType())) 3411 if (proto->getReturnType() == Context.UnknownAnyTy) { 3412 type = Context.UnknownAnyTy; 3413 valueKind = VK_PRValue; 3414 break; 3415 } 3416 3417 // C++ methods are l-values if static, r-values if non-static. 3418 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3419 valueKind = VK_LValue; 3420 break; 3421 } 3422 LLVM_FALLTHROUGH; 3423 3424 case Decl::CXXConversion: 3425 case Decl::CXXDestructor: 3426 case Decl::CXXConstructor: 3427 valueKind = VK_PRValue; 3428 break; 3429 } 3430 3431 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3432 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3433 TemplateArgs); 3434 } 3435 3436 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3437 SmallString<32> &Target) { 3438 Target.resize(CharByteWidth * (Source.size() + 1)); 3439 char *ResultPtr = &Target[0]; 3440 const llvm::UTF8 *ErrorPtr; 3441 bool success = 3442 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3443 (void)success; 3444 assert(success); 3445 Target.resize(ResultPtr - &Target[0]); 3446 } 3447 3448 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3449 PredefinedExpr::IdentKind IK) { 3450 // Pick the current block, lambda, captured statement or function. 3451 Decl *currentDecl = nullptr; 3452 if (const BlockScopeInfo *BSI = getCurBlock()) 3453 currentDecl = BSI->TheDecl; 3454 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3455 currentDecl = LSI->CallOperator; 3456 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3457 currentDecl = CSI->TheCapturedDecl; 3458 else 3459 currentDecl = getCurFunctionOrMethodDecl(); 3460 3461 if (!currentDecl) { 3462 Diag(Loc, diag::ext_predef_outside_function); 3463 currentDecl = Context.getTranslationUnitDecl(); 3464 } 3465 3466 QualType ResTy; 3467 StringLiteral *SL = nullptr; 3468 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3469 ResTy = Context.DependentTy; 3470 else { 3471 // Pre-defined identifiers are of type char[x], where x is the length of 3472 // the string. 3473 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3474 unsigned Length = Str.length(); 3475 3476 llvm::APInt LengthI(32, Length + 1); 3477 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3478 ResTy = 3479 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3480 SmallString<32> RawChars; 3481 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3482 Str, RawChars); 3483 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3484 ArrayType::Normal, 3485 /*IndexTypeQuals*/ 0); 3486 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3487 /*Pascal*/ false, ResTy, Loc); 3488 } else { 3489 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3490 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3491 ArrayType::Normal, 3492 /*IndexTypeQuals*/ 0); 3493 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3494 /*Pascal*/ false, ResTy, Loc); 3495 } 3496 } 3497 3498 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3499 } 3500 3501 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3502 SourceLocation LParen, 3503 SourceLocation RParen, 3504 TypeSourceInfo *TSI) { 3505 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3506 } 3507 3508 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3509 SourceLocation LParen, 3510 SourceLocation RParen, 3511 ParsedType ParsedTy) { 3512 TypeSourceInfo *TSI = nullptr; 3513 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3514 3515 if (Ty.isNull()) 3516 return ExprError(); 3517 if (!TSI) 3518 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3519 3520 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3521 } 3522 3523 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3524 PredefinedExpr::IdentKind IK; 3525 3526 switch (Kind) { 3527 default: llvm_unreachable("Unknown simple primary expr!"); 3528 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3529 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3530 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3531 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3532 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3533 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3534 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3535 } 3536 3537 return BuildPredefinedExpr(Loc, IK); 3538 } 3539 3540 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3541 SmallString<16> CharBuffer; 3542 bool Invalid = false; 3543 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3544 if (Invalid) 3545 return ExprError(); 3546 3547 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3548 PP, Tok.getKind()); 3549 if (Literal.hadError()) 3550 return ExprError(); 3551 3552 QualType Ty; 3553 if (Literal.isWide()) 3554 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3555 else if (Literal.isUTF8() && getLangOpts().Char8) 3556 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3557 else if (Literal.isUTF16()) 3558 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3559 else if (Literal.isUTF32()) 3560 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3561 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3562 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3563 else 3564 Ty = Context.CharTy; // 'x' -> char in C++ 3565 3566 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3567 if (Literal.isWide()) 3568 Kind = CharacterLiteral::Wide; 3569 else if (Literal.isUTF16()) 3570 Kind = CharacterLiteral::UTF16; 3571 else if (Literal.isUTF32()) 3572 Kind = CharacterLiteral::UTF32; 3573 else if (Literal.isUTF8()) 3574 Kind = CharacterLiteral::UTF8; 3575 3576 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3577 Tok.getLocation()); 3578 3579 if (Literal.getUDSuffix().empty()) 3580 return Lit; 3581 3582 // We're building a user-defined literal. 3583 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3584 SourceLocation UDSuffixLoc = 3585 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3586 3587 // Make sure we're allowed user-defined literals here. 3588 if (!UDLScope) 3589 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3590 3591 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3592 // operator "" X (ch) 3593 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3594 Lit, Tok.getLocation()); 3595 } 3596 3597 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3598 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3599 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3600 Context.IntTy, Loc); 3601 } 3602 3603 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3604 QualType Ty, SourceLocation Loc) { 3605 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3606 3607 using llvm::APFloat; 3608 APFloat Val(Format); 3609 3610 APFloat::opStatus result = Literal.GetFloatValue(Val); 3611 3612 // Overflow is always an error, but underflow is only an error if 3613 // we underflowed to zero (APFloat reports denormals as underflow). 3614 if ((result & APFloat::opOverflow) || 3615 ((result & APFloat::opUnderflow) && Val.isZero())) { 3616 unsigned diagnostic; 3617 SmallString<20> buffer; 3618 if (result & APFloat::opOverflow) { 3619 diagnostic = diag::warn_float_overflow; 3620 APFloat::getLargest(Format).toString(buffer); 3621 } else { 3622 diagnostic = diag::warn_float_underflow; 3623 APFloat::getSmallest(Format).toString(buffer); 3624 } 3625 3626 S.Diag(Loc, diagnostic) 3627 << Ty 3628 << StringRef(buffer.data(), buffer.size()); 3629 } 3630 3631 bool isExact = (result == APFloat::opOK); 3632 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3633 } 3634 3635 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3636 assert(E && "Invalid expression"); 3637 3638 if (E->isValueDependent()) 3639 return false; 3640 3641 QualType QT = E->getType(); 3642 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3643 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3644 return true; 3645 } 3646 3647 llvm::APSInt ValueAPS; 3648 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3649 3650 if (R.isInvalid()) 3651 return true; 3652 3653 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3654 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3655 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3656 << toString(ValueAPS, 10) << ValueIsPositive; 3657 return true; 3658 } 3659 3660 return false; 3661 } 3662 3663 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3664 // Fast path for a single digit (which is quite common). A single digit 3665 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3666 if (Tok.getLength() == 1) { 3667 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3668 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3669 } 3670 3671 SmallString<128> SpellingBuffer; 3672 // NumericLiteralParser wants to overread by one character. Add padding to 3673 // the buffer in case the token is copied to the buffer. If getSpelling() 3674 // returns a StringRef to the memory buffer, it should have a null char at 3675 // the EOF, so it is also safe. 3676 SpellingBuffer.resize(Tok.getLength() + 1); 3677 3678 // Get the spelling of the token, which eliminates trigraphs, etc. 3679 bool Invalid = false; 3680 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3681 if (Invalid) 3682 return ExprError(); 3683 3684 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3685 PP.getSourceManager(), PP.getLangOpts(), 3686 PP.getTargetInfo(), PP.getDiagnostics()); 3687 if (Literal.hadError) 3688 return ExprError(); 3689 3690 if (Literal.hasUDSuffix()) { 3691 // We're building a user-defined literal. 3692 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3693 SourceLocation UDSuffixLoc = 3694 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3695 3696 // Make sure we're allowed user-defined literals here. 3697 if (!UDLScope) 3698 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3699 3700 QualType CookedTy; 3701 if (Literal.isFloatingLiteral()) { 3702 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3703 // long double, the literal is treated as a call of the form 3704 // operator "" X (f L) 3705 CookedTy = Context.LongDoubleTy; 3706 } else { 3707 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3708 // unsigned long long, the literal is treated as a call of the form 3709 // operator "" X (n ULL) 3710 CookedTy = Context.UnsignedLongLongTy; 3711 } 3712 3713 DeclarationName OpName = 3714 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3715 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3716 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3717 3718 SourceLocation TokLoc = Tok.getLocation(); 3719 3720 // Perform literal operator lookup to determine if we're building a raw 3721 // literal or a cooked one. 3722 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3723 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3724 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3725 /*AllowStringTemplatePack*/ false, 3726 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3727 case LOLR_ErrorNoDiagnostic: 3728 // Lookup failure for imaginary constants isn't fatal, there's still the 3729 // GNU extension producing _Complex types. 3730 break; 3731 case LOLR_Error: 3732 return ExprError(); 3733 case LOLR_Cooked: { 3734 Expr *Lit; 3735 if (Literal.isFloatingLiteral()) { 3736 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3737 } else { 3738 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3739 if (Literal.GetIntegerValue(ResultVal)) 3740 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3741 << /* Unsigned */ 1; 3742 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3743 Tok.getLocation()); 3744 } 3745 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3746 } 3747 3748 case LOLR_Raw: { 3749 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3750 // literal is treated as a call of the form 3751 // operator "" X ("n") 3752 unsigned Length = Literal.getUDSuffixOffset(); 3753 QualType StrTy = Context.getConstantArrayType( 3754 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3755 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3756 Expr *Lit = StringLiteral::Create( 3757 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3758 /*Pascal*/false, StrTy, &TokLoc, 1); 3759 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3760 } 3761 3762 case LOLR_Template: { 3763 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3764 // template), L is treated as a call fo the form 3765 // operator "" X <'c1', 'c2', ... 'ck'>() 3766 // where n is the source character sequence c1 c2 ... ck. 3767 TemplateArgumentListInfo ExplicitArgs; 3768 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3769 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3770 llvm::APSInt Value(CharBits, CharIsUnsigned); 3771 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3772 Value = TokSpelling[I]; 3773 TemplateArgument Arg(Context, Value, Context.CharTy); 3774 TemplateArgumentLocInfo ArgInfo; 3775 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3776 } 3777 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3778 &ExplicitArgs); 3779 } 3780 case LOLR_StringTemplatePack: 3781 llvm_unreachable("unexpected literal operator lookup result"); 3782 } 3783 } 3784 3785 Expr *Res; 3786 3787 if (Literal.isFixedPointLiteral()) { 3788 QualType Ty; 3789 3790 if (Literal.isAccum) { 3791 if (Literal.isHalf) { 3792 Ty = Context.ShortAccumTy; 3793 } else if (Literal.isLong) { 3794 Ty = Context.LongAccumTy; 3795 } else { 3796 Ty = Context.AccumTy; 3797 } 3798 } else if (Literal.isFract) { 3799 if (Literal.isHalf) { 3800 Ty = Context.ShortFractTy; 3801 } else if (Literal.isLong) { 3802 Ty = Context.LongFractTy; 3803 } else { 3804 Ty = Context.FractTy; 3805 } 3806 } 3807 3808 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3809 3810 bool isSigned = !Literal.isUnsigned; 3811 unsigned scale = Context.getFixedPointScale(Ty); 3812 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3813 3814 llvm::APInt Val(bit_width, 0, isSigned); 3815 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3816 bool ValIsZero = Val.isZero() && !Overflowed; 3817 3818 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3819 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3820 // Clause 6.4.4 - The value of a constant shall be in the range of 3821 // representable values for its type, with exception for constants of a 3822 // fract type with a value of exactly 1; such a constant shall denote 3823 // the maximal value for the type. 3824 --Val; 3825 else if (Val.ugt(MaxVal) || Overflowed) 3826 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3827 3828 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3829 Tok.getLocation(), scale); 3830 } else if (Literal.isFloatingLiteral()) { 3831 QualType Ty; 3832 if (Literal.isHalf){ 3833 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3834 Ty = Context.HalfTy; 3835 else { 3836 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3837 return ExprError(); 3838 } 3839 } else if (Literal.isFloat) 3840 Ty = Context.FloatTy; 3841 else if (Literal.isLong) 3842 Ty = Context.LongDoubleTy; 3843 else if (Literal.isFloat16) 3844 Ty = Context.Float16Ty; 3845 else if (Literal.isFloat128) 3846 Ty = Context.Float128Ty; 3847 else 3848 Ty = Context.DoubleTy; 3849 3850 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3851 3852 if (Ty == Context.DoubleTy) { 3853 if (getLangOpts().SinglePrecisionConstants) { 3854 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3855 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3856 } 3857 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3858 "cl_khr_fp64", getLangOpts())) { 3859 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3860 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3861 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3862 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3863 } 3864 } 3865 } else if (!Literal.isIntegerLiteral()) { 3866 return ExprError(); 3867 } else { 3868 QualType Ty; 3869 3870 // 'long long' is a C99 or C++11 feature. 3871 if (!getLangOpts().C99 && Literal.isLongLong) { 3872 if (getLangOpts().CPlusPlus) 3873 Diag(Tok.getLocation(), 3874 getLangOpts().CPlusPlus11 ? 3875 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3876 else 3877 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3878 } 3879 3880 // 'z/uz' literals are a C++2b feature. 3881 if (Literal.isSizeT) 3882 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3883 ? getLangOpts().CPlusPlus2b 3884 ? diag::warn_cxx20_compat_size_t_suffix 3885 : diag::ext_cxx2b_size_t_suffix 3886 : diag::err_cxx2b_size_t_suffix); 3887 3888 // Get the value in the widest-possible width. 3889 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3890 llvm::APInt ResultVal(MaxWidth, 0); 3891 3892 if (Literal.GetIntegerValue(ResultVal)) { 3893 // If this value didn't fit into uintmax_t, error and force to ull. 3894 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3895 << /* Unsigned */ 1; 3896 Ty = Context.UnsignedLongLongTy; 3897 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3898 "long long is not intmax_t?"); 3899 } else { 3900 // If this value fits into a ULL, try to figure out what else it fits into 3901 // according to the rules of C99 6.4.4.1p5. 3902 3903 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3904 // be an unsigned int. 3905 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3906 3907 // Check from smallest to largest, picking the smallest type we can. 3908 unsigned Width = 0; 3909 3910 // Microsoft specific integer suffixes are explicitly sized. 3911 if (Literal.MicrosoftInteger) { 3912 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3913 Width = 8; 3914 Ty = Context.CharTy; 3915 } else { 3916 Width = Literal.MicrosoftInteger; 3917 Ty = Context.getIntTypeForBitwidth(Width, 3918 /*Signed=*/!Literal.isUnsigned); 3919 } 3920 } 3921 3922 // Check C++2b size_t literals. 3923 if (Literal.isSizeT) { 3924 assert(!Literal.MicrosoftInteger && 3925 "size_t literals can't be Microsoft literals"); 3926 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3927 Context.getTargetInfo().getSizeType()); 3928 3929 // Does it fit in size_t? 3930 if (ResultVal.isIntN(SizeTSize)) { 3931 // Does it fit in ssize_t? 3932 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3933 Ty = Context.getSignedSizeType(); 3934 else if (AllowUnsigned) 3935 Ty = Context.getSizeType(); 3936 Width = SizeTSize; 3937 } 3938 } 3939 3940 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3941 !Literal.isSizeT) { 3942 // Are int/unsigned possibilities? 3943 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3944 3945 // Does it fit in a unsigned int? 3946 if (ResultVal.isIntN(IntSize)) { 3947 // Does it fit in a signed int? 3948 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3949 Ty = Context.IntTy; 3950 else if (AllowUnsigned) 3951 Ty = Context.UnsignedIntTy; 3952 Width = IntSize; 3953 } 3954 } 3955 3956 // Are long/unsigned long possibilities? 3957 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3958 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3959 3960 // Does it fit in a unsigned long? 3961 if (ResultVal.isIntN(LongSize)) { 3962 // Does it fit in a signed long? 3963 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3964 Ty = Context.LongTy; 3965 else if (AllowUnsigned) 3966 Ty = Context.UnsignedLongTy; 3967 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3968 // is compatible. 3969 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3970 const unsigned LongLongSize = 3971 Context.getTargetInfo().getLongLongWidth(); 3972 Diag(Tok.getLocation(), 3973 getLangOpts().CPlusPlus 3974 ? Literal.isLong 3975 ? diag::warn_old_implicitly_unsigned_long_cxx 3976 : /*C++98 UB*/ diag:: 3977 ext_old_implicitly_unsigned_long_cxx 3978 : diag::warn_old_implicitly_unsigned_long) 3979 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3980 : /*will be ill-formed*/ 1); 3981 Ty = Context.UnsignedLongTy; 3982 } 3983 Width = LongSize; 3984 } 3985 } 3986 3987 // Check long long if needed. 3988 if (Ty.isNull() && !Literal.isSizeT) { 3989 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3990 3991 // Does it fit in a unsigned long long? 3992 if (ResultVal.isIntN(LongLongSize)) { 3993 // Does it fit in a signed long long? 3994 // To be compatible with MSVC, hex integer literals ending with the 3995 // LL or i64 suffix are always signed in Microsoft mode. 3996 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3997 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3998 Ty = Context.LongLongTy; 3999 else if (AllowUnsigned) 4000 Ty = Context.UnsignedLongLongTy; 4001 Width = LongLongSize; 4002 } 4003 } 4004 4005 // If we still couldn't decide a type, we either have 'size_t' literal 4006 // that is out of range, or a decimal literal that does not fit in a 4007 // signed long long and has no U suffix. 4008 if (Ty.isNull()) { 4009 if (Literal.isSizeT) 4010 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4011 << Literal.isUnsigned; 4012 else 4013 Diag(Tok.getLocation(), 4014 diag::ext_integer_literal_too_large_for_signed); 4015 Ty = Context.UnsignedLongLongTy; 4016 Width = Context.getTargetInfo().getLongLongWidth(); 4017 } 4018 4019 if (ResultVal.getBitWidth() != Width) 4020 ResultVal = ResultVal.trunc(Width); 4021 } 4022 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4023 } 4024 4025 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4026 if (Literal.isImaginary) { 4027 Res = new (Context) ImaginaryLiteral(Res, 4028 Context.getComplexType(Res->getType())); 4029 4030 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4031 } 4032 return Res; 4033 } 4034 4035 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4036 assert(E && "ActOnParenExpr() missing expr"); 4037 QualType ExprTy = E->getType(); 4038 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4039 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4040 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4041 return new (Context) ParenExpr(L, R, E); 4042 } 4043 4044 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4045 SourceLocation Loc, 4046 SourceRange ArgRange) { 4047 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4048 // scalar or vector data type argument..." 4049 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4050 // type (C99 6.2.5p18) or void. 4051 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4052 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4053 << T << ArgRange; 4054 return true; 4055 } 4056 4057 assert((T->isVoidType() || !T->isIncompleteType()) && 4058 "Scalar types should always be complete"); 4059 return false; 4060 } 4061 4062 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4063 SourceLocation Loc, 4064 SourceRange ArgRange, 4065 UnaryExprOrTypeTrait TraitKind) { 4066 // Invalid types must be hard errors for SFINAE in C++. 4067 if (S.LangOpts.CPlusPlus) 4068 return true; 4069 4070 // C99 6.5.3.4p1: 4071 if (T->isFunctionType() && 4072 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4073 TraitKind == UETT_PreferredAlignOf)) { 4074 // sizeof(function)/alignof(function) is allowed as an extension. 4075 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4076 << getTraitSpelling(TraitKind) << ArgRange; 4077 return false; 4078 } 4079 4080 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4081 // this is an error (OpenCL v1.1 s6.3.k) 4082 if (T->isVoidType()) { 4083 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4084 : diag::ext_sizeof_alignof_void_type; 4085 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4086 return false; 4087 } 4088 4089 return true; 4090 } 4091 4092 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4093 SourceLocation Loc, 4094 SourceRange ArgRange, 4095 UnaryExprOrTypeTrait TraitKind) { 4096 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4097 // runtime doesn't allow it. 4098 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4099 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4100 << T << (TraitKind == UETT_SizeOf) 4101 << ArgRange; 4102 return true; 4103 } 4104 4105 return false; 4106 } 4107 4108 /// Check whether E is a pointer from a decayed array type (the decayed 4109 /// pointer type is equal to T) and emit a warning if it is. 4110 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4111 Expr *E) { 4112 // Don't warn if the operation changed the type. 4113 if (T != E->getType()) 4114 return; 4115 4116 // Now look for array decays. 4117 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4118 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4119 return; 4120 4121 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4122 << ICE->getType() 4123 << ICE->getSubExpr()->getType(); 4124 } 4125 4126 /// Check the constraints on expression operands to unary type expression 4127 /// and type traits. 4128 /// 4129 /// Completes any types necessary and validates the constraints on the operand 4130 /// expression. The logic mostly mirrors the type-based overload, but may modify 4131 /// the expression as it completes the type for that expression through template 4132 /// instantiation, etc. 4133 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4134 UnaryExprOrTypeTrait ExprKind) { 4135 QualType ExprTy = E->getType(); 4136 assert(!ExprTy->isReferenceType()); 4137 4138 bool IsUnevaluatedOperand = 4139 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4140 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4141 if (IsUnevaluatedOperand) { 4142 ExprResult Result = CheckUnevaluatedOperand(E); 4143 if (Result.isInvalid()) 4144 return true; 4145 E = Result.get(); 4146 } 4147 4148 // The operand for sizeof and alignof is in an unevaluated expression context, 4149 // so side effects could result in unintended consequences. 4150 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4151 // used to build SFINAE gadgets. 4152 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4153 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4154 !E->isInstantiationDependent() && 4155 E->HasSideEffects(Context, false)) 4156 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4157 4158 if (ExprKind == UETT_VecStep) 4159 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4160 E->getSourceRange()); 4161 4162 // Explicitly list some types as extensions. 4163 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4164 E->getSourceRange(), ExprKind)) 4165 return false; 4166 4167 // 'alignof' applied to an expression only requires the base element type of 4168 // the expression to be complete. 'sizeof' requires the expression's type to 4169 // be complete (and will attempt to complete it if it's an array of unknown 4170 // bound). 4171 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4172 if (RequireCompleteSizedType( 4173 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4174 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4175 getTraitSpelling(ExprKind), E->getSourceRange())) 4176 return true; 4177 } else { 4178 if (RequireCompleteSizedExprType( 4179 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4180 getTraitSpelling(ExprKind), E->getSourceRange())) 4181 return true; 4182 } 4183 4184 // Completing the expression's type may have changed it. 4185 ExprTy = E->getType(); 4186 assert(!ExprTy->isReferenceType()); 4187 4188 if (ExprTy->isFunctionType()) { 4189 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4190 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4191 return true; 4192 } 4193 4194 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4195 E->getSourceRange(), ExprKind)) 4196 return true; 4197 4198 if (ExprKind == UETT_SizeOf) { 4199 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4200 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4201 QualType OType = PVD->getOriginalType(); 4202 QualType Type = PVD->getType(); 4203 if (Type->isPointerType() && OType->isArrayType()) { 4204 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4205 << Type << OType; 4206 Diag(PVD->getLocation(), diag::note_declared_at); 4207 } 4208 } 4209 } 4210 4211 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4212 // decays into a pointer and returns an unintended result. This is most 4213 // likely a typo for "sizeof(array) op x". 4214 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4215 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4216 BO->getLHS()); 4217 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4218 BO->getRHS()); 4219 } 4220 } 4221 4222 return false; 4223 } 4224 4225 /// Check the constraints on operands to unary expression and type 4226 /// traits. 4227 /// 4228 /// This will complete any types necessary, and validate the various constraints 4229 /// on those operands. 4230 /// 4231 /// The UsualUnaryConversions() function is *not* called by this routine. 4232 /// C99 6.3.2.1p[2-4] all state: 4233 /// Except when it is the operand of the sizeof operator ... 4234 /// 4235 /// C++ [expr.sizeof]p4 4236 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4237 /// standard conversions are not applied to the operand of sizeof. 4238 /// 4239 /// This policy is followed for all of the unary trait expressions. 4240 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4241 SourceLocation OpLoc, 4242 SourceRange ExprRange, 4243 UnaryExprOrTypeTrait ExprKind) { 4244 if (ExprType->isDependentType()) 4245 return false; 4246 4247 // C++ [expr.sizeof]p2: 4248 // When applied to a reference or a reference type, the result 4249 // is the size of the referenced type. 4250 // C++11 [expr.alignof]p3: 4251 // When alignof is applied to a reference type, the result 4252 // shall be the alignment of the referenced type. 4253 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4254 ExprType = Ref->getPointeeType(); 4255 4256 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4257 // When alignof or _Alignof is applied to an array type, the result 4258 // is the alignment of the element type. 4259 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4260 ExprKind == UETT_OpenMPRequiredSimdAlign) 4261 ExprType = Context.getBaseElementType(ExprType); 4262 4263 if (ExprKind == UETT_VecStep) 4264 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4265 4266 // Explicitly list some types as extensions. 4267 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4268 ExprKind)) 4269 return false; 4270 4271 if (RequireCompleteSizedType( 4272 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4273 getTraitSpelling(ExprKind), ExprRange)) 4274 return true; 4275 4276 if (ExprType->isFunctionType()) { 4277 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4278 << getTraitSpelling(ExprKind) << ExprRange; 4279 return true; 4280 } 4281 4282 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4283 ExprKind)) 4284 return true; 4285 4286 return false; 4287 } 4288 4289 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4290 // Cannot know anything else if the expression is dependent. 4291 if (E->isTypeDependent()) 4292 return false; 4293 4294 if (E->getObjectKind() == OK_BitField) { 4295 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4296 << 1 << E->getSourceRange(); 4297 return true; 4298 } 4299 4300 ValueDecl *D = nullptr; 4301 Expr *Inner = E->IgnoreParens(); 4302 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4303 D = DRE->getDecl(); 4304 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4305 D = ME->getMemberDecl(); 4306 } 4307 4308 // If it's a field, require the containing struct to have a 4309 // complete definition so that we can compute the layout. 4310 // 4311 // This can happen in C++11 onwards, either by naming the member 4312 // in a way that is not transformed into a member access expression 4313 // (in an unevaluated operand, for instance), or by naming the member 4314 // in a trailing-return-type. 4315 // 4316 // For the record, since __alignof__ on expressions is a GCC 4317 // extension, GCC seems to permit this but always gives the 4318 // nonsensical answer 0. 4319 // 4320 // We don't really need the layout here --- we could instead just 4321 // directly check for all the appropriate alignment-lowing 4322 // attributes --- but that would require duplicating a lot of 4323 // logic that just isn't worth duplicating for such a marginal 4324 // use-case. 4325 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4326 // Fast path this check, since we at least know the record has a 4327 // definition if we can find a member of it. 4328 if (!FD->getParent()->isCompleteDefinition()) { 4329 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4330 << E->getSourceRange(); 4331 return true; 4332 } 4333 4334 // Otherwise, if it's a field, and the field doesn't have 4335 // reference type, then it must have a complete type (or be a 4336 // flexible array member, which we explicitly want to 4337 // white-list anyway), which makes the following checks trivial. 4338 if (!FD->getType()->isReferenceType()) 4339 return false; 4340 } 4341 4342 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4343 } 4344 4345 bool Sema::CheckVecStepExpr(Expr *E) { 4346 E = E->IgnoreParens(); 4347 4348 // Cannot know anything else if the expression is dependent. 4349 if (E->isTypeDependent()) 4350 return false; 4351 4352 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4353 } 4354 4355 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4356 CapturingScopeInfo *CSI) { 4357 assert(T->isVariablyModifiedType()); 4358 assert(CSI != nullptr); 4359 4360 // We're going to walk down into the type and look for VLA expressions. 4361 do { 4362 const Type *Ty = T.getTypePtr(); 4363 switch (Ty->getTypeClass()) { 4364 #define TYPE(Class, Base) 4365 #define ABSTRACT_TYPE(Class, Base) 4366 #define NON_CANONICAL_TYPE(Class, Base) 4367 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4368 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4369 #include "clang/AST/TypeNodes.inc" 4370 T = QualType(); 4371 break; 4372 // These types are never variably-modified. 4373 case Type::Builtin: 4374 case Type::Complex: 4375 case Type::Vector: 4376 case Type::ExtVector: 4377 case Type::ConstantMatrix: 4378 case Type::Record: 4379 case Type::Enum: 4380 case Type::Elaborated: 4381 case Type::TemplateSpecialization: 4382 case Type::ObjCObject: 4383 case Type::ObjCInterface: 4384 case Type::ObjCObjectPointer: 4385 case Type::ObjCTypeParam: 4386 case Type::Pipe: 4387 case Type::BitInt: 4388 llvm_unreachable("type class is never variably-modified!"); 4389 case Type::Adjusted: 4390 T = cast<AdjustedType>(Ty)->getOriginalType(); 4391 break; 4392 case Type::Decayed: 4393 T = cast<DecayedType>(Ty)->getPointeeType(); 4394 break; 4395 case Type::Pointer: 4396 T = cast<PointerType>(Ty)->getPointeeType(); 4397 break; 4398 case Type::BlockPointer: 4399 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4400 break; 4401 case Type::LValueReference: 4402 case Type::RValueReference: 4403 T = cast<ReferenceType>(Ty)->getPointeeType(); 4404 break; 4405 case Type::MemberPointer: 4406 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4407 break; 4408 case Type::ConstantArray: 4409 case Type::IncompleteArray: 4410 // Losing element qualification here is fine. 4411 T = cast<ArrayType>(Ty)->getElementType(); 4412 break; 4413 case Type::VariableArray: { 4414 // Losing element qualification here is fine. 4415 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4416 4417 // Unknown size indication requires no size computation. 4418 // Otherwise, evaluate and record it. 4419 auto Size = VAT->getSizeExpr(); 4420 if (Size && !CSI->isVLATypeCaptured(VAT) && 4421 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4422 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4423 4424 T = VAT->getElementType(); 4425 break; 4426 } 4427 case Type::FunctionProto: 4428 case Type::FunctionNoProto: 4429 T = cast<FunctionType>(Ty)->getReturnType(); 4430 break; 4431 case Type::Paren: 4432 case Type::TypeOf: 4433 case Type::UnaryTransform: 4434 case Type::Attributed: 4435 case Type::SubstTemplateTypeParm: 4436 case Type::MacroQualified: 4437 // Keep walking after single level desugaring. 4438 T = T.getSingleStepDesugaredType(Context); 4439 break; 4440 case Type::Typedef: 4441 T = cast<TypedefType>(Ty)->desugar(); 4442 break; 4443 case Type::Decltype: 4444 T = cast<DecltypeType>(Ty)->desugar(); 4445 break; 4446 case Type::Auto: 4447 case Type::DeducedTemplateSpecialization: 4448 T = cast<DeducedType>(Ty)->getDeducedType(); 4449 break; 4450 case Type::TypeOfExpr: 4451 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4452 break; 4453 case Type::Atomic: 4454 T = cast<AtomicType>(Ty)->getValueType(); 4455 break; 4456 } 4457 } while (!T.isNull() && T->isVariablyModifiedType()); 4458 } 4459 4460 /// Build a sizeof or alignof expression given a type operand. 4461 ExprResult 4462 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4463 SourceLocation OpLoc, 4464 UnaryExprOrTypeTrait ExprKind, 4465 SourceRange R) { 4466 if (!TInfo) 4467 return ExprError(); 4468 4469 QualType T = TInfo->getType(); 4470 4471 if (!T->isDependentType() && 4472 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4473 return ExprError(); 4474 4475 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4476 if (auto *TT = T->getAs<TypedefType>()) { 4477 for (auto I = FunctionScopes.rbegin(), 4478 E = std::prev(FunctionScopes.rend()); 4479 I != E; ++I) { 4480 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4481 if (CSI == nullptr) 4482 break; 4483 DeclContext *DC = nullptr; 4484 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4485 DC = LSI->CallOperator; 4486 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4487 DC = CRSI->TheCapturedDecl; 4488 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4489 DC = BSI->TheDecl; 4490 if (DC) { 4491 if (DC->containsDecl(TT->getDecl())) 4492 break; 4493 captureVariablyModifiedType(Context, T, CSI); 4494 } 4495 } 4496 } 4497 } 4498 4499 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4500 return new (Context) UnaryExprOrTypeTraitExpr( 4501 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4502 } 4503 4504 /// Build a sizeof or alignof expression given an expression 4505 /// operand. 4506 ExprResult 4507 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4508 UnaryExprOrTypeTrait ExprKind) { 4509 ExprResult PE = CheckPlaceholderExpr(E); 4510 if (PE.isInvalid()) 4511 return ExprError(); 4512 4513 E = PE.get(); 4514 4515 // Verify that the operand is valid. 4516 bool isInvalid = false; 4517 if (E->isTypeDependent()) { 4518 // Delay type-checking for type-dependent expressions. 4519 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4520 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4521 } else if (ExprKind == UETT_VecStep) { 4522 isInvalid = CheckVecStepExpr(E); 4523 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4524 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4525 isInvalid = true; 4526 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4527 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4528 isInvalid = true; 4529 } else { 4530 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4531 } 4532 4533 if (isInvalid) 4534 return ExprError(); 4535 4536 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4537 PE = TransformToPotentiallyEvaluated(E); 4538 if (PE.isInvalid()) return ExprError(); 4539 E = PE.get(); 4540 } 4541 4542 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4543 return new (Context) UnaryExprOrTypeTraitExpr( 4544 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4545 } 4546 4547 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4548 /// expr and the same for @c alignof and @c __alignof 4549 /// Note that the ArgRange is invalid if isType is false. 4550 ExprResult 4551 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4552 UnaryExprOrTypeTrait ExprKind, bool IsType, 4553 void *TyOrEx, SourceRange ArgRange) { 4554 // If error parsing type, ignore. 4555 if (!TyOrEx) return ExprError(); 4556 4557 if (IsType) { 4558 TypeSourceInfo *TInfo; 4559 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4560 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4561 } 4562 4563 Expr *ArgEx = (Expr *)TyOrEx; 4564 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4565 return Result; 4566 } 4567 4568 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4569 bool IsReal) { 4570 if (V.get()->isTypeDependent()) 4571 return S.Context.DependentTy; 4572 4573 // _Real and _Imag are only l-values for normal l-values. 4574 if (V.get()->getObjectKind() != OK_Ordinary) { 4575 V = S.DefaultLvalueConversion(V.get()); 4576 if (V.isInvalid()) 4577 return QualType(); 4578 } 4579 4580 // These operators return the element type of a complex type. 4581 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4582 return CT->getElementType(); 4583 4584 // Otherwise they pass through real integer and floating point types here. 4585 if (V.get()->getType()->isArithmeticType()) 4586 return V.get()->getType(); 4587 4588 // Test for placeholders. 4589 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4590 if (PR.isInvalid()) return QualType(); 4591 if (PR.get() != V.get()) { 4592 V = PR; 4593 return CheckRealImagOperand(S, V, Loc, IsReal); 4594 } 4595 4596 // Reject anything else. 4597 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4598 << (IsReal ? "__real" : "__imag"); 4599 return QualType(); 4600 } 4601 4602 4603 4604 ExprResult 4605 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4606 tok::TokenKind Kind, Expr *Input) { 4607 UnaryOperatorKind Opc; 4608 switch (Kind) { 4609 default: llvm_unreachable("Unknown unary op!"); 4610 case tok::plusplus: Opc = UO_PostInc; break; 4611 case tok::minusminus: Opc = UO_PostDec; break; 4612 } 4613 4614 // Since this might is a postfix expression, get rid of ParenListExprs. 4615 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4616 if (Result.isInvalid()) return ExprError(); 4617 Input = Result.get(); 4618 4619 return BuildUnaryOp(S, OpLoc, Opc, Input); 4620 } 4621 4622 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4623 /// 4624 /// \return true on error 4625 static bool checkArithmeticOnObjCPointer(Sema &S, 4626 SourceLocation opLoc, 4627 Expr *op) { 4628 assert(op->getType()->isObjCObjectPointerType()); 4629 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4630 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4631 return false; 4632 4633 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4634 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4635 << op->getSourceRange(); 4636 return true; 4637 } 4638 4639 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4640 auto *BaseNoParens = Base->IgnoreParens(); 4641 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4642 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4643 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4644 } 4645 4646 ExprResult 4647 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4648 Expr *idx, SourceLocation rbLoc) { 4649 if (base && !base->getType().isNull() && 4650 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4651 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4652 SourceLocation(), /*Length*/ nullptr, 4653 /*Stride=*/nullptr, rbLoc); 4654 4655 // Since this might be a postfix expression, get rid of ParenListExprs. 4656 if (isa<ParenListExpr>(base)) { 4657 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4658 if (result.isInvalid()) return ExprError(); 4659 base = result.get(); 4660 } 4661 4662 // Check if base and idx form a MatrixSubscriptExpr. 4663 // 4664 // Helper to check for comma expressions, which are not allowed as indices for 4665 // matrix subscript expressions. 4666 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4667 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4668 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4669 << SourceRange(base->getBeginLoc(), rbLoc); 4670 return true; 4671 } 4672 return false; 4673 }; 4674 // The matrix subscript operator ([][])is considered a single operator. 4675 // Separating the index expressions by parenthesis is not allowed. 4676 if (base->getType()->isSpecificPlaceholderType( 4677 BuiltinType::IncompleteMatrixIdx) && 4678 !isa<MatrixSubscriptExpr>(base)) { 4679 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4680 << SourceRange(base->getBeginLoc(), rbLoc); 4681 return ExprError(); 4682 } 4683 // If the base is a MatrixSubscriptExpr, try to create a new 4684 // MatrixSubscriptExpr. 4685 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4686 if (matSubscriptE) { 4687 if (CheckAndReportCommaError(idx)) 4688 return ExprError(); 4689 4690 assert(matSubscriptE->isIncomplete() && 4691 "base has to be an incomplete matrix subscript"); 4692 return CreateBuiltinMatrixSubscriptExpr( 4693 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4694 } 4695 4696 // Handle any non-overload placeholder types in the base and index 4697 // expressions. We can't handle overloads here because the other 4698 // operand might be an overloadable type, in which case the overload 4699 // resolution for the operator overload should get the first crack 4700 // at the overload. 4701 bool IsMSPropertySubscript = false; 4702 if (base->getType()->isNonOverloadPlaceholderType()) { 4703 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4704 if (!IsMSPropertySubscript) { 4705 ExprResult result = CheckPlaceholderExpr(base); 4706 if (result.isInvalid()) 4707 return ExprError(); 4708 base = result.get(); 4709 } 4710 } 4711 4712 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4713 if (base->getType()->isMatrixType()) { 4714 if (CheckAndReportCommaError(idx)) 4715 return ExprError(); 4716 4717 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4718 } 4719 4720 // A comma-expression as the index is deprecated in C++2a onwards. 4721 if (getLangOpts().CPlusPlus20 && 4722 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4723 (isa<CXXOperatorCallExpr>(idx) && 4724 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4725 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4726 << SourceRange(base->getBeginLoc(), rbLoc); 4727 } 4728 4729 if (idx->getType()->isNonOverloadPlaceholderType()) { 4730 ExprResult result = CheckPlaceholderExpr(idx); 4731 if (result.isInvalid()) return ExprError(); 4732 idx = result.get(); 4733 } 4734 4735 // Build an unanalyzed expression if either operand is type-dependent. 4736 if (getLangOpts().CPlusPlus && 4737 (base->isTypeDependent() || idx->isTypeDependent())) { 4738 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4739 VK_LValue, OK_Ordinary, rbLoc); 4740 } 4741 4742 // MSDN, property (C++) 4743 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4744 // This attribute can also be used in the declaration of an empty array in a 4745 // class or structure definition. For example: 4746 // __declspec(property(get=GetX, put=PutX)) int x[]; 4747 // The above statement indicates that x[] can be used with one or more array 4748 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4749 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4750 if (IsMSPropertySubscript) { 4751 // Build MS property subscript expression if base is MS property reference 4752 // or MS property subscript. 4753 return new (Context) MSPropertySubscriptExpr( 4754 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4755 } 4756 4757 // Use C++ overloaded-operator rules if either operand has record 4758 // type. The spec says to do this if either type is *overloadable*, 4759 // but enum types can't declare subscript operators or conversion 4760 // operators, so there's nothing interesting for overload resolution 4761 // to do if there aren't any record types involved. 4762 // 4763 // ObjC pointers have their own subscripting logic that is not tied 4764 // to overload resolution and so should not take this path. 4765 if (getLangOpts().CPlusPlus && 4766 (base->getType()->isRecordType() || 4767 (!base->getType()->isObjCObjectPointerType() && 4768 idx->getType()->isRecordType()))) { 4769 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4770 } 4771 4772 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4773 4774 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4775 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4776 4777 return Res; 4778 } 4779 4780 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4781 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4782 InitializationKind Kind = 4783 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4784 InitializationSequence InitSeq(*this, Entity, Kind, E); 4785 return InitSeq.Perform(*this, Entity, Kind, E); 4786 } 4787 4788 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4789 Expr *ColumnIdx, 4790 SourceLocation RBLoc) { 4791 ExprResult BaseR = CheckPlaceholderExpr(Base); 4792 if (BaseR.isInvalid()) 4793 return BaseR; 4794 Base = BaseR.get(); 4795 4796 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4797 if (RowR.isInvalid()) 4798 return RowR; 4799 RowIdx = RowR.get(); 4800 4801 if (!ColumnIdx) 4802 return new (Context) MatrixSubscriptExpr( 4803 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4804 4805 // Build an unanalyzed expression if any of the operands is type-dependent. 4806 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4807 ColumnIdx->isTypeDependent()) 4808 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4809 Context.DependentTy, RBLoc); 4810 4811 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4812 if (ColumnR.isInvalid()) 4813 return ColumnR; 4814 ColumnIdx = ColumnR.get(); 4815 4816 // Check that IndexExpr is an integer expression. If it is a constant 4817 // expression, check that it is less than Dim (= the number of elements in the 4818 // corresponding dimension). 4819 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4820 bool IsColumnIdx) -> Expr * { 4821 if (!IndexExpr->getType()->isIntegerType() && 4822 !IndexExpr->isTypeDependent()) { 4823 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4824 << IsColumnIdx; 4825 return nullptr; 4826 } 4827 4828 if (Optional<llvm::APSInt> Idx = 4829 IndexExpr->getIntegerConstantExpr(Context)) { 4830 if ((*Idx < 0 || *Idx >= Dim)) { 4831 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4832 << IsColumnIdx << Dim; 4833 return nullptr; 4834 } 4835 } 4836 4837 ExprResult ConvExpr = 4838 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4839 assert(!ConvExpr.isInvalid() && 4840 "should be able to convert any integer type to size type"); 4841 return ConvExpr.get(); 4842 }; 4843 4844 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4845 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4846 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4847 if (!RowIdx || !ColumnIdx) 4848 return ExprError(); 4849 4850 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4851 MTy->getElementType(), RBLoc); 4852 } 4853 4854 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4855 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4856 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4857 4858 // For expressions like `&(*s).b`, the base is recorded and what should be 4859 // checked. 4860 const MemberExpr *Member = nullptr; 4861 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4862 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4863 4864 LastRecord.PossibleDerefs.erase(StrippedExpr); 4865 } 4866 4867 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4868 if (isUnevaluatedContext()) 4869 return; 4870 4871 QualType ResultTy = E->getType(); 4872 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4873 4874 // Bail if the element is an array since it is not memory access. 4875 if (isa<ArrayType>(ResultTy)) 4876 return; 4877 4878 if (ResultTy->hasAttr(attr::NoDeref)) { 4879 LastRecord.PossibleDerefs.insert(E); 4880 return; 4881 } 4882 4883 // Check if the base type is a pointer to a member access of a struct 4884 // marked with noderef. 4885 const Expr *Base = E->getBase(); 4886 QualType BaseTy = Base->getType(); 4887 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4888 // Not a pointer access 4889 return; 4890 4891 const MemberExpr *Member = nullptr; 4892 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4893 Member->isArrow()) 4894 Base = Member->getBase(); 4895 4896 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4897 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4898 LastRecord.PossibleDerefs.insert(E); 4899 } 4900 } 4901 4902 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4903 Expr *LowerBound, 4904 SourceLocation ColonLocFirst, 4905 SourceLocation ColonLocSecond, 4906 Expr *Length, Expr *Stride, 4907 SourceLocation RBLoc) { 4908 if (Base->getType()->isPlaceholderType() && 4909 !Base->getType()->isSpecificPlaceholderType( 4910 BuiltinType::OMPArraySection)) { 4911 ExprResult Result = CheckPlaceholderExpr(Base); 4912 if (Result.isInvalid()) 4913 return ExprError(); 4914 Base = Result.get(); 4915 } 4916 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4917 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4918 if (Result.isInvalid()) 4919 return ExprError(); 4920 Result = DefaultLvalueConversion(Result.get()); 4921 if (Result.isInvalid()) 4922 return ExprError(); 4923 LowerBound = Result.get(); 4924 } 4925 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4926 ExprResult Result = CheckPlaceholderExpr(Length); 4927 if (Result.isInvalid()) 4928 return ExprError(); 4929 Result = DefaultLvalueConversion(Result.get()); 4930 if (Result.isInvalid()) 4931 return ExprError(); 4932 Length = Result.get(); 4933 } 4934 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4935 ExprResult Result = CheckPlaceholderExpr(Stride); 4936 if (Result.isInvalid()) 4937 return ExprError(); 4938 Result = DefaultLvalueConversion(Result.get()); 4939 if (Result.isInvalid()) 4940 return ExprError(); 4941 Stride = Result.get(); 4942 } 4943 4944 // Build an unanalyzed expression if either operand is type-dependent. 4945 if (Base->isTypeDependent() || 4946 (LowerBound && 4947 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4948 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4949 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4950 return new (Context) OMPArraySectionExpr( 4951 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4952 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4953 } 4954 4955 // Perform default conversions. 4956 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4957 QualType ResultTy; 4958 if (OriginalTy->isAnyPointerType()) { 4959 ResultTy = OriginalTy->getPointeeType(); 4960 } else if (OriginalTy->isArrayType()) { 4961 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4962 } else { 4963 return ExprError( 4964 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4965 << Base->getSourceRange()); 4966 } 4967 // C99 6.5.2.1p1 4968 if (LowerBound) { 4969 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4970 LowerBound); 4971 if (Res.isInvalid()) 4972 return ExprError(Diag(LowerBound->getExprLoc(), 4973 diag::err_omp_typecheck_section_not_integer) 4974 << 0 << LowerBound->getSourceRange()); 4975 LowerBound = Res.get(); 4976 4977 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4978 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4979 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4980 << 0 << LowerBound->getSourceRange(); 4981 } 4982 if (Length) { 4983 auto Res = 4984 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4985 if (Res.isInvalid()) 4986 return ExprError(Diag(Length->getExprLoc(), 4987 diag::err_omp_typecheck_section_not_integer) 4988 << 1 << Length->getSourceRange()); 4989 Length = Res.get(); 4990 4991 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4992 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4993 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4994 << 1 << Length->getSourceRange(); 4995 } 4996 if (Stride) { 4997 ExprResult Res = 4998 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4999 if (Res.isInvalid()) 5000 return ExprError(Diag(Stride->getExprLoc(), 5001 diag::err_omp_typecheck_section_not_integer) 5002 << 1 << Stride->getSourceRange()); 5003 Stride = Res.get(); 5004 5005 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5006 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5007 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5008 << 1 << Stride->getSourceRange(); 5009 } 5010 5011 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5012 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5013 // type. Note that functions are not objects, and that (in C99 parlance) 5014 // incomplete types are not object types. 5015 if (ResultTy->isFunctionType()) { 5016 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5017 << ResultTy << Base->getSourceRange(); 5018 return ExprError(); 5019 } 5020 5021 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5022 diag::err_omp_section_incomplete_type, Base)) 5023 return ExprError(); 5024 5025 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5026 Expr::EvalResult Result; 5027 if (LowerBound->EvaluateAsInt(Result, Context)) { 5028 // OpenMP 5.0, [2.1.5 Array Sections] 5029 // The array section must be a subset of the original array. 5030 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5031 if (LowerBoundValue.isNegative()) { 5032 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5033 << LowerBound->getSourceRange(); 5034 return ExprError(); 5035 } 5036 } 5037 } 5038 5039 if (Length) { 5040 Expr::EvalResult Result; 5041 if (Length->EvaluateAsInt(Result, Context)) { 5042 // OpenMP 5.0, [2.1.5 Array Sections] 5043 // The length must evaluate to non-negative integers. 5044 llvm::APSInt LengthValue = Result.Val.getInt(); 5045 if (LengthValue.isNegative()) { 5046 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5047 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5048 << Length->getSourceRange(); 5049 return ExprError(); 5050 } 5051 } 5052 } else if (ColonLocFirst.isValid() && 5053 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5054 !OriginalTy->isVariableArrayType()))) { 5055 // OpenMP 5.0, [2.1.5 Array Sections] 5056 // When the size of the array dimension is not known, the length must be 5057 // specified explicitly. 5058 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5059 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5060 return ExprError(); 5061 } 5062 5063 if (Stride) { 5064 Expr::EvalResult Result; 5065 if (Stride->EvaluateAsInt(Result, Context)) { 5066 // OpenMP 5.0, [2.1.5 Array Sections] 5067 // The stride must evaluate to a positive integer. 5068 llvm::APSInt StrideValue = Result.Val.getInt(); 5069 if (!StrideValue.isStrictlyPositive()) { 5070 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5071 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5072 << Stride->getSourceRange(); 5073 return ExprError(); 5074 } 5075 } 5076 } 5077 5078 if (!Base->getType()->isSpecificPlaceholderType( 5079 BuiltinType::OMPArraySection)) { 5080 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5081 if (Result.isInvalid()) 5082 return ExprError(); 5083 Base = Result.get(); 5084 } 5085 return new (Context) OMPArraySectionExpr( 5086 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5087 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5088 } 5089 5090 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5091 SourceLocation RParenLoc, 5092 ArrayRef<Expr *> Dims, 5093 ArrayRef<SourceRange> Brackets) { 5094 if (Base->getType()->isPlaceholderType()) { 5095 ExprResult Result = CheckPlaceholderExpr(Base); 5096 if (Result.isInvalid()) 5097 return ExprError(); 5098 Result = DefaultLvalueConversion(Result.get()); 5099 if (Result.isInvalid()) 5100 return ExprError(); 5101 Base = Result.get(); 5102 } 5103 QualType BaseTy = Base->getType(); 5104 // Delay analysis of the types/expressions if instantiation/specialization is 5105 // required. 5106 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5107 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5108 LParenLoc, RParenLoc, Dims, Brackets); 5109 if (!BaseTy->isPointerType() || 5110 (!Base->isTypeDependent() && 5111 BaseTy->getPointeeType()->isIncompleteType())) 5112 return ExprError(Diag(Base->getExprLoc(), 5113 diag::err_omp_non_pointer_type_array_shaping_base) 5114 << Base->getSourceRange()); 5115 5116 SmallVector<Expr *, 4> NewDims; 5117 bool ErrorFound = false; 5118 for (Expr *Dim : Dims) { 5119 if (Dim->getType()->isPlaceholderType()) { 5120 ExprResult Result = CheckPlaceholderExpr(Dim); 5121 if (Result.isInvalid()) { 5122 ErrorFound = true; 5123 continue; 5124 } 5125 Result = DefaultLvalueConversion(Result.get()); 5126 if (Result.isInvalid()) { 5127 ErrorFound = true; 5128 continue; 5129 } 5130 Dim = Result.get(); 5131 } 5132 if (!Dim->isTypeDependent()) { 5133 ExprResult Result = 5134 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5135 if (Result.isInvalid()) { 5136 ErrorFound = true; 5137 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5138 << Dim->getSourceRange(); 5139 continue; 5140 } 5141 Dim = Result.get(); 5142 Expr::EvalResult EvResult; 5143 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5144 // OpenMP 5.0, [2.1.4 Array Shaping] 5145 // Each si is an integral type expression that must evaluate to a 5146 // positive integer. 5147 llvm::APSInt Value = EvResult.Val.getInt(); 5148 if (!Value.isStrictlyPositive()) { 5149 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5150 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5151 << Dim->getSourceRange(); 5152 ErrorFound = true; 5153 continue; 5154 } 5155 } 5156 } 5157 NewDims.push_back(Dim); 5158 } 5159 if (ErrorFound) 5160 return ExprError(); 5161 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5162 LParenLoc, RParenLoc, NewDims, Brackets); 5163 } 5164 5165 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5166 SourceLocation LLoc, SourceLocation RLoc, 5167 ArrayRef<OMPIteratorData> Data) { 5168 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5169 bool IsCorrect = true; 5170 for (const OMPIteratorData &D : Data) { 5171 TypeSourceInfo *TInfo = nullptr; 5172 SourceLocation StartLoc; 5173 QualType DeclTy; 5174 if (!D.Type.getAsOpaquePtr()) { 5175 // OpenMP 5.0, 2.1.6 Iterators 5176 // In an iterator-specifier, if the iterator-type is not specified then 5177 // the type of that iterator is of int type. 5178 DeclTy = Context.IntTy; 5179 StartLoc = D.DeclIdentLoc; 5180 } else { 5181 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5182 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5183 } 5184 5185 bool IsDeclTyDependent = DeclTy->isDependentType() || 5186 DeclTy->containsUnexpandedParameterPack() || 5187 DeclTy->isInstantiationDependentType(); 5188 if (!IsDeclTyDependent) { 5189 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5190 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5191 // The iterator-type must be an integral or pointer type. 5192 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5193 << DeclTy; 5194 IsCorrect = false; 5195 continue; 5196 } 5197 if (DeclTy.isConstant(Context)) { 5198 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5199 // The iterator-type must not be const qualified. 5200 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5201 << DeclTy; 5202 IsCorrect = false; 5203 continue; 5204 } 5205 } 5206 5207 // Iterator declaration. 5208 assert(D.DeclIdent && "Identifier expected."); 5209 // Always try to create iterator declarator to avoid extra error messages 5210 // about unknown declarations use. 5211 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5212 D.DeclIdent, DeclTy, TInfo, SC_None); 5213 VD->setImplicit(); 5214 if (S) { 5215 // Check for conflicting previous declaration. 5216 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5217 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5218 ForVisibleRedeclaration); 5219 Previous.suppressDiagnostics(); 5220 LookupName(Previous, S); 5221 5222 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5223 /*AllowInlineNamespace=*/false); 5224 if (!Previous.empty()) { 5225 NamedDecl *Old = Previous.getRepresentativeDecl(); 5226 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5227 Diag(Old->getLocation(), diag::note_previous_definition); 5228 } else { 5229 PushOnScopeChains(VD, S); 5230 } 5231 } else { 5232 CurContext->addDecl(VD); 5233 } 5234 Expr *Begin = D.Range.Begin; 5235 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5236 ExprResult BeginRes = 5237 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5238 Begin = BeginRes.get(); 5239 } 5240 Expr *End = D.Range.End; 5241 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5242 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5243 End = EndRes.get(); 5244 } 5245 Expr *Step = D.Range.Step; 5246 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5247 if (!Step->getType()->isIntegralType(Context)) { 5248 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5249 << Step << Step->getSourceRange(); 5250 IsCorrect = false; 5251 continue; 5252 } 5253 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5254 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5255 // If the step expression of a range-specification equals zero, the 5256 // behavior is unspecified. 5257 if (Result && Result->isZero()) { 5258 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5259 << Step << Step->getSourceRange(); 5260 IsCorrect = false; 5261 continue; 5262 } 5263 } 5264 if (!Begin || !End || !IsCorrect) { 5265 IsCorrect = false; 5266 continue; 5267 } 5268 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5269 IDElem.IteratorDecl = VD; 5270 IDElem.AssignmentLoc = D.AssignLoc; 5271 IDElem.Range.Begin = Begin; 5272 IDElem.Range.End = End; 5273 IDElem.Range.Step = Step; 5274 IDElem.ColonLoc = D.ColonLoc; 5275 IDElem.SecondColonLoc = D.SecColonLoc; 5276 } 5277 if (!IsCorrect) { 5278 // Invalidate all created iterator declarations if error is found. 5279 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5280 if (Decl *ID = D.IteratorDecl) 5281 ID->setInvalidDecl(); 5282 } 5283 return ExprError(); 5284 } 5285 SmallVector<OMPIteratorHelperData, 4> Helpers; 5286 if (!CurContext->isDependentContext()) { 5287 // Build number of ityeration for each iteration range. 5288 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5289 // ((Begini-Stepi-1-Endi) / -Stepi); 5290 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5291 // (Endi - Begini) 5292 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5293 D.Range.Begin); 5294 if(!Res.isUsable()) { 5295 IsCorrect = false; 5296 continue; 5297 } 5298 ExprResult St, St1; 5299 if (D.Range.Step) { 5300 St = D.Range.Step; 5301 // (Endi - Begini) + Stepi 5302 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5303 if (!Res.isUsable()) { 5304 IsCorrect = false; 5305 continue; 5306 } 5307 // (Endi - Begini) + Stepi - 1 5308 Res = 5309 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5310 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5311 if (!Res.isUsable()) { 5312 IsCorrect = false; 5313 continue; 5314 } 5315 // ((Endi - Begini) + Stepi - 1) / Stepi 5316 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5317 if (!Res.isUsable()) { 5318 IsCorrect = false; 5319 continue; 5320 } 5321 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5322 // (Begini - Endi) 5323 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5324 D.Range.Begin, D.Range.End); 5325 if (!Res1.isUsable()) { 5326 IsCorrect = false; 5327 continue; 5328 } 5329 // (Begini - Endi) - Stepi 5330 Res1 = 5331 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5332 if (!Res1.isUsable()) { 5333 IsCorrect = false; 5334 continue; 5335 } 5336 // (Begini - Endi) - Stepi - 1 5337 Res1 = 5338 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5339 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5340 if (!Res1.isUsable()) { 5341 IsCorrect = false; 5342 continue; 5343 } 5344 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5345 Res1 = 5346 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5347 if (!Res1.isUsable()) { 5348 IsCorrect = false; 5349 continue; 5350 } 5351 // Stepi > 0. 5352 ExprResult CmpRes = 5353 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5354 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5355 if (!CmpRes.isUsable()) { 5356 IsCorrect = false; 5357 continue; 5358 } 5359 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5360 Res.get(), Res1.get()); 5361 if (!Res.isUsable()) { 5362 IsCorrect = false; 5363 continue; 5364 } 5365 } 5366 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5367 if (!Res.isUsable()) { 5368 IsCorrect = false; 5369 continue; 5370 } 5371 5372 // Build counter update. 5373 // Build counter. 5374 auto *CounterVD = 5375 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5376 D.IteratorDecl->getBeginLoc(), nullptr, 5377 Res.get()->getType(), nullptr, SC_None); 5378 CounterVD->setImplicit(); 5379 ExprResult RefRes = 5380 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5381 D.IteratorDecl->getBeginLoc()); 5382 // Build counter update. 5383 // I = Begini + counter * Stepi; 5384 ExprResult UpdateRes; 5385 if (D.Range.Step) { 5386 UpdateRes = CreateBuiltinBinOp( 5387 D.AssignmentLoc, BO_Mul, 5388 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5389 } else { 5390 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5391 } 5392 if (!UpdateRes.isUsable()) { 5393 IsCorrect = false; 5394 continue; 5395 } 5396 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5397 UpdateRes.get()); 5398 if (!UpdateRes.isUsable()) { 5399 IsCorrect = false; 5400 continue; 5401 } 5402 ExprResult VDRes = 5403 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5404 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5405 D.IteratorDecl->getBeginLoc()); 5406 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5407 UpdateRes.get()); 5408 if (!UpdateRes.isUsable()) { 5409 IsCorrect = false; 5410 continue; 5411 } 5412 UpdateRes = 5413 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5414 if (!UpdateRes.isUsable()) { 5415 IsCorrect = false; 5416 continue; 5417 } 5418 ExprResult CounterUpdateRes = 5419 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5420 if (!CounterUpdateRes.isUsable()) { 5421 IsCorrect = false; 5422 continue; 5423 } 5424 CounterUpdateRes = 5425 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5426 if (!CounterUpdateRes.isUsable()) { 5427 IsCorrect = false; 5428 continue; 5429 } 5430 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5431 HD.CounterVD = CounterVD; 5432 HD.Upper = Res.get(); 5433 HD.Update = UpdateRes.get(); 5434 HD.CounterUpdate = CounterUpdateRes.get(); 5435 } 5436 } else { 5437 Helpers.assign(ID.size(), {}); 5438 } 5439 if (!IsCorrect) { 5440 // Invalidate all created iterator declarations if error is found. 5441 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5442 if (Decl *ID = D.IteratorDecl) 5443 ID->setInvalidDecl(); 5444 } 5445 return ExprError(); 5446 } 5447 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5448 LLoc, RLoc, ID, Helpers); 5449 } 5450 5451 ExprResult 5452 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5453 Expr *Idx, SourceLocation RLoc) { 5454 Expr *LHSExp = Base; 5455 Expr *RHSExp = Idx; 5456 5457 ExprValueKind VK = VK_LValue; 5458 ExprObjectKind OK = OK_Ordinary; 5459 5460 // Per C++ core issue 1213, the result is an xvalue if either operand is 5461 // a non-lvalue array, and an lvalue otherwise. 5462 if (getLangOpts().CPlusPlus11) { 5463 for (auto *Op : {LHSExp, RHSExp}) { 5464 Op = Op->IgnoreImplicit(); 5465 if (Op->getType()->isArrayType() && !Op->isLValue()) 5466 VK = VK_XValue; 5467 } 5468 } 5469 5470 // Perform default conversions. 5471 if (!LHSExp->getType()->getAs<VectorType>()) { 5472 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5473 if (Result.isInvalid()) 5474 return ExprError(); 5475 LHSExp = Result.get(); 5476 } 5477 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5478 if (Result.isInvalid()) 5479 return ExprError(); 5480 RHSExp = Result.get(); 5481 5482 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5483 5484 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5485 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5486 // in the subscript position. As a result, we need to derive the array base 5487 // and index from the expression types. 5488 Expr *BaseExpr, *IndexExpr; 5489 QualType ResultType; 5490 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5491 BaseExpr = LHSExp; 5492 IndexExpr = RHSExp; 5493 ResultType = Context.DependentTy; 5494 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5495 BaseExpr = LHSExp; 5496 IndexExpr = RHSExp; 5497 ResultType = PTy->getPointeeType(); 5498 } else if (const ObjCObjectPointerType *PTy = 5499 LHSTy->getAs<ObjCObjectPointerType>()) { 5500 BaseExpr = LHSExp; 5501 IndexExpr = RHSExp; 5502 5503 // Use custom logic if this should be the pseudo-object subscript 5504 // expression. 5505 if (!LangOpts.isSubscriptPointerArithmetic()) 5506 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5507 nullptr); 5508 5509 ResultType = PTy->getPointeeType(); 5510 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5511 // Handle the uncommon case of "123[Ptr]". 5512 BaseExpr = RHSExp; 5513 IndexExpr = LHSExp; 5514 ResultType = PTy->getPointeeType(); 5515 } else if (const ObjCObjectPointerType *PTy = 5516 RHSTy->getAs<ObjCObjectPointerType>()) { 5517 // Handle the uncommon case of "123[Ptr]". 5518 BaseExpr = RHSExp; 5519 IndexExpr = LHSExp; 5520 ResultType = PTy->getPointeeType(); 5521 if (!LangOpts.isSubscriptPointerArithmetic()) { 5522 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5523 << ResultType << BaseExpr->getSourceRange(); 5524 return ExprError(); 5525 } 5526 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5527 BaseExpr = LHSExp; // vectors: V[123] 5528 IndexExpr = RHSExp; 5529 // We apply C++ DR1213 to vector subscripting too. 5530 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5531 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5532 if (Materialized.isInvalid()) 5533 return ExprError(); 5534 LHSExp = Materialized.get(); 5535 } 5536 VK = LHSExp->getValueKind(); 5537 if (VK != VK_PRValue) 5538 OK = OK_VectorComponent; 5539 5540 ResultType = VTy->getElementType(); 5541 QualType BaseType = BaseExpr->getType(); 5542 Qualifiers BaseQuals = BaseType.getQualifiers(); 5543 Qualifiers MemberQuals = ResultType.getQualifiers(); 5544 Qualifiers Combined = BaseQuals + MemberQuals; 5545 if (Combined != MemberQuals) 5546 ResultType = Context.getQualifiedType(ResultType, Combined); 5547 } else if (LHSTy->isArrayType()) { 5548 // If we see an array that wasn't promoted by 5549 // DefaultFunctionArrayLvalueConversion, it must be an array that 5550 // wasn't promoted because of the C90 rule that doesn't 5551 // allow promoting non-lvalue arrays. Warn, then 5552 // force the promotion here. 5553 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5554 << LHSExp->getSourceRange(); 5555 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5556 CK_ArrayToPointerDecay).get(); 5557 LHSTy = LHSExp->getType(); 5558 5559 BaseExpr = LHSExp; 5560 IndexExpr = RHSExp; 5561 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5562 } else if (RHSTy->isArrayType()) { 5563 // Same as previous, except for 123[f().a] case 5564 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5565 << RHSExp->getSourceRange(); 5566 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5567 CK_ArrayToPointerDecay).get(); 5568 RHSTy = RHSExp->getType(); 5569 5570 BaseExpr = RHSExp; 5571 IndexExpr = LHSExp; 5572 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5573 } else { 5574 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5575 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5576 } 5577 // C99 6.5.2.1p1 5578 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5579 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5580 << IndexExpr->getSourceRange()); 5581 5582 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5583 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5584 && !IndexExpr->isTypeDependent()) 5585 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5586 5587 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5588 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5589 // type. Note that Functions are not objects, and that (in C99 parlance) 5590 // incomplete types are not object types. 5591 if (ResultType->isFunctionType()) { 5592 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5593 << ResultType << BaseExpr->getSourceRange(); 5594 return ExprError(); 5595 } 5596 5597 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5598 // GNU extension: subscripting on pointer to void 5599 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5600 << BaseExpr->getSourceRange(); 5601 5602 // C forbids expressions of unqualified void type from being l-values. 5603 // See IsCForbiddenLValueType. 5604 if (!ResultType.hasQualifiers()) 5605 VK = VK_PRValue; 5606 } else if (!ResultType->isDependentType() && 5607 RequireCompleteSizedType( 5608 LLoc, ResultType, 5609 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5610 return ExprError(); 5611 5612 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5613 !ResultType.isCForbiddenLValueType()); 5614 5615 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5616 FunctionScopes.size() > 1) { 5617 if (auto *TT = 5618 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5619 for (auto I = FunctionScopes.rbegin(), 5620 E = std::prev(FunctionScopes.rend()); 5621 I != E; ++I) { 5622 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5623 if (CSI == nullptr) 5624 break; 5625 DeclContext *DC = nullptr; 5626 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5627 DC = LSI->CallOperator; 5628 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5629 DC = CRSI->TheCapturedDecl; 5630 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5631 DC = BSI->TheDecl; 5632 if (DC) { 5633 if (DC->containsDecl(TT->getDecl())) 5634 break; 5635 captureVariablyModifiedType( 5636 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5637 } 5638 } 5639 } 5640 } 5641 5642 return new (Context) 5643 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5644 } 5645 5646 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5647 ParmVarDecl *Param) { 5648 if (Param->hasUnparsedDefaultArg()) { 5649 // If we've already cleared out the location for the default argument, 5650 // that means we're parsing it right now. 5651 if (!UnparsedDefaultArgLocs.count(Param)) { 5652 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5653 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5654 Param->setInvalidDecl(); 5655 return true; 5656 } 5657 5658 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5659 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5660 Diag(UnparsedDefaultArgLocs[Param], 5661 diag::note_default_argument_declared_here); 5662 return true; 5663 } 5664 5665 if (Param->hasUninstantiatedDefaultArg() && 5666 InstantiateDefaultArgument(CallLoc, FD, Param)) 5667 return true; 5668 5669 assert(Param->hasInit() && "default argument but no initializer?"); 5670 5671 // If the default expression creates temporaries, we need to 5672 // push them to the current stack of expression temporaries so they'll 5673 // be properly destroyed. 5674 // FIXME: We should really be rebuilding the default argument with new 5675 // bound temporaries; see the comment in PR5810. 5676 // We don't need to do that with block decls, though, because 5677 // blocks in default argument expression can never capture anything. 5678 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5679 // Set the "needs cleanups" bit regardless of whether there are 5680 // any explicit objects. 5681 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5682 5683 // Append all the objects to the cleanup list. Right now, this 5684 // should always be a no-op, because blocks in default argument 5685 // expressions should never be able to capture anything. 5686 assert(!Init->getNumObjects() && 5687 "default argument expression has capturing blocks?"); 5688 } 5689 5690 // We already type-checked the argument, so we know it works. 5691 // Just mark all of the declarations in this potentially-evaluated expression 5692 // as being "referenced". 5693 EnterExpressionEvaluationContext EvalContext( 5694 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5695 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5696 /*SkipLocalVariables=*/true); 5697 return false; 5698 } 5699 5700 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5701 FunctionDecl *FD, ParmVarDecl *Param) { 5702 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5703 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5704 return ExprError(); 5705 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5706 } 5707 5708 Sema::VariadicCallType 5709 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5710 Expr *Fn) { 5711 if (Proto && Proto->isVariadic()) { 5712 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 5713 return VariadicConstructor; 5714 else if (Fn && Fn->getType()->isBlockPointerType()) 5715 return VariadicBlock; 5716 else if (FDecl) { 5717 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5718 if (Method->isInstance()) 5719 return VariadicMethod; 5720 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5721 return VariadicMethod; 5722 return VariadicFunction; 5723 } 5724 return VariadicDoesNotApply; 5725 } 5726 5727 namespace { 5728 class FunctionCallCCC final : public FunctionCallFilterCCC { 5729 public: 5730 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5731 unsigned NumArgs, MemberExpr *ME) 5732 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5733 FunctionName(FuncName) {} 5734 5735 bool ValidateCandidate(const TypoCorrection &candidate) override { 5736 if (!candidate.getCorrectionSpecifier() || 5737 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5738 return false; 5739 } 5740 5741 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5742 } 5743 5744 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5745 return std::make_unique<FunctionCallCCC>(*this); 5746 } 5747 5748 private: 5749 const IdentifierInfo *const FunctionName; 5750 }; 5751 } 5752 5753 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5754 FunctionDecl *FDecl, 5755 ArrayRef<Expr *> Args) { 5756 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5757 DeclarationName FuncName = FDecl->getDeclName(); 5758 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5759 5760 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5761 if (TypoCorrection Corrected = S.CorrectTypo( 5762 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5763 S.getScopeForContext(S.CurContext), nullptr, CCC, 5764 Sema::CTK_ErrorRecovery)) { 5765 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5766 if (Corrected.isOverloaded()) { 5767 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5768 OverloadCandidateSet::iterator Best; 5769 for (NamedDecl *CD : Corrected) { 5770 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5771 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5772 OCS); 5773 } 5774 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5775 case OR_Success: 5776 ND = Best->FoundDecl; 5777 Corrected.setCorrectionDecl(ND); 5778 break; 5779 default: 5780 break; 5781 } 5782 } 5783 ND = ND->getUnderlyingDecl(); 5784 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5785 return Corrected; 5786 } 5787 } 5788 return TypoCorrection(); 5789 } 5790 5791 /// ConvertArgumentsForCall - Converts the arguments specified in 5792 /// Args/NumArgs to the parameter types of the function FDecl with 5793 /// function prototype Proto. Call is the call expression itself, and 5794 /// Fn is the function expression. For a C++ member function, this 5795 /// routine does not attempt to convert the object argument. Returns 5796 /// true if the call is ill-formed. 5797 bool 5798 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5799 FunctionDecl *FDecl, 5800 const FunctionProtoType *Proto, 5801 ArrayRef<Expr *> Args, 5802 SourceLocation RParenLoc, 5803 bool IsExecConfig) { 5804 // Bail out early if calling a builtin with custom typechecking. 5805 if (FDecl) 5806 if (unsigned ID = FDecl->getBuiltinID()) 5807 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5808 return false; 5809 5810 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5811 // assignment, to the types of the corresponding parameter, ... 5812 unsigned NumParams = Proto->getNumParams(); 5813 bool Invalid = false; 5814 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5815 unsigned FnKind = Fn->getType()->isBlockPointerType() 5816 ? 1 /* block */ 5817 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5818 : 0 /* function */); 5819 5820 // If too few arguments are available (and we don't have default 5821 // arguments for the remaining parameters), don't make the call. 5822 if (Args.size() < NumParams) { 5823 if (Args.size() < MinArgs) { 5824 TypoCorrection TC; 5825 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5826 unsigned diag_id = 5827 MinArgs == NumParams && !Proto->isVariadic() 5828 ? diag::err_typecheck_call_too_few_args_suggest 5829 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5830 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5831 << static_cast<unsigned>(Args.size()) 5832 << TC.getCorrectionRange()); 5833 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5834 Diag(RParenLoc, 5835 MinArgs == NumParams && !Proto->isVariadic() 5836 ? diag::err_typecheck_call_too_few_args_one 5837 : diag::err_typecheck_call_too_few_args_at_least_one) 5838 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5839 else 5840 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5841 ? diag::err_typecheck_call_too_few_args 5842 : diag::err_typecheck_call_too_few_args_at_least) 5843 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5844 << Fn->getSourceRange(); 5845 5846 // Emit the location of the prototype. 5847 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5848 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5849 5850 return true; 5851 } 5852 // We reserve space for the default arguments when we create 5853 // the call expression, before calling ConvertArgumentsForCall. 5854 assert((Call->getNumArgs() == NumParams) && 5855 "We should have reserved space for the default arguments before!"); 5856 } 5857 5858 // If too many are passed and not variadic, error on the extras and drop 5859 // them. 5860 if (Args.size() > NumParams) { 5861 if (!Proto->isVariadic()) { 5862 TypoCorrection TC; 5863 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5864 unsigned diag_id = 5865 MinArgs == NumParams && !Proto->isVariadic() 5866 ? diag::err_typecheck_call_too_many_args_suggest 5867 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5868 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5869 << static_cast<unsigned>(Args.size()) 5870 << TC.getCorrectionRange()); 5871 } else if (NumParams == 1 && FDecl && 5872 FDecl->getParamDecl(0)->getDeclName()) 5873 Diag(Args[NumParams]->getBeginLoc(), 5874 MinArgs == NumParams 5875 ? diag::err_typecheck_call_too_many_args_one 5876 : diag::err_typecheck_call_too_many_args_at_most_one) 5877 << FnKind << FDecl->getParamDecl(0) 5878 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5879 << SourceRange(Args[NumParams]->getBeginLoc(), 5880 Args.back()->getEndLoc()); 5881 else 5882 Diag(Args[NumParams]->getBeginLoc(), 5883 MinArgs == NumParams 5884 ? diag::err_typecheck_call_too_many_args 5885 : diag::err_typecheck_call_too_many_args_at_most) 5886 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5887 << Fn->getSourceRange() 5888 << SourceRange(Args[NumParams]->getBeginLoc(), 5889 Args.back()->getEndLoc()); 5890 5891 // Emit the location of the prototype. 5892 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5893 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5894 5895 // This deletes the extra arguments. 5896 Call->shrinkNumArgs(NumParams); 5897 return true; 5898 } 5899 } 5900 SmallVector<Expr *, 8> AllArgs; 5901 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5902 5903 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5904 AllArgs, CallType); 5905 if (Invalid) 5906 return true; 5907 unsigned TotalNumArgs = AllArgs.size(); 5908 for (unsigned i = 0; i < TotalNumArgs; ++i) 5909 Call->setArg(i, AllArgs[i]); 5910 5911 Call->computeDependence(); 5912 return false; 5913 } 5914 5915 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5916 const FunctionProtoType *Proto, 5917 unsigned FirstParam, ArrayRef<Expr *> Args, 5918 SmallVectorImpl<Expr *> &AllArgs, 5919 VariadicCallType CallType, bool AllowExplicit, 5920 bool IsListInitialization) { 5921 unsigned NumParams = Proto->getNumParams(); 5922 bool Invalid = false; 5923 size_t ArgIx = 0; 5924 // Continue to check argument types (even if we have too few/many args). 5925 for (unsigned i = FirstParam; i < NumParams; i++) { 5926 QualType ProtoArgType = Proto->getParamType(i); 5927 5928 Expr *Arg; 5929 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5930 if (ArgIx < Args.size()) { 5931 Arg = Args[ArgIx++]; 5932 5933 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5934 diag::err_call_incomplete_argument, Arg)) 5935 return true; 5936 5937 // Strip the unbridged-cast placeholder expression off, if applicable. 5938 bool CFAudited = false; 5939 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5940 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5941 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5942 Arg = stripARCUnbridgedCast(Arg); 5943 else if (getLangOpts().ObjCAutoRefCount && 5944 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5945 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5946 CFAudited = true; 5947 5948 if (Proto->getExtParameterInfo(i).isNoEscape() && 5949 ProtoArgType->isBlockPointerType()) 5950 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5951 BE->getBlockDecl()->setDoesNotEscape(); 5952 5953 InitializedEntity Entity = 5954 Param ? InitializedEntity::InitializeParameter(Context, Param, 5955 ProtoArgType) 5956 : InitializedEntity::InitializeParameter( 5957 Context, ProtoArgType, Proto->isParamConsumed(i)); 5958 5959 // Remember that parameter belongs to a CF audited API. 5960 if (CFAudited) 5961 Entity.setParameterCFAudited(); 5962 5963 ExprResult ArgE = PerformCopyInitialization( 5964 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5965 if (ArgE.isInvalid()) 5966 return true; 5967 5968 Arg = ArgE.getAs<Expr>(); 5969 } else { 5970 assert(Param && "can't use default arguments without a known callee"); 5971 5972 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5973 if (ArgExpr.isInvalid()) 5974 return true; 5975 5976 Arg = ArgExpr.getAs<Expr>(); 5977 } 5978 5979 // Check for array bounds violations for each argument to the call. This 5980 // check only triggers warnings when the argument isn't a more complex Expr 5981 // with its own checking, such as a BinaryOperator. 5982 CheckArrayAccess(Arg); 5983 5984 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5985 CheckStaticArrayArgument(CallLoc, Param, Arg); 5986 5987 AllArgs.push_back(Arg); 5988 } 5989 5990 // If this is a variadic call, handle args passed through "...". 5991 if (CallType != VariadicDoesNotApply) { 5992 // Assume that extern "C" functions with variadic arguments that 5993 // return __unknown_anytype aren't *really* variadic. 5994 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5995 FDecl->isExternC()) { 5996 for (Expr *A : Args.slice(ArgIx)) { 5997 QualType paramType; // ignored 5998 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5999 Invalid |= arg.isInvalid(); 6000 AllArgs.push_back(arg.get()); 6001 } 6002 6003 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6004 } else { 6005 for (Expr *A : Args.slice(ArgIx)) { 6006 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6007 Invalid |= Arg.isInvalid(); 6008 AllArgs.push_back(Arg.get()); 6009 } 6010 } 6011 6012 // Check for array bounds violations. 6013 for (Expr *A : Args.slice(ArgIx)) 6014 CheckArrayAccess(A); 6015 } 6016 return Invalid; 6017 } 6018 6019 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6020 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6021 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6022 TL = DTL.getOriginalLoc(); 6023 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6024 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6025 << ATL.getLocalSourceRange(); 6026 } 6027 6028 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6029 /// array parameter, check that it is non-null, and that if it is formed by 6030 /// array-to-pointer decay, the underlying array is sufficiently large. 6031 /// 6032 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6033 /// array type derivation, then for each call to the function, the value of the 6034 /// corresponding actual argument shall provide access to the first element of 6035 /// an array with at least as many elements as specified by the size expression. 6036 void 6037 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6038 ParmVarDecl *Param, 6039 const Expr *ArgExpr) { 6040 // Static array parameters are not supported in C++. 6041 if (!Param || getLangOpts().CPlusPlus) 6042 return; 6043 6044 QualType OrigTy = Param->getOriginalType(); 6045 6046 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6047 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6048 return; 6049 6050 if (ArgExpr->isNullPointerConstant(Context, 6051 Expr::NPC_NeverValueDependent)) { 6052 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6053 DiagnoseCalleeStaticArrayParam(*this, Param); 6054 return; 6055 } 6056 6057 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6058 if (!CAT) 6059 return; 6060 6061 const ConstantArrayType *ArgCAT = 6062 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6063 if (!ArgCAT) 6064 return; 6065 6066 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6067 ArgCAT->getElementType())) { 6068 if (ArgCAT->getSize().ult(CAT->getSize())) { 6069 Diag(CallLoc, diag::warn_static_array_too_small) 6070 << ArgExpr->getSourceRange() 6071 << (unsigned)ArgCAT->getSize().getZExtValue() 6072 << (unsigned)CAT->getSize().getZExtValue() << 0; 6073 DiagnoseCalleeStaticArrayParam(*this, Param); 6074 } 6075 return; 6076 } 6077 6078 Optional<CharUnits> ArgSize = 6079 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6080 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6081 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6082 Diag(CallLoc, diag::warn_static_array_too_small) 6083 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6084 << (unsigned)ParmSize->getQuantity() << 1; 6085 DiagnoseCalleeStaticArrayParam(*this, Param); 6086 } 6087 } 6088 6089 /// Given a function expression of unknown-any type, try to rebuild it 6090 /// to have a function type. 6091 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6092 6093 /// Is the given type a placeholder that we need to lower out 6094 /// immediately during argument processing? 6095 static bool isPlaceholderToRemoveAsArg(QualType type) { 6096 // Placeholders are never sugared. 6097 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6098 if (!placeholder) return false; 6099 6100 switch (placeholder->getKind()) { 6101 // Ignore all the non-placeholder types. 6102 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6103 case BuiltinType::Id: 6104 #include "clang/Basic/OpenCLImageTypes.def" 6105 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6106 case BuiltinType::Id: 6107 #include "clang/Basic/OpenCLExtensionTypes.def" 6108 // In practice we'll never use this, since all SVE types are sugared 6109 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6110 #define SVE_TYPE(Name, Id, SingletonId) \ 6111 case BuiltinType::Id: 6112 #include "clang/Basic/AArch64SVEACLETypes.def" 6113 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6114 case BuiltinType::Id: 6115 #include "clang/Basic/PPCTypes.def" 6116 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6117 #include "clang/Basic/RISCVVTypes.def" 6118 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6119 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6120 #include "clang/AST/BuiltinTypes.def" 6121 return false; 6122 6123 // We cannot lower out overload sets; they might validly be resolved 6124 // by the call machinery. 6125 case BuiltinType::Overload: 6126 return false; 6127 6128 // Unbridged casts in ARC can be handled in some call positions and 6129 // should be left in place. 6130 case BuiltinType::ARCUnbridgedCast: 6131 return false; 6132 6133 // Pseudo-objects should be converted as soon as possible. 6134 case BuiltinType::PseudoObject: 6135 return true; 6136 6137 // The debugger mode could theoretically but currently does not try 6138 // to resolve unknown-typed arguments based on known parameter types. 6139 case BuiltinType::UnknownAny: 6140 return true; 6141 6142 // These are always invalid as call arguments and should be reported. 6143 case BuiltinType::BoundMember: 6144 case BuiltinType::BuiltinFn: 6145 case BuiltinType::IncompleteMatrixIdx: 6146 case BuiltinType::OMPArraySection: 6147 case BuiltinType::OMPArrayShaping: 6148 case BuiltinType::OMPIterator: 6149 return true; 6150 6151 } 6152 llvm_unreachable("bad builtin type kind"); 6153 } 6154 6155 /// Check an argument list for placeholders that we won't try to 6156 /// handle later. 6157 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6158 // Apply this processing to all the arguments at once instead of 6159 // dying at the first failure. 6160 bool hasInvalid = false; 6161 for (size_t i = 0, e = args.size(); i != e; i++) { 6162 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6163 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6164 if (result.isInvalid()) hasInvalid = true; 6165 else args[i] = result.get(); 6166 } 6167 } 6168 return hasInvalid; 6169 } 6170 6171 /// If a builtin function has a pointer argument with no explicit address 6172 /// space, then it should be able to accept a pointer to any address 6173 /// space as input. In order to do this, we need to replace the 6174 /// standard builtin declaration with one that uses the same address space 6175 /// as the call. 6176 /// 6177 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6178 /// it does not contain any pointer arguments without 6179 /// an address space qualifer. Otherwise the rewritten 6180 /// FunctionDecl is returned. 6181 /// TODO: Handle pointer return types. 6182 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6183 FunctionDecl *FDecl, 6184 MultiExprArg ArgExprs) { 6185 6186 QualType DeclType = FDecl->getType(); 6187 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6188 6189 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6190 ArgExprs.size() < FT->getNumParams()) 6191 return nullptr; 6192 6193 bool NeedsNewDecl = false; 6194 unsigned i = 0; 6195 SmallVector<QualType, 8> OverloadParams; 6196 6197 for (QualType ParamType : FT->param_types()) { 6198 6199 // Convert array arguments to pointer to simplify type lookup. 6200 ExprResult ArgRes = 6201 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6202 if (ArgRes.isInvalid()) 6203 return nullptr; 6204 Expr *Arg = ArgRes.get(); 6205 QualType ArgType = Arg->getType(); 6206 if (!ParamType->isPointerType() || 6207 ParamType.hasAddressSpace() || 6208 !ArgType->isPointerType() || 6209 !ArgType->getPointeeType().hasAddressSpace()) { 6210 OverloadParams.push_back(ParamType); 6211 continue; 6212 } 6213 6214 QualType PointeeType = ParamType->getPointeeType(); 6215 if (PointeeType.hasAddressSpace()) 6216 continue; 6217 6218 NeedsNewDecl = true; 6219 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6220 6221 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6222 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6223 } 6224 6225 if (!NeedsNewDecl) 6226 return nullptr; 6227 6228 FunctionProtoType::ExtProtoInfo EPI; 6229 EPI.Variadic = FT->isVariadic(); 6230 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6231 OverloadParams, EPI); 6232 DeclContext *Parent = FDecl->getParent(); 6233 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6234 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6235 FDecl->getIdentifier(), OverloadTy, 6236 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6237 false, 6238 /*hasPrototype=*/true); 6239 SmallVector<ParmVarDecl*, 16> Params; 6240 FT = cast<FunctionProtoType>(OverloadTy); 6241 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6242 QualType ParamType = FT->getParamType(i); 6243 ParmVarDecl *Parm = 6244 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6245 SourceLocation(), nullptr, ParamType, 6246 /*TInfo=*/nullptr, SC_None, nullptr); 6247 Parm->setScopeInfo(0, i); 6248 Params.push_back(Parm); 6249 } 6250 OverloadDecl->setParams(Params); 6251 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6252 return OverloadDecl; 6253 } 6254 6255 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6256 FunctionDecl *Callee, 6257 MultiExprArg ArgExprs) { 6258 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6259 // similar attributes) really don't like it when functions are called with an 6260 // invalid number of args. 6261 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6262 /*PartialOverloading=*/false) && 6263 !Callee->isVariadic()) 6264 return; 6265 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6266 return; 6267 6268 if (const EnableIfAttr *Attr = 6269 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6270 S.Diag(Fn->getBeginLoc(), 6271 isa<CXXMethodDecl>(Callee) 6272 ? diag::err_ovl_no_viable_member_function_in_call 6273 : diag::err_ovl_no_viable_function_in_call) 6274 << Callee << Callee->getSourceRange(); 6275 S.Diag(Callee->getLocation(), 6276 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6277 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6278 return; 6279 } 6280 } 6281 6282 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6283 const UnresolvedMemberExpr *const UME, Sema &S) { 6284 6285 const auto GetFunctionLevelDCIfCXXClass = 6286 [](Sema &S) -> const CXXRecordDecl * { 6287 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6288 if (!DC || !DC->getParent()) 6289 return nullptr; 6290 6291 // If the call to some member function was made from within a member 6292 // function body 'M' return return 'M's parent. 6293 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6294 return MD->getParent()->getCanonicalDecl(); 6295 // else the call was made from within a default member initializer of a 6296 // class, so return the class. 6297 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6298 return RD->getCanonicalDecl(); 6299 return nullptr; 6300 }; 6301 // If our DeclContext is neither a member function nor a class (in the 6302 // case of a lambda in a default member initializer), we can't have an 6303 // enclosing 'this'. 6304 6305 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6306 if (!CurParentClass) 6307 return false; 6308 6309 // The naming class for implicit member functions call is the class in which 6310 // name lookup starts. 6311 const CXXRecordDecl *const NamingClass = 6312 UME->getNamingClass()->getCanonicalDecl(); 6313 assert(NamingClass && "Must have naming class even for implicit access"); 6314 6315 // If the unresolved member functions were found in a 'naming class' that is 6316 // related (either the same or derived from) to the class that contains the 6317 // member function that itself contained the implicit member access. 6318 6319 return CurParentClass == NamingClass || 6320 CurParentClass->isDerivedFrom(NamingClass); 6321 } 6322 6323 static void 6324 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6325 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6326 6327 if (!UME) 6328 return; 6329 6330 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6331 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6332 // already been captured, or if this is an implicit member function call (if 6333 // it isn't, an attempt to capture 'this' should already have been made). 6334 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6335 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6336 return; 6337 6338 // Check if the naming class in which the unresolved members were found is 6339 // related (same as or is a base of) to the enclosing class. 6340 6341 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6342 return; 6343 6344 6345 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6346 // If the enclosing function is not dependent, then this lambda is 6347 // capture ready, so if we can capture this, do so. 6348 if (!EnclosingFunctionCtx->isDependentContext()) { 6349 // If the current lambda and all enclosing lambdas can capture 'this' - 6350 // then go ahead and capture 'this' (since our unresolved overload set 6351 // contains at least one non-static member function). 6352 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6353 S.CheckCXXThisCapture(CallLoc); 6354 } else if (S.CurContext->isDependentContext()) { 6355 // ... since this is an implicit member reference, that might potentially 6356 // involve a 'this' capture, mark 'this' for potential capture in 6357 // enclosing lambdas. 6358 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6359 CurLSI->addPotentialThisCapture(CallLoc); 6360 } 6361 } 6362 6363 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6364 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6365 Expr *ExecConfig) { 6366 ExprResult Call = 6367 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6368 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6369 if (Call.isInvalid()) 6370 return Call; 6371 6372 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6373 // language modes. 6374 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6375 if (ULE->hasExplicitTemplateArgs() && 6376 ULE->decls_begin() == ULE->decls_end()) { 6377 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6378 ? diag::warn_cxx17_compat_adl_only_template_id 6379 : diag::ext_adl_only_template_id) 6380 << ULE->getName(); 6381 } 6382 } 6383 6384 if (LangOpts.OpenMP) 6385 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6386 ExecConfig); 6387 6388 return Call; 6389 } 6390 6391 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6392 /// This provides the location of the left/right parens and a list of comma 6393 /// locations. 6394 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6395 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6396 Expr *ExecConfig, bool IsExecConfig, 6397 bool AllowRecovery) { 6398 // Since this might be a postfix expression, get rid of ParenListExprs. 6399 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6400 if (Result.isInvalid()) return ExprError(); 6401 Fn = Result.get(); 6402 6403 if (checkArgsForPlaceholders(*this, ArgExprs)) 6404 return ExprError(); 6405 6406 if (getLangOpts().CPlusPlus) { 6407 // If this is a pseudo-destructor expression, build the call immediately. 6408 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6409 if (!ArgExprs.empty()) { 6410 // Pseudo-destructor calls should not have any arguments. 6411 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6412 << FixItHint::CreateRemoval( 6413 SourceRange(ArgExprs.front()->getBeginLoc(), 6414 ArgExprs.back()->getEndLoc())); 6415 } 6416 6417 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6418 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6419 } 6420 if (Fn->getType() == Context.PseudoObjectTy) { 6421 ExprResult result = CheckPlaceholderExpr(Fn); 6422 if (result.isInvalid()) return ExprError(); 6423 Fn = result.get(); 6424 } 6425 6426 // Determine whether this is a dependent call inside a C++ template, 6427 // in which case we won't do any semantic analysis now. 6428 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6429 if (ExecConfig) { 6430 return CUDAKernelCallExpr::Create(Context, Fn, 6431 cast<CallExpr>(ExecConfig), ArgExprs, 6432 Context.DependentTy, VK_PRValue, 6433 RParenLoc, CurFPFeatureOverrides()); 6434 } else { 6435 6436 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6437 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6438 Fn->getBeginLoc()); 6439 6440 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6441 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6442 } 6443 } 6444 6445 // Determine whether this is a call to an object (C++ [over.call.object]). 6446 if (Fn->getType()->isRecordType()) 6447 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6448 RParenLoc); 6449 6450 if (Fn->getType() == Context.UnknownAnyTy) { 6451 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6452 if (result.isInvalid()) return ExprError(); 6453 Fn = result.get(); 6454 } 6455 6456 if (Fn->getType() == Context.BoundMemberTy) { 6457 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6458 RParenLoc, ExecConfig, IsExecConfig, 6459 AllowRecovery); 6460 } 6461 } 6462 6463 // Check for overloaded calls. This can happen even in C due to extensions. 6464 if (Fn->getType() == Context.OverloadTy) { 6465 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6466 6467 // We aren't supposed to apply this logic if there's an '&' involved. 6468 if (!find.HasFormOfMemberPointer) { 6469 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6470 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6471 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6472 OverloadExpr *ovl = find.Expression; 6473 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6474 return BuildOverloadedCallExpr( 6475 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6476 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6477 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6478 RParenLoc, ExecConfig, IsExecConfig, 6479 AllowRecovery); 6480 } 6481 } 6482 6483 // If we're directly calling a function, get the appropriate declaration. 6484 if (Fn->getType() == Context.UnknownAnyTy) { 6485 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6486 if (result.isInvalid()) return ExprError(); 6487 Fn = result.get(); 6488 } 6489 6490 Expr *NakedFn = Fn->IgnoreParens(); 6491 6492 bool CallingNDeclIndirectly = false; 6493 NamedDecl *NDecl = nullptr; 6494 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6495 if (UnOp->getOpcode() == UO_AddrOf) { 6496 CallingNDeclIndirectly = true; 6497 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6498 } 6499 } 6500 6501 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6502 NDecl = DRE->getDecl(); 6503 6504 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6505 if (FDecl && FDecl->getBuiltinID()) { 6506 // Rewrite the function decl for this builtin by replacing parameters 6507 // with no explicit address space with the address space of the arguments 6508 // in ArgExprs. 6509 if ((FDecl = 6510 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6511 NDecl = FDecl; 6512 Fn = DeclRefExpr::Create( 6513 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6514 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6515 nullptr, DRE->isNonOdrUse()); 6516 } 6517 } 6518 } else if (isa<MemberExpr>(NakedFn)) 6519 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6520 6521 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6522 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6523 FD, /*Complain=*/true, Fn->getBeginLoc())) 6524 return ExprError(); 6525 6526 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6527 6528 // If this expression is a call to a builtin function in HIP device 6529 // compilation, allow a pointer-type argument to default address space to be 6530 // passed as a pointer-type parameter to a non-default address space. 6531 // If Arg is declared in the default address space and Param is declared 6532 // in a non-default address space, perform an implicit address space cast to 6533 // the parameter type. 6534 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6535 FD->getBuiltinID()) { 6536 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6537 ParmVarDecl *Param = FD->getParamDecl(Idx); 6538 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6539 !ArgExprs[Idx]->getType()->isPointerType()) 6540 continue; 6541 6542 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6543 auto ArgTy = ArgExprs[Idx]->getType(); 6544 auto ArgPtTy = ArgTy->getPointeeType(); 6545 auto ArgAS = ArgPtTy.getAddressSpace(); 6546 6547 // Add address space cast if target address spaces are different 6548 bool NeedImplicitASC = 6549 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6550 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6551 // or from specific AS which has target AS matching that of Param. 6552 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6553 if (!NeedImplicitASC) 6554 continue; 6555 6556 // First, ensure that the Arg is an RValue. 6557 if (ArgExprs[Idx]->isGLValue()) { 6558 ArgExprs[Idx] = ImplicitCastExpr::Create( 6559 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6560 nullptr, VK_PRValue, FPOptionsOverride()); 6561 } 6562 6563 // Construct a new arg type with address space of Param 6564 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6565 ArgPtQuals.setAddressSpace(ParamAS); 6566 auto NewArgPtTy = 6567 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6568 auto NewArgTy = 6569 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6570 ArgTy.getQualifiers()); 6571 6572 // Finally perform an implicit address space cast 6573 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6574 CK_AddressSpaceConversion) 6575 .get(); 6576 } 6577 } 6578 } 6579 6580 if (Context.isDependenceAllowed() && 6581 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6582 assert(!getLangOpts().CPlusPlus); 6583 assert((Fn->containsErrors() || 6584 llvm::any_of(ArgExprs, 6585 [](clang::Expr *E) { return E->containsErrors(); })) && 6586 "should only occur in error-recovery path."); 6587 QualType ReturnType = 6588 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6589 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6590 : Context.DependentTy; 6591 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6592 Expr::getValueKindForType(ReturnType), RParenLoc, 6593 CurFPFeatureOverrides()); 6594 } 6595 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6596 ExecConfig, IsExecConfig); 6597 } 6598 6599 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6600 // with the specified CallArgs 6601 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6602 MultiExprArg CallArgs) { 6603 StringRef Name = Context.BuiltinInfo.getName(Id); 6604 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6605 Sema::LookupOrdinaryName); 6606 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6607 6608 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6609 assert(BuiltInDecl && "failed to find builtin declaration"); 6610 6611 ExprResult DeclRef = 6612 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6613 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6614 6615 ExprResult Call = 6616 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6617 6618 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6619 return Call.get(); 6620 } 6621 6622 /// Parse a __builtin_astype expression. 6623 /// 6624 /// __builtin_astype( value, dst type ) 6625 /// 6626 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6627 SourceLocation BuiltinLoc, 6628 SourceLocation RParenLoc) { 6629 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6630 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6631 } 6632 6633 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6634 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6635 SourceLocation BuiltinLoc, 6636 SourceLocation RParenLoc) { 6637 ExprValueKind VK = VK_PRValue; 6638 ExprObjectKind OK = OK_Ordinary; 6639 QualType SrcTy = E->getType(); 6640 if (!SrcTy->isDependentType() && 6641 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6642 return ExprError( 6643 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6644 << DestTy << SrcTy << E->getSourceRange()); 6645 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6646 } 6647 6648 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6649 /// provided arguments. 6650 /// 6651 /// __builtin_convertvector( value, dst type ) 6652 /// 6653 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6654 SourceLocation BuiltinLoc, 6655 SourceLocation RParenLoc) { 6656 TypeSourceInfo *TInfo; 6657 GetTypeFromParser(ParsedDestTy, &TInfo); 6658 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6659 } 6660 6661 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6662 /// i.e. an expression not of \p OverloadTy. The expression should 6663 /// unary-convert to an expression of function-pointer or 6664 /// block-pointer type. 6665 /// 6666 /// \param NDecl the declaration being called, if available 6667 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6668 SourceLocation LParenLoc, 6669 ArrayRef<Expr *> Args, 6670 SourceLocation RParenLoc, Expr *Config, 6671 bool IsExecConfig, ADLCallKind UsesADL) { 6672 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6673 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6674 6675 // Functions with 'interrupt' attribute cannot be called directly. 6676 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6677 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6678 return ExprError(); 6679 } 6680 6681 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6682 // so there's some risk when calling out to non-interrupt handler functions 6683 // that the callee might not preserve them. This is easy to diagnose here, 6684 // but can be very challenging to debug. 6685 // Likewise, X86 interrupt handlers may only call routines with attribute 6686 // no_caller_saved_registers since there is no efficient way to 6687 // save and restore the non-GPR state. 6688 if (auto *Caller = getCurFunctionDecl()) { 6689 if (Caller->hasAttr<ARMInterruptAttr>()) { 6690 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6691 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6692 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6693 if (FDecl) 6694 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6695 } 6696 } 6697 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6698 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6699 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6700 if (FDecl) 6701 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6702 } 6703 } 6704 6705 // Promote the function operand. 6706 // We special-case function promotion here because we only allow promoting 6707 // builtin functions to function pointers in the callee of a call. 6708 ExprResult Result; 6709 QualType ResultTy; 6710 if (BuiltinID && 6711 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6712 // Extract the return type from the (builtin) function pointer type. 6713 // FIXME Several builtins still have setType in 6714 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6715 // Builtins.def to ensure they are correct before removing setType calls. 6716 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6717 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6718 ResultTy = FDecl->getCallResultType(); 6719 } else { 6720 Result = CallExprUnaryConversions(Fn); 6721 ResultTy = Context.BoolTy; 6722 } 6723 if (Result.isInvalid()) 6724 return ExprError(); 6725 Fn = Result.get(); 6726 6727 // Check for a valid function type, but only if it is not a builtin which 6728 // requires custom type checking. These will be handled by 6729 // CheckBuiltinFunctionCall below just after creation of the call expression. 6730 const FunctionType *FuncT = nullptr; 6731 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6732 retry: 6733 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6734 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6735 // have type pointer to function". 6736 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6737 if (!FuncT) 6738 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6739 << Fn->getType() << Fn->getSourceRange()); 6740 } else if (const BlockPointerType *BPT = 6741 Fn->getType()->getAs<BlockPointerType>()) { 6742 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6743 } else { 6744 // Handle calls to expressions of unknown-any type. 6745 if (Fn->getType() == Context.UnknownAnyTy) { 6746 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6747 if (rewrite.isInvalid()) 6748 return ExprError(); 6749 Fn = rewrite.get(); 6750 goto retry; 6751 } 6752 6753 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6754 << Fn->getType() << Fn->getSourceRange()); 6755 } 6756 } 6757 6758 // Get the number of parameters in the function prototype, if any. 6759 // We will allocate space for max(Args.size(), NumParams) arguments 6760 // in the call expression. 6761 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6762 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6763 6764 CallExpr *TheCall; 6765 if (Config) { 6766 assert(UsesADL == ADLCallKind::NotADL && 6767 "CUDAKernelCallExpr should not use ADL"); 6768 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6769 Args, ResultTy, VK_PRValue, RParenLoc, 6770 CurFPFeatureOverrides(), NumParams); 6771 } else { 6772 TheCall = 6773 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6774 CurFPFeatureOverrides(), NumParams, UsesADL); 6775 } 6776 6777 if (!Context.isDependenceAllowed()) { 6778 // Forget about the nulled arguments since typo correction 6779 // do not handle them well. 6780 TheCall->shrinkNumArgs(Args.size()); 6781 // C cannot always handle TypoExpr nodes in builtin calls and direct 6782 // function calls as their argument checking don't necessarily handle 6783 // dependent types properly, so make sure any TypoExprs have been 6784 // dealt with. 6785 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6786 if (!Result.isUsable()) return ExprError(); 6787 CallExpr *TheOldCall = TheCall; 6788 TheCall = dyn_cast<CallExpr>(Result.get()); 6789 bool CorrectedTypos = TheCall != TheOldCall; 6790 if (!TheCall) return Result; 6791 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6792 6793 // A new call expression node was created if some typos were corrected. 6794 // However it may not have been constructed with enough storage. In this 6795 // case, rebuild the node with enough storage. The waste of space is 6796 // immaterial since this only happens when some typos were corrected. 6797 if (CorrectedTypos && Args.size() < NumParams) { 6798 if (Config) 6799 TheCall = CUDAKernelCallExpr::Create( 6800 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6801 RParenLoc, CurFPFeatureOverrides(), NumParams); 6802 else 6803 TheCall = 6804 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6805 CurFPFeatureOverrides(), NumParams, UsesADL); 6806 } 6807 // We can now handle the nulled arguments for the default arguments. 6808 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6809 } 6810 6811 // Bail out early if calling a builtin with custom type checking. 6812 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6813 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6814 6815 if (getLangOpts().CUDA) { 6816 if (Config) { 6817 // CUDA: Kernel calls must be to global functions 6818 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6819 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6820 << FDecl << Fn->getSourceRange()); 6821 6822 // CUDA: Kernel function must have 'void' return type 6823 if (!FuncT->getReturnType()->isVoidType() && 6824 !FuncT->getReturnType()->getAs<AutoType>() && 6825 !FuncT->getReturnType()->isInstantiationDependentType()) 6826 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6827 << Fn->getType() << Fn->getSourceRange()); 6828 } else { 6829 // CUDA: Calls to global functions must be configured 6830 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6831 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6832 << FDecl << Fn->getSourceRange()); 6833 } 6834 } 6835 6836 // Check for a valid return type 6837 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6838 FDecl)) 6839 return ExprError(); 6840 6841 // We know the result type of the call, set it. 6842 TheCall->setType(FuncT->getCallResultType(Context)); 6843 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6844 6845 if (Proto) { 6846 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6847 IsExecConfig)) 6848 return ExprError(); 6849 } else { 6850 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6851 6852 if (FDecl) { 6853 // Check if we have too few/too many template arguments, based 6854 // on our knowledge of the function definition. 6855 const FunctionDecl *Def = nullptr; 6856 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6857 Proto = Def->getType()->getAs<FunctionProtoType>(); 6858 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6859 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6860 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6861 } 6862 6863 // If the function we're calling isn't a function prototype, but we have 6864 // a function prototype from a prior declaratiom, use that prototype. 6865 if (!FDecl->hasPrototype()) 6866 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6867 } 6868 6869 // Promote the arguments (C99 6.5.2.2p6). 6870 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6871 Expr *Arg = Args[i]; 6872 6873 if (Proto && i < Proto->getNumParams()) { 6874 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6875 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6876 ExprResult ArgE = 6877 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6878 if (ArgE.isInvalid()) 6879 return true; 6880 6881 Arg = ArgE.getAs<Expr>(); 6882 6883 } else { 6884 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6885 6886 if (ArgE.isInvalid()) 6887 return true; 6888 6889 Arg = ArgE.getAs<Expr>(); 6890 } 6891 6892 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6893 diag::err_call_incomplete_argument, Arg)) 6894 return ExprError(); 6895 6896 TheCall->setArg(i, Arg); 6897 } 6898 TheCall->computeDependence(); 6899 } 6900 6901 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6902 if (!Method->isStatic()) 6903 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6904 << Fn->getSourceRange()); 6905 6906 // Check for sentinels 6907 if (NDecl) 6908 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6909 6910 // Warn for unions passing across security boundary (CMSE). 6911 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6912 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6913 if (const auto *RT = 6914 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6915 if (RT->getDecl()->isOrContainsUnion()) 6916 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6917 << 0 << i; 6918 } 6919 } 6920 } 6921 6922 // Do special checking on direct calls to functions. 6923 if (FDecl) { 6924 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6925 return ExprError(); 6926 6927 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6928 6929 if (BuiltinID) 6930 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6931 } else if (NDecl) { 6932 if (CheckPointerCall(NDecl, TheCall, Proto)) 6933 return ExprError(); 6934 } else { 6935 if (CheckOtherCall(TheCall, Proto)) 6936 return ExprError(); 6937 } 6938 6939 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6940 } 6941 6942 ExprResult 6943 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6944 SourceLocation RParenLoc, Expr *InitExpr) { 6945 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6946 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6947 6948 TypeSourceInfo *TInfo; 6949 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6950 if (!TInfo) 6951 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6952 6953 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6954 } 6955 6956 ExprResult 6957 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6958 SourceLocation RParenLoc, Expr *LiteralExpr) { 6959 QualType literalType = TInfo->getType(); 6960 6961 if (literalType->isArrayType()) { 6962 if (RequireCompleteSizedType( 6963 LParenLoc, Context.getBaseElementType(literalType), 6964 diag::err_array_incomplete_or_sizeless_type, 6965 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6966 return ExprError(); 6967 if (literalType->isVariableArrayType()) { 6968 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6969 diag::err_variable_object_no_init)) { 6970 return ExprError(); 6971 } 6972 } 6973 } else if (!literalType->isDependentType() && 6974 RequireCompleteType(LParenLoc, literalType, 6975 diag::err_typecheck_decl_incomplete_type, 6976 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6977 return ExprError(); 6978 6979 InitializedEntity Entity 6980 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6981 InitializationKind Kind 6982 = InitializationKind::CreateCStyleCast(LParenLoc, 6983 SourceRange(LParenLoc, RParenLoc), 6984 /*InitList=*/true); 6985 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6986 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6987 &literalType); 6988 if (Result.isInvalid()) 6989 return ExprError(); 6990 LiteralExpr = Result.get(); 6991 6992 bool isFileScope = !CurContext->isFunctionOrMethod(); 6993 6994 // In C, compound literals are l-values for some reason. 6995 // For GCC compatibility, in C++, file-scope array compound literals with 6996 // constant initializers are also l-values, and compound literals are 6997 // otherwise prvalues. 6998 // 6999 // (GCC also treats C++ list-initialized file-scope array prvalues with 7000 // constant initializers as l-values, but that's non-conforming, so we don't 7001 // follow it there.) 7002 // 7003 // FIXME: It would be better to handle the lvalue cases as materializing and 7004 // lifetime-extending a temporary object, but our materialized temporaries 7005 // representation only supports lifetime extension from a variable, not "out 7006 // of thin air". 7007 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7008 // is bound to the result of applying array-to-pointer decay to the compound 7009 // literal. 7010 // FIXME: GCC supports compound literals of reference type, which should 7011 // obviously have a value kind derived from the kind of reference involved. 7012 ExprValueKind VK = 7013 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7014 ? VK_PRValue 7015 : VK_LValue; 7016 7017 if (isFileScope) 7018 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7019 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7020 Expr *Init = ILE->getInit(i); 7021 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7022 } 7023 7024 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7025 VK, LiteralExpr, isFileScope); 7026 if (isFileScope) { 7027 if (!LiteralExpr->isTypeDependent() && 7028 !LiteralExpr->isValueDependent() && 7029 !literalType->isDependentType()) // C99 6.5.2.5p3 7030 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7031 return ExprError(); 7032 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7033 literalType.getAddressSpace() != LangAS::Default) { 7034 // Embedded-C extensions to C99 6.5.2.5: 7035 // "If the compound literal occurs inside the body of a function, the 7036 // type name shall not be qualified by an address-space qualifier." 7037 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7038 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7039 return ExprError(); 7040 } 7041 7042 if (!isFileScope && !getLangOpts().CPlusPlus) { 7043 // Compound literals that have automatic storage duration are destroyed at 7044 // the end of the scope in C; in C++, they're just temporaries. 7045 7046 // Emit diagnostics if it is or contains a C union type that is non-trivial 7047 // to destruct. 7048 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7049 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7050 NTCUC_CompoundLiteral, NTCUK_Destruct); 7051 7052 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7053 if (literalType.isDestructedType()) { 7054 Cleanup.setExprNeedsCleanups(true); 7055 ExprCleanupObjects.push_back(E); 7056 getCurFunction()->setHasBranchProtectedScope(); 7057 } 7058 } 7059 7060 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7061 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7062 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7063 E->getInitializer()->getExprLoc()); 7064 7065 return MaybeBindToTemporary(E); 7066 } 7067 7068 ExprResult 7069 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7070 SourceLocation RBraceLoc) { 7071 // Only produce each kind of designated initialization diagnostic once. 7072 SourceLocation FirstDesignator; 7073 bool DiagnosedArrayDesignator = false; 7074 bool DiagnosedNestedDesignator = false; 7075 bool DiagnosedMixedDesignator = false; 7076 7077 // Check that any designated initializers are syntactically valid in the 7078 // current language mode. 7079 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7080 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7081 if (FirstDesignator.isInvalid()) 7082 FirstDesignator = DIE->getBeginLoc(); 7083 7084 if (!getLangOpts().CPlusPlus) 7085 break; 7086 7087 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7088 DiagnosedNestedDesignator = true; 7089 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7090 << DIE->getDesignatorsSourceRange(); 7091 } 7092 7093 for (auto &Desig : DIE->designators()) { 7094 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7095 DiagnosedArrayDesignator = true; 7096 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7097 << Desig.getSourceRange(); 7098 } 7099 } 7100 7101 if (!DiagnosedMixedDesignator && 7102 !isa<DesignatedInitExpr>(InitArgList[0])) { 7103 DiagnosedMixedDesignator = true; 7104 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7105 << DIE->getSourceRange(); 7106 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7107 << InitArgList[0]->getSourceRange(); 7108 } 7109 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7110 isa<DesignatedInitExpr>(InitArgList[0])) { 7111 DiagnosedMixedDesignator = true; 7112 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7113 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7114 << DIE->getSourceRange(); 7115 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7116 << InitArgList[I]->getSourceRange(); 7117 } 7118 } 7119 7120 if (FirstDesignator.isValid()) { 7121 // Only diagnose designated initiaization as a C++20 extension if we didn't 7122 // already diagnose use of (non-C++20) C99 designator syntax. 7123 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7124 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7125 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7126 ? diag::warn_cxx17_compat_designated_init 7127 : diag::ext_cxx_designated_init); 7128 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7129 Diag(FirstDesignator, diag::ext_designated_init); 7130 } 7131 } 7132 7133 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7134 } 7135 7136 ExprResult 7137 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7138 SourceLocation RBraceLoc) { 7139 // Semantic analysis for initializers is done by ActOnDeclarator() and 7140 // CheckInitializer() - it requires knowledge of the object being initialized. 7141 7142 // Immediately handle non-overload placeholders. Overloads can be 7143 // resolved contextually, but everything else here can't. 7144 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7145 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7146 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7147 7148 // Ignore failures; dropping the entire initializer list because 7149 // of one failure would be terrible for indexing/etc. 7150 if (result.isInvalid()) continue; 7151 7152 InitArgList[I] = result.get(); 7153 } 7154 } 7155 7156 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7157 RBraceLoc); 7158 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7159 return E; 7160 } 7161 7162 /// Do an explicit extend of the given block pointer if we're in ARC. 7163 void Sema::maybeExtendBlockObject(ExprResult &E) { 7164 assert(E.get()->getType()->isBlockPointerType()); 7165 assert(E.get()->isPRValue()); 7166 7167 // Only do this in an r-value context. 7168 if (!getLangOpts().ObjCAutoRefCount) return; 7169 7170 E = ImplicitCastExpr::Create( 7171 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7172 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7173 Cleanup.setExprNeedsCleanups(true); 7174 } 7175 7176 /// Prepare a conversion of the given expression to an ObjC object 7177 /// pointer type. 7178 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7179 QualType type = E.get()->getType(); 7180 if (type->isObjCObjectPointerType()) { 7181 return CK_BitCast; 7182 } else if (type->isBlockPointerType()) { 7183 maybeExtendBlockObject(E); 7184 return CK_BlockPointerToObjCPointerCast; 7185 } else { 7186 assert(type->isPointerType()); 7187 return CK_CPointerToObjCPointerCast; 7188 } 7189 } 7190 7191 /// Prepares for a scalar cast, performing all the necessary stages 7192 /// except the final cast and returning the kind required. 7193 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7194 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7195 // Also, callers should have filtered out the invalid cases with 7196 // pointers. Everything else should be possible. 7197 7198 QualType SrcTy = Src.get()->getType(); 7199 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7200 return CK_NoOp; 7201 7202 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7203 case Type::STK_MemberPointer: 7204 llvm_unreachable("member pointer type in C"); 7205 7206 case Type::STK_CPointer: 7207 case Type::STK_BlockPointer: 7208 case Type::STK_ObjCObjectPointer: 7209 switch (DestTy->getScalarTypeKind()) { 7210 case Type::STK_CPointer: { 7211 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7212 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7213 if (SrcAS != DestAS) 7214 return CK_AddressSpaceConversion; 7215 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7216 return CK_NoOp; 7217 return CK_BitCast; 7218 } 7219 case Type::STK_BlockPointer: 7220 return (SrcKind == Type::STK_BlockPointer 7221 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7222 case Type::STK_ObjCObjectPointer: 7223 if (SrcKind == Type::STK_ObjCObjectPointer) 7224 return CK_BitCast; 7225 if (SrcKind == Type::STK_CPointer) 7226 return CK_CPointerToObjCPointerCast; 7227 maybeExtendBlockObject(Src); 7228 return CK_BlockPointerToObjCPointerCast; 7229 case Type::STK_Bool: 7230 return CK_PointerToBoolean; 7231 case Type::STK_Integral: 7232 return CK_PointerToIntegral; 7233 case Type::STK_Floating: 7234 case Type::STK_FloatingComplex: 7235 case Type::STK_IntegralComplex: 7236 case Type::STK_MemberPointer: 7237 case Type::STK_FixedPoint: 7238 llvm_unreachable("illegal cast from pointer"); 7239 } 7240 llvm_unreachable("Should have returned before this"); 7241 7242 case Type::STK_FixedPoint: 7243 switch (DestTy->getScalarTypeKind()) { 7244 case Type::STK_FixedPoint: 7245 return CK_FixedPointCast; 7246 case Type::STK_Bool: 7247 return CK_FixedPointToBoolean; 7248 case Type::STK_Integral: 7249 return CK_FixedPointToIntegral; 7250 case Type::STK_Floating: 7251 return CK_FixedPointToFloating; 7252 case Type::STK_IntegralComplex: 7253 case Type::STK_FloatingComplex: 7254 Diag(Src.get()->getExprLoc(), 7255 diag::err_unimplemented_conversion_with_fixed_point_type) 7256 << DestTy; 7257 return CK_IntegralCast; 7258 case Type::STK_CPointer: 7259 case Type::STK_ObjCObjectPointer: 7260 case Type::STK_BlockPointer: 7261 case Type::STK_MemberPointer: 7262 llvm_unreachable("illegal cast to pointer type"); 7263 } 7264 llvm_unreachable("Should have returned before this"); 7265 7266 case Type::STK_Bool: // casting from bool is like casting from an integer 7267 case Type::STK_Integral: 7268 switch (DestTy->getScalarTypeKind()) { 7269 case Type::STK_CPointer: 7270 case Type::STK_ObjCObjectPointer: 7271 case Type::STK_BlockPointer: 7272 if (Src.get()->isNullPointerConstant(Context, 7273 Expr::NPC_ValueDependentIsNull)) 7274 return CK_NullToPointer; 7275 return CK_IntegralToPointer; 7276 case Type::STK_Bool: 7277 return CK_IntegralToBoolean; 7278 case Type::STK_Integral: 7279 return CK_IntegralCast; 7280 case Type::STK_Floating: 7281 return CK_IntegralToFloating; 7282 case Type::STK_IntegralComplex: 7283 Src = ImpCastExprToType(Src.get(), 7284 DestTy->castAs<ComplexType>()->getElementType(), 7285 CK_IntegralCast); 7286 return CK_IntegralRealToComplex; 7287 case Type::STK_FloatingComplex: 7288 Src = ImpCastExprToType(Src.get(), 7289 DestTy->castAs<ComplexType>()->getElementType(), 7290 CK_IntegralToFloating); 7291 return CK_FloatingRealToComplex; 7292 case Type::STK_MemberPointer: 7293 llvm_unreachable("member pointer type in C"); 7294 case Type::STK_FixedPoint: 7295 return CK_IntegralToFixedPoint; 7296 } 7297 llvm_unreachable("Should have returned before this"); 7298 7299 case Type::STK_Floating: 7300 switch (DestTy->getScalarTypeKind()) { 7301 case Type::STK_Floating: 7302 return CK_FloatingCast; 7303 case Type::STK_Bool: 7304 return CK_FloatingToBoolean; 7305 case Type::STK_Integral: 7306 return CK_FloatingToIntegral; 7307 case Type::STK_FloatingComplex: 7308 Src = ImpCastExprToType(Src.get(), 7309 DestTy->castAs<ComplexType>()->getElementType(), 7310 CK_FloatingCast); 7311 return CK_FloatingRealToComplex; 7312 case Type::STK_IntegralComplex: 7313 Src = ImpCastExprToType(Src.get(), 7314 DestTy->castAs<ComplexType>()->getElementType(), 7315 CK_FloatingToIntegral); 7316 return CK_IntegralRealToComplex; 7317 case Type::STK_CPointer: 7318 case Type::STK_ObjCObjectPointer: 7319 case Type::STK_BlockPointer: 7320 llvm_unreachable("valid float->pointer cast?"); 7321 case Type::STK_MemberPointer: 7322 llvm_unreachable("member pointer type in C"); 7323 case Type::STK_FixedPoint: 7324 return CK_FloatingToFixedPoint; 7325 } 7326 llvm_unreachable("Should have returned before this"); 7327 7328 case Type::STK_FloatingComplex: 7329 switch (DestTy->getScalarTypeKind()) { 7330 case Type::STK_FloatingComplex: 7331 return CK_FloatingComplexCast; 7332 case Type::STK_IntegralComplex: 7333 return CK_FloatingComplexToIntegralComplex; 7334 case Type::STK_Floating: { 7335 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7336 if (Context.hasSameType(ET, DestTy)) 7337 return CK_FloatingComplexToReal; 7338 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7339 return CK_FloatingCast; 7340 } 7341 case Type::STK_Bool: 7342 return CK_FloatingComplexToBoolean; 7343 case Type::STK_Integral: 7344 Src = ImpCastExprToType(Src.get(), 7345 SrcTy->castAs<ComplexType>()->getElementType(), 7346 CK_FloatingComplexToReal); 7347 return CK_FloatingToIntegral; 7348 case Type::STK_CPointer: 7349 case Type::STK_ObjCObjectPointer: 7350 case Type::STK_BlockPointer: 7351 llvm_unreachable("valid complex float->pointer cast?"); 7352 case Type::STK_MemberPointer: 7353 llvm_unreachable("member pointer type in C"); 7354 case Type::STK_FixedPoint: 7355 Diag(Src.get()->getExprLoc(), 7356 diag::err_unimplemented_conversion_with_fixed_point_type) 7357 << SrcTy; 7358 return CK_IntegralCast; 7359 } 7360 llvm_unreachable("Should have returned before this"); 7361 7362 case Type::STK_IntegralComplex: 7363 switch (DestTy->getScalarTypeKind()) { 7364 case Type::STK_FloatingComplex: 7365 return CK_IntegralComplexToFloatingComplex; 7366 case Type::STK_IntegralComplex: 7367 return CK_IntegralComplexCast; 7368 case Type::STK_Integral: { 7369 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7370 if (Context.hasSameType(ET, DestTy)) 7371 return CK_IntegralComplexToReal; 7372 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7373 return CK_IntegralCast; 7374 } 7375 case Type::STK_Bool: 7376 return CK_IntegralComplexToBoolean; 7377 case Type::STK_Floating: 7378 Src = ImpCastExprToType(Src.get(), 7379 SrcTy->castAs<ComplexType>()->getElementType(), 7380 CK_IntegralComplexToReal); 7381 return CK_IntegralToFloating; 7382 case Type::STK_CPointer: 7383 case Type::STK_ObjCObjectPointer: 7384 case Type::STK_BlockPointer: 7385 llvm_unreachable("valid complex int->pointer cast?"); 7386 case Type::STK_MemberPointer: 7387 llvm_unreachable("member pointer type in C"); 7388 case Type::STK_FixedPoint: 7389 Diag(Src.get()->getExprLoc(), 7390 diag::err_unimplemented_conversion_with_fixed_point_type) 7391 << SrcTy; 7392 return CK_IntegralCast; 7393 } 7394 llvm_unreachable("Should have returned before this"); 7395 } 7396 7397 llvm_unreachable("Unhandled scalar cast"); 7398 } 7399 7400 static bool breakDownVectorType(QualType type, uint64_t &len, 7401 QualType &eltType) { 7402 // Vectors are simple. 7403 if (const VectorType *vecType = type->getAs<VectorType>()) { 7404 len = vecType->getNumElements(); 7405 eltType = vecType->getElementType(); 7406 assert(eltType->isScalarType()); 7407 return true; 7408 } 7409 7410 // We allow lax conversion to and from non-vector types, but only if 7411 // they're real types (i.e. non-complex, non-pointer scalar types). 7412 if (!type->isRealType()) return false; 7413 7414 len = 1; 7415 eltType = type; 7416 return true; 7417 } 7418 7419 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7420 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7421 /// allowed? 7422 /// 7423 /// This will also return false if the two given types do not make sense from 7424 /// the perspective of SVE bitcasts. 7425 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7426 assert(srcTy->isVectorType() || destTy->isVectorType()); 7427 7428 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7429 if (!FirstType->isSizelessBuiltinType()) 7430 return false; 7431 7432 const auto *VecTy = SecondType->getAs<VectorType>(); 7433 return VecTy && 7434 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7435 }; 7436 7437 return ValidScalableConversion(srcTy, destTy) || 7438 ValidScalableConversion(destTy, srcTy); 7439 } 7440 7441 /// Are the two types matrix types and do they have the same dimensions i.e. 7442 /// do they have the same number of rows and the same number of columns? 7443 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7444 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7445 return false; 7446 7447 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7448 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7449 7450 return matSrcType->getNumRows() == matDestType->getNumRows() && 7451 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7452 } 7453 7454 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7455 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7456 7457 uint64_t SrcLen, DestLen; 7458 QualType SrcEltTy, DestEltTy; 7459 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7460 return false; 7461 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7462 return false; 7463 7464 // ASTContext::getTypeSize will return the size rounded up to a 7465 // power of 2, so instead of using that, we need to use the raw 7466 // element size multiplied by the element count. 7467 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7468 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7469 7470 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7471 } 7472 7473 /// Are the two types lax-compatible vector types? That is, given 7474 /// that one of them is a vector, do they have equal storage sizes, 7475 /// where the storage size is the number of elements times the element 7476 /// size? 7477 /// 7478 /// This will also return false if either of the types is neither a 7479 /// vector nor a real type. 7480 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7481 assert(destTy->isVectorType() || srcTy->isVectorType()); 7482 7483 // Disallow lax conversions between scalars and ExtVectors (these 7484 // conversions are allowed for other vector types because common headers 7485 // depend on them). Most scalar OP ExtVector cases are handled by the 7486 // splat path anyway, which does what we want (convert, not bitcast). 7487 // What this rules out for ExtVectors is crazy things like char4*float. 7488 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7489 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7490 7491 return areVectorTypesSameSize(srcTy, destTy); 7492 } 7493 7494 /// Is this a legal conversion between two types, one of which is 7495 /// known to be a vector type? 7496 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7497 assert(destTy->isVectorType() || srcTy->isVectorType()); 7498 7499 switch (Context.getLangOpts().getLaxVectorConversions()) { 7500 case LangOptions::LaxVectorConversionKind::None: 7501 return false; 7502 7503 case LangOptions::LaxVectorConversionKind::Integer: 7504 if (!srcTy->isIntegralOrEnumerationType()) { 7505 auto *Vec = srcTy->getAs<VectorType>(); 7506 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7507 return false; 7508 } 7509 if (!destTy->isIntegralOrEnumerationType()) { 7510 auto *Vec = destTy->getAs<VectorType>(); 7511 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7512 return false; 7513 } 7514 // OK, integer (vector) -> integer (vector) bitcast. 7515 break; 7516 7517 case LangOptions::LaxVectorConversionKind::All: 7518 break; 7519 } 7520 7521 return areLaxCompatibleVectorTypes(srcTy, destTy); 7522 } 7523 7524 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7525 CastKind &Kind) { 7526 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7527 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7528 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7529 << DestTy << SrcTy << R; 7530 } 7531 } else if (SrcTy->isMatrixType()) { 7532 return Diag(R.getBegin(), 7533 diag::err_invalid_conversion_between_matrix_and_type) 7534 << SrcTy << DestTy << R; 7535 } else if (DestTy->isMatrixType()) { 7536 return Diag(R.getBegin(), 7537 diag::err_invalid_conversion_between_matrix_and_type) 7538 << DestTy << SrcTy << R; 7539 } 7540 7541 Kind = CK_MatrixCast; 7542 return false; 7543 } 7544 7545 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7546 CastKind &Kind) { 7547 assert(VectorTy->isVectorType() && "Not a vector type!"); 7548 7549 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7550 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7551 return Diag(R.getBegin(), 7552 Ty->isVectorType() ? 7553 diag::err_invalid_conversion_between_vectors : 7554 diag::err_invalid_conversion_between_vector_and_integer) 7555 << VectorTy << Ty << R; 7556 } else 7557 return Diag(R.getBegin(), 7558 diag::err_invalid_conversion_between_vector_and_scalar) 7559 << VectorTy << Ty << R; 7560 7561 Kind = CK_BitCast; 7562 return false; 7563 } 7564 7565 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7566 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7567 7568 if (DestElemTy == SplattedExpr->getType()) 7569 return SplattedExpr; 7570 7571 assert(DestElemTy->isFloatingType() || 7572 DestElemTy->isIntegralOrEnumerationType()); 7573 7574 CastKind CK; 7575 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7576 // OpenCL requires that we convert `true` boolean expressions to -1, but 7577 // only when splatting vectors. 7578 if (DestElemTy->isFloatingType()) { 7579 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7580 // in two steps: boolean to signed integral, then to floating. 7581 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7582 CK_BooleanToSignedIntegral); 7583 SplattedExpr = CastExprRes.get(); 7584 CK = CK_IntegralToFloating; 7585 } else { 7586 CK = CK_BooleanToSignedIntegral; 7587 } 7588 } else { 7589 ExprResult CastExprRes = SplattedExpr; 7590 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7591 if (CastExprRes.isInvalid()) 7592 return ExprError(); 7593 SplattedExpr = CastExprRes.get(); 7594 } 7595 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7596 } 7597 7598 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7599 Expr *CastExpr, CastKind &Kind) { 7600 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7601 7602 QualType SrcTy = CastExpr->getType(); 7603 7604 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7605 // an ExtVectorType. 7606 // In OpenCL, casts between vectors of different types are not allowed. 7607 // (See OpenCL 6.2). 7608 if (SrcTy->isVectorType()) { 7609 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7610 (getLangOpts().OpenCL && 7611 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7612 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7613 << DestTy << SrcTy << R; 7614 return ExprError(); 7615 } 7616 Kind = CK_BitCast; 7617 return CastExpr; 7618 } 7619 7620 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7621 // conversion will take place first from scalar to elt type, and then 7622 // splat from elt type to vector. 7623 if (SrcTy->isPointerType()) 7624 return Diag(R.getBegin(), 7625 diag::err_invalid_conversion_between_vector_and_scalar) 7626 << DestTy << SrcTy << R; 7627 7628 Kind = CK_VectorSplat; 7629 return prepareVectorSplat(DestTy, CastExpr); 7630 } 7631 7632 ExprResult 7633 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7634 Declarator &D, ParsedType &Ty, 7635 SourceLocation RParenLoc, Expr *CastExpr) { 7636 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7637 "ActOnCastExpr(): missing type or expr"); 7638 7639 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7640 if (D.isInvalidType()) 7641 return ExprError(); 7642 7643 if (getLangOpts().CPlusPlus) { 7644 // Check that there are no default arguments (C++ only). 7645 CheckExtraCXXDefaultArguments(D); 7646 } else { 7647 // Make sure any TypoExprs have been dealt with. 7648 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7649 if (!Res.isUsable()) 7650 return ExprError(); 7651 CastExpr = Res.get(); 7652 } 7653 7654 checkUnusedDeclAttributes(D); 7655 7656 QualType castType = castTInfo->getType(); 7657 Ty = CreateParsedType(castType, castTInfo); 7658 7659 bool isVectorLiteral = false; 7660 7661 // Check for an altivec or OpenCL literal, 7662 // i.e. all the elements are integer constants. 7663 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7664 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7665 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7666 && castType->isVectorType() && (PE || PLE)) { 7667 if (PLE && PLE->getNumExprs() == 0) { 7668 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7669 return ExprError(); 7670 } 7671 if (PE || PLE->getNumExprs() == 1) { 7672 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7673 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7674 isVectorLiteral = true; 7675 } 7676 else 7677 isVectorLiteral = true; 7678 } 7679 7680 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7681 // then handle it as such. 7682 if (isVectorLiteral) 7683 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7684 7685 // If the Expr being casted is a ParenListExpr, handle it specially. 7686 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7687 // sequence of BinOp comma operators. 7688 if (isa<ParenListExpr>(CastExpr)) { 7689 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7690 if (Result.isInvalid()) return ExprError(); 7691 CastExpr = Result.get(); 7692 } 7693 7694 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7695 !getSourceManager().isInSystemMacro(LParenLoc)) 7696 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7697 7698 CheckTollFreeBridgeCast(castType, CastExpr); 7699 7700 CheckObjCBridgeRelatedCast(castType, CastExpr); 7701 7702 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7703 7704 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7705 } 7706 7707 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7708 SourceLocation RParenLoc, Expr *E, 7709 TypeSourceInfo *TInfo) { 7710 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7711 "Expected paren or paren list expression"); 7712 7713 Expr **exprs; 7714 unsigned numExprs; 7715 Expr *subExpr; 7716 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7717 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7718 LiteralLParenLoc = PE->getLParenLoc(); 7719 LiteralRParenLoc = PE->getRParenLoc(); 7720 exprs = PE->getExprs(); 7721 numExprs = PE->getNumExprs(); 7722 } else { // isa<ParenExpr> by assertion at function entrance 7723 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7724 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7725 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7726 exprs = &subExpr; 7727 numExprs = 1; 7728 } 7729 7730 QualType Ty = TInfo->getType(); 7731 assert(Ty->isVectorType() && "Expected vector type"); 7732 7733 SmallVector<Expr *, 8> initExprs; 7734 const VectorType *VTy = Ty->castAs<VectorType>(); 7735 unsigned numElems = VTy->getNumElements(); 7736 7737 // '(...)' form of vector initialization in AltiVec: the number of 7738 // initializers must be one or must match the size of the vector. 7739 // If a single value is specified in the initializer then it will be 7740 // replicated to all the components of the vector 7741 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7742 VTy->getElementType())) 7743 return ExprError(); 7744 if (ShouldSplatAltivecScalarInCast(VTy)) { 7745 // The number of initializers must be one or must match the size of the 7746 // vector. If a single value is specified in the initializer then it will 7747 // be replicated to all the components of the vector 7748 if (numExprs == 1) { 7749 QualType ElemTy = VTy->getElementType(); 7750 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7751 if (Literal.isInvalid()) 7752 return ExprError(); 7753 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7754 PrepareScalarCast(Literal, ElemTy)); 7755 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7756 } 7757 else if (numExprs < numElems) { 7758 Diag(E->getExprLoc(), 7759 diag::err_incorrect_number_of_vector_initializers); 7760 return ExprError(); 7761 } 7762 else 7763 initExprs.append(exprs, exprs + numExprs); 7764 } 7765 else { 7766 // For OpenCL, when the number of initializers is a single value, 7767 // it will be replicated to all components of the vector. 7768 if (getLangOpts().OpenCL && 7769 VTy->getVectorKind() == VectorType::GenericVector && 7770 numExprs == 1) { 7771 QualType ElemTy = VTy->getElementType(); 7772 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7773 if (Literal.isInvalid()) 7774 return ExprError(); 7775 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7776 PrepareScalarCast(Literal, ElemTy)); 7777 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7778 } 7779 7780 initExprs.append(exprs, exprs + numExprs); 7781 } 7782 // FIXME: This means that pretty-printing the final AST will produce curly 7783 // braces instead of the original commas. 7784 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7785 initExprs, LiteralRParenLoc); 7786 initE->setType(Ty); 7787 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7788 } 7789 7790 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7791 /// the ParenListExpr into a sequence of comma binary operators. 7792 ExprResult 7793 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7794 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7795 if (!E) 7796 return OrigExpr; 7797 7798 ExprResult Result(E->getExpr(0)); 7799 7800 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7801 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7802 E->getExpr(i)); 7803 7804 if (Result.isInvalid()) return ExprError(); 7805 7806 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7807 } 7808 7809 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7810 SourceLocation R, 7811 MultiExprArg Val) { 7812 return ParenListExpr::Create(Context, L, Val, R); 7813 } 7814 7815 /// Emit a specialized diagnostic when one expression is a null pointer 7816 /// constant and the other is not a pointer. Returns true if a diagnostic is 7817 /// emitted. 7818 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7819 SourceLocation QuestionLoc) { 7820 Expr *NullExpr = LHSExpr; 7821 Expr *NonPointerExpr = RHSExpr; 7822 Expr::NullPointerConstantKind NullKind = 7823 NullExpr->isNullPointerConstant(Context, 7824 Expr::NPC_ValueDependentIsNotNull); 7825 7826 if (NullKind == Expr::NPCK_NotNull) { 7827 NullExpr = RHSExpr; 7828 NonPointerExpr = LHSExpr; 7829 NullKind = 7830 NullExpr->isNullPointerConstant(Context, 7831 Expr::NPC_ValueDependentIsNotNull); 7832 } 7833 7834 if (NullKind == Expr::NPCK_NotNull) 7835 return false; 7836 7837 if (NullKind == Expr::NPCK_ZeroExpression) 7838 return false; 7839 7840 if (NullKind == Expr::NPCK_ZeroLiteral) { 7841 // In this case, check to make sure that we got here from a "NULL" 7842 // string in the source code. 7843 NullExpr = NullExpr->IgnoreParenImpCasts(); 7844 SourceLocation loc = NullExpr->getExprLoc(); 7845 if (!findMacroSpelling(loc, "NULL")) 7846 return false; 7847 } 7848 7849 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7850 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7851 << NonPointerExpr->getType() << DiagType 7852 << NonPointerExpr->getSourceRange(); 7853 return true; 7854 } 7855 7856 /// Return false if the condition expression is valid, true otherwise. 7857 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7858 QualType CondTy = Cond->getType(); 7859 7860 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7861 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7862 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7863 << CondTy << Cond->getSourceRange(); 7864 return true; 7865 } 7866 7867 // C99 6.5.15p2 7868 if (CondTy->isScalarType()) return false; 7869 7870 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7871 << CondTy << Cond->getSourceRange(); 7872 return true; 7873 } 7874 7875 /// Handle when one or both operands are void type. 7876 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7877 ExprResult &RHS) { 7878 Expr *LHSExpr = LHS.get(); 7879 Expr *RHSExpr = RHS.get(); 7880 7881 if (!LHSExpr->getType()->isVoidType()) 7882 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7883 << RHSExpr->getSourceRange(); 7884 if (!RHSExpr->getType()->isVoidType()) 7885 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7886 << LHSExpr->getSourceRange(); 7887 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7888 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7889 return S.Context.VoidTy; 7890 } 7891 7892 /// Return false if the NullExpr can be promoted to PointerTy, 7893 /// true otherwise. 7894 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7895 QualType PointerTy) { 7896 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7897 !NullExpr.get()->isNullPointerConstant(S.Context, 7898 Expr::NPC_ValueDependentIsNull)) 7899 return true; 7900 7901 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7902 return false; 7903 } 7904 7905 /// Checks compatibility between two pointers and return the resulting 7906 /// type. 7907 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7908 ExprResult &RHS, 7909 SourceLocation Loc) { 7910 QualType LHSTy = LHS.get()->getType(); 7911 QualType RHSTy = RHS.get()->getType(); 7912 7913 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7914 // Two identical pointers types are always compatible. 7915 return LHSTy; 7916 } 7917 7918 QualType lhptee, rhptee; 7919 7920 // Get the pointee types. 7921 bool IsBlockPointer = false; 7922 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7923 lhptee = LHSBTy->getPointeeType(); 7924 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7925 IsBlockPointer = true; 7926 } else { 7927 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7928 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7929 } 7930 7931 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7932 // differently qualified versions of compatible types, the result type is 7933 // a pointer to an appropriately qualified version of the composite 7934 // type. 7935 7936 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7937 // clause doesn't make sense for our extensions. E.g. address space 2 should 7938 // be incompatible with address space 3: they may live on different devices or 7939 // anything. 7940 Qualifiers lhQual = lhptee.getQualifiers(); 7941 Qualifiers rhQual = rhptee.getQualifiers(); 7942 7943 LangAS ResultAddrSpace = LangAS::Default; 7944 LangAS LAddrSpace = lhQual.getAddressSpace(); 7945 LangAS RAddrSpace = rhQual.getAddressSpace(); 7946 7947 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7948 // spaces is disallowed. 7949 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7950 ResultAddrSpace = LAddrSpace; 7951 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7952 ResultAddrSpace = RAddrSpace; 7953 else { 7954 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7955 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7956 << RHS.get()->getSourceRange(); 7957 return QualType(); 7958 } 7959 7960 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7961 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7962 lhQual.removeCVRQualifiers(); 7963 rhQual.removeCVRQualifiers(); 7964 7965 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7966 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7967 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7968 // qual types are compatible iff 7969 // * corresponded types are compatible 7970 // * CVR qualifiers are equal 7971 // * address spaces are equal 7972 // Thus for conditional operator we merge CVR and address space unqualified 7973 // pointees and if there is a composite type we return a pointer to it with 7974 // merged qualifiers. 7975 LHSCastKind = 7976 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7977 RHSCastKind = 7978 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7979 lhQual.removeAddressSpace(); 7980 rhQual.removeAddressSpace(); 7981 7982 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7983 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7984 7985 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7986 7987 if (CompositeTy.isNull()) { 7988 // In this situation, we assume void* type. No especially good 7989 // reason, but this is what gcc does, and we do have to pick 7990 // to get a consistent AST. 7991 QualType incompatTy; 7992 incompatTy = S.Context.getPointerType( 7993 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7994 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7995 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7996 7997 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7998 // for casts between types with incompatible address space qualifiers. 7999 // For the following code the compiler produces casts between global and 8000 // local address spaces of the corresponded innermost pointees: 8001 // local int *global *a; 8002 // global int *global *b; 8003 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8004 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8005 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8006 << RHS.get()->getSourceRange(); 8007 8008 return incompatTy; 8009 } 8010 8011 // The pointer types are compatible. 8012 // In case of OpenCL ResultTy should have the address space qualifier 8013 // which is a superset of address spaces of both the 2nd and the 3rd 8014 // operands of the conditional operator. 8015 QualType ResultTy = [&, ResultAddrSpace]() { 8016 if (S.getLangOpts().OpenCL) { 8017 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8018 CompositeQuals.setAddressSpace(ResultAddrSpace); 8019 return S.Context 8020 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8021 .withCVRQualifiers(MergedCVRQual); 8022 } 8023 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8024 }(); 8025 if (IsBlockPointer) 8026 ResultTy = S.Context.getBlockPointerType(ResultTy); 8027 else 8028 ResultTy = S.Context.getPointerType(ResultTy); 8029 8030 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8031 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8032 return ResultTy; 8033 } 8034 8035 /// Return the resulting type when the operands are both block pointers. 8036 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8037 ExprResult &LHS, 8038 ExprResult &RHS, 8039 SourceLocation Loc) { 8040 QualType LHSTy = LHS.get()->getType(); 8041 QualType RHSTy = RHS.get()->getType(); 8042 8043 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8044 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8045 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8046 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8047 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8048 return destType; 8049 } 8050 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8051 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8052 << RHS.get()->getSourceRange(); 8053 return QualType(); 8054 } 8055 8056 // We have 2 block pointer types. 8057 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8058 } 8059 8060 /// Return the resulting type when the operands are both pointers. 8061 static QualType 8062 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8063 ExprResult &RHS, 8064 SourceLocation Loc) { 8065 // get the pointer types 8066 QualType LHSTy = LHS.get()->getType(); 8067 QualType RHSTy = RHS.get()->getType(); 8068 8069 // get the "pointed to" types 8070 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8071 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8072 8073 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8074 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8075 // Figure out necessary qualifiers (C99 6.5.15p6) 8076 QualType destPointee 8077 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8078 QualType destType = S.Context.getPointerType(destPointee); 8079 // Add qualifiers if necessary. 8080 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8081 // Promote to void*. 8082 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8083 return destType; 8084 } 8085 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8086 QualType destPointee 8087 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8088 QualType destType = S.Context.getPointerType(destPointee); 8089 // Add qualifiers if necessary. 8090 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8091 // Promote to void*. 8092 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8093 return destType; 8094 } 8095 8096 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8097 } 8098 8099 /// Return false if the first expression is not an integer and the second 8100 /// expression is not a pointer, true otherwise. 8101 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8102 Expr* PointerExpr, SourceLocation Loc, 8103 bool IsIntFirstExpr) { 8104 if (!PointerExpr->getType()->isPointerType() || 8105 !Int.get()->getType()->isIntegerType()) 8106 return false; 8107 8108 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8109 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8110 8111 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8112 << Expr1->getType() << Expr2->getType() 8113 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8114 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8115 CK_IntegralToPointer); 8116 return true; 8117 } 8118 8119 /// Simple conversion between integer and floating point types. 8120 /// 8121 /// Used when handling the OpenCL conditional operator where the 8122 /// condition is a vector while the other operands are scalar. 8123 /// 8124 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8125 /// types are either integer or floating type. Between the two 8126 /// operands, the type with the higher rank is defined as the "result 8127 /// type". The other operand needs to be promoted to the same type. No 8128 /// other type promotion is allowed. We cannot use 8129 /// UsualArithmeticConversions() for this purpose, since it always 8130 /// promotes promotable types. 8131 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8132 ExprResult &RHS, 8133 SourceLocation QuestionLoc) { 8134 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8135 if (LHS.isInvalid()) 8136 return QualType(); 8137 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8138 if (RHS.isInvalid()) 8139 return QualType(); 8140 8141 // For conversion purposes, we ignore any qualifiers. 8142 // For example, "const float" and "float" are equivalent. 8143 QualType LHSType = 8144 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8145 QualType RHSType = 8146 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8147 8148 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8149 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8150 << LHSType << LHS.get()->getSourceRange(); 8151 return QualType(); 8152 } 8153 8154 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8155 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8156 << RHSType << RHS.get()->getSourceRange(); 8157 return QualType(); 8158 } 8159 8160 // If both types are identical, no conversion is needed. 8161 if (LHSType == RHSType) 8162 return LHSType; 8163 8164 // Now handle "real" floating types (i.e. float, double, long double). 8165 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8166 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8167 /*IsCompAssign = */ false); 8168 8169 // Finally, we have two differing integer types. 8170 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8171 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8172 } 8173 8174 /// Convert scalar operands to a vector that matches the 8175 /// condition in length. 8176 /// 8177 /// Used when handling the OpenCL conditional operator where the 8178 /// condition is a vector while the other operands are scalar. 8179 /// 8180 /// We first compute the "result type" for the scalar operands 8181 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8182 /// into a vector of that type where the length matches the condition 8183 /// vector type. s6.11.6 requires that the element types of the result 8184 /// and the condition must have the same number of bits. 8185 static QualType 8186 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8187 QualType CondTy, SourceLocation QuestionLoc) { 8188 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8189 if (ResTy.isNull()) return QualType(); 8190 8191 const VectorType *CV = CondTy->getAs<VectorType>(); 8192 assert(CV); 8193 8194 // Determine the vector result type 8195 unsigned NumElements = CV->getNumElements(); 8196 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8197 8198 // Ensure that all types have the same number of bits 8199 if (S.Context.getTypeSize(CV->getElementType()) 8200 != S.Context.getTypeSize(ResTy)) { 8201 // Since VectorTy is created internally, it does not pretty print 8202 // with an OpenCL name. Instead, we just print a description. 8203 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8204 SmallString<64> Str; 8205 llvm::raw_svector_ostream OS(Str); 8206 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8207 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8208 << CondTy << OS.str(); 8209 return QualType(); 8210 } 8211 8212 // Convert operands to the vector result type 8213 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8214 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8215 8216 return VectorTy; 8217 } 8218 8219 /// Return false if this is a valid OpenCL condition vector 8220 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8221 SourceLocation QuestionLoc) { 8222 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8223 // integral type. 8224 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8225 assert(CondTy); 8226 QualType EleTy = CondTy->getElementType(); 8227 if (EleTy->isIntegerType()) return false; 8228 8229 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8230 << Cond->getType() << Cond->getSourceRange(); 8231 return true; 8232 } 8233 8234 /// Return false if the vector condition type and the vector 8235 /// result type are compatible. 8236 /// 8237 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8238 /// number of elements, and their element types have the same number 8239 /// of bits. 8240 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8241 SourceLocation QuestionLoc) { 8242 const VectorType *CV = CondTy->getAs<VectorType>(); 8243 const VectorType *RV = VecResTy->getAs<VectorType>(); 8244 assert(CV && RV); 8245 8246 if (CV->getNumElements() != RV->getNumElements()) { 8247 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8248 << CondTy << VecResTy; 8249 return true; 8250 } 8251 8252 QualType CVE = CV->getElementType(); 8253 QualType RVE = RV->getElementType(); 8254 8255 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8256 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8257 << CondTy << VecResTy; 8258 return true; 8259 } 8260 8261 return false; 8262 } 8263 8264 /// Return the resulting type for the conditional operator in 8265 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8266 /// s6.3.i) when the condition is a vector type. 8267 static QualType 8268 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8269 ExprResult &LHS, ExprResult &RHS, 8270 SourceLocation QuestionLoc) { 8271 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8272 if (Cond.isInvalid()) 8273 return QualType(); 8274 QualType CondTy = Cond.get()->getType(); 8275 8276 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8277 return QualType(); 8278 8279 // If either operand is a vector then find the vector type of the 8280 // result as specified in OpenCL v1.1 s6.3.i. 8281 if (LHS.get()->getType()->isVectorType() || 8282 RHS.get()->getType()->isVectorType()) { 8283 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8284 /*isCompAssign*/false, 8285 /*AllowBothBool*/true, 8286 /*AllowBoolConversions*/false); 8287 if (VecResTy.isNull()) return QualType(); 8288 // The result type must match the condition type as specified in 8289 // OpenCL v1.1 s6.11.6. 8290 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8291 return QualType(); 8292 return VecResTy; 8293 } 8294 8295 // Both operands are scalar. 8296 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8297 } 8298 8299 /// Return true if the Expr is block type 8300 static bool checkBlockType(Sema &S, const Expr *E) { 8301 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8302 QualType Ty = CE->getCallee()->getType(); 8303 if (Ty->isBlockPointerType()) { 8304 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8305 return true; 8306 } 8307 } 8308 return false; 8309 } 8310 8311 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8312 /// In that case, LHS = cond. 8313 /// C99 6.5.15 8314 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8315 ExprResult &RHS, ExprValueKind &VK, 8316 ExprObjectKind &OK, 8317 SourceLocation QuestionLoc) { 8318 8319 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8320 if (!LHSResult.isUsable()) return QualType(); 8321 LHS = LHSResult; 8322 8323 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8324 if (!RHSResult.isUsable()) return QualType(); 8325 RHS = RHSResult; 8326 8327 // C++ is sufficiently different to merit its own checker. 8328 if (getLangOpts().CPlusPlus) 8329 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8330 8331 VK = VK_PRValue; 8332 OK = OK_Ordinary; 8333 8334 if (Context.isDependenceAllowed() && 8335 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8336 RHS.get()->isTypeDependent())) { 8337 assert(!getLangOpts().CPlusPlus); 8338 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8339 RHS.get()->containsErrors()) && 8340 "should only occur in error-recovery path."); 8341 return Context.DependentTy; 8342 } 8343 8344 // The OpenCL operator with a vector condition is sufficiently 8345 // different to merit its own checker. 8346 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8347 Cond.get()->getType()->isExtVectorType()) 8348 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8349 8350 // First, check the condition. 8351 Cond = UsualUnaryConversions(Cond.get()); 8352 if (Cond.isInvalid()) 8353 return QualType(); 8354 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8355 return QualType(); 8356 8357 // Now check the two expressions. 8358 if (LHS.get()->getType()->isVectorType() || 8359 RHS.get()->getType()->isVectorType()) 8360 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8361 /*AllowBothBool*/true, 8362 /*AllowBoolConversions*/false); 8363 8364 QualType ResTy = 8365 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8366 if (LHS.isInvalid() || RHS.isInvalid()) 8367 return QualType(); 8368 8369 QualType LHSTy = LHS.get()->getType(); 8370 QualType RHSTy = RHS.get()->getType(); 8371 8372 // Diagnose attempts to convert between __ibm128, __float128 and long double 8373 // where such conversions currently can't be handled. 8374 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8375 Diag(QuestionLoc, 8376 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8377 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8378 return QualType(); 8379 } 8380 8381 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8382 // selection operator (?:). 8383 if (getLangOpts().OpenCL && 8384 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8385 return QualType(); 8386 } 8387 8388 // If both operands have arithmetic type, do the usual arithmetic conversions 8389 // to find a common type: C99 6.5.15p3,5. 8390 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8391 // Disallow invalid arithmetic conversions, such as those between bit- 8392 // precise integers types of different sizes, or between a bit-precise 8393 // integer and another type. 8394 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { 8395 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8396 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8397 << RHS.get()->getSourceRange(); 8398 return QualType(); 8399 } 8400 8401 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8402 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8403 8404 return ResTy; 8405 } 8406 8407 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8408 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8409 return LHSTy; 8410 } 8411 8412 // If both operands are the same structure or union type, the result is that 8413 // type. 8414 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8415 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8416 if (LHSRT->getDecl() == RHSRT->getDecl()) 8417 // "If both the operands have structure or union type, the result has 8418 // that type." This implies that CV qualifiers are dropped. 8419 return LHSTy.getUnqualifiedType(); 8420 // FIXME: Type of conditional expression must be complete in C mode. 8421 } 8422 8423 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8424 // The following || allows only one side to be void (a GCC-ism). 8425 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8426 return checkConditionalVoidType(*this, LHS, RHS); 8427 } 8428 8429 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8430 // the type of the other operand." 8431 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8432 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8433 8434 // All objective-c pointer type analysis is done here. 8435 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8436 QuestionLoc); 8437 if (LHS.isInvalid() || RHS.isInvalid()) 8438 return QualType(); 8439 if (!compositeType.isNull()) 8440 return compositeType; 8441 8442 8443 // Handle block pointer types. 8444 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8445 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8446 QuestionLoc); 8447 8448 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8449 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8450 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8451 QuestionLoc); 8452 8453 // GCC compatibility: soften pointer/integer mismatch. Note that 8454 // null pointers have been filtered out by this point. 8455 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8456 /*IsIntFirstExpr=*/true)) 8457 return RHSTy; 8458 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8459 /*IsIntFirstExpr=*/false)) 8460 return LHSTy; 8461 8462 // Allow ?: operations in which both operands have the same 8463 // built-in sizeless type. 8464 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8465 return LHSTy; 8466 8467 // Emit a better diagnostic if one of the expressions is a null pointer 8468 // constant and the other is not a pointer type. In this case, the user most 8469 // likely forgot to take the address of the other expression. 8470 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8471 return QualType(); 8472 8473 // Otherwise, the operands are not compatible. 8474 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8475 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8476 << RHS.get()->getSourceRange(); 8477 return QualType(); 8478 } 8479 8480 /// FindCompositeObjCPointerType - Helper method to find composite type of 8481 /// two objective-c pointer types of the two input expressions. 8482 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8483 SourceLocation QuestionLoc) { 8484 QualType LHSTy = LHS.get()->getType(); 8485 QualType RHSTy = RHS.get()->getType(); 8486 8487 // Handle things like Class and struct objc_class*. Here we case the result 8488 // to the pseudo-builtin, because that will be implicitly cast back to the 8489 // redefinition type if an attempt is made to access its fields. 8490 if (LHSTy->isObjCClassType() && 8491 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8492 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8493 return LHSTy; 8494 } 8495 if (RHSTy->isObjCClassType() && 8496 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8497 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8498 return RHSTy; 8499 } 8500 // And the same for struct objc_object* / id 8501 if (LHSTy->isObjCIdType() && 8502 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8503 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8504 return LHSTy; 8505 } 8506 if (RHSTy->isObjCIdType() && 8507 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8508 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8509 return RHSTy; 8510 } 8511 // And the same for struct objc_selector* / SEL 8512 if (Context.isObjCSelType(LHSTy) && 8513 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8514 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8515 return LHSTy; 8516 } 8517 if (Context.isObjCSelType(RHSTy) && 8518 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8519 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8520 return RHSTy; 8521 } 8522 // Check constraints for Objective-C object pointers types. 8523 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8524 8525 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8526 // Two identical object pointer types are always compatible. 8527 return LHSTy; 8528 } 8529 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8530 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8531 QualType compositeType = LHSTy; 8532 8533 // If both operands are interfaces and either operand can be 8534 // assigned to the other, use that type as the composite 8535 // type. This allows 8536 // xxx ? (A*) a : (B*) b 8537 // where B is a subclass of A. 8538 // 8539 // Additionally, as for assignment, if either type is 'id' 8540 // allow silent coercion. Finally, if the types are 8541 // incompatible then make sure to use 'id' as the composite 8542 // type so the result is acceptable for sending messages to. 8543 8544 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8545 // It could return the composite type. 8546 if (!(compositeType = 8547 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8548 // Nothing more to do. 8549 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8550 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8551 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8552 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8553 } else if ((LHSOPT->isObjCQualifiedIdType() || 8554 RHSOPT->isObjCQualifiedIdType()) && 8555 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8556 true)) { 8557 // Need to handle "id<xx>" explicitly. 8558 // GCC allows qualified id and any Objective-C type to devolve to 8559 // id. Currently localizing to here until clear this should be 8560 // part of ObjCQualifiedIdTypesAreCompatible. 8561 compositeType = Context.getObjCIdType(); 8562 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8563 compositeType = Context.getObjCIdType(); 8564 } else { 8565 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8566 << LHSTy << RHSTy 8567 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8568 QualType incompatTy = Context.getObjCIdType(); 8569 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8570 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8571 return incompatTy; 8572 } 8573 // The object pointer types are compatible. 8574 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8575 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8576 return compositeType; 8577 } 8578 // Check Objective-C object pointer types and 'void *' 8579 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8580 if (getLangOpts().ObjCAutoRefCount) { 8581 // ARC forbids the implicit conversion of object pointers to 'void *', 8582 // so these types are not compatible. 8583 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8584 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8585 LHS = RHS = true; 8586 return QualType(); 8587 } 8588 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8589 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8590 QualType destPointee 8591 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8592 QualType destType = Context.getPointerType(destPointee); 8593 // Add qualifiers if necessary. 8594 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8595 // Promote to void*. 8596 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8597 return destType; 8598 } 8599 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8600 if (getLangOpts().ObjCAutoRefCount) { 8601 // ARC forbids the implicit conversion of object pointers to 'void *', 8602 // so these types are not compatible. 8603 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8604 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8605 LHS = RHS = true; 8606 return QualType(); 8607 } 8608 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8609 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8610 QualType destPointee 8611 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8612 QualType destType = Context.getPointerType(destPointee); 8613 // Add qualifiers if necessary. 8614 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8615 // Promote to void*. 8616 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8617 return destType; 8618 } 8619 return QualType(); 8620 } 8621 8622 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8623 /// ParenRange in parentheses. 8624 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8625 const PartialDiagnostic &Note, 8626 SourceRange ParenRange) { 8627 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8628 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8629 EndLoc.isValid()) { 8630 Self.Diag(Loc, Note) 8631 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8632 << FixItHint::CreateInsertion(EndLoc, ")"); 8633 } else { 8634 // We can't display the parentheses, so just show the bare note. 8635 Self.Diag(Loc, Note) << ParenRange; 8636 } 8637 } 8638 8639 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8640 return BinaryOperator::isAdditiveOp(Opc) || 8641 BinaryOperator::isMultiplicativeOp(Opc) || 8642 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8643 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8644 // not any of the logical operators. Bitwise-xor is commonly used as a 8645 // logical-xor because there is no logical-xor operator. The logical 8646 // operators, including uses of xor, have a high false positive rate for 8647 // precedence warnings. 8648 } 8649 8650 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8651 /// expression, either using a built-in or overloaded operator, 8652 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8653 /// expression. 8654 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8655 Expr **RHSExprs) { 8656 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8657 E = E->IgnoreImpCasts(); 8658 E = E->IgnoreConversionOperatorSingleStep(); 8659 E = E->IgnoreImpCasts(); 8660 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8661 E = MTE->getSubExpr(); 8662 E = E->IgnoreImpCasts(); 8663 } 8664 8665 // Built-in binary operator. 8666 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8667 if (IsArithmeticOp(OP->getOpcode())) { 8668 *Opcode = OP->getOpcode(); 8669 *RHSExprs = OP->getRHS(); 8670 return true; 8671 } 8672 } 8673 8674 // Overloaded operator. 8675 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8676 if (Call->getNumArgs() != 2) 8677 return false; 8678 8679 // Make sure this is really a binary operator that is safe to pass into 8680 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8681 OverloadedOperatorKind OO = Call->getOperator(); 8682 if (OO < OO_Plus || OO > OO_Arrow || 8683 OO == OO_PlusPlus || OO == OO_MinusMinus) 8684 return false; 8685 8686 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8687 if (IsArithmeticOp(OpKind)) { 8688 *Opcode = OpKind; 8689 *RHSExprs = Call->getArg(1); 8690 return true; 8691 } 8692 } 8693 8694 return false; 8695 } 8696 8697 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8698 /// or is a logical expression such as (x==y) which has int type, but is 8699 /// commonly interpreted as boolean. 8700 static bool ExprLooksBoolean(Expr *E) { 8701 E = E->IgnoreParenImpCasts(); 8702 8703 if (E->getType()->isBooleanType()) 8704 return true; 8705 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8706 return OP->isComparisonOp() || OP->isLogicalOp(); 8707 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8708 return OP->getOpcode() == UO_LNot; 8709 if (E->getType()->isPointerType()) 8710 return true; 8711 // FIXME: What about overloaded operator calls returning "unspecified boolean 8712 // type"s (commonly pointer-to-members)? 8713 8714 return false; 8715 } 8716 8717 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8718 /// and binary operator are mixed in a way that suggests the programmer assumed 8719 /// the conditional operator has higher precedence, for example: 8720 /// "int x = a + someBinaryCondition ? 1 : 2". 8721 static void DiagnoseConditionalPrecedence(Sema &Self, 8722 SourceLocation OpLoc, 8723 Expr *Condition, 8724 Expr *LHSExpr, 8725 Expr *RHSExpr) { 8726 BinaryOperatorKind CondOpcode; 8727 Expr *CondRHS; 8728 8729 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8730 return; 8731 if (!ExprLooksBoolean(CondRHS)) 8732 return; 8733 8734 // The condition is an arithmetic binary expression, with a right- 8735 // hand side that looks boolean, so warn. 8736 8737 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8738 ? diag::warn_precedence_bitwise_conditional 8739 : diag::warn_precedence_conditional; 8740 8741 Self.Diag(OpLoc, DiagID) 8742 << Condition->getSourceRange() 8743 << BinaryOperator::getOpcodeStr(CondOpcode); 8744 8745 SuggestParentheses( 8746 Self, OpLoc, 8747 Self.PDiag(diag::note_precedence_silence) 8748 << BinaryOperator::getOpcodeStr(CondOpcode), 8749 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8750 8751 SuggestParentheses(Self, OpLoc, 8752 Self.PDiag(diag::note_precedence_conditional_first), 8753 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8754 } 8755 8756 /// Compute the nullability of a conditional expression. 8757 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8758 QualType LHSTy, QualType RHSTy, 8759 ASTContext &Ctx) { 8760 if (!ResTy->isAnyPointerType()) 8761 return ResTy; 8762 8763 auto GetNullability = [&Ctx](QualType Ty) { 8764 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8765 if (Kind) { 8766 // For our purposes, treat _Nullable_result as _Nullable. 8767 if (*Kind == NullabilityKind::NullableResult) 8768 return NullabilityKind::Nullable; 8769 return *Kind; 8770 } 8771 return NullabilityKind::Unspecified; 8772 }; 8773 8774 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8775 NullabilityKind MergedKind; 8776 8777 // Compute nullability of a binary conditional expression. 8778 if (IsBin) { 8779 if (LHSKind == NullabilityKind::NonNull) 8780 MergedKind = NullabilityKind::NonNull; 8781 else 8782 MergedKind = RHSKind; 8783 // Compute nullability of a normal conditional expression. 8784 } else { 8785 if (LHSKind == NullabilityKind::Nullable || 8786 RHSKind == NullabilityKind::Nullable) 8787 MergedKind = NullabilityKind::Nullable; 8788 else if (LHSKind == NullabilityKind::NonNull) 8789 MergedKind = RHSKind; 8790 else if (RHSKind == NullabilityKind::NonNull) 8791 MergedKind = LHSKind; 8792 else 8793 MergedKind = NullabilityKind::Unspecified; 8794 } 8795 8796 // Return if ResTy already has the correct nullability. 8797 if (GetNullability(ResTy) == MergedKind) 8798 return ResTy; 8799 8800 // Strip all nullability from ResTy. 8801 while (ResTy->getNullability(Ctx)) 8802 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8803 8804 // Create a new AttributedType with the new nullability kind. 8805 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8806 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8807 } 8808 8809 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8810 /// in the case of a the GNU conditional expr extension. 8811 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8812 SourceLocation ColonLoc, 8813 Expr *CondExpr, Expr *LHSExpr, 8814 Expr *RHSExpr) { 8815 if (!Context.isDependenceAllowed()) { 8816 // C cannot handle TypoExpr nodes in the condition because it 8817 // doesn't handle dependent types properly, so make sure any TypoExprs have 8818 // been dealt with before checking the operands. 8819 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8820 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8821 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8822 8823 if (!CondResult.isUsable()) 8824 return ExprError(); 8825 8826 if (LHSExpr) { 8827 if (!LHSResult.isUsable()) 8828 return ExprError(); 8829 } 8830 8831 if (!RHSResult.isUsable()) 8832 return ExprError(); 8833 8834 CondExpr = CondResult.get(); 8835 LHSExpr = LHSResult.get(); 8836 RHSExpr = RHSResult.get(); 8837 } 8838 8839 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8840 // was the condition. 8841 OpaqueValueExpr *opaqueValue = nullptr; 8842 Expr *commonExpr = nullptr; 8843 if (!LHSExpr) { 8844 commonExpr = CondExpr; 8845 // Lower out placeholder types first. This is important so that we don't 8846 // try to capture a placeholder. This happens in few cases in C++; such 8847 // as Objective-C++'s dictionary subscripting syntax. 8848 if (commonExpr->hasPlaceholderType()) { 8849 ExprResult result = CheckPlaceholderExpr(commonExpr); 8850 if (!result.isUsable()) return ExprError(); 8851 commonExpr = result.get(); 8852 } 8853 // We usually want to apply unary conversions *before* saving, except 8854 // in the special case of a C++ l-value conditional. 8855 if (!(getLangOpts().CPlusPlus 8856 && !commonExpr->isTypeDependent() 8857 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8858 && commonExpr->isGLValue() 8859 && commonExpr->isOrdinaryOrBitFieldObject() 8860 && RHSExpr->isOrdinaryOrBitFieldObject() 8861 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8862 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8863 if (commonRes.isInvalid()) 8864 return ExprError(); 8865 commonExpr = commonRes.get(); 8866 } 8867 8868 // If the common expression is a class or array prvalue, materialize it 8869 // so that we can safely refer to it multiple times. 8870 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8871 commonExpr->getType()->isArrayType())) { 8872 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8873 if (MatExpr.isInvalid()) 8874 return ExprError(); 8875 commonExpr = MatExpr.get(); 8876 } 8877 8878 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8879 commonExpr->getType(), 8880 commonExpr->getValueKind(), 8881 commonExpr->getObjectKind(), 8882 commonExpr); 8883 LHSExpr = CondExpr = opaqueValue; 8884 } 8885 8886 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8887 ExprValueKind VK = VK_PRValue; 8888 ExprObjectKind OK = OK_Ordinary; 8889 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8890 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8891 VK, OK, QuestionLoc); 8892 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8893 RHS.isInvalid()) 8894 return ExprError(); 8895 8896 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8897 RHS.get()); 8898 8899 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8900 8901 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8902 Context); 8903 8904 if (!commonExpr) 8905 return new (Context) 8906 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8907 RHS.get(), result, VK, OK); 8908 8909 return new (Context) BinaryConditionalOperator( 8910 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8911 ColonLoc, result, VK, OK); 8912 } 8913 8914 // Check if we have a conversion between incompatible cmse function pointer 8915 // types, that is, a conversion between a function pointer with the 8916 // cmse_nonsecure_call attribute and one without. 8917 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8918 QualType ToType) { 8919 if (const auto *ToFn = 8920 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8921 if (const auto *FromFn = 8922 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8923 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8924 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8925 8926 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8927 } 8928 } 8929 return false; 8930 } 8931 8932 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8933 // being closely modeled after the C99 spec:-). The odd characteristic of this 8934 // routine is it effectively iqnores the qualifiers on the top level pointee. 8935 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8936 // FIXME: add a couple examples in this comment. 8937 static Sema::AssignConvertType 8938 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8939 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8940 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8941 8942 // get the "pointed to" type (ignoring qualifiers at the top level) 8943 const Type *lhptee, *rhptee; 8944 Qualifiers lhq, rhq; 8945 std::tie(lhptee, lhq) = 8946 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8947 std::tie(rhptee, rhq) = 8948 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8949 8950 Sema::AssignConvertType ConvTy = Sema::Compatible; 8951 8952 // C99 6.5.16.1p1: This following citation is common to constraints 8953 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8954 // qualifiers of the type *pointed to* by the right; 8955 8956 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8957 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8958 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8959 // Ignore lifetime for further calculation. 8960 lhq.removeObjCLifetime(); 8961 rhq.removeObjCLifetime(); 8962 } 8963 8964 if (!lhq.compatiblyIncludes(rhq)) { 8965 // Treat address-space mismatches as fatal. 8966 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8967 return Sema::IncompatiblePointerDiscardsQualifiers; 8968 8969 // It's okay to add or remove GC or lifetime qualifiers when converting to 8970 // and from void*. 8971 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8972 .compatiblyIncludes( 8973 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8974 && (lhptee->isVoidType() || rhptee->isVoidType())) 8975 ; // keep old 8976 8977 // Treat lifetime mismatches as fatal. 8978 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8979 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8980 8981 // For GCC/MS compatibility, other qualifier mismatches are treated 8982 // as still compatible in C. 8983 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8984 } 8985 8986 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8987 // incomplete type and the other is a pointer to a qualified or unqualified 8988 // version of void... 8989 if (lhptee->isVoidType()) { 8990 if (rhptee->isIncompleteOrObjectType()) 8991 return ConvTy; 8992 8993 // As an extension, we allow cast to/from void* to function pointer. 8994 assert(rhptee->isFunctionType()); 8995 return Sema::FunctionVoidPointer; 8996 } 8997 8998 if (rhptee->isVoidType()) { 8999 if (lhptee->isIncompleteOrObjectType()) 9000 return ConvTy; 9001 9002 // As an extension, we allow cast to/from void* to function pointer. 9003 assert(lhptee->isFunctionType()); 9004 return Sema::FunctionVoidPointer; 9005 } 9006 9007 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9008 // unqualified versions of compatible types, ... 9009 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9010 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9011 // Check if the pointee types are compatible ignoring the sign. 9012 // We explicitly check for char so that we catch "char" vs 9013 // "unsigned char" on systems where "char" is unsigned. 9014 if (lhptee->isCharType()) 9015 ltrans = S.Context.UnsignedCharTy; 9016 else if (lhptee->hasSignedIntegerRepresentation()) 9017 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9018 9019 if (rhptee->isCharType()) 9020 rtrans = S.Context.UnsignedCharTy; 9021 else if (rhptee->hasSignedIntegerRepresentation()) 9022 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9023 9024 if (ltrans == rtrans) { 9025 // Types are compatible ignoring the sign. Qualifier incompatibility 9026 // takes priority over sign incompatibility because the sign 9027 // warning can be disabled. 9028 if (ConvTy != Sema::Compatible) 9029 return ConvTy; 9030 9031 return Sema::IncompatiblePointerSign; 9032 } 9033 9034 // If we are a multi-level pointer, it's possible that our issue is simply 9035 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9036 // the eventual target type is the same and the pointers have the same 9037 // level of indirection, this must be the issue. 9038 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9039 do { 9040 std::tie(lhptee, lhq) = 9041 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9042 std::tie(rhptee, rhq) = 9043 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9044 9045 // Inconsistent address spaces at this point is invalid, even if the 9046 // address spaces would be compatible. 9047 // FIXME: This doesn't catch address space mismatches for pointers of 9048 // different nesting levels, like: 9049 // __local int *** a; 9050 // int ** b = a; 9051 // It's not clear how to actually determine when such pointers are 9052 // invalidly incompatible. 9053 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9054 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9055 9056 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9057 9058 if (lhptee == rhptee) 9059 return Sema::IncompatibleNestedPointerQualifiers; 9060 } 9061 9062 // General pointer incompatibility takes priority over qualifiers. 9063 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9064 return Sema::IncompatibleFunctionPointer; 9065 return Sema::IncompatiblePointer; 9066 } 9067 if (!S.getLangOpts().CPlusPlus && 9068 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9069 return Sema::IncompatibleFunctionPointer; 9070 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9071 return Sema::IncompatibleFunctionPointer; 9072 return ConvTy; 9073 } 9074 9075 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9076 /// block pointer types are compatible or whether a block and normal pointer 9077 /// are compatible. It is more restrict than comparing two function pointer 9078 // types. 9079 static Sema::AssignConvertType 9080 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9081 QualType RHSType) { 9082 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9083 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9084 9085 QualType lhptee, rhptee; 9086 9087 // get the "pointed to" type (ignoring qualifiers at the top level) 9088 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9089 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9090 9091 // In C++, the types have to match exactly. 9092 if (S.getLangOpts().CPlusPlus) 9093 return Sema::IncompatibleBlockPointer; 9094 9095 Sema::AssignConvertType ConvTy = Sema::Compatible; 9096 9097 // For blocks we enforce that qualifiers are identical. 9098 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9099 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9100 if (S.getLangOpts().OpenCL) { 9101 LQuals.removeAddressSpace(); 9102 RQuals.removeAddressSpace(); 9103 } 9104 if (LQuals != RQuals) 9105 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9106 9107 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9108 // assignment. 9109 // The current behavior is similar to C++ lambdas. A block might be 9110 // assigned to a variable iff its return type and parameters are compatible 9111 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9112 // an assignment. Presumably it should behave in way that a function pointer 9113 // assignment does in C, so for each parameter and return type: 9114 // * CVR and address space of LHS should be a superset of CVR and address 9115 // space of RHS. 9116 // * unqualified types should be compatible. 9117 if (S.getLangOpts().OpenCL) { 9118 if (!S.Context.typesAreBlockPointerCompatible( 9119 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9120 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9121 return Sema::IncompatibleBlockPointer; 9122 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9123 return Sema::IncompatibleBlockPointer; 9124 9125 return ConvTy; 9126 } 9127 9128 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9129 /// for assignment compatibility. 9130 static Sema::AssignConvertType 9131 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9132 QualType RHSType) { 9133 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9134 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9135 9136 if (LHSType->isObjCBuiltinType()) { 9137 // Class is not compatible with ObjC object pointers. 9138 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9139 !RHSType->isObjCQualifiedClassType()) 9140 return Sema::IncompatiblePointer; 9141 return Sema::Compatible; 9142 } 9143 if (RHSType->isObjCBuiltinType()) { 9144 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9145 !LHSType->isObjCQualifiedClassType()) 9146 return Sema::IncompatiblePointer; 9147 return Sema::Compatible; 9148 } 9149 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9150 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9151 9152 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9153 // make an exception for id<P> 9154 !LHSType->isObjCQualifiedIdType()) 9155 return Sema::CompatiblePointerDiscardsQualifiers; 9156 9157 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9158 return Sema::Compatible; 9159 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9160 return Sema::IncompatibleObjCQualifiedId; 9161 return Sema::IncompatiblePointer; 9162 } 9163 9164 Sema::AssignConvertType 9165 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9166 QualType LHSType, QualType RHSType) { 9167 // Fake up an opaque expression. We don't actually care about what 9168 // cast operations are required, so if CheckAssignmentConstraints 9169 // adds casts to this they'll be wasted, but fortunately that doesn't 9170 // usually happen on valid code. 9171 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9172 ExprResult RHSPtr = &RHSExpr; 9173 CastKind K; 9174 9175 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9176 } 9177 9178 /// This helper function returns true if QT is a vector type that has element 9179 /// type ElementType. 9180 static bool isVector(QualType QT, QualType ElementType) { 9181 if (const VectorType *VT = QT->getAs<VectorType>()) 9182 return VT->getElementType().getCanonicalType() == ElementType; 9183 return false; 9184 } 9185 9186 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9187 /// has code to accommodate several GCC extensions when type checking 9188 /// pointers. Here are some objectionable examples that GCC considers warnings: 9189 /// 9190 /// int a, *pint; 9191 /// short *pshort; 9192 /// struct foo *pfoo; 9193 /// 9194 /// pint = pshort; // warning: assignment from incompatible pointer type 9195 /// a = pint; // warning: assignment makes integer from pointer without a cast 9196 /// pint = a; // warning: assignment makes pointer from integer without a cast 9197 /// pint = pfoo; // warning: assignment from incompatible pointer type 9198 /// 9199 /// As a result, the code for dealing with pointers is more complex than the 9200 /// C99 spec dictates. 9201 /// 9202 /// Sets 'Kind' for any result kind except Incompatible. 9203 Sema::AssignConvertType 9204 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9205 CastKind &Kind, bool ConvertRHS) { 9206 QualType RHSType = RHS.get()->getType(); 9207 QualType OrigLHSType = LHSType; 9208 9209 // Get canonical types. We're not formatting these types, just comparing 9210 // them. 9211 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9212 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9213 9214 // Common case: no conversion required. 9215 if (LHSType == RHSType) { 9216 Kind = CK_NoOp; 9217 return Compatible; 9218 } 9219 9220 // If we have an atomic type, try a non-atomic assignment, then just add an 9221 // atomic qualification step. 9222 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9223 Sema::AssignConvertType result = 9224 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9225 if (result != Compatible) 9226 return result; 9227 if (Kind != CK_NoOp && ConvertRHS) 9228 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9229 Kind = CK_NonAtomicToAtomic; 9230 return Compatible; 9231 } 9232 9233 // If the left-hand side is a reference type, then we are in a 9234 // (rare!) case where we've allowed the use of references in C, 9235 // e.g., as a parameter type in a built-in function. In this case, 9236 // just make sure that the type referenced is compatible with the 9237 // right-hand side type. The caller is responsible for adjusting 9238 // LHSType so that the resulting expression does not have reference 9239 // type. 9240 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9241 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9242 Kind = CK_LValueBitCast; 9243 return Compatible; 9244 } 9245 return Incompatible; 9246 } 9247 9248 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9249 // to the same ExtVector type. 9250 if (LHSType->isExtVectorType()) { 9251 if (RHSType->isExtVectorType()) 9252 return Incompatible; 9253 if (RHSType->isArithmeticType()) { 9254 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9255 if (ConvertRHS) 9256 RHS = prepareVectorSplat(LHSType, RHS.get()); 9257 Kind = CK_VectorSplat; 9258 return Compatible; 9259 } 9260 } 9261 9262 // Conversions to or from vector type. 9263 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9264 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9265 // Allow assignments of an AltiVec vector type to an equivalent GCC 9266 // vector type and vice versa 9267 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9268 Kind = CK_BitCast; 9269 return Compatible; 9270 } 9271 9272 // If we are allowing lax vector conversions, and LHS and RHS are both 9273 // vectors, the total size only needs to be the same. This is a bitcast; 9274 // no bits are changed but the result type is different. 9275 if (isLaxVectorConversion(RHSType, LHSType)) { 9276 Kind = CK_BitCast; 9277 return IncompatibleVectors; 9278 } 9279 } 9280 9281 // When the RHS comes from another lax conversion (e.g. binops between 9282 // scalars and vectors) the result is canonicalized as a vector. When the 9283 // LHS is also a vector, the lax is allowed by the condition above. Handle 9284 // the case where LHS is a scalar. 9285 if (LHSType->isScalarType()) { 9286 const VectorType *VecType = RHSType->getAs<VectorType>(); 9287 if (VecType && VecType->getNumElements() == 1 && 9288 isLaxVectorConversion(RHSType, LHSType)) { 9289 ExprResult *VecExpr = &RHS; 9290 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9291 Kind = CK_BitCast; 9292 return Compatible; 9293 } 9294 } 9295 9296 // Allow assignments between fixed-length and sizeless SVE vectors. 9297 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9298 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9299 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9300 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9301 Kind = CK_BitCast; 9302 return Compatible; 9303 } 9304 9305 return Incompatible; 9306 } 9307 9308 // Diagnose attempts to convert between __ibm128, __float128 and long double 9309 // where such conversions currently can't be handled. 9310 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9311 return Incompatible; 9312 9313 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9314 // discards the imaginary part. 9315 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9316 !LHSType->getAs<ComplexType>()) 9317 return Incompatible; 9318 9319 // Arithmetic conversions. 9320 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9321 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9322 if (ConvertRHS) 9323 Kind = PrepareScalarCast(RHS, LHSType); 9324 return Compatible; 9325 } 9326 9327 // Conversions to normal pointers. 9328 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9329 // U* -> T* 9330 if (isa<PointerType>(RHSType)) { 9331 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9332 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9333 if (AddrSpaceL != AddrSpaceR) 9334 Kind = CK_AddressSpaceConversion; 9335 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9336 Kind = CK_NoOp; 9337 else 9338 Kind = CK_BitCast; 9339 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9340 } 9341 9342 // int -> T* 9343 if (RHSType->isIntegerType()) { 9344 Kind = CK_IntegralToPointer; // FIXME: null? 9345 return IntToPointer; 9346 } 9347 9348 // C pointers are not compatible with ObjC object pointers, 9349 // with two exceptions: 9350 if (isa<ObjCObjectPointerType>(RHSType)) { 9351 // - conversions to void* 9352 if (LHSPointer->getPointeeType()->isVoidType()) { 9353 Kind = CK_BitCast; 9354 return Compatible; 9355 } 9356 9357 // - conversions from 'Class' to the redefinition type 9358 if (RHSType->isObjCClassType() && 9359 Context.hasSameType(LHSType, 9360 Context.getObjCClassRedefinitionType())) { 9361 Kind = CK_BitCast; 9362 return Compatible; 9363 } 9364 9365 Kind = CK_BitCast; 9366 return IncompatiblePointer; 9367 } 9368 9369 // U^ -> void* 9370 if (RHSType->getAs<BlockPointerType>()) { 9371 if (LHSPointer->getPointeeType()->isVoidType()) { 9372 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9373 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9374 ->getPointeeType() 9375 .getAddressSpace(); 9376 Kind = 9377 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9378 return Compatible; 9379 } 9380 } 9381 9382 return Incompatible; 9383 } 9384 9385 // Conversions to block pointers. 9386 if (isa<BlockPointerType>(LHSType)) { 9387 // U^ -> T^ 9388 if (RHSType->isBlockPointerType()) { 9389 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9390 ->getPointeeType() 9391 .getAddressSpace(); 9392 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9393 ->getPointeeType() 9394 .getAddressSpace(); 9395 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9396 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9397 } 9398 9399 // int or null -> T^ 9400 if (RHSType->isIntegerType()) { 9401 Kind = CK_IntegralToPointer; // FIXME: null 9402 return IntToBlockPointer; 9403 } 9404 9405 // id -> T^ 9406 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9407 Kind = CK_AnyPointerToBlockPointerCast; 9408 return Compatible; 9409 } 9410 9411 // void* -> T^ 9412 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9413 if (RHSPT->getPointeeType()->isVoidType()) { 9414 Kind = CK_AnyPointerToBlockPointerCast; 9415 return Compatible; 9416 } 9417 9418 return Incompatible; 9419 } 9420 9421 // Conversions to Objective-C pointers. 9422 if (isa<ObjCObjectPointerType>(LHSType)) { 9423 // A* -> B* 9424 if (RHSType->isObjCObjectPointerType()) { 9425 Kind = CK_BitCast; 9426 Sema::AssignConvertType result = 9427 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9428 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9429 result == Compatible && 9430 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9431 result = IncompatibleObjCWeakRef; 9432 return result; 9433 } 9434 9435 // int or null -> A* 9436 if (RHSType->isIntegerType()) { 9437 Kind = CK_IntegralToPointer; // FIXME: null 9438 return IntToPointer; 9439 } 9440 9441 // In general, C pointers are not compatible with ObjC object pointers, 9442 // with two exceptions: 9443 if (isa<PointerType>(RHSType)) { 9444 Kind = CK_CPointerToObjCPointerCast; 9445 9446 // - conversions from 'void*' 9447 if (RHSType->isVoidPointerType()) { 9448 return Compatible; 9449 } 9450 9451 // - conversions to 'Class' from its redefinition type 9452 if (LHSType->isObjCClassType() && 9453 Context.hasSameType(RHSType, 9454 Context.getObjCClassRedefinitionType())) { 9455 return Compatible; 9456 } 9457 9458 return IncompatiblePointer; 9459 } 9460 9461 // Only under strict condition T^ is compatible with an Objective-C pointer. 9462 if (RHSType->isBlockPointerType() && 9463 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9464 if (ConvertRHS) 9465 maybeExtendBlockObject(RHS); 9466 Kind = CK_BlockPointerToObjCPointerCast; 9467 return Compatible; 9468 } 9469 9470 return Incompatible; 9471 } 9472 9473 // Conversions from pointers that are not covered by the above. 9474 if (isa<PointerType>(RHSType)) { 9475 // T* -> _Bool 9476 if (LHSType == Context.BoolTy) { 9477 Kind = CK_PointerToBoolean; 9478 return Compatible; 9479 } 9480 9481 // T* -> int 9482 if (LHSType->isIntegerType()) { 9483 Kind = CK_PointerToIntegral; 9484 return PointerToInt; 9485 } 9486 9487 return Incompatible; 9488 } 9489 9490 // Conversions from Objective-C pointers that are not covered by the above. 9491 if (isa<ObjCObjectPointerType>(RHSType)) { 9492 // T* -> _Bool 9493 if (LHSType == Context.BoolTy) { 9494 Kind = CK_PointerToBoolean; 9495 return Compatible; 9496 } 9497 9498 // T* -> int 9499 if (LHSType->isIntegerType()) { 9500 Kind = CK_PointerToIntegral; 9501 return PointerToInt; 9502 } 9503 9504 return Incompatible; 9505 } 9506 9507 // struct A -> struct B 9508 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9509 if (Context.typesAreCompatible(LHSType, RHSType)) { 9510 Kind = CK_NoOp; 9511 return Compatible; 9512 } 9513 } 9514 9515 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9516 Kind = CK_IntToOCLSampler; 9517 return Compatible; 9518 } 9519 9520 return Incompatible; 9521 } 9522 9523 /// Constructs a transparent union from an expression that is 9524 /// used to initialize the transparent union. 9525 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9526 ExprResult &EResult, QualType UnionType, 9527 FieldDecl *Field) { 9528 // Build an initializer list that designates the appropriate member 9529 // of the transparent union. 9530 Expr *E = EResult.get(); 9531 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9532 E, SourceLocation()); 9533 Initializer->setType(UnionType); 9534 Initializer->setInitializedFieldInUnion(Field); 9535 9536 // Build a compound literal constructing a value of the transparent 9537 // union type from this initializer list. 9538 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9539 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9540 VK_PRValue, Initializer, false); 9541 } 9542 9543 Sema::AssignConvertType 9544 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9545 ExprResult &RHS) { 9546 QualType RHSType = RHS.get()->getType(); 9547 9548 // If the ArgType is a Union type, we want to handle a potential 9549 // transparent_union GCC extension. 9550 const RecordType *UT = ArgType->getAsUnionType(); 9551 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9552 return Incompatible; 9553 9554 // The field to initialize within the transparent union. 9555 RecordDecl *UD = UT->getDecl(); 9556 FieldDecl *InitField = nullptr; 9557 // It's compatible if the expression matches any of the fields. 9558 for (auto *it : UD->fields()) { 9559 if (it->getType()->isPointerType()) { 9560 // If the transparent union contains a pointer type, we allow: 9561 // 1) void pointer 9562 // 2) null pointer constant 9563 if (RHSType->isPointerType()) 9564 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9565 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9566 InitField = it; 9567 break; 9568 } 9569 9570 if (RHS.get()->isNullPointerConstant(Context, 9571 Expr::NPC_ValueDependentIsNull)) { 9572 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9573 CK_NullToPointer); 9574 InitField = it; 9575 break; 9576 } 9577 } 9578 9579 CastKind Kind; 9580 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9581 == Compatible) { 9582 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9583 InitField = it; 9584 break; 9585 } 9586 } 9587 9588 if (!InitField) 9589 return Incompatible; 9590 9591 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9592 return Compatible; 9593 } 9594 9595 Sema::AssignConvertType 9596 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9597 bool Diagnose, 9598 bool DiagnoseCFAudited, 9599 bool ConvertRHS) { 9600 // We need to be able to tell the caller whether we diagnosed a problem, if 9601 // they ask us to issue diagnostics. 9602 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9603 9604 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9605 // we can't avoid *all* modifications at the moment, so we need some somewhere 9606 // to put the updated value. 9607 ExprResult LocalRHS = CallerRHS; 9608 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9609 9610 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9611 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9612 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9613 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9614 Diag(RHS.get()->getExprLoc(), 9615 diag::warn_noderef_to_dereferenceable_pointer) 9616 << RHS.get()->getSourceRange(); 9617 } 9618 } 9619 } 9620 9621 if (getLangOpts().CPlusPlus) { 9622 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9623 // C++ 5.17p3: If the left operand is not of class type, the 9624 // expression is implicitly converted (C++ 4) to the 9625 // cv-unqualified type of the left operand. 9626 QualType RHSType = RHS.get()->getType(); 9627 if (Diagnose) { 9628 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9629 AA_Assigning); 9630 } else { 9631 ImplicitConversionSequence ICS = 9632 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9633 /*SuppressUserConversions=*/false, 9634 AllowedExplicit::None, 9635 /*InOverloadResolution=*/false, 9636 /*CStyle=*/false, 9637 /*AllowObjCWritebackConversion=*/false); 9638 if (ICS.isFailure()) 9639 return Incompatible; 9640 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9641 ICS, AA_Assigning); 9642 } 9643 if (RHS.isInvalid()) 9644 return Incompatible; 9645 Sema::AssignConvertType result = Compatible; 9646 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9647 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9648 result = IncompatibleObjCWeakRef; 9649 return result; 9650 } 9651 9652 // FIXME: Currently, we fall through and treat C++ classes like C 9653 // structures. 9654 // FIXME: We also fall through for atomics; not sure what should 9655 // happen there, though. 9656 } else if (RHS.get()->getType() == Context.OverloadTy) { 9657 // As a set of extensions to C, we support overloading on functions. These 9658 // functions need to be resolved here. 9659 DeclAccessPair DAP; 9660 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9661 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9662 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9663 else 9664 return Incompatible; 9665 } 9666 9667 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9668 // a null pointer constant. 9669 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9670 LHSType->isBlockPointerType()) && 9671 RHS.get()->isNullPointerConstant(Context, 9672 Expr::NPC_ValueDependentIsNull)) { 9673 if (Diagnose || ConvertRHS) { 9674 CastKind Kind; 9675 CXXCastPath Path; 9676 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9677 /*IgnoreBaseAccess=*/false, Diagnose); 9678 if (ConvertRHS) 9679 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9680 } 9681 return Compatible; 9682 } 9683 9684 // OpenCL queue_t type assignment. 9685 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9686 Context, Expr::NPC_ValueDependentIsNull)) { 9687 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9688 return Compatible; 9689 } 9690 9691 // This check seems unnatural, however it is necessary to ensure the proper 9692 // conversion of functions/arrays. If the conversion were done for all 9693 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9694 // expressions that suppress this implicit conversion (&, sizeof). 9695 // 9696 // Suppress this for references: C++ 8.5.3p5. 9697 if (!LHSType->isReferenceType()) { 9698 // FIXME: We potentially allocate here even if ConvertRHS is false. 9699 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9700 if (RHS.isInvalid()) 9701 return Incompatible; 9702 } 9703 CastKind Kind; 9704 Sema::AssignConvertType result = 9705 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9706 9707 // C99 6.5.16.1p2: The value of the right operand is converted to the 9708 // type of the assignment expression. 9709 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9710 // so that we can use references in built-in functions even in C. 9711 // The getNonReferenceType() call makes sure that the resulting expression 9712 // does not have reference type. 9713 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9714 QualType Ty = LHSType.getNonLValueExprType(Context); 9715 Expr *E = RHS.get(); 9716 9717 // Check for various Objective-C errors. If we are not reporting 9718 // diagnostics and just checking for errors, e.g., during overload 9719 // resolution, return Incompatible to indicate the failure. 9720 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9721 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9722 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9723 if (!Diagnose) 9724 return Incompatible; 9725 } 9726 if (getLangOpts().ObjC && 9727 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9728 E->getType(), E, Diagnose) || 9729 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9730 if (!Diagnose) 9731 return Incompatible; 9732 // Replace the expression with a corrected version and continue so we 9733 // can find further errors. 9734 RHS = E; 9735 return Compatible; 9736 } 9737 9738 if (ConvertRHS) 9739 RHS = ImpCastExprToType(E, Ty, Kind); 9740 } 9741 9742 return result; 9743 } 9744 9745 namespace { 9746 /// The original operand to an operator, prior to the application of the usual 9747 /// arithmetic conversions and converting the arguments of a builtin operator 9748 /// candidate. 9749 struct OriginalOperand { 9750 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9751 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9752 Op = MTE->getSubExpr(); 9753 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9754 Op = BTE->getSubExpr(); 9755 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9756 Orig = ICE->getSubExprAsWritten(); 9757 Conversion = ICE->getConversionFunction(); 9758 } 9759 } 9760 9761 QualType getType() const { return Orig->getType(); } 9762 9763 Expr *Orig; 9764 NamedDecl *Conversion; 9765 }; 9766 } 9767 9768 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9769 ExprResult &RHS) { 9770 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9771 9772 Diag(Loc, diag::err_typecheck_invalid_operands) 9773 << OrigLHS.getType() << OrigRHS.getType() 9774 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9775 9776 // If a user-defined conversion was applied to either of the operands prior 9777 // to applying the built-in operator rules, tell the user about it. 9778 if (OrigLHS.Conversion) { 9779 Diag(OrigLHS.Conversion->getLocation(), 9780 diag::note_typecheck_invalid_operands_converted) 9781 << 0 << LHS.get()->getType(); 9782 } 9783 if (OrigRHS.Conversion) { 9784 Diag(OrigRHS.Conversion->getLocation(), 9785 diag::note_typecheck_invalid_operands_converted) 9786 << 1 << RHS.get()->getType(); 9787 } 9788 9789 return QualType(); 9790 } 9791 9792 // Diagnose cases where a scalar was implicitly converted to a vector and 9793 // diagnose the underlying types. Otherwise, diagnose the error 9794 // as invalid vector logical operands for non-C++ cases. 9795 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9796 ExprResult &RHS) { 9797 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9798 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9799 9800 bool LHSNatVec = LHSType->isVectorType(); 9801 bool RHSNatVec = RHSType->isVectorType(); 9802 9803 if (!(LHSNatVec && RHSNatVec)) { 9804 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9805 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9806 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9807 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9808 << Vector->getSourceRange(); 9809 return QualType(); 9810 } 9811 9812 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9813 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9814 << RHS.get()->getSourceRange(); 9815 9816 return QualType(); 9817 } 9818 9819 /// Try to convert a value of non-vector type to a vector type by converting 9820 /// the type to the element type of the vector and then performing a splat. 9821 /// If the language is OpenCL, we only use conversions that promote scalar 9822 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9823 /// for float->int. 9824 /// 9825 /// OpenCL V2.0 6.2.6.p2: 9826 /// An error shall occur if any scalar operand type has greater rank 9827 /// than the type of the vector element. 9828 /// 9829 /// \param scalar - if non-null, actually perform the conversions 9830 /// \return true if the operation fails (but without diagnosing the failure) 9831 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9832 QualType scalarTy, 9833 QualType vectorEltTy, 9834 QualType vectorTy, 9835 unsigned &DiagID) { 9836 // The conversion to apply to the scalar before splatting it, 9837 // if necessary. 9838 CastKind scalarCast = CK_NoOp; 9839 9840 if (vectorEltTy->isIntegralType(S.Context)) { 9841 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9842 (scalarTy->isIntegerType() && 9843 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9844 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9845 return true; 9846 } 9847 if (!scalarTy->isIntegralType(S.Context)) 9848 return true; 9849 scalarCast = CK_IntegralCast; 9850 } else if (vectorEltTy->isRealFloatingType()) { 9851 if (scalarTy->isRealFloatingType()) { 9852 if (S.getLangOpts().OpenCL && 9853 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9854 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9855 return true; 9856 } 9857 scalarCast = CK_FloatingCast; 9858 } 9859 else if (scalarTy->isIntegralType(S.Context)) 9860 scalarCast = CK_IntegralToFloating; 9861 else 9862 return true; 9863 } else { 9864 return true; 9865 } 9866 9867 // Adjust scalar if desired. 9868 if (scalar) { 9869 if (scalarCast != CK_NoOp) 9870 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9871 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9872 } 9873 return false; 9874 } 9875 9876 /// Convert vector E to a vector with the same number of elements but different 9877 /// element type. 9878 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9879 const auto *VecTy = E->getType()->getAs<VectorType>(); 9880 assert(VecTy && "Expression E must be a vector"); 9881 QualType NewVecTy = S.Context.getVectorType(ElementType, 9882 VecTy->getNumElements(), 9883 VecTy->getVectorKind()); 9884 9885 // Look through the implicit cast. Return the subexpression if its type is 9886 // NewVecTy. 9887 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9888 if (ICE->getSubExpr()->getType() == NewVecTy) 9889 return ICE->getSubExpr(); 9890 9891 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9892 return S.ImpCastExprToType(E, NewVecTy, Cast); 9893 } 9894 9895 /// Test if a (constant) integer Int can be casted to another integer type 9896 /// IntTy without losing precision. 9897 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9898 QualType OtherIntTy) { 9899 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9900 9901 // Reject cases where the value of the Int is unknown as that would 9902 // possibly cause truncation, but accept cases where the scalar can be 9903 // demoted without loss of precision. 9904 Expr::EvalResult EVResult; 9905 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9906 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9907 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9908 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9909 9910 if (CstInt) { 9911 // If the scalar is constant and is of a higher order and has more active 9912 // bits that the vector element type, reject it. 9913 llvm::APSInt Result = EVResult.Val.getInt(); 9914 unsigned NumBits = IntSigned 9915 ? (Result.isNegative() ? Result.getMinSignedBits() 9916 : Result.getActiveBits()) 9917 : Result.getActiveBits(); 9918 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9919 return true; 9920 9921 // If the signedness of the scalar type and the vector element type 9922 // differs and the number of bits is greater than that of the vector 9923 // element reject it. 9924 return (IntSigned != OtherIntSigned && 9925 NumBits > S.Context.getIntWidth(OtherIntTy)); 9926 } 9927 9928 // Reject cases where the value of the scalar is not constant and it's 9929 // order is greater than that of the vector element type. 9930 return (Order < 0); 9931 } 9932 9933 /// Test if a (constant) integer Int can be casted to floating point type 9934 /// FloatTy without losing precision. 9935 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9936 QualType FloatTy) { 9937 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9938 9939 // Determine if the integer constant can be expressed as a floating point 9940 // number of the appropriate type. 9941 Expr::EvalResult EVResult; 9942 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9943 9944 uint64_t Bits = 0; 9945 if (CstInt) { 9946 // Reject constants that would be truncated if they were converted to 9947 // the floating point type. Test by simple to/from conversion. 9948 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9949 // could be avoided if there was a convertFromAPInt method 9950 // which could signal back if implicit truncation occurred. 9951 llvm::APSInt Result = EVResult.Val.getInt(); 9952 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9953 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9954 llvm::APFloat::rmTowardZero); 9955 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9956 !IntTy->hasSignedIntegerRepresentation()); 9957 bool Ignored = false; 9958 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9959 &Ignored); 9960 if (Result != ConvertBack) 9961 return true; 9962 } else { 9963 // Reject types that cannot be fully encoded into the mantissa of 9964 // the float. 9965 Bits = S.Context.getTypeSize(IntTy); 9966 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9967 S.Context.getFloatTypeSemantics(FloatTy)); 9968 if (Bits > FloatPrec) 9969 return true; 9970 } 9971 9972 return false; 9973 } 9974 9975 /// Attempt to convert and splat Scalar into a vector whose types matches 9976 /// Vector following GCC conversion rules. The rule is that implicit 9977 /// conversion can occur when Scalar can be casted to match Vector's element 9978 /// type without causing truncation of Scalar. 9979 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9980 ExprResult *Vector) { 9981 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9982 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9983 const VectorType *VT = VectorTy->getAs<VectorType>(); 9984 9985 assert(!isa<ExtVectorType>(VT) && 9986 "ExtVectorTypes should not be handled here!"); 9987 9988 QualType VectorEltTy = VT->getElementType(); 9989 9990 // Reject cases where the vector element type or the scalar element type are 9991 // not integral or floating point types. 9992 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9993 return true; 9994 9995 // The conversion to apply to the scalar before splatting it, 9996 // if necessary. 9997 CastKind ScalarCast = CK_NoOp; 9998 9999 // Accept cases where the vector elements are integers and the scalar is 10000 // an integer. 10001 // FIXME: Notionally if the scalar was a floating point value with a precise 10002 // integral representation, we could cast it to an appropriate integer 10003 // type and then perform the rest of the checks here. GCC will perform 10004 // this conversion in some cases as determined by the input language. 10005 // We should accept it on a language independent basis. 10006 if (VectorEltTy->isIntegralType(S.Context) && 10007 ScalarTy->isIntegralType(S.Context) && 10008 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10009 10010 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10011 return true; 10012 10013 ScalarCast = CK_IntegralCast; 10014 } else if (VectorEltTy->isIntegralType(S.Context) && 10015 ScalarTy->isRealFloatingType()) { 10016 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10017 ScalarCast = CK_FloatingToIntegral; 10018 else 10019 return true; 10020 } else if (VectorEltTy->isRealFloatingType()) { 10021 if (ScalarTy->isRealFloatingType()) { 10022 10023 // Reject cases where the scalar type is not a constant and has a higher 10024 // Order than the vector element type. 10025 llvm::APFloat Result(0.0); 10026 10027 // Determine whether this is a constant scalar. In the event that the 10028 // value is dependent (and thus cannot be evaluated by the constant 10029 // evaluator), skip the evaluation. This will then diagnose once the 10030 // expression is instantiated. 10031 bool CstScalar = Scalar->get()->isValueDependent() || 10032 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10033 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10034 if (!CstScalar && Order < 0) 10035 return true; 10036 10037 // If the scalar cannot be safely casted to the vector element type, 10038 // reject it. 10039 if (CstScalar) { 10040 bool Truncated = false; 10041 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10042 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10043 if (Truncated) 10044 return true; 10045 } 10046 10047 ScalarCast = CK_FloatingCast; 10048 } else if (ScalarTy->isIntegralType(S.Context)) { 10049 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10050 return true; 10051 10052 ScalarCast = CK_IntegralToFloating; 10053 } else 10054 return true; 10055 } else if (ScalarTy->isEnumeralType()) 10056 return true; 10057 10058 // Adjust scalar if desired. 10059 if (Scalar) { 10060 if (ScalarCast != CK_NoOp) 10061 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10062 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10063 } 10064 return false; 10065 } 10066 10067 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10068 SourceLocation Loc, bool IsCompAssign, 10069 bool AllowBothBool, 10070 bool AllowBoolConversions) { 10071 if (!IsCompAssign) { 10072 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10073 if (LHS.isInvalid()) 10074 return QualType(); 10075 } 10076 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10077 if (RHS.isInvalid()) 10078 return QualType(); 10079 10080 // For conversion purposes, we ignore any qualifiers. 10081 // For example, "const float" and "float" are equivalent. 10082 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10083 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10084 10085 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10086 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10087 assert(LHSVecType || RHSVecType); 10088 10089 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10090 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10091 return InvalidOperands(Loc, LHS, RHS); 10092 10093 // AltiVec-style "vector bool op vector bool" combinations are allowed 10094 // for some operators but not others. 10095 if (!AllowBothBool && 10096 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10097 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10098 return InvalidOperands(Loc, LHS, RHS); 10099 10100 // If the vector types are identical, return. 10101 if (Context.hasSameType(LHSType, RHSType)) 10102 return LHSType; 10103 10104 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10105 if (LHSVecType && RHSVecType && 10106 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10107 if (isa<ExtVectorType>(LHSVecType)) { 10108 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10109 return LHSType; 10110 } 10111 10112 if (!IsCompAssign) 10113 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10114 return RHSType; 10115 } 10116 10117 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10118 // can be mixed, with the result being the non-bool type. The non-bool 10119 // operand must have integer element type. 10120 if (AllowBoolConversions && LHSVecType && RHSVecType && 10121 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10122 (Context.getTypeSize(LHSVecType->getElementType()) == 10123 Context.getTypeSize(RHSVecType->getElementType()))) { 10124 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10125 LHSVecType->getElementType()->isIntegerType() && 10126 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10127 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10128 return LHSType; 10129 } 10130 if (!IsCompAssign && 10131 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10132 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10133 RHSVecType->getElementType()->isIntegerType()) { 10134 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10135 return RHSType; 10136 } 10137 } 10138 10139 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10140 // since the ambiguity can affect the ABI. 10141 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10142 const VectorType *VecType = SecondType->getAs<VectorType>(); 10143 return FirstType->isSizelessBuiltinType() && VecType && 10144 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10145 VecType->getVectorKind() == 10146 VectorType::SveFixedLengthPredicateVector); 10147 }; 10148 10149 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10150 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10151 return QualType(); 10152 } 10153 10154 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10155 // since the ambiguity can affect the ABI. 10156 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10157 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10158 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10159 10160 if (FirstVecType && SecondVecType) 10161 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10162 (SecondVecType->getVectorKind() == 10163 VectorType::SveFixedLengthDataVector || 10164 SecondVecType->getVectorKind() == 10165 VectorType::SveFixedLengthPredicateVector); 10166 10167 return FirstType->isSizelessBuiltinType() && SecondVecType && 10168 SecondVecType->getVectorKind() == VectorType::GenericVector; 10169 }; 10170 10171 if (IsSveGnuConversion(LHSType, RHSType) || 10172 IsSveGnuConversion(RHSType, LHSType)) { 10173 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10174 return QualType(); 10175 } 10176 10177 // If there's a vector type and a scalar, try to convert the scalar to 10178 // the vector element type and splat. 10179 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10180 if (!RHSVecType) { 10181 if (isa<ExtVectorType>(LHSVecType)) { 10182 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10183 LHSVecType->getElementType(), LHSType, 10184 DiagID)) 10185 return LHSType; 10186 } else { 10187 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10188 return LHSType; 10189 } 10190 } 10191 if (!LHSVecType) { 10192 if (isa<ExtVectorType>(RHSVecType)) { 10193 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10194 LHSType, RHSVecType->getElementType(), 10195 RHSType, DiagID)) 10196 return RHSType; 10197 } else { 10198 if (LHS.get()->isLValue() || 10199 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10200 return RHSType; 10201 } 10202 } 10203 10204 // FIXME: The code below also handles conversion between vectors and 10205 // non-scalars, we should break this down into fine grained specific checks 10206 // and emit proper diagnostics. 10207 QualType VecType = LHSVecType ? LHSType : RHSType; 10208 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10209 QualType OtherType = LHSVecType ? RHSType : LHSType; 10210 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10211 if (isLaxVectorConversion(OtherType, VecType)) { 10212 // If we're allowing lax vector conversions, only the total (data) size 10213 // needs to be the same. For non compound assignment, if one of the types is 10214 // scalar, the result is always the vector type. 10215 if (!IsCompAssign) { 10216 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10217 return VecType; 10218 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10219 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10220 // type. Note that this is already done by non-compound assignments in 10221 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10222 // <1 x T> -> T. The result is also a vector type. 10223 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10224 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10225 ExprResult *RHSExpr = &RHS; 10226 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10227 return VecType; 10228 } 10229 } 10230 10231 // Okay, the expression is invalid. 10232 10233 // If there's a non-vector, non-real operand, diagnose that. 10234 if ((!RHSVecType && !RHSType->isRealType()) || 10235 (!LHSVecType && !LHSType->isRealType())) { 10236 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10237 << LHSType << RHSType 10238 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10239 return QualType(); 10240 } 10241 10242 // OpenCL V1.1 6.2.6.p1: 10243 // If the operands are of more than one vector type, then an error shall 10244 // occur. Implicit conversions between vector types are not permitted, per 10245 // section 6.2.1. 10246 if (getLangOpts().OpenCL && 10247 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10248 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10249 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10250 << RHSType; 10251 return QualType(); 10252 } 10253 10254 10255 // If there is a vector type that is not a ExtVector and a scalar, we reach 10256 // this point if scalar could not be converted to the vector's element type 10257 // without truncation. 10258 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10259 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10260 QualType Scalar = LHSVecType ? RHSType : LHSType; 10261 QualType Vector = LHSVecType ? LHSType : RHSType; 10262 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10263 Diag(Loc, 10264 diag::err_typecheck_vector_not_convertable_implict_truncation) 10265 << ScalarOrVector << Scalar << Vector; 10266 10267 return QualType(); 10268 } 10269 10270 // Otherwise, use the generic diagnostic. 10271 Diag(Loc, DiagID) 10272 << LHSType << RHSType 10273 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10274 return QualType(); 10275 } 10276 10277 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10278 // expression. These are mainly cases where the null pointer is used as an 10279 // integer instead of a pointer. 10280 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10281 SourceLocation Loc, bool IsCompare) { 10282 // The canonical way to check for a GNU null is with isNullPointerConstant, 10283 // but we use a bit of a hack here for speed; this is a relatively 10284 // hot path, and isNullPointerConstant is slow. 10285 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10286 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10287 10288 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10289 10290 // Avoid analyzing cases where the result will either be invalid (and 10291 // diagnosed as such) or entirely valid and not something to warn about. 10292 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10293 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10294 return; 10295 10296 // Comparison operations would not make sense with a null pointer no matter 10297 // what the other expression is. 10298 if (!IsCompare) { 10299 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10300 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10301 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10302 return; 10303 } 10304 10305 // The rest of the operations only make sense with a null pointer 10306 // if the other expression is a pointer. 10307 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10308 NonNullType->canDecayToPointerType()) 10309 return; 10310 10311 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10312 << LHSNull /* LHS is NULL */ << NonNullType 10313 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10314 } 10315 10316 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10317 SourceLocation Loc) { 10318 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10319 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10320 if (!LUE || !RUE) 10321 return; 10322 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10323 RUE->getKind() != UETT_SizeOf) 10324 return; 10325 10326 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10327 QualType LHSTy = LHSArg->getType(); 10328 QualType RHSTy; 10329 10330 if (RUE->isArgumentType()) 10331 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10332 else 10333 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10334 10335 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10336 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10337 return; 10338 10339 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10340 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10341 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10342 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10343 << LHSArgDecl; 10344 } 10345 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10346 QualType ArrayElemTy = ArrayTy->getElementType(); 10347 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10348 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10349 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10350 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10351 return; 10352 S.Diag(Loc, diag::warn_division_sizeof_array) 10353 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10354 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10355 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10356 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10357 << LHSArgDecl; 10358 } 10359 10360 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10361 } 10362 } 10363 10364 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10365 ExprResult &RHS, 10366 SourceLocation Loc, bool IsDiv) { 10367 // Check for division/remainder by zero. 10368 Expr::EvalResult RHSValue; 10369 if (!RHS.get()->isValueDependent() && 10370 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10371 RHSValue.Val.getInt() == 0) 10372 S.DiagRuntimeBehavior(Loc, RHS.get(), 10373 S.PDiag(diag::warn_remainder_division_by_zero) 10374 << IsDiv << RHS.get()->getSourceRange()); 10375 } 10376 10377 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10378 SourceLocation Loc, 10379 bool IsCompAssign, bool IsDiv) { 10380 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10381 10382 QualType LHSTy = LHS.get()->getType(); 10383 QualType RHSTy = RHS.get()->getType(); 10384 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10385 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10386 /*AllowBothBool*/getLangOpts().AltiVec, 10387 /*AllowBoolConversions*/false); 10388 if (!IsDiv && 10389 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10390 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10391 // For division, only matrix-by-scalar is supported. Other combinations with 10392 // matrix types are invalid. 10393 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10394 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10395 10396 QualType compType = UsualArithmeticConversions( 10397 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10398 if (LHS.isInvalid() || RHS.isInvalid()) 10399 return QualType(); 10400 10401 10402 if (compType.isNull() || !compType->isArithmeticType()) 10403 return InvalidOperands(Loc, LHS, RHS); 10404 if (IsDiv) { 10405 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10406 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10407 } 10408 return compType; 10409 } 10410 10411 QualType Sema::CheckRemainderOperands( 10412 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10413 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10414 10415 if (LHS.get()->getType()->isVectorType() || 10416 RHS.get()->getType()->isVectorType()) { 10417 if (LHS.get()->getType()->hasIntegerRepresentation() && 10418 RHS.get()->getType()->hasIntegerRepresentation()) 10419 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10420 /*AllowBothBool*/getLangOpts().AltiVec, 10421 /*AllowBoolConversions*/false); 10422 return InvalidOperands(Loc, LHS, RHS); 10423 } 10424 10425 QualType compType = UsualArithmeticConversions( 10426 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10427 if (LHS.isInvalid() || RHS.isInvalid()) 10428 return QualType(); 10429 10430 if (compType.isNull() || !compType->isIntegerType()) 10431 return InvalidOperands(Loc, LHS, RHS); 10432 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10433 return compType; 10434 } 10435 10436 /// Diagnose invalid arithmetic on two void pointers. 10437 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10438 Expr *LHSExpr, Expr *RHSExpr) { 10439 S.Diag(Loc, S.getLangOpts().CPlusPlus 10440 ? diag::err_typecheck_pointer_arith_void_type 10441 : diag::ext_gnu_void_ptr) 10442 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10443 << RHSExpr->getSourceRange(); 10444 } 10445 10446 /// Diagnose invalid arithmetic on a void pointer. 10447 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10448 Expr *Pointer) { 10449 S.Diag(Loc, S.getLangOpts().CPlusPlus 10450 ? diag::err_typecheck_pointer_arith_void_type 10451 : diag::ext_gnu_void_ptr) 10452 << 0 /* one pointer */ << Pointer->getSourceRange(); 10453 } 10454 10455 /// Diagnose invalid arithmetic on a null pointer. 10456 /// 10457 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10458 /// idiom, which we recognize as a GNU extension. 10459 /// 10460 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10461 Expr *Pointer, bool IsGNUIdiom) { 10462 if (IsGNUIdiom) 10463 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10464 << Pointer->getSourceRange(); 10465 else 10466 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10467 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10468 } 10469 10470 /// Diagnose invalid subraction on a null pointer. 10471 /// 10472 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10473 Expr *Pointer, bool BothNull) { 10474 // Null - null is valid in C++ [expr.add]p7 10475 if (BothNull && S.getLangOpts().CPlusPlus) 10476 return; 10477 10478 // Is this s a macro from a system header? 10479 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10480 return; 10481 10482 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10483 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10484 } 10485 10486 /// Diagnose invalid arithmetic on two function pointers. 10487 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10488 Expr *LHS, Expr *RHS) { 10489 assert(LHS->getType()->isAnyPointerType()); 10490 assert(RHS->getType()->isAnyPointerType()); 10491 S.Diag(Loc, S.getLangOpts().CPlusPlus 10492 ? diag::err_typecheck_pointer_arith_function_type 10493 : diag::ext_gnu_ptr_func_arith) 10494 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10495 // We only show the second type if it differs from the first. 10496 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10497 RHS->getType()) 10498 << RHS->getType()->getPointeeType() 10499 << LHS->getSourceRange() << RHS->getSourceRange(); 10500 } 10501 10502 /// Diagnose invalid arithmetic on a function pointer. 10503 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10504 Expr *Pointer) { 10505 assert(Pointer->getType()->isAnyPointerType()); 10506 S.Diag(Loc, S.getLangOpts().CPlusPlus 10507 ? diag::err_typecheck_pointer_arith_function_type 10508 : diag::ext_gnu_ptr_func_arith) 10509 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10510 << 0 /* one pointer, so only one type */ 10511 << Pointer->getSourceRange(); 10512 } 10513 10514 /// Emit error if Operand is incomplete pointer type 10515 /// 10516 /// \returns True if pointer has incomplete type 10517 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10518 Expr *Operand) { 10519 QualType ResType = Operand->getType(); 10520 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10521 ResType = ResAtomicType->getValueType(); 10522 10523 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10524 QualType PointeeTy = ResType->getPointeeType(); 10525 return S.RequireCompleteSizedType( 10526 Loc, PointeeTy, 10527 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10528 Operand->getSourceRange()); 10529 } 10530 10531 /// Check the validity of an arithmetic pointer operand. 10532 /// 10533 /// If the operand has pointer type, this code will check for pointer types 10534 /// which are invalid in arithmetic operations. These will be diagnosed 10535 /// appropriately, including whether or not the use is supported as an 10536 /// extension. 10537 /// 10538 /// \returns True when the operand is valid to use (even if as an extension). 10539 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10540 Expr *Operand) { 10541 QualType ResType = Operand->getType(); 10542 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10543 ResType = ResAtomicType->getValueType(); 10544 10545 if (!ResType->isAnyPointerType()) return true; 10546 10547 QualType PointeeTy = ResType->getPointeeType(); 10548 if (PointeeTy->isVoidType()) { 10549 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10550 return !S.getLangOpts().CPlusPlus; 10551 } 10552 if (PointeeTy->isFunctionType()) { 10553 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10554 return !S.getLangOpts().CPlusPlus; 10555 } 10556 10557 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10558 10559 return true; 10560 } 10561 10562 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10563 /// operands. 10564 /// 10565 /// This routine will diagnose any invalid arithmetic on pointer operands much 10566 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10567 /// for emitting a single diagnostic even for operations where both LHS and RHS 10568 /// are (potentially problematic) pointers. 10569 /// 10570 /// \returns True when the operand is valid to use (even if as an extension). 10571 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10572 Expr *LHSExpr, Expr *RHSExpr) { 10573 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10574 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10575 if (!isLHSPointer && !isRHSPointer) return true; 10576 10577 QualType LHSPointeeTy, RHSPointeeTy; 10578 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10579 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10580 10581 // if both are pointers check if operation is valid wrt address spaces 10582 if (isLHSPointer && isRHSPointer) { 10583 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10584 S.Diag(Loc, 10585 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10586 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10587 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10588 return false; 10589 } 10590 } 10591 10592 // Check for arithmetic on pointers to incomplete types. 10593 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10594 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10595 if (isLHSVoidPtr || isRHSVoidPtr) { 10596 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10597 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10598 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10599 10600 return !S.getLangOpts().CPlusPlus; 10601 } 10602 10603 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10604 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10605 if (isLHSFuncPtr || isRHSFuncPtr) { 10606 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10607 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10608 RHSExpr); 10609 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10610 10611 return !S.getLangOpts().CPlusPlus; 10612 } 10613 10614 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10615 return false; 10616 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10617 return false; 10618 10619 return true; 10620 } 10621 10622 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10623 /// literal. 10624 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10625 Expr *LHSExpr, Expr *RHSExpr) { 10626 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10627 Expr* IndexExpr = RHSExpr; 10628 if (!StrExpr) { 10629 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10630 IndexExpr = LHSExpr; 10631 } 10632 10633 bool IsStringPlusInt = StrExpr && 10634 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10635 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10636 return; 10637 10638 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10639 Self.Diag(OpLoc, diag::warn_string_plus_int) 10640 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10641 10642 // Only print a fixit for "str" + int, not for int + "str". 10643 if (IndexExpr == RHSExpr) { 10644 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10645 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10646 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10647 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10648 << FixItHint::CreateInsertion(EndLoc, "]"); 10649 } else 10650 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10651 } 10652 10653 /// Emit a warning when adding a char literal to a string. 10654 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10655 Expr *LHSExpr, Expr *RHSExpr) { 10656 const Expr *StringRefExpr = LHSExpr; 10657 const CharacterLiteral *CharExpr = 10658 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10659 10660 if (!CharExpr) { 10661 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10662 StringRefExpr = RHSExpr; 10663 } 10664 10665 if (!CharExpr || !StringRefExpr) 10666 return; 10667 10668 const QualType StringType = StringRefExpr->getType(); 10669 10670 // Return if not a PointerType. 10671 if (!StringType->isAnyPointerType()) 10672 return; 10673 10674 // Return if not a CharacterType. 10675 if (!StringType->getPointeeType()->isAnyCharacterType()) 10676 return; 10677 10678 ASTContext &Ctx = Self.getASTContext(); 10679 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10680 10681 const QualType CharType = CharExpr->getType(); 10682 if (!CharType->isAnyCharacterType() && 10683 CharType->isIntegerType() && 10684 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10685 Self.Diag(OpLoc, diag::warn_string_plus_char) 10686 << DiagRange << Ctx.CharTy; 10687 } else { 10688 Self.Diag(OpLoc, diag::warn_string_plus_char) 10689 << DiagRange << CharExpr->getType(); 10690 } 10691 10692 // Only print a fixit for str + char, not for char + str. 10693 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10694 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10695 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10696 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10697 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10698 << FixItHint::CreateInsertion(EndLoc, "]"); 10699 } else { 10700 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10701 } 10702 } 10703 10704 /// Emit error when two pointers are incompatible. 10705 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10706 Expr *LHSExpr, Expr *RHSExpr) { 10707 assert(LHSExpr->getType()->isAnyPointerType()); 10708 assert(RHSExpr->getType()->isAnyPointerType()); 10709 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10710 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10711 << RHSExpr->getSourceRange(); 10712 } 10713 10714 // C99 6.5.6 10715 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10716 SourceLocation Loc, BinaryOperatorKind Opc, 10717 QualType* CompLHSTy) { 10718 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10719 10720 if (LHS.get()->getType()->isVectorType() || 10721 RHS.get()->getType()->isVectorType()) { 10722 QualType compType = CheckVectorOperands( 10723 LHS, RHS, Loc, CompLHSTy, 10724 /*AllowBothBool*/getLangOpts().AltiVec, 10725 /*AllowBoolConversions*/getLangOpts().ZVector); 10726 if (CompLHSTy) *CompLHSTy = compType; 10727 return compType; 10728 } 10729 10730 if (LHS.get()->getType()->isConstantMatrixType() || 10731 RHS.get()->getType()->isConstantMatrixType()) { 10732 QualType compType = 10733 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10734 if (CompLHSTy) 10735 *CompLHSTy = compType; 10736 return compType; 10737 } 10738 10739 QualType compType = UsualArithmeticConversions( 10740 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10741 if (LHS.isInvalid() || RHS.isInvalid()) 10742 return QualType(); 10743 10744 // Diagnose "string literal" '+' int and string '+' "char literal". 10745 if (Opc == BO_Add) { 10746 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10747 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10748 } 10749 10750 // handle the common case first (both operands are arithmetic). 10751 if (!compType.isNull() && compType->isArithmeticType()) { 10752 if (CompLHSTy) *CompLHSTy = compType; 10753 return compType; 10754 } 10755 10756 // Type-checking. Ultimately the pointer's going to be in PExp; 10757 // note that we bias towards the LHS being the pointer. 10758 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10759 10760 bool isObjCPointer; 10761 if (PExp->getType()->isPointerType()) { 10762 isObjCPointer = false; 10763 } else if (PExp->getType()->isObjCObjectPointerType()) { 10764 isObjCPointer = true; 10765 } else { 10766 std::swap(PExp, IExp); 10767 if (PExp->getType()->isPointerType()) { 10768 isObjCPointer = false; 10769 } else if (PExp->getType()->isObjCObjectPointerType()) { 10770 isObjCPointer = true; 10771 } else { 10772 return InvalidOperands(Loc, LHS, RHS); 10773 } 10774 } 10775 assert(PExp->getType()->isAnyPointerType()); 10776 10777 if (!IExp->getType()->isIntegerType()) 10778 return InvalidOperands(Loc, LHS, RHS); 10779 10780 // Adding to a null pointer results in undefined behavior. 10781 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10782 Context, Expr::NPC_ValueDependentIsNotNull)) { 10783 // In C++ adding zero to a null pointer is defined. 10784 Expr::EvalResult KnownVal; 10785 if (!getLangOpts().CPlusPlus || 10786 (!IExp->isValueDependent() && 10787 (!IExp->EvaluateAsInt(KnownVal, Context) || 10788 KnownVal.Val.getInt() != 0))) { 10789 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10790 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10791 Context, BO_Add, PExp, IExp); 10792 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10793 } 10794 } 10795 10796 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10797 return QualType(); 10798 10799 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10800 return QualType(); 10801 10802 // Check array bounds for pointer arithemtic 10803 CheckArrayAccess(PExp, IExp); 10804 10805 if (CompLHSTy) { 10806 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10807 if (LHSTy.isNull()) { 10808 LHSTy = LHS.get()->getType(); 10809 if (LHSTy->isPromotableIntegerType()) 10810 LHSTy = Context.getPromotedIntegerType(LHSTy); 10811 } 10812 *CompLHSTy = LHSTy; 10813 } 10814 10815 return PExp->getType(); 10816 } 10817 10818 // C99 6.5.6 10819 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10820 SourceLocation Loc, 10821 QualType* CompLHSTy) { 10822 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10823 10824 if (LHS.get()->getType()->isVectorType() || 10825 RHS.get()->getType()->isVectorType()) { 10826 QualType compType = CheckVectorOperands( 10827 LHS, RHS, Loc, CompLHSTy, 10828 /*AllowBothBool*/getLangOpts().AltiVec, 10829 /*AllowBoolConversions*/getLangOpts().ZVector); 10830 if (CompLHSTy) *CompLHSTy = compType; 10831 return compType; 10832 } 10833 10834 if (LHS.get()->getType()->isConstantMatrixType() || 10835 RHS.get()->getType()->isConstantMatrixType()) { 10836 QualType compType = 10837 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10838 if (CompLHSTy) 10839 *CompLHSTy = compType; 10840 return compType; 10841 } 10842 10843 QualType compType = UsualArithmeticConversions( 10844 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10845 if (LHS.isInvalid() || RHS.isInvalid()) 10846 return QualType(); 10847 10848 // Enforce type constraints: C99 6.5.6p3. 10849 10850 // Handle the common case first (both operands are arithmetic). 10851 if (!compType.isNull() && compType->isArithmeticType()) { 10852 if (CompLHSTy) *CompLHSTy = compType; 10853 return compType; 10854 } 10855 10856 // Either ptr - int or ptr - ptr. 10857 if (LHS.get()->getType()->isAnyPointerType()) { 10858 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10859 10860 // Diagnose bad cases where we step over interface counts. 10861 if (LHS.get()->getType()->isObjCObjectPointerType() && 10862 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10863 return QualType(); 10864 10865 // The result type of a pointer-int computation is the pointer type. 10866 if (RHS.get()->getType()->isIntegerType()) { 10867 // Subtracting from a null pointer should produce a warning. 10868 // The last argument to the diagnose call says this doesn't match the 10869 // GNU int-to-pointer idiom. 10870 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10871 Expr::NPC_ValueDependentIsNotNull)) { 10872 // In C++ adding zero to a null pointer is defined. 10873 Expr::EvalResult KnownVal; 10874 if (!getLangOpts().CPlusPlus || 10875 (!RHS.get()->isValueDependent() && 10876 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10877 KnownVal.Val.getInt() != 0))) { 10878 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10879 } 10880 } 10881 10882 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10883 return QualType(); 10884 10885 // Check array bounds for pointer arithemtic 10886 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10887 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10888 10889 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10890 return LHS.get()->getType(); 10891 } 10892 10893 // Handle pointer-pointer subtractions. 10894 if (const PointerType *RHSPTy 10895 = RHS.get()->getType()->getAs<PointerType>()) { 10896 QualType rpointee = RHSPTy->getPointeeType(); 10897 10898 if (getLangOpts().CPlusPlus) { 10899 // Pointee types must be the same: C++ [expr.add] 10900 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10901 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10902 } 10903 } else { 10904 // Pointee types must be compatible C99 6.5.6p3 10905 if (!Context.typesAreCompatible( 10906 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10907 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10908 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10909 return QualType(); 10910 } 10911 } 10912 10913 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10914 LHS.get(), RHS.get())) 10915 return QualType(); 10916 10917 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10918 Context, Expr::NPC_ValueDependentIsNotNull); 10919 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10920 Context, Expr::NPC_ValueDependentIsNotNull); 10921 10922 // Subtracting nullptr or from nullptr is suspect 10923 if (LHSIsNullPtr) 10924 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10925 if (RHSIsNullPtr) 10926 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10927 10928 // The pointee type may have zero size. As an extension, a structure or 10929 // union may have zero size or an array may have zero length. In this 10930 // case subtraction does not make sense. 10931 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10932 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10933 if (ElementSize.isZero()) { 10934 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10935 << rpointee.getUnqualifiedType() 10936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10937 } 10938 } 10939 10940 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10941 return Context.getPointerDiffType(); 10942 } 10943 } 10944 10945 return InvalidOperands(Loc, LHS, RHS); 10946 } 10947 10948 static bool isScopedEnumerationType(QualType T) { 10949 if (const EnumType *ET = T->getAs<EnumType>()) 10950 return ET->getDecl()->isScoped(); 10951 return false; 10952 } 10953 10954 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10955 SourceLocation Loc, BinaryOperatorKind Opc, 10956 QualType LHSType) { 10957 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10958 // so skip remaining warnings as we don't want to modify values within Sema. 10959 if (S.getLangOpts().OpenCL) 10960 return; 10961 10962 // Check right/shifter operand 10963 Expr::EvalResult RHSResult; 10964 if (RHS.get()->isValueDependent() || 10965 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10966 return; 10967 llvm::APSInt Right = RHSResult.Val.getInt(); 10968 10969 if (Right.isNegative()) { 10970 S.DiagRuntimeBehavior(Loc, RHS.get(), 10971 S.PDiag(diag::warn_shift_negative) 10972 << RHS.get()->getSourceRange()); 10973 return; 10974 } 10975 10976 QualType LHSExprType = LHS.get()->getType(); 10977 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10978 if (LHSExprType->isBitIntType()) 10979 LeftSize = S.Context.getIntWidth(LHSExprType); 10980 else if (LHSExprType->isFixedPointType()) { 10981 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10982 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10983 } 10984 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10985 if (Right.uge(LeftBits)) { 10986 S.DiagRuntimeBehavior(Loc, RHS.get(), 10987 S.PDiag(diag::warn_shift_gt_typewidth) 10988 << RHS.get()->getSourceRange()); 10989 return; 10990 } 10991 10992 // FIXME: We probably need to handle fixed point types specially here. 10993 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10994 return; 10995 10996 // When left shifting an ICE which is signed, we can check for overflow which 10997 // according to C++ standards prior to C++2a has undefined behavior 10998 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10999 // more than the maximum value representable in the result type, so never 11000 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11001 // expression is still probably a bug.) 11002 Expr::EvalResult LHSResult; 11003 if (LHS.get()->isValueDependent() || 11004 LHSType->hasUnsignedIntegerRepresentation() || 11005 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11006 return; 11007 llvm::APSInt Left = LHSResult.Val.getInt(); 11008 11009 // If LHS does not have a signed type and non-negative value 11010 // then, the behavior is undefined before C++2a. Warn about it. 11011 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11012 !S.getLangOpts().CPlusPlus20) { 11013 S.DiagRuntimeBehavior(Loc, LHS.get(), 11014 S.PDiag(diag::warn_shift_lhs_negative) 11015 << LHS.get()->getSourceRange()); 11016 return; 11017 } 11018 11019 llvm::APInt ResultBits = 11020 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11021 if (LeftBits.uge(ResultBits)) 11022 return; 11023 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11024 Result = Result.shl(Right); 11025 11026 // Print the bit representation of the signed integer as an unsigned 11027 // hexadecimal number. 11028 SmallString<40> HexResult; 11029 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11030 11031 // If we are only missing a sign bit, this is less likely to result in actual 11032 // bugs -- if the result is cast back to an unsigned type, it will have the 11033 // expected value. Thus we place this behind a different warning that can be 11034 // turned off separately if needed. 11035 if (LeftBits == ResultBits - 1) { 11036 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11037 << HexResult << LHSType 11038 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11039 return; 11040 } 11041 11042 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11043 << HexResult.str() << Result.getMinSignedBits() << LHSType 11044 << Left.getBitWidth() << LHS.get()->getSourceRange() 11045 << RHS.get()->getSourceRange(); 11046 } 11047 11048 /// Return the resulting type when a vector is shifted 11049 /// by a scalar or vector shift amount. 11050 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11051 SourceLocation Loc, bool IsCompAssign) { 11052 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11053 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11054 !LHS.get()->getType()->isVectorType()) { 11055 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11056 << RHS.get()->getType() << LHS.get()->getType() 11057 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11058 return QualType(); 11059 } 11060 11061 if (!IsCompAssign) { 11062 LHS = S.UsualUnaryConversions(LHS.get()); 11063 if (LHS.isInvalid()) return QualType(); 11064 } 11065 11066 RHS = S.UsualUnaryConversions(RHS.get()); 11067 if (RHS.isInvalid()) return QualType(); 11068 11069 QualType LHSType = LHS.get()->getType(); 11070 // Note that LHS might be a scalar because the routine calls not only in 11071 // OpenCL case. 11072 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11073 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11074 11075 // Note that RHS might not be a vector. 11076 QualType RHSType = RHS.get()->getType(); 11077 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11078 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11079 11080 // The operands need to be integers. 11081 if (!LHSEleType->isIntegerType()) { 11082 S.Diag(Loc, diag::err_typecheck_expect_int) 11083 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11084 return QualType(); 11085 } 11086 11087 if (!RHSEleType->isIntegerType()) { 11088 S.Diag(Loc, diag::err_typecheck_expect_int) 11089 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11090 return QualType(); 11091 } 11092 11093 if (!LHSVecTy) { 11094 assert(RHSVecTy); 11095 if (IsCompAssign) 11096 return RHSType; 11097 if (LHSEleType != RHSEleType) { 11098 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11099 LHSEleType = RHSEleType; 11100 } 11101 QualType VecTy = 11102 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11103 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11104 LHSType = VecTy; 11105 } else if (RHSVecTy) { 11106 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11107 // are applied component-wise. So if RHS is a vector, then ensure 11108 // that the number of elements is the same as LHS... 11109 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11110 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11111 << LHS.get()->getType() << RHS.get()->getType() 11112 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11113 return QualType(); 11114 } 11115 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11116 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11117 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11118 if (LHSBT != RHSBT && 11119 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11120 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11121 << LHS.get()->getType() << RHS.get()->getType() 11122 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11123 } 11124 } 11125 } else { 11126 // ...else expand RHS to match the number of elements in LHS. 11127 QualType VecTy = 11128 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11129 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11130 } 11131 11132 return LHSType; 11133 } 11134 11135 // C99 6.5.7 11136 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11137 SourceLocation Loc, BinaryOperatorKind Opc, 11138 bool IsCompAssign) { 11139 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11140 11141 // Vector shifts promote their scalar inputs to vector type. 11142 if (LHS.get()->getType()->isVectorType() || 11143 RHS.get()->getType()->isVectorType()) { 11144 if (LangOpts.ZVector) { 11145 // The shift operators for the z vector extensions work basically 11146 // like general shifts, except that neither the LHS nor the RHS is 11147 // allowed to be a "vector bool". 11148 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11149 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11150 return InvalidOperands(Loc, LHS, RHS); 11151 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11152 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11153 return InvalidOperands(Loc, LHS, RHS); 11154 } 11155 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11156 } 11157 11158 // Shifts don't perform usual arithmetic conversions, they just do integer 11159 // promotions on each operand. C99 6.5.7p3 11160 11161 // For the LHS, do usual unary conversions, but then reset them away 11162 // if this is a compound assignment. 11163 ExprResult OldLHS = LHS; 11164 LHS = UsualUnaryConversions(LHS.get()); 11165 if (LHS.isInvalid()) 11166 return QualType(); 11167 QualType LHSType = LHS.get()->getType(); 11168 if (IsCompAssign) LHS = OldLHS; 11169 11170 // The RHS is simpler. 11171 RHS = UsualUnaryConversions(RHS.get()); 11172 if (RHS.isInvalid()) 11173 return QualType(); 11174 QualType RHSType = RHS.get()->getType(); 11175 11176 // C99 6.5.7p2: Each of the operands shall have integer type. 11177 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11178 if ((!LHSType->isFixedPointOrIntegerType() && 11179 !LHSType->hasIntegerRepresentation()) || 11180 !RHSType->hasIntegerRepresentation()) 11181 return InvalidOperands(Loc, LHS, RHS); 11182 11183 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11184 // hasIntegerRepresentation() above instead of this. 11185 if (isScopedEnumerationType(LHSType) || 11186 isScopedEnumerationType(RHSType)) { 11187 return InvalidOperands(Loc, LHS, RHS); 11188 } 11189 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11190 11191 // "The type of the result is that of the promoted left operand." 11192 return LHSType; 11193 } 11194 11195 /// Diagnose bad pointer comparisons. 11196 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11197 ExprResult &LHS, ExprResult &RHS, 11198 bool IsError) { 11199 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11200 : diag::ext_typecheck_comparison_of_distinct_pointers) 11201 << LHS.get()->getType() << RHS.get()->getType() 11202 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11203 } 11204 11205 /// Returns false if the pointers are converted to a composite type, 11206 /// true otherwise. 11207 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11208 ExprResult &LHS, ExprResult &RHS) { 11209 // C++ [expr.rel]p2: 11210 // [...] Pointer conversions (4.10) and qualification 11211 // conversions (4.4) are performed on pointer operands (or on 11212 // a pointer operand and a null pointer constant) to bring 11213 // them to their composite pointer type. [...] 11214 // 11215 // C++ [expr.eq]p1 uses the same notion for (in)equality 11216 // comparisons of pointers. 11217 11218 QualType LHSType = LHS.get()->getType(); 11219 QualType RHSType = RHS.get()->getType(); 11220 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11221 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11222 11223 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11224 if (T.isNull()) { 11225 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11226 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11227 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11228 else 11229 S.InvalidOperands(Loc, LHS, RHS); 11230 return true; 11231 } 11232 11233 return false; 11234 } 11235 11236 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11237 ExprResult &LHS, 11238 ExprResult &RHS, 11239 bool IsError) { 11240 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11241 : diag::ext_typecheck_comparison_of_fptr_to_void) 11242 << LHS.get()->getType() << RHS.get()->getType() 11243 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11244 } 11245 11246 static bool isObjCObjectLiteral(ExprResult &E) { 11247 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11248 case Stmt::ObjCArrayLiteralClass: 11249 case Stmt::ObjCDictionaryLiteralClass: 11250 case Stmt::ObjCStringLiteralClass: 11251 case Stmt::ObjCBoxedExprClass: 11252 return true; 11253 default: 11254 // Note that ObjCBoolLiteral is NOT an object literal! 11255 return false; 11256 } 11257 } 11258 11259 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11260 const ObjCObjectPointerType *Type = 11261 LHS->getType()->getAs<ObjCObjectPointerType>(); 11262 11263 // If this is not actually an Objective-C object, bail out. 11264 if (!Type) 11265 return false; 11266 11267 // Get the LHS object's interface type. 11268 QualType InterfaceType = Type->getPointeeType(); 11269 11270 // If the RHS isn't an Objective-C object, bail out. 11271 if (!RHS->getType()->isObjCObjectPointerType()) 11272 return false; 11273 11274 // Try to find the -isEqual: method. 11275 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11276 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11277 InterfaceType, 11278 /*IsInstance=*/true); 11279 if (!Method) { 11280 if (Type->isObjCIdType()) { 11281 // For 'id', just check the global pool. 11282 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11283 /*receiverId=*/true); 11284 } else { 11285 // Check protocols. 11286 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11287 /*IsInstance=*/true); 11288 } 11289 } 11290 11291 if (!Method) 11292 return false; 11293 11294 QualType T = Method->parameters()[0]->getType(); 11295 if (!T->isObjCObjectPointerType()) 11296 return false; 11297 11298 QualType R = Method->getReturnType(); 11299 if (!R->isScalarType()) 11300 return false; 11301 11302 return true; 11303 } 11304 11305 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11306 FromE = FromE->IgnoreParenImpCasts(); 11307 switch (FromE->getStmtClass()) { 11308 default: 11309 break; 11310 case Stmt::ObjCStringLiteralClass: 11311 // "string literal" 11312 return LK_String; 11313 case Stmt::ObjCArrayLiteralClass: 11314 // "array literal" 11315 return LK_Array; 11316 case Stmt::ObjCDictionaryLiteralClass: 11317 // "dictionary literal" 11318 return LK_Dictionary; 11319 case Stmt::BlockExprClass: 11320 return LK_Block; 11321 case Stmt::ObjCBoxedExprClass: { 11322 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11323 switch (Inner->getStmtClass()) { 11324 case Stmt::IntegerLiteralClass: 11325 case Stmt::FloatingLiteralClass: 11326 case Stmt::CharacterLiteralClass: 11327 case Stmt::ObjCBoolLiteralExprClass: 11328 case Stmt::CXXBoolLiteralExprClass: 11329 // "numeric literal" 11330 return LK_Numeric; 11331 case Stmt::ImplicitCastExprClass: { 11332 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11333 // Boolean literals can be represented by implicit casts. 11334 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11335 return LK_Numeric; 11336 break; 11337 } 11338 default: 11339 break; 11340 } 11341 return LK_Boxed; 11342 } 11343 } 11344 return LK_None; 11345 } 11346 11347 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11348 ExprResult &LHS, ExprResult &RHS, 11349 BinaryOperator::Opcode Opc){ 11350 Expr *Literal; 11351 Expr *Other; 11352 if (isObjCObjectLiteral(LHS)) { 11353 Literal = LHS.get(); 11354 Other = RHS.get(); 11355 } else { 11356 Literal = RHS.get(); 11357 Other = LHS.get(); 11358 } 11359 11360 // Don't warn on comparisons against nil. 11361 Other = Other->IgnoreParenCasts(); 11362 if (Other->isNullPointerConstant(S.getASTContext(), 11363 Expr::NPC_ValueDependentIsNotNull)) 11364 return; 11365 11366 // This should be kept in sync with warn_objc_literal_comparison. 11367 // LK_String should always be after the other literals, since it has its own 11368 // warning flag. 11369 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11370 assert(LiteralKind != Sema::LK_Block); 11371 if (LiteralKind == Sema::LK_None) { 11372 llvm_unreachable("Unknown Objective-C object literal kind"); 11373 } 11374 11375 if (LiteralKind == Sema::LK_String) 11376 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11377 << Literal->getSourceRange(); 11378 else 11379 S.Diag(Loc, diag::warn_objc_literal_comparison) 11380 << LiteralKind << Literal->getSourceRange(); 11381 11382 if (BinaryOperator::isEqualityOp(Opc) && 11383 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11384 SourceLocation Start = LHS.get()->getBeginLoc(); 11385 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11386 CharSourceRange OpRange = 11387 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11388 11389 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11390 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11391 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11392 << FixItHint::CreateInsertion(End, "]"); 11393 } 11394 } 11395 11396 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11397 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11398 ExprResult &RHS, SourceLocation Loc, 11399 BinaryOperatorKind Opc) { 11400 // Check that left hand side is !something. 11401 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11402 if (!UO || UO->getOpcode() != UO_LNot) return; 11403 11404 // Only check if the right hand side is non-bool arithmetic type. 11405 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11406 11407 // Make sure that the something in !something is not bool. 11408 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11409 if (SubExpr->isKnownToHaveBooleanValue()) return; 11410 11411 // Emit warning. 11412 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11413 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11414 << Loc << IsBitwiseOp; 11415 11416 // First note suggest !(x < y) 11417 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11418 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11419 FirstClose = S.getLocForEndOfToken(FirstClose); 11420 if (FirstClose.isInvalid()) 11421 FirstOpen = SourceLocation(); 11422 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11423 << IsBitwiseOp 11424 << FixItHint::CreateInsertion(FirstOpen, "(") 11425 << FixItHint::CreateInsertion(FirstClose, ")"); 11426 11427 // Second note suggests (!x) < y 11428 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11429 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11430 SecondClose = S.getLocForEndOfToken(SecondClose); 11431 if (SecondClose.isInvalid()) 11432 SecondOpen = SourceLocation(); 11433 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11434 << FixItHint::CreateInsertion(SecondOpen, "(") 11435 << FixItHint::CreateInsertion(SecondClose, ")"); 11436 } 11437 11438 // Returns true if E refers to a non-weak array. 11439 static bool checkForArray(const Expr *E) { 11440 const ValueDecl *D = nullptr; 11441 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11442 D = DR->getDecl(); 11443 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11444 if (Mem->isImplicitAccess()) 11445 D = Mem->getMemberDecl(); 11446 } 11447 if (!D) 11448 return false; 11449 return D->getType()->isArrayType() && !D->isWeak(); 11450 } 11451 11452 /// Diagnose some forms of syntactically-obvious tautological comparison. 11453 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11454 Expr *LHS, Expr *RHS, 11455 BinaryOperatorKind Opc) { 11456 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11457 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11458 11459 QualType LHSType = LHS->getType(); 11460 QualType RHSType = RHS->getType(); 11461 if (LHSType->hasFloatingRepresentation() || 11462 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11463 S.inTemplateInstantiation()) 11464 return; 11465 11466 // Comparisons between two array types are ill-formed for operator<=>, so 11467 // we shouldn't emit any additional warnings about it. 11468 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11469 return; 11470 11471 // For non-floating point types, check for self-comparisons of the form 11472 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11473 // often indicate logic errors in the program. 11474 // 11475 // NOTE: Don't warn about comparison expressions resulting from macro 11476 // expansion. Also don't warn about comparisons which are only self 11477 // comparisons within a template instantiation. The warnings should catch 11478 // obvious cases in the definition of the template anyways. The idea is to 11479 // warn when the typed comparison operator will always evaluate to the same 11480 // result. 11481 11482 // Used for indexing into %select in warn_comparison_always 11483 enum { 11484 AlwaysConstant, 11485 AlwaysTrue, 11486 AlwaysFalse, 11487 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11488 }; 11489 11490 // C++2a [depr.array.comp]: 11491 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11492 // operands of array type are deprecated. 11493 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11494 RHSStripped->getType()->isArrayType()) { 11495 S.Diag(Loc, diag::warn_depr_array_comparison) 11496 << LHS->getSourceRange() << RHS->getSourceRange() 11497 << LHSStripped->getType() << RHSStripped->getType(); 11498 // Carry on to produce the tautological comparison warning, if this 11499 // expression is potentially-evaluated, we can resolve the array to a 11500 // non-weak declaration, and so on. 11501 } 11502 11503 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11504 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11505 unsigned Result; 11506 switch (Opc) { 11507 case BO_EQ: 11508 case BO_LE: 11509 case BO_GE: 11510 Result = AlwaysTrue; 11511 break; 11512 case BO_NE: 11513 case BO_LT: 11514 case BO_GT: 11515 Result = AlwaysFalse; 11516 break; 11517 case BO_Cmp: 11518 Result = AlwaysEqual; 11519 break; 11520 default: 11521 Result = AlwaysConstant; 11522 break; 11523 } 11524 S.DiagRuntimeBehavior(Loc, nullptr, 11525 S.PDiag(diag::warn_comparison_always) 11526 << 0 /*self-comparison*/ 11527 << Result); 11528 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11529 // What is it always going to evaluate to? 11530 unsigned Result; 11531 switch (Opc) { 11532 case BO_EQ: // e.g. array1 == array2 11533 Result = AlwaysFalse; 11534 break; 11535 case BO_NE: // e.g. array1 != array2 11536 Result = AlwaysTrue; 11537 break; 11538 default: // e.g. array1 <= array2 11539 // The best we can say is 'a constant' 11540 Result = AlwaysConstant; 11541 break; 11542 } 11543 S.DiagRuntimeBehavior(Loc, nullptr, 11544 S.PDiag(diag::warn_comparison_always) 11545 << 1 /*array comparison*/ 11546 << Result); 11547 } 11548 } 11549 11550 if (isa<CastExpr>(LHSStripped)) 11551 LHSStripped = LHSStripped->IgnoreParenCasts(); 11552 if (isa<CastExpr>(RHSStripped)) 11553 RHSStripped = RHSStripped->IgnoreParenCasts(); 11554 11555 // Warn about comparisons against a string constant (unless the other 11556 // operand is null); the user probably wants string comparison function. 11557 Expr *LiteralString = nullptr; 11558 Expr *LiteralStringStripped = nullptr; 11559 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11560 !RHSStripped->isNullPointerConstant(S.Context, 11561 Expr::NPC_ValueDependentIsNull)) { 11562 LiteralString = LHS; 11563 LiteralStringStripped = LHSStripped; 11564 } else if ((isa<StringLiteral>(RHSStripped) || 11565 isa<ObjCEncodeExpr>(RHSStripped)) && 11566 !LHSStripped->isNullPointerConstant(S.Context, 11567 Expr::NPC_ValueDependentIsNull)) { 11568 LiteralString = RHS; 11569 LiteralStringStripped = RHSStripped; 11570 } 11571 11572 if (LiteralString) { 11573 S.DiagRuntimeBehavior(Loc, nullptr, 11574 S.PDiag(diag::warn_stringcompare) 11575 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11576 << LiteralString->getSourceRange()); 11577 } 11578 } 11579 11580 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11581 switch (CK) { 11582 default: { 11583 #ifndef NDEBUG 11584 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11585 << "\n"; 11586 #endif 11587 llvm_unreachable("unhandled cast kind"); 11588 } 11589 case CK_UserDefinedConversion: 11590 return ICK_Identity; 11591 case CK_LValueToRValue: 11592 return ICK_Lvalue_To_Rvalue; 11593 case CK_ArrayToPointerDecay: 11594 return ICK_Array_To_Pointer; 11595 case CK_FunctionToPointerDecay: 11596 return ICK_Function_To_Pointer; 11597 case CK_IntegralCast: 11598 return ICK_Integral_Conversion; 11599 case CK_FloatingCast: 11600 return ICK_Floating_Conversion; 11601 case CK_IntegralToFloating: 11602 case CK_FloatingToIntegral: 11603 return ICK_Floating_Integral; 11604 case CK_IntegralComplexCast: 11605 case CK_FloatingComplexCast: 11606 case CK_FloatingComplexToIntegralComplex: 11607 case CK_IntegralComplexToFloatingComplex: 11608 return ICK_Complex_Conversion; 11609 case CK_FloatingComplexToReal: 11610 case CK_FloatingRealToComplex: 11611 case CK_IntegralComplexToReal: 11612 case CK_IntegralRealToComplex: 11613 return ICK_Complex_Real; 11614 } 11615 } 11616 11617 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11618 QualType FromType, 11619 SourceLocation Loc) { 11620 // Check for a narrowing implicit conversion. 11621 StandardConversionSequence SCS; 11622 SCS.setAsIdentityConversion(); 11623 SCS.setToType(0, FromType); 11624 SCS.setToType(1, ToType); 11625 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11626 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11627 11628 APValue PreNarrowingValue; 11629 QualType PreNarrowingType; 11630 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11631 PreNarrowingType, 11632 /*IgnoreFloatToIntegralConversion*/ true)) { 11633 case NK_Dependent_Narrowing: 11634 // Implicit conversion to a narrower type, but the expression is 11635 // value-dependent so we can't tell whether it's actually narrowing. 11636 case NK_Not_Narrowing: 11637 return false; 11638 11639 case NK_Constant_Narrowing: 11640 // Implicit conversion to a narrower type, and the value is not a constant 11641 // expression. 11642 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11643 << /*Constant*/ 1 11644 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11645 return true; 11646 11647 case NK_Variable_Narrowing: 11648 // Implicit conversion to a narrower type, and the value is not a constant 11649 // expression. 11650 case NK_Type_Narrowing: 11651 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11652 << /*Constant*/ 0 << FromType << ToType; 11653 // TODO: It's not a constant expression, but what if the user intended it 11654 // to be? Can we produce notes to help them figure out why it isn't? 11655 return true; 11656 } 11657 llvm_unreachable("unhandled case in switch"); 11658 } 11659 11660 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11661 ExprResult &LHS, 11662 ExprResult &RHS, 11663 SourceLocation Loc) { 11664 QualType LHSType = LHS.get()->getType(); 11665 QualType RHSType = RHS.get()->getType(); 11666 // Dig out the original argument type and expression before implicit casts 11667 // were applied. These are the types/expressions we need to check the 11668 // [expr.spaceship] requirements against. 11669 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11670 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11671 QualType LHSStrippedType = LHSStripped.get()->getType(); 11672 QualType RHSStrippedType = RHSStripped.get()->getType(); 11673 11674 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11675 // other is not, the program is ill-formed. 11676 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11677 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11678 return QualType(); 11679 } 11680 11681 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11682 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11683 RHSStrippedType->isEnumeralType(); 11684 if (NumEnumArgs == 1) { 11685 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11686 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11687 if (OtherTy->hasFloatingRepresentation()) { 11688 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11689 return QualType(); 11690 } 11691 } 11692 if (NumEnumArgs == 2) { 11693 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11694 // type E, the operator yields the result of converting the operands 11695 // to the underlying type of E and applying <=> to the converted operands. 11696 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11697 S.InvalidOperands(Loc, LHS, RHS); 11698 return QualType(); 11699 } 11700 QualType IntType = 11701 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11702 assert(IntType->isArithmeticType()); 11703 11704 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11705 // promote the boolean type, and all other promotable integer types, to 11706 // avoid this. 11707 if (IntType->isPromotableIntegerType()) 11708 IntType = S.Context.getPromotedIntegerType(IntType); 11709 11710 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11711 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11712 LHSType = RHSType = IntType; 11713 } 11714 11715 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11716 // usual arithmetic conversions are applied to the operands. 11717 QualType Type = 11718 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11719 if (LHS.isInvalid() || RHS.isInvalid()) 11720 return QualType(); 11721 if (Type.isNull()) 11722 return S.InvalidOperands(Loc, LHS, RHS); 11723 11724 Optional<ComparisonCategoryType> CCT = 11725 getComparisonCategoryForBuiltinCmp(Type); 11726 if (!CCT) 11727 return S.InvalidOperands(Loc, LHS, RHS); 11728 11729 bool HasNarrowing = checkThreeWayNarrowingConversion( 11730 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11731 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11732 RHS.get()->getBeginLoc()); 11733 if (HasNarrowing) 11734 return QualType(); 11735 11736 assert(!Type.isNull() && "composite type for <=> has not been set"); 11737 11738 return S.CheckComparisonCategoryType( 11739 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11740 } 11741 11742 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11743 ExprResult &RHS, 11744 SourceLocation Loc, 11745 BinaryOperatorKind Opc) { 11746 if (Opc == BO_Cmp) 11747 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11748 11749 // C99 6.5.8p3 / C99 6.5.9p4 11750 QualType Type = 11751 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11752 if (LHS.isInvalid() || RHS.isInvalid()) 11753 return QualType(); 11754 if (Type.isNull()) 11755 return S.InvalidOperands(Loc, LHS, RHS); 11756 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11757 11758 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11759 return S.InvalidOperands(Loc, LHS, RHS); 11760 11761 // Check for comparisons of floating point operands using != and ==. 11762 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11763 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11764 11765 // The result of comparisons is 'bool' in C++, 'int' in C. 11766 return S.Context.getLogicalOperationType(); 11767 } 11768 11769 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11770 if (!NullE.get()->getType()->isAnyPointerType()) 11771 return; 11772 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11773 if (!E.get()->getType()->isAnyPointerType() && 11774 E.get()->isNullPointerConstant(Context, 11775 Expr::NPC_ValueDependentIsNotNull) == 11776 Expr::NPCK_ZeroExpression) { 11777 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11778 if (CL->getValue() == 0) 11779 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11780 << NullValue 11781 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11782 NullValue ? "NULL" : "(void *)0"); 11783 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11784 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11785 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11786 if (T == Context.CharTy) 11787 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11788 << NullValue 11789 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11790 NullValue ? "NULL" : "(void *)0"); 11791 } 11792 } 11793 } 11794 11795 // C99 6.5.8, C++ [expr.rel] 11796 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11797 SourceLocation Loc, 11798 BinaryOperatorKind Opc) { 11799 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11800 bool IsThreeWay = Opc == BO_Cmp; 11801 bool IsOrdered = IsRelational || IsThreeWay; 11802 auto IsAnyPointerType = [](ExprResult E) { 11803 QualType Ty = E.get()->getType(); 11804 return Ty->isPointerType() || Ty->isMemberPointerType(); 11805 }; 11806 11807 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11808 // type, array-to-pointer, ..., conversions are performed on both operands to 11809 // bring them to their composite type. 11810 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11811 // any type-related checks. 11812 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11813 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11814 if (LHS.isInvalid()) 11815 return QualType(); 11816 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11817 if (RHS.isInvalid()) 11818 return QualType(); 11819 } else { 11820 LHS = DefaultLvalueConversion(LHS.get()); 11821 if (LHS.isInvalid()) 11822 return QualType(); 11823 RHS = DefaultLvalueConversion(RHS.get()); 11824 if (RHS.isInvalid()) 11825 return QualType(); 11826 } 11827 11828 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11829 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11830 CheckPtrComparisonWithNullChar(LHS, RHS); 11831 CheckPtrComparisonWithNullChar(RHS, LHS); 11832 } 11833 11834 // Handle vector comparisons separately. 11835 if (LHS.get()->getType()->isVectorType() || 11836 RHS.get()->getType()->isVectorType()) 11837 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11838 11839 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11840 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11841 11842 QualType LHSType = LHS.get()->getType(); 11843 QualType RHSType = RHS.get()->getType(); 11844 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11845 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11846 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11847 11848 const Expr::NullPointerConstantKind LHSNullKind = 11849 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11850 const Expr::NullPointerConstantKind RHSNullKind = 11851 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11852 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11853 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11854 11855 auto computeResultTy = [&]() { 11856 if (Opc != BO_Cmp) 11857 return Context.getLogicalOperationType(); 11858 assert(getLangOpts().CPlusPlus); 11859 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11860 11861 QualType CompositeTy = LHS.get()->getType(); 11862 assert(!CompositeTy->isReferenceType()); 11863 11864 Optional<ComparisonCategoryType> CCT = 11865 getComparisonCategoryForBuiltinCmp(CompositeTy); 11866 if (!CCT) 11867 return InvalidOperands(Loc, LHS, RHS); 11868 11869 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11870 // P0946R0: Comparisons between a null pointer constant and an object 11871 // pointer result in std::strong_equality, which is ill-formed under 11872 // P1959R0. 11873 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11874 << (LHSIsNull ? LHS.get()->getSourceRange() 11875 : RHS.get()->getSourceRange()); 11876 return QualType(); 11877 } 11878 11879 return CheckComparisonCategoryType( 11880 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11881 }; 11882 11883 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11884 bool IsEquality = Opc == BO_EQ; 11885 if (RHSIsNull) 11886 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11887 RHS.get()->getSourceRange()); 11888 else 11889 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11890 LHS.get()->getSourceRange()); 11891 } 11892 11893 if (IsOrdered && LHSType->isFunctionPointerType() && 11894 RHSType->isFunctionPointerType()) { 11895 // Valid unless a relational comparison of function pointers 11896 bool IsError = Opc == BO_Cmp; 11897 auto DiagID = 11898 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11899 : getLangOpts().CPlusPlus 11900 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11901 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11902 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11903 << RHS.get()->getSourceRange(); 11904 if (IsError) 11905 return QualType(); 11906 } 11907 11908 if ((LHSType->isIntegerType() && !LHSIsNull) || 11909 (RHSType->isIntegerType() && !RHSIsNull)) { 11910 // Skip normal pointer conversion checks in this case; we have better 11911 // diagnostics for this below. 11912 } else if (getLangOpts().CPlusPlus) { 11913 // Equality comparison of a function pointer to a void pointer is invalid, 11914 // but we allow it as an extension. 11915 // FIXME: If we really want to allow this, should it be part of composite 11916 // pointer type computation so it works in conditionals too? 11917 if (!IsOrdered && 11918 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11919 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11920 // This is a gcc extension compatibility comparison. 11921 // In a SFINAE context, we treat this as a hard error to maintain 11922 // conformance with the C++ standard. 11923 diagnoseFunctionPointerToVoidComparison( 11924 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11925 11926 if (isSFINAEContext()) 11927 return QualType(); 11928 11929 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11930 return computeResultTy(); 11931 } 11932 11933 // C++ [expr.eq]p2: 11934 // If at least one operand is a pointer [...] bring them to their 11935 // composite pointer type. 11936 // C++ [expr.spaceship]p6 11937 // If at least one of the operands is of pointer type, [...] bring them 11938 // to their composite pointer type. 11939 // C++ [expr.rel]p2: 11940 // If both operands are pointers, [...] bring them to their composite 11941 // pointer type. 11942 // For <=>, the only valid non-pointer types are arrays and functions, and 11943 // we already decayed those, so this is really the same as the relational 11944 // comparison rule. 11945 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11946 (IsOrdered ? 2 : 1) && 11947 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11948 RHSType->isObjCObjectPointerType()))) { 11949 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11950 return QualType(); 11951 return computeResultTy(); 11952 } 11953 } else if (LHSType->isPointerType() && 11954 RHSType->isPointerType()) { // C99 6.5.8p2 11955 // All of the following pointer-related warnings are GCC extensions, except 11956 // when handling null pointer constants. 11957 QualType LCanPointeeTy = 11958 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11959 QualType RCanPointeeTy = 11960 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11961 11962 // C99 6.5.9p2 and C99 6.5.8p2 11963 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11964 RCanPointeeTy.getUnqualifiedType())) { 11965 if (IsRelational) { 11966 // Pointers both need to point to complete or incomplete types 11967 if ((LCanPointeeTy->isIncompleteType() != 11968 RCanPointeeTy->isIncompleteType()) && 11969 !getLangOpts().C11) { 11970 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11971 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11972 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11973 << RCanPointeeTy->isIncompleteType(); 11974 } 11975 } 11976 } else if (!IsRelational && 11977 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11978 // Valid unless comparison between non-null pointer and function pointer 11979 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11980 && !LHSIsNull && !RHSIsNull) 11981 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11982 /*isError*/false); 11983 } else { 11984 // Invalid 11985 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11986 } 11987 if (LCanPointeeTy != RCanPointeeTy) { 11988 // Treat NULL constant as a special case in OpenCL. 11989 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11990 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11991 Diag(Loc, 11992 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11993 << LHSType << RHSType << 0 /* comparison */ 11994 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11995 } 11996 } 11997 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11998 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11999 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12000 : CK_BitCast; 12001 if (LHSIsNull && !RHSIsNull) 12002 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12003 else 12004 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12005 } 12006 return computeResultTy(); 12007 } 12008 12009 if (getLangOpts().CPlusPlus) { 12010 // C++ [expr.eq]p4: 12011 // Two operands of type std::nullptr_t or one operand of type 12012 // std::nullptr_t and the other a null pointer constant compare equal. 12013 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12014 if (LHSType->isNullPtrType()) { 12015 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12016 return computeResultTy(); 12017 } 12018 if (RHSType->isNullPtrType()) { 12019 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12020 return computeResultTy(); 12021 } 12022 } 12023 12024 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12025 // These aren't covered by the composite pointer type rules. 12026 if (!IsOrdered && RHSType->isNullPtrType() && 12027 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12028 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12029 return computeResultTy(); 12030 } 12031 if (!IsOrdered && LHSType->isNullPtrType() && 12032 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12033 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12034 return computeResultTy(); 12035 } 12036 12037 if (IsRelational && 12038 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12039 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12040 // HACK: Relational comparison of nullptr_t against a pointer type is 12041 // invalid per DR583, but we allow it within std::less<> and friends, 12042 // since otherwise common uses of it break. 12043 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12044 // friends to have std::nullptr_t overload candidates. 12045 DeclContext *DC = CurContext; 12046 if (isa<FunctionDecl>(DC)) 12047 DC = DC->getParent(); 12048 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12049 if (CTSD->isInStdNamespace() && 12050 llvm::StringSwitch<bool>(CTSD->getName()) 12051 .Cases("less", "less_equal", "greater", "greater_equal", true) 12052 .Default(false)) { 12053 if (RHSType->isNullPtrType()) 12054 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12055 else 12056 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12057 return computeResultTy(); 12058 } 12059 } 12060 } 12061 12062 // C++ [expr.eq]p2: 12063 // If at least one operand is a pointer to member, [...] bring them to 12064 // their composite pointer type. 12065 if (!IsOrdered && 12066 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12067 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12068 return QualType(); 12069 else 12070 return computeResultTy(); 12071 } 12072 } 12073 12074 // Handle block pointer types. 12075 if (!IsOrdered && LHSType->isBlockPointerType() && 12076 RHSType->isBlockPointerType()) { 12077 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12078 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12079 12080 if (!LHSIsNull && !RHSIsNull && 12081 !Context.typesAreCompatible(lpointee, rpointee)) { 12082 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12083 << LHSType << RHSType << LHS.get()->getSourceRange() 12084 << RHS.get()->getSourceRange(); 12085 } 12086 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12087 return computeResultTy(); 12088 } 12089 12090 // Allow block pointers to be compared with null pointer constants. 12091 if (!IsOrdered 12092 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12093 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12094 if (!LHSIsNull && !RHSIsNull) { 12095 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12096 ->getPointeeType()->isVoidType()) 12097 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12098 ->getPointeeType()->isVoidType()))) 12099 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12100 << LHSType << RHSType << LHS.get()->getSourceRange() 12101 << RHS.get()->getSourceRange(); 12102 } 12103 if (LHSIsNull && !RHSIsNull) 12104 LHS = ImpCastExprToType(LHS.get(), RHSType, 12105 RHSType->isPointerType() ? CK_BitCast 12106 : CK_AnyPointerToBlockPointerCast); 12107 else 12108 RHS = ImpCastExprToType(RHS.get(), LHSType, 12109 LHSType->isPointerType() ? CK_BitCast 12110 : CK_AnyPointerToBlockPointerCast); 12111 return computeResultTy(); 12112 } 12113 12114 if (LHSType->isObjCObjectPointerType() || 12115 RHSType->isObjCObjectPointerType()) { 12116 const PointerType *LPT = LHSType->getAs<PointerType>(); 12117 const PointerType *RPT = RHSType->getAs<PointerType>(); 12118 if (LPT || RPT) { 12119 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12120 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12121 12122 if (!LPtrToVoid && !RPtrToVoid && 12123 !Context.typesAreCompatible(LHSType, RHSType)) { 12124 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12125 /*isError*/false); 12126 } 12127 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12128 // the RHS, but we have test coverage for this behavior. 12129 // FIXME: Consider using convertPointersToCompositeType in C++. 12130 if (LHSIsNull && !RHSIsNull) { 12131 Expr *E = LHS.get(); 12132 if (getLangOpts().ObjCAutoRefCount) 12133 CheckObjCConversion(SourceRange(), RHSType, E, 12134 CCK_ImplicitConversion); 12135 LHS = ImpCastExprToType(E, RHSType, 12136 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12137 } 12138 else { 12139 Expr *E = RHS.get(); 12140 if (getLangOpts().ObjCAutoRefCount) 12141 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12142 /*Diagnose=*/true, 12143 /*DiagnoseCFAudited=*/false, Opc); 12144 RHS = ImpCastExprToType(E, LHSType, 12145 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12146 } 12147 return computeResultTy(); 12148 } 12149 if (LHSType->isObjCObjectPointerType() && 12150 RHSType->isObjCObjectPointerType()) { 12151 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12152 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12153 /*isError*/false); 12154 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12155 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12156 12157 if (LHSIsNull && !RHSIsNull) 12158 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12159 else 12160 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12161 return computeResultTy(); 12162 } 12163 12164 if (!IsOrdered && LHSType->isBlockPointerType() && 12165 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12166 LHS = ImpCastExprToType(LHS.get(), RHSType, 12167 CK_BlockPointerToObjCPointerCast); 12168 return computeResultTy(); 12169 } else if (!IsOrdered && 12170 LHSType->isBlockCompatibleObjCPointerType(Context) && 12171 RHSType->isBlockPointerType()) { 12172 RHS = ImpCastExprToType(RHS.get(), LHSType, 12173 CK_BlockPointerToObjCPointerCast); 12174 return computeResultTy(); 12175 } 12176 } 12177 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12178 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12179 unsigned DiagID = 0; 12180 bool isError = false; 12181 if (LangOpts.DebuggerSupport) { 12182 // Under a debugger, allow the comparison of pointers to integers, 12183 // since users tend to want to compare addresses. 12184 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12185 (RHSIsNull && RHSType->isIntegerType())) { 12186 if (IsOrdered) { 12187 isError = getLangOpts().CPlusPlus; 12188 DiagID = 12189 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12190 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12191 } 12192 } else if (getLangOpts().CPlusPlus) { 12193 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12194 isError = true; 12195 } else if (IsOrdered) 12196 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12197 else 12198 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12199 12200 if (DiagID) { 12201 Diag(Loc, DiagID) 12202 << LHSType << RHSType << LHS.get()->getSourceRange() 12203 << RHS.get()->getSourceRange(); 12204 if (isError) 12205 return QualType(); 12206 } 12207 12208 if (LHSType->isIntegerType()) 12209 LHS = ImpCastExprToType(LHS.get(), RHSType, 12210 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12211 else 12212 RHS = ImpCastExprToType(RHS.get(), LHSType, 12213 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12214 return computeResultTy(); 12215 } 12216 12217 // Handle block pointers. 12218 if (!IsOrdered && RHSIsNull 12219 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12220 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12221 return computeResultTy(); 12222 } 12223 if (!IsOrdered && LHSIsNull 12224 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12225 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12226 return computeResultTy(); 12227 } 12228 12229 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12230 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12231 return computeResultTy(); 12232 } 12233 12234 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12235 return computeResultTy(); 12236 } 12237 12238 if (LHSIsNull && RHSType->isQueueT()) { 12239 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12240 return computeResultTy(); 12241 } 12242 12243 if (LHSType->isQueueT() && RHSIsNull) { 12244 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12245 return computeResultTy(); 12246 } 12247 } 12248 12249 return InvalidOperands(Loc, LHS, RHS); 12250 } 12251 12252 // Return a signed ext_vector_type that is of identical size and number of 12253 // elements. For floating point vectors, return an integer type of identical 12254 // size and number of elements. In the non ext_vector_type case, search from 12255 // the largest type to the smallest type to avoid cases where long long == long, 12256 // where long gets picked over long long. 12257 QualType Sema::GetSignedVectorType(QualType V) { 12258 const VectorType *VTy = V->castAs<VectorType>(); 12259 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12260 12261 if (isa<ExtVectorType>(VTy)) { 12262 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12263 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12264 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12265 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12266 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12267 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12268 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12269 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12270 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12271 "Unhandled vector element size in vector compare"); 12272 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12273 } 12274 12275 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12276 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12277 VectorType::GenericVector); 12278 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12279 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12280 VectorType::GenericVector); 12281 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12282 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12283 VectorType::GenericVector); 12284 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12285 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12286 VectorType::GenericVector); 12287 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12288 "Unhandled vector element size in vector compare"); 12289 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12290 VectorType::GenericVector); 12291 } 12292 12293 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12294 /// operates on extended vector types. Instead of producing an IntTy result, 12295 /// like a scalar comparison, a vector comparison produces a vector of integer 12296 /// types. 12297 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12298 SourceLocation Loc, 12299 BinaryOperatorKind Opc) { 12300 if (Opc == BO_Cmp) { 12301 Diag(Loc, diag::err_three_way_vector_comparison); 12302 return QualType(); 12303 } 12304 12305 // Check to make sure we're operating on vectors of the same type and width, 12306 // Allowing one side to be a scalar of element type. 12307 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12308 /*AllowBothBool*/true, 12309 /*AllowBoolConversions*/getLangOpts().ZVector); 12310 if (vType.isNull()) 12311 return vType; 12312 12313 QualType LHSType = LHS.get()->getType(); 12314 12315 // Determine the return type of a vector compare. By default clang will return 12316 // a scalar for all vector compares except vector bool and vector pixel. 12317 // With the gcc compiler we will always return a vector type and with the xl 12318 // compiler we will always return a scalar type. This switch allows choosing 12319 // which behavior is prefered. 12320 if (getLangOpts().AltiVec) { 12321 switch (getLangOpts().getAltivecSrcCompat()) { 12322 case LangOptions::AltivecSrcCompatKind::Mixed: 12323 // If AltiVec, the comparison results in a numeric type, i.e. 12324 // bool for C++, int for C 12325 if (vType->castAs<VectorType>()->getVectorKind() == 12326 VectorType::AltiVecVector) 12327 return Context.getLogicalOperationType(); 12328 else 12329 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12330 break; 12331 case LangOptions::AltivecSrcCompatKind::GCC: 12332 // For GCC we always return the vector type. 12333 break; 12334 case LangOptions::AltivecSrcCompatKind::XL: 12335 return Context.getLogicalOperationType(); 12336 break; 12337 } 12338 } 12339 12340 // For non-floating point types, check for self-comparisons of the form 12341 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12342 // often indicate logic errors in the program. 12343 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12344 12345 // Check for comparisons of floating point operands using != and ==. 12346 if (BinaryOperator::isEqualityOp(Opc) && 12347 LHSType->hasFloatingRepresentation()) { 12348 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12349 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12350 } 12351 12352 // Return a signed type for the vector. 12353 return GetSignedVectorType(vType); 12354 } 12355 12356 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12357 const ExprResult &XorRHS, 12358 const SourceLocation Loc) { 12359 // Do not diagnose macros. 12360 if (Loc.isMacroID()) 12361 return; 12362 12363 // Do not diagnose if both LHS and RHS are macros. 12364 if (XorLHS.get()->getExprLoc().isMacroID() && 12365 XorRHS.get()->getExprLoc().isMacroID()) 12366 return; 12367 12368 bool Negative = false; 12369 bool ExplicitPlus = false; 12370 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12371 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12372 12373 if (!LHSInt) 12374 return; 12375 if (!RHSInt) { 12376 // Check negative literals. 12377 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12378 UnaryOperatorKind Opc = UO->getOpcode(); 12379 if (Opc != UO_Minus && Opc != UO_Plus) 12380 return; 12381 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12382 if (!RHSInt) 12383 return; 12384 Negative = (Opc == UO_Minus); 12385 ExplicitPlus = !Negative; 12386 } else { 12387 return; 12388 } 12389 } 12390 12391 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12392 llvm::APInt RightSideValue = RHSInt->getValue(); 12393 if (LeftSideValue != 2 && LeftSideValue != 10) 12394 return; 12395 12396 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12397 return; 12398 12399 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12400 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12401 llvm::StringRef ExprStr = 12402 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12403 12404 CharSourceRange XorRange = 12405 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12406 llvm::StringRef XorStr = 12407 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12408 // Do not diagnose if xor keyword/macro is used. 12409 if (XorStr == "xor") 12410 return; 12411 12412 std::string LHSStr = std::string(Lexer::getSourceText( 12413 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12414 S.getSourceManager(), S.getLangOpts())); 12415 std::string RHSStr = std::string(Lexer::getSourceText( 12416 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12417 S.getSourceManager(), S.getLangOpts())); 12418 12419 if (Negative) { 12420 RightSideValue = -RightSideValue; 12421 RHSStr = "-" + RHSStr; 12422 } else if (ExplicitPlus) { 12423 RHSStr = "+" + RHSStr; 12424 } 12425 12426 StringRef LHSStrRef = LHSStr; 12427 StringRef RHSStrRef = RHSStr; 12428 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12429 // literals. 12430 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12431 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12432 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12433 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12434 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12435 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12436 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12437 return; 12438 12439 bool SuggestXor = 12440 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12441 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12442 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12443 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12444 std::string SuggestedExpr = "1 << " + RHSStr; 12445 bool Overflow = false; 12446 llvm::APInt One = (LeftSideValue - 1); 12447 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12448 if (Overflow) { 12449 if (RightSideIntValue < 64) 12450 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12451 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12452 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12453 else if (RightSideIntValue == 64) 12454 S.Diag(Loc, diag::warn_xor_used_as_pow) 12455 << ExprStr << toString(XorValue, 10, true); 12456 else 12457 return; 12458 } else { 12459 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12460 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12461 << toString(PowValue, 10, true) 12462 << FixItHint::CreateReplacement( 12463 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12464 } 12465 12466 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12467 << ("0x2 ^ " + RHSStr) << SuggestXor; 12468 } else if (LeftSideValue == 10) { 12469 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12470 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12471 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12472 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12473 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12474 << ("0xA ^ " + RHSStr) << SuggestXor; 12475 } 12476 } 12477 12478 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12479 SourceLocation Loc) { 12480 // Ensure that either both operands are of the same vector type, or 12481 // one operand is of a vector type and the other is of its element type. 12482 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12483 /*AllowBothBool*/true, 12484 /*AllowBoolConversions*/false); 12485 if (vType.isNull()) 12486 return InvalidOperands(Loc, LHS, RHS); 12487 if (getLangOpts().OpenCL && 12488 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12489 vType->hasFloatingRepresentation()) 12490 return InvalidOperands(Loc, LHS, RHS); 12491 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12492 // usage of the logical operators && and || with vectors in C. This 12493 // check could be notionally dropped. 12494 if (!getLangOpts().CPlusPlus && 12495 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12496 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12497 12498 return GetSignedVectorType(LHS.get()->getType()); 12499 } 12500 12501 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12502 SourceLocation Loc, 12503 bool IsCompAssign) { 12504 if (!IsCompAssign) { 12505 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12506 if (LHS.isInvalid()) 12507 return QualType(); 12508 } 12509 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12510 if (RHS.isInvalid()) 12511 return QualType(); 12512 12513 // For conversion purposes, we ignore any qualifiers. 12514 // For example, "const float" and "float" are equivalent. 12515 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12516 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12517 12518 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12519 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12520 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12521 12522 if (Context.hasSameType(LHSType, RHSType)) 12523 return LHSType; 12524 12525 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12526 // case we have to return InvalidOperands. 12527 ExprResult OriginalLHS = LHS; 12528 ExprResult OriginalRHS = RHS; 12529 if (LHSMatType && !RHSMatType) { 12530 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12531 if (!RHS.isInvalid()) 12532 return LHSType; 12533 12534 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12535 } 12536 12537 if (!LHSMatType && RHSMatType) { 12538 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12539 if (!LHS.isInvalid()) 12540 return RHSType; 12541 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12542 } 12543 12544 return InvalidOperands(Loc, LHS, RHS); 12545 } 12546 12547 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12548 SourceLocation Loc, 12549 bool IsCompAssign) { 12550 if (!IsCompAssign) { 12551 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12552 if (LHS.isInvalid()) 12553 return QualType(); 12554 } 12555 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12556 if (RHS.isInvalid()) 12557 return QualType(); 12558 12559 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12560 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12561 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12562 12563 if (LHSMatType && RHSMatType) { 12564 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12565 return InvalidOperands(Loc, LHS, RHS); 12566 12567 if (!Context.hasSameType(LHSMatType->getElementType(), 12568 RHSMatType->getElementType())) 12569 return InvalidOperands(Loc, LHS, RHS); 12570 12571 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12572 LHSMatType->getNumRows(), 12573 RHSMatType->getNumColumns()); 12574 } 12575 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12576 } 12577 12578 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12579 SourceLocation Loc, 12580 BinaryOperatorKind Opc) { 12581 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12582 12583 bool IsCompAssign = 12584 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12585 12586 if (LHS.get()->getType()->isVectorType() || 12587 RHS.get()->getType()->isVectorType()) { 12588 if (LHS.get()->getType()->hasIntegerRepresentation() && 12589 RHS.get()->getType()->hasIntegerRepresentation()) 12590 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12591 /*AllowBothBool*/true, 12592 /*AllowBoolConversions*/getLangOpts().ZVector); 12593 return InvalidOperands(Loc, LHS, RHS); 12594 } 12595 12596 if (Opc == BO_And) 12597 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12598 12599 if (LHS.get()->getType()->hasFloatingRepresentation() || 12600 RHS.get()->getType()->hasFloatingRepresentation()) 12601 return InvalidOperands(Loc, LHS, RHS); 12602 12603 ExprResult LHSResult = LHS, RHSResult = RHS; 12604 QualType compType = UsualArithmeticConversions( 12605 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12606 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12607 return QualType(); 12608 LHS = LHSResult.get(); 12609 RHS = RHSResult.get(); 12610 12611 if (Opc == BO_Xor) 12612 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12613 12614 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12615 return compType; 12616 return InvalidOperands(Loc, LHS, RHS); 12617 } 12618 12619 // C99 6.5.[13,14] 12620 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12621 SourceLocation Loc, 12622 BinaryOperatorKind Opc) { 12623 // Check vector operands differently. 12624 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12625 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12626 12627 bool EnumConstantInBoolContext = false; 12628 for (const ExprResult &HS : {LHS, RHS}) { 12629 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12630 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12631 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12632 EnumConstantInBoolContext = true; 12633 } 12634 } 12635 12636 if (EnumConstantInBoolContext) 12637 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12638 12639 // Diagnose cases where the user write a logical and/or but probably meant a 12640 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12641 // is a constant. 12642 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12643 !LHS.get()->getType()->isBooleanType() && 12644 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12645 // Don't warn in macros or template instantiations. 12646 !Loc.isMacroID() && !inTemplateInstantiation()) { 12647 // If the RHS can be constant folded, and if it constant folds to something 12648 // that isn't 0 or 1 (which indicate a potential logical operation that 12649 // happened to fold to true/false) then warn. 12650 // Parens on the RHS are ignored. 12651 Expr::EvalResult EVResult; 12652 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12653 llvm::APSInt Result = EVResult.Val.getInt(); 12654 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12655 !RHS.get()->getExprLoc().isMacroID()) || 12656 (Result != 0 && Result != 1)) { 12657 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12658 << RHS.get()->getSourceRange() 12659 << (Opc == BO_LAnd ? "&&" : "||"); 12660 // Suggest replacing the logical operator with the bitwise version 12661 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12662 << (Opc == BO_LAnd ? "&" : "|") 12663 << FixItHint::CreateReplacement(SourceRange( 12664 Loc, getLocForEndOfToken(Loc)), 12665 Opc == BO_LAnd ? "&" : "|"); 12666 if (Opc == BO_LAnd) 12667 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12668 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12669 << FixItHint::CreateRemoval( 12670 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12671 RHS.get()->getEndLoc())); 12672 } 12673 } 12674 } 12675 12676 if (!Context.getLangOpts().CPlusPlus) { 12677 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12678 // not operate on the built-in scalar and vector float types. 12679 if (Context.getLangOpts().OpenCL && 12680 Context.getLangOpts().OpenCLVersion < 120) { 12681 if (LHS.get()->getType()->isFloatingType() || 12682 RHS.get()->getType()->isFloatingType()) 12683 return InvalidOperands(Loc, LHS, RHS); 12684 } 12685 12686 LHS = UsualUnaryConversions(LHS.get()); 12687 if (LHS.isInvalid()) 12688 return QualType(); 12689 12690 RHS = UsualUnaryConversions(RHS.get()); 12691 if (RHS.isInvalid()) 12692 return QualType(); 12693 12694 if (!LHS.get()->getType()->isScalarType() || 12695 !RHS.get()->getType()->isScalarType()) 12696 return InvalidOperands(Loc, LHS, RHS); 12697 12698 return Context.IntTy; 12699 } 12700 12701 // The following is safe because we only use this method for 12702 // non-overloadable operands. 12703 12704 // C++ [expr.log.and]p1 12705 // C++ [expr.log.or]p1 12706 // The operands are both contextually converted to type bool. 12707 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12708 if (LHSRes.isInvalid()) 12709 return InvalidOperands(Loc, LHS, RHS); 12710 LHS = LHSRes; 12711 12712 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12713 if (RHSRes.isInvalid()) 12714 return InvalidOperands(Loc, LHS, RHS); 12715 RHS = RHSRes; 12716 12717 // C++ [expr.log.and]p2 12718 // C++ [expr.log.or]p2 12719 // The result is a bool. 12720 return Context.BoolTy; 12721 } 12722 12723 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12724 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12725 if (!ME) return false; 12726 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12727 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12728 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12729 if (!Base) return false; 12730 return Base->getMethodDecl() != nullptr; 12731 } 12732 12733 /// Is the given expression (which must be 'const') a reference to a 12734 /// variable which was originally non-const, but which has become 12735 /// 'const' due to being captured within a block? 12736 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12737 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12738 assert(E->isLValue() && E->getType().isConstQualified()); 12739 E = E->IgnoreParens(); 12740 12741 // Must be a reference to a declaration from an enclosing scope. 12742 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12743 if (!DRE) return NCCK_None; 12744 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12745 12746 // The declaration must be a variable which is not declared 'const'. 12747 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12748 if (!var) return NCCK_None; 12749 if (var->getType().isConstQualified()) return NCCK_None; 12750 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12751 12752 // Decide whether the first capture was for a block or a lambda. 12753 DeclContext *DC = S.CurContext, *Prev = nullptr; 12754 // Decide whether the first capture was for a block or a lambda. 12755 while (DC) { 12756 // For init-capture, it is possible that the variable belongs to the 12757 // template pattern of the current context. 12758 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12759 if (var->isInitCapture() && 12760 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12761 break; 12762 if (DC == var->getDeclContext()) 12763 break; 12764 Prev = DC; 12765 DC = DC->getParent(); 12766 } 12767 // Unless we have an init-capture, we've gone one step too far. 12768 if (!var->isInitCapture()) 12769 DC = Prev; 12770 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12771 } 12772 12773 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12774 Ty = Ty.getNonReferenceType(); 12775 if (IsDereference && Ty->isPointerType()) 12776 Ty = Ty->getPointeeType(); 12777 return !Ty.isConstQualified(); 12778 } 12779 12780 // Update err_typecheck_assign_const and note_typecheck_assign_const 12781 // when this enum is changed. 12782 enum { 12783 ConstFunction, 12784 ConstVariable, 12785 ConstMember, 12786 ConstMethod, 12787 NestedConstMember, 12788 ConstUnknown, // Keep as last element 12789 }; 12790 12791 /// Emit the "read-only variable not assignable" error and print notes to give 12792 /// more information about why the variable is not assignable, such as pointing 12793 /// to the declaration of a const variable, showing that a method is const, or 12794 /// that the function is returning a const reference. 12795 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12796 SourceLocation Loc) { 12797 SourceRange ExprRange = E->getSourceRange(); 12798 12799 // Only emit one error on the first const found. All other consts will emit 12800 // a note to the error. 12801 bool DiagnosticEmitted = false; 12802 12803 // Track if the current expression is the result of a dereference, and if the 12804 // next checked expression is the result of a dereference. 12805 bool IsDereference = false; 12806 bool NextIsDereference = false; 12807 12808 // Loop to process MemberExpr chains. 12809 while (true) { 12810 IsDereference = NextIsDereference; 12811 12812 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12813 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12814 NextIsDereference = ME->isArrow(); 12815 const ValueDecl *VD = ME->getMemberDecl(); 12816 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12817 // Mutable fields can be modified even if the class is const. 12818 if (Field->isMutable()) { 12819 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12820 break; 12821 } 12822 12823 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12824 if (!DiagnosticEmitted) { 12825 S.Diag(Loc, diag::err_typecheck_assign_const) 12826 << ExprRange << ConstMember << false /*static*/ << Field 12827 << Field->getType(); 12828 DiagnosticEmitted = true; 12829 } 12830 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12831 << ConstMember << false /*static*/ << Field << Field->getType() 12832 << Field->getSourceRange(); 12833 } 12834 E = ME->getBase(); 12835 continue; 12836 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12837 if (VDecl->getType().isConstQualified()) { 12838 if (!DiagnosticEmitted) { 12839 S.Diag(Loc, diag::err_typecheck_assign_const) 12840 << ExprRange << ConstMember << true /*static*/ << VDecl 12841 << VDecl->getType(); 12842 DiagnosticEmitted = true; 12843 } 12844 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12845 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12846 << VDecl->getSourceRange(); 12847 } 12848 // Static fields do not inherit constness from parents. 12849 break; 12850 } 12851 break; // End MemberExpr 12852 } else if (const ArraySubscriptExpr *ASE = 12853 dyn_cast<ArraySubscriptExpr>(E)) { 12854 E = ASE->getBase()->IgnoreParenImpCasts(); 12855 continue; 12856 } else if (const ExtVectorElementExpr *EVE = 12857 dyn_cast<ExtVectorElementExpr>(E)) { 12858 E = EVE->getBase()->IgnoreParenImpCasts(); 12859 continue; 12860 } 12861 break; 12862 } 12863 12864 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12865 // Function calls 12866 const FunctionDecl *FD = CE->getDirectCallee(); 12867 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12868 if (!DiagnosticEmitted) { 12869 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12870 << ConstFunction << FD; 12871 DiagnosticEmitted = true; 12872 } 12873 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12874 diag::note_typecheck_assign_const) 12875 << ConstFunction << FD << FD->getReturnType() 12876 << FD->getReturnTypeSourceRange(); 12877 } 12878 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12879 // Point to variable declaration. 12880 if (const ValueDecl *VD = DRE->getDecl()) { 12881 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12882 if (!DiagnosticEmitted) { 12883 S.Diag(Loc, diag::err_typecheck_assign_const) 12884 << ExprRange << ConstVariable << VD << VD->getType(); 12885 DiagnosticEmitted = true; 12886 } 12887 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12888 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12889 } 12890 } 12891 } else if (isa<CXXThisExpr>(E)) { 12892 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12893 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12894 if (MD->isConst()) { 12895 if (!DiagnosticEmitted) { 12896 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12897 << ConstMethod << MD; 12898 DiagnosticEmitted = true; 12899 } 12900 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12901 << ConstMethod << MD << MD->getSourceRange(); 12902 } 12903 } 12904 } 12905 } 12906 12907 if (DiagnosticEmitted) 12908 return; 12909 12910 // Can't determine a more specific message, so display the generic error. 12911 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12912 } 12913 12914 enum OriginalExprKind { 12915 OEK_Variable, 12916 OEK_Member, 12917 OEK_LValue 12918 }; 12919 12920 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12921 const RecordType *Ty, 12922 SourceLocation Loc, SourceRange Range, 12923 OriginalExprKind OEK, 12924 bool &DiagnosticEmitted) { 12925 std::vector<const RecordType *> RecordTypeList; 12926 RecordTypeList.push_back(Ty); 12927 unsigned NextToCheckIndex = 0; 12928 // We walk the record hierarchy breadth-first to ensure that we print 12929 // diagnostics in field nesting order. 12930 while (RecordTypeList.size() > NextToCheckIndex) { 12931 bool IsNested = NextToCheckIndex > 0; 12932 for (const FieldDecl *Field : 12933 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12934 // First, check every field for constness. 12935 QualType FieldTy = Field->getType(); 12936 if (FieldTy.isConstQualified()) { 12937 if (!DiagnosticEmitted) { 12938 S.Diag(Loc, diag::err_typecheck_assign_const) 12939 << Range << NestedConstMember << OEK << VD 12940 << IsNested << Field; 12941 DiagnosticEmitted = true; 12942 } 12943 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12944 << NestedConstMember << IsNested << Field 12945 << FieldTy << Field->getSourceRange(); 12946 } 12947 12948 // Then we append it to the list to check next in order. 12949 FieldTy = FieldTy.getCanonicalType(); 12950 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12951 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 12952 RecordTypeList.push_back(FieldRecTy); 12953 } 12954 } 12955 ++NextToCheckIndex; 12956 } 12957 } 12958 12959 /// Emit an error for the case where a record we are trying to assign to has a 12960 /// const-qualified field somewhere in its hierarchy. 12961 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12962 SourceLocation Loc) { 12963 QualType Ty = E->getType(); 12964 assert(Ty->isRecordType() && "lvalue was not record?"); 12965 SourceRange Range = E->getSourceRange(); 12966 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12967 bool DiagEmitted = false; 12968 12969 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12970 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12971 Range, OEK_Member, DiagEmitted); 12972 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12973 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12974 Range, OEK_Variable, DiagEmitted); 12975 else 12976 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12977 Range, OEK_LValue, DiagEmitted); 12978 if (!DiagEmitted) 12979 DiagnoseConstAssignment(S, E, Loc); 12980 } 12981 12982 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12983 /// emit an error and return true. If so, return false. 12984 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12985 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12986 12987 S.CheckShadowingDeclModification(E, Loc); 12988 12989 SourceLocation OrigLoc = Loc; 12990 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12991 &Loc); 12992 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12993 IsLV = Expr::MLV_InvalidMessageExpression; 12994 if (IsLV == Expr::MLV_Valid) 12995 return false; 12996 12997 unsigned DiagID = 0; 12998 bool NeedType = false; 12999 switch (IsLV) { // C99 6.5.16p2 13000 case Expr::MLV_ConstQualified: 13001 // Use a specialized diagnostic when we're assigning to an object 13002 // from an enclosing function or block. 13003 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13004 if (NCCK == NCCK_Block) 13005 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13006 else 13007 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13008 break; 13009 } 13010 13011 // In ARC, use some specialized diagnostics for occasions where we 13012 // infer 'const'. These are always pseudo-strong variables. 13013 if (S.getLangOpts().ObjCAutoRefCount) { 13014 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13015 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13016 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13017 13018 // Use the normal diagnostic if it's pseudo-__strong but the 13019 // user actually wrote 'const'. 13020 if (var->isARCPseudoStrong() && 13021 (!var->getTypeSourceInfo() || 13022 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13023 // There are three pseudo-strong cases: 13024 // - self 13025 ObjCMethodDecl *method = S.getCurMethodDecl(); 13026 if (method && var == method->getSelfDecl()) { 13027 DiagID = method->isClassMethod() 13028 ? diag::err_typecheck_arc_assign_self_class_method 13029 : diag::err_typecheck_arc_assign_self; 13030 13031 // - Objective-C externally_retained attribute. 13032 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13033 isa<ParmVarDecl>(var)) { 13034 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13035 13036 // - fast enumeration variables 13037 } else { 13038 DiagID = diag::err_typecheck_arr_assign_enumeration; 13039 } 13040 13041 SourceRange Assign; 13042 if (Loc != OrigLoc) 13043 Assign = SourceRange(OrigLoc, OrigLoc); 13044 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13045 // We need to preserve the AST regardless, so migration tool 13046 // can do its job. 13047 return false; 13048 } 13049 } 13050 } 13051 13052 // If none of the special cases above are triggered, then this is a 13053 // simple const assignment. 13054 if (DiagID == 0) { 13055 DiagnoseConstAssignment(S, E, Loc); 13056 return true; 13057 } 13058 13059 break; 13060 case Expr::MLV_ConstAddrSpace: 13061 DiagnoseConstAssignment(S, E, Loc); 13062 return true; 13063 case Expr::MLV_ConstQualifiedField: 13064 DiagnoseRecursiveConstFields(S, E, Loc); 13065 return true; 13066 case Expr::MLV_ArrayType: 13067 case Expr::MLV_ArrayTemporary: 13068 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13069 NeedType = true; 13070 break; 13071 case Expr::MLV_NotObjectType: 13072 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13073 NeedType = true; 13074 break; 13075 case Expr::MLV_LValueCast: 13076 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13077 break; 13078 case Expr::MLV_Valid: 13079 llvm_unreachable("did not take early return for MLV_Valid"); 13080 case Expr::MLV_InvalidExpression: 13081 case Expr::MLV_MemberFunction: 13082 case Expr::MLV_ClassTemporary: 13083 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13084 break; 13085 case Expr::MLV_IncompleteType: 13086 case Expr::MLV_IncompleteVoidType: 13087 return S.RequireCompleteType(Loc, E->getType(), 13088 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13089 case Expr::MLV_DuplicateVectorComponents: 13090 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13091 break; 13092 case Expr::MLV_NoSetterProperty: 13093 llvm_unreachable("readonly properties should be processed differently"); 13094 case Expr::MLV_InvalidMessageExpression: 13095 DiagID = diag::err_readonly_message_assignment; 13096 break; 13097 case Expr::MLV_SubObjCPropertySetting: 13098 DiagID = diag::err_no_subobject_property_setting; 13099 break; 13100 } 13101 13102 SourceRange Assign; 13103 if (Loc != OrigLoc) 13104 Assign = SourceRange(OrigLoc, OrigLoc); 13105 if (NeedType) 13106 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13107 else 13108 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13109 return true; 13110 } 13111 13112 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13113 SourceLocation Loc, 13114 Sema &Sema) { 13115 if (Sema.inTemplateInstantiation()) 13116 return; 13117 if (Sema.isUnevaluatedContext()) 13118 return; 13119 if (Loc.isInvalid() || Loc.isMacroID()) 13120 return; 13121 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13122 return; 13123 13124 // C / C++ fields 13125 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13126 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13127 if (ML && MR) { 13128 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13129 return; 13130 const ValueDecl *LHSDecl = 13131 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13132 const ValueDecl *RHSDecl = 13133 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13134 if (LHSDecl != RHSDecl) 13135 return; 13136 if (LHSDecl->getType().isVolatileQualified()) 13137 return; 13138 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13139 if (RefTy->getPointeeType().isVolatileQualified()) 13140 return; 13141 13142 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13143 } 13144 13145 // Objective-C instance variables 13146 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13147 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13148 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13149 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13150 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13151 if (RL && RR && RL->getDecl() == RR->getDecl()) 13152 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13153 } 13154 } 13155 13156 // C99 6.5.16.1 13157 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13158 SourceLocation Loc, 13159 QualType CompoundType) { 13160 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13161 13162 // Verify that LHS is a modifiable lvalue, and emit error if not. 13163 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13164 return QualType(); 13165 13166 QualType LHSType = LHSExpr->getType(); 13167 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13168 CompoundType; 13169 // OpenCL v1.2 s6.1.1.1 p2: 13170 // The half data type can only be used to declare a pointer to a buffer that 13171 // contains half values 13172 if (getLangOpts().OpenCL && 13173 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13174 LHSType->isHalfType()) { 13175 Diag(Loc, diag::err_opencl_half_load_store) << 1 13176 << LHSType.getUnqualifiedType(); 13177 return QualType(); 13178 } 13179 13180 AssignConvertType ConvTy; 13181 if (CompoundType.isNull()) { 13182 Expr *RHSCheck = RHS.get(); 13183 13184 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13185 13186 QualType LHSTy(LHSType); 13187 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13188 if (RHS.isInvalid()) 13189 return QualType(); 13190 // Special case of NSObject attributes on c-style pointer types. 13191 if (ConvTy == IncompatiblePointer && 13192 ((Context.isObjCNSObjectType(LHSType) && 13193 RHSType->isObjCObjectPointerType()) || 13194 (Context.isObjCNSObjectType(RHSType) && 13195 LHSType->isObjCObjectPointerType()))) 13196 ConvTy = Compatible; 13197 13198 if (ConvTy == Compatible && 13199 LHSType->isObjCObjectType()) 13200 Diag(Loc, diag::err_objc_object_assignment) 13201 << LHSType; 13202 13203 // If the RHS is a unary plus or minus, check to see if they = and + are 13204 // right next to each other. If so, the user may have typo'd "x =+ 4" 13205 // instead of "x += 4". 13206 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13207 RHSCheck = ICE->getSubExpr(); 13208 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13209 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13210 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13211 // Only if the two operators are exactly adjacent. 13212 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13213 // And there is a space or other character before the subexpr of the 13214 // unary +/-. We don't want to warn on "x=-1". 13215 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13216 UO->getSubExpr()->getBeginLoc().isFileID()) { 13217 Diag(Loc, diag::warn_not_compound_assign) 13218 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13219 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13220 } 13221 } 13222 13223 if (ConvTy == Compatible) { 13224 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13225 // Warn about retain cycles where a block captures the LHS, but 13226 // not if the LHS is a simple variable into which the block is 13227 // being stored...unless that variable can be captured by reference! 13228 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13229 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13230 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13231 checkRetainCycles(LHSExpr, RHS.get()); 13232 } 13233 13234 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13235 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13236 // It is safe to assign a weak reference into a strong variable. 13237 // Although this code can still have problems: 13238 // id x = self.weakProp; 13239 // id y = self.weakProp; 13240 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13241 // paths through the function. This should be revisited if 13242 // -Wrepeated-use-of-weak is made flow-sensitive. 13243 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13244 // variable, which will be valid for the current autorelease scope. 13245 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13246 RHS.get()->getBeginLoc())) 13247 getCurFunction()->markSafeWeakUse(RHS.get()); 13248 13249 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13250 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13251 } 13252 } 13253 } else { 13254 // Compound assignment "x += y" 13255 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13256 } 13257 13258 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13259 RHS.get(), AA_Assigning)) 13260 return QualType(); 13261 13262 CheckForNullPointerDereference(*this, LHSExpr); 13263 13264 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13265 if (CompoundType.isNull()) { 13266 // C++2a [expr.ass]p5: 13267 // A simple-assignment whose left operand is of a volatile-qualified 13268 // type is deprecated unless the assignment is either a discarded-value 13269 // expression or an unevaluated operand 13270 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13271 } else { 13272 // C++2a [expr.ass]p6: 13273 // [Compound-assignment] expressions are deprecated if E1 has 13274 // volatile-qualified type 13275 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13276 } 13277 } 13278 13279 // C99 6.5.16p3: The type of an assignment expression is the type of the 13280 // left operand unless the left operand has qualified type, in which case 13281 // it is the unqualified version of the type of the left operand. 13282 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13283 // is converted to the type of the assignment expression (above). 13284 // C++ 5.17p1: the type of the assignment expression is that of its left 13285 // operand. 13286 return (getLangOpts().CPlusPlus 13287 ? LHSType : LHSType.getUnqualifiedType()); 13288 } 13289 13290 // Only ignore explicit casts to void. 13291 static bool IgnoreCommaOperand(const Expr *E) { 13292 E = E->IgnoreParens(); 13293 13294 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13295 if (CE->getCastKind() == CK_ToVoid) { 13296 return true; 13297 } 13298 13299 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13300 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13301 CE->getSubExpr()->getType()->isDependentType()) { 13302 return true; 13303 } 13304 } 13305 13306 return false; 13307 } 13308 13309 // Look for instances where it is likely the comma operator is confused with 13310 // another operator. There is an explicit list of acceptable expressions for 13311 // the left hand side of the comma operator, otherwise emit a warning. 13312 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13313 // No warnings in macros 13314 if (Loc.isMacroID()) 13315 return; 13316 13317 // Don't warn in template instantiations. 13318 if (inTemplateInstantiation()) 13319 return; 13320 13321 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13322 // instead, skip more than needed, then call back into here with the 13323 // CommaVisitor in SemaStmt.cpp. 13324 // The listed locations are the initialization and increment portions 13325 // of a for loop. The additional checks are on the condition of 13326 // if statements, do/while loops, and for loops. 13327 // Differences in scope flags for C89 mode requires the extra logic. 13328 const unsigned ForIncrementFlags = 13329 getLangOpts().C99 || getLangOpts().CPlusPlus 13330 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13331 : Scope::ContinueScope | Scope::BreakScope; 13332 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13333 const unsigned ScopeFlags = getCurScope()->getFlags(); 13334 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13335 (ScopeFlags & ForInitFlags) == ForInitFlags) 13336 return; 13337 13338 // If there are multiple comma operators used together, get the RHS of the 13339 // of the comma operator as the LHS. 13340 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13341 if (BO->getOpcode() != BO_Comma) 13342 break; 13343 LHS = BO->getRHS(); 13344 } 13345 13346 // Only allow some expressions on LHS to not warn. 13347 if (IgnoreCommaOperand(LHS)) 13348 return; 13349 13350 Diag(Loc, diag::warn_comma_operator); 13351 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13352 << LHS->getSourceRange() 13353 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13354 LangOpts.CPlusPlus ? "static_cast<void>(" 13355 : "(void)(") 13356 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13357 ")"); 13358 } 13359 13360 // C99 6.5.17 13361 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13362 SourceLocation Loc) { 13363 LHS = S.CheckPlaceholderExpr(LHS.get()); 13364 RHS = S.CheckPlaceholderExpr(RHS.get()); 13365 if (LHS.isInvalid() || RHS.isInvalid()) 13366 return QualType(); 13367 13368 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13369 // operands, but not unary promotions. 13370 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13371 13372 // So we treat the LHS as a ignored value, and in C++ we allow the 13373 // containing site to determine what should be done with the RHS. 13374 LHS = S.IgnoredValueConversions(LHS.get()); 13375 if (LHS.isInvalid()) 13376 return QualType(); 13377 13378 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13379 13380 if (!S.getLangOpts().CPlusPlus) { 13381 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13382 if (RHS.isInvalid()) 13383 return QualType(); 13384 if (!RHS.get()->getType()->isVoidType()) 13385 S.RequireCompleteType(Loc, RHS.get()->getType(), 13386 diag::err_incomplete_type); 13387 } 13388 13389 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13390 S.DiagnoseCommaOperator(LHS.get(), Loc); 13391 13392 return RHS.get()->getType(); 13393 } 13394 13395 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13396 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13397 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13398 ExprValueKind &VK, 13399 ExprObjectKind &OK, 13400 SourceLocation OpLoc, 13401 bool IsInc, bool IsPrefix) { 13402 if (Op->isTypeDependent()) 13403 return S.Context.DependentTy; 13404 13405 QualType ResType = Op->getType(); 13406 // Atomic types can be used for increment / decrement where the non-atomic 13407 // versions can, so ignore the _Atomic() specifier for the purpose of 13408 // checking. 13409 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13410 ResType = ResAtomicType->getValueType(); 13411 13412 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13413 13414 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13415 // Decrement of bool is not allowed. 13416 if (!IsInc) { 13417 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13418 return QualType(); 13419 } 13420 // Increment of bool sets it to true, but is deprecated. 13421 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13422 : diag::warn_increment_bool) 13423 << Op->getSourceRange(); 13424 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13425 // Error on enum increments and decrements in C++ mode 13426 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13427 return QualType(); 13428 } else if (ResType->isRealType()) { 13429 // OK! 13430 } else if (ResType->isPointerType()) { 13431 // C99 6.5.2.4p2, 6.5.6p2 13432 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13433 return QualType(); 13434 } else if (ResType->isObjCObjectPointerType()) { 13435 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13436 // Otherwise, we just need a complete type. 13437 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13438 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13439 return QualType(); 13440 } else if (ResType->isAnyComplexType()) { 13441 // C99 does not support ++/-- on complex types, we allow as an extension. 13442 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13443 << ResType << Op->getSourceRange(); 13444 } else if (ResType->isPlaceholderType()) { 13445 ExprResult PR = S.CheckPlaceholderExpr(Op); 13446 if (PR.isInvalid()) return QualType(); 13447 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13448 IsInc, IsPrefix); 13449 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13450 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13451 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13452 (ResType->castAs<VectorType>()->getVectorKind() != 13453 VectorType::AltiVecBool)) { 13454 // The z vector extensions allow ++ and -- for non-bool vectors. 13455 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13456 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13457 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13458 } else { 13459 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13460 << ResType << int(IsInc) << Op->getSourceRange(); 13461 return QualType(); 13462 } 13463 // At this point, we know we have a real, complex or pointer type. 13464 // Now make sure the operand is a modifiable lvalue. 13465 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13466 return QualType(); 13467 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13468 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13469 // An operand with volatile-qualified type is deprecated 13470 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13471 << IsInc << ResType; 13472 } 13473 // In C++, a prefix increment is the same type as the operand. Otherwise 13474 // (in C or with postfix), the increment is the unqualified type of the 13475 // operand. 13476 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13477 VK = VK_LValue; 13478 OK = Op->getObjectKind(); 13479 return ResType; 13480 } else { 13481 VK = VK_PRValue; 13482 return ResType.getUnqualifiedType(); 13483 } 13484 } 13485 13486 13487 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13488 /// This routine allows us to typecheck complex/recursive expressions 13489 /// where the declaration is needed for type checking. We only need to 13490 /// handle cases when the expression references a function designator 13491 /// or is an lvalue. Here are some examples: 13492 /// - &(x) => x 13493 /// - &*****f => f for f a function designator. 13494 /// - &s.xx => s 13495 /// - &s.zz[1].yy -> s, if zz is an array 13496 /// - *(x + 1) -> x, if x is an array 13497 /// - &"123"[2] -> 0 13498 /// - & __real__ x -> x 13499 /// 13500 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13501 /// members. 13502 static ValueDecl *getPrimaryDecl(Expr *E) { 13503 switch (E->getStmtClass()) { 13504 case Stmt::DeclRefExprClass: 13505 return cast<DeclRefExpr>(E)->getDecl(); 13506 case Stmt::MemberExprClass: 13507 // If this is an arrow operator, the address is an offset from 13508 // the base's value, so the object the base refers to is 13509 // irrelevant. 13510 if (cast<MemberExpr>(E)->isArrow()) 13511 return nullptr; 13512 // Otherwise, the expression refers to a part of the base 13513 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13514 case Stmt::ArraySubscriptExprClass: { 13515 // FIXME: This code shouldn't be necessary! We should catch the implicit 13516 // promotion of register arrays earlier. 13517 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13518 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13519 if (ICE->getSubExpr()->getType()->isArrayType()) 13520 return getPrimaryDecl(ICE->getSubExpr()); 13521 } 13522 return nullptr; 13523 } 13524 case Stmt::UnaryOperatorClass: { 13525 UnaryOperator *UO = cast<UnaryOperator>(E); 13526 13527 switch(UO->getOpcode()) { 13528 case UO_Real: 13529 case UO_Imag: 13530 case UO_Extension: 13531 return getPrimaryDecl(UO->getSubExpr()); 13532 default: 13533 return nullptr; 13534 } 13535 } 13536 case Stmt::ParenExprClass: 13537 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13538 case Stmt::ImplicitCastExprClass: 13539 // If the result of an implicit cast is an l-value, we care about 13540 // the sub-expression; otherwise, the result here doesn't matter. 13541 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13542 case Stmt::CXXUuidofExprClass: 13543 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13544 default: 13545 return nullptr; 13546 } 13547 } 13548 13549 namespace { 13550 enum { 13551 AO_Bit_Field = 0, 13552 AO_Vector_Element = 1, 13553 AO_Property_Expansion = 2, 13554 AO_Register_Variable = 3, 13555 AO_Matrix_Element = 4, 13556 AO_No_Error = 5 13557 }; 13558 } 13559 /// Diagnose invalid operand for address of operations. 13560 /// 13561 /// \param Type The type of operand which cannot have its address taken. 13562 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13563 Expr *E, unsigned Type) { 13564 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13565 } 13566 13567 /// CheckAddressOfOperand - The operand of & must be either a function 13568 /// designator or an lvalue designating an object. If it is an lvalue, the 13569 /// object cannot be declared with storage class register or be a bit field. 13570 /// Note: The usual conversions are *not* applied to the operand of the & 13571 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13572 /// In C++, the operand might be an overloaded function name, in which case 13573 /// we allow the '&' but retain the overloaded-function type. 13574 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13575 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13576 if (PTy->getKind() == BuiltinType::Overload) { 13577 Expr *E = OrigOp.get()->IgnoreParens(); 13578 if (!isa<OverloadExpr>(E)) { 13579 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13580 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13581 << OrigOp.get()->getSourceRange(); 13582 return QualType(); 13583 } 13584 13585 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13586 if (isa<UnresolvedMemberExpr>(Ovl)) 13587 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13588 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13589 << OrigOp.get()->getSourceRange(); 13590 return QualType(); 13591 } 13592 13593 return Context.OverloadTy; 13594 } 13595 13596 if (PTy->getKind() == BuiltinType::UnknownAny) 13597 return Context.UnknownAnyTy; 13598 13599 if (PTy->getKind() == BuiltinType::BoundMember) { 13600 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13601 << OrigOp.get()->getSourceRange(); 13602 return QualType(); 13603 } 13604 13605 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13606 if (OrigOp.isInvalid()) return QualType(); 13607 } 13608 13609 if (OrigOp.get()->isTypeDependent()) 13610 return Context.DependentTy; 13611 13612 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13613 13614 // Make sure to ignore parentheses in subsequent checks 13615 Expr *op = OrigOp.get()->IgnoreParens(); 13616 13617 // In OpenCL captures for blocks called as lambda functions 13618 // are located in the private address space. Blocks used in 13619 // enqueue_kernel can be located in a different address space 13620 // depending on a vendor implementation. Thus preventing 13621 // taking an address of the capture to avoid invalid AS casts. 13622 if (LangOpts.OpenCL) { 13623 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13624 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13625 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13626 return QualType(); 13627 } 13628 } 13629 13630 if (getLangOpts().C99) { 13631 // Implement C99-only parts of addressof rules. 13632 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13633 if (uOp->getOpcode() == UO_Deref) 13634 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13635 // (assuming the deref expression is valid). 13636 return uOp->getSubExpr()->getType(); 13637 } 13638 // Technically, there should be a check for array subscript 13639 // expressions here, but the result of one is always an lvalue anyway. 13640 } 13641 ValueDecl *dcl = getPrimaryDecl(op); 13642 13643 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13644 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13645 op->getBeginLoc())) 13646 return QualType(); 13647 13648 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13649 unsigned AddressOfError = AO_No_Error; 13650 13651 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13652 bool sfinae = (bool)isSFINAEContext(); 13653 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13654 : diag::ext_typecheck_addrof_temporary) 13655 << op->getType() << op->getSourceRange(); 13656 if (sfinae) 13657 return QualType(); 13658 // Materialize the temporary as an lvalue so that we can take its address. 13659 OrigOp = op = 13660 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13661 } else if (isa<ObjCSelectorExpr>(op)) { 13662 return Context.getPointerType(op->getType()); 13663 } else if (lval == Expr::LV_MemberFunction) { 13664 // If it's an instance method, make a member pointer. 13665 // The expression must have exactly the form &A::foo. 13666 13667 // If the underlying expression isn't a decl ref, give up. 13668 if (!isa<DeclRefExpr>(op)) { 13669 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13670 << OrigOp.get()->getSourceRange(); 13671 return QualType(); 13672 } 13673 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13674 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13675 13676 // The id-expression was parenthesized. 13677 if (OrigOp.get() != DRE) { 13678 Diag(OpLoc, diag::err_parens_pointer_member_function) 13679 << OrigOp.get()->getSourceRange(); 13680 13681 // The method was named without a qualifier. 13682 } else if (!DRE->getQualifier()) { 13683 if (MD->getParent()->getName().empty()) 13684 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13685 << op->getSourceRange(); 13686 else { 13687 SmallString<32> Str; 13688 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13689 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13690 << op->getSourceRange() 13691 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13692 } 13693 } 13694 13695 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13696 if (isa<CXXDestructorDecl>(MD)) 13697 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13698 13699 QualType MPTy = Context.getMemberPointerType( 13700 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13701 // Under the MS ABI, lock down the inheritance model now. 13702 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13703 (void)isCompleteType(OpLoc, MPTy); 13704 return MPTy; 13705 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13706 // C99 6.5.3.2p1 13707 // The operand must be either an l-value or a function designator 13708 if (!op->getType()->isFunctionType()) { 13709 // Use a special diagnostic for loads from property references. 13710 if (isa<PseudoObjectExpr>(op)) { 13711 AddressOfError = AO_Property_Expansion; 13712 } else { 13713 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13714 << op->getType() << op->getSourceRange(); 13715 return QualType(); 13716 } 13717 } 13718 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13719 // The operand cannot be a bit-field 13720 AddressOfError = AO_Bit_Field; 13721 } else if (op->getObjectKind() == OK_VectorComponent) { 13722 // The operand cannot be an element of a vector 13723 AddressOfError = AO_Vector_Element; 13724 } else if (op->getObjectKind() == OK_MatrixComponent) { 13725 // The operand cannot be an element of a matrix. 13726 AddressOfError = AO_Matrix_Element; 13727 } else if (dcl) { // C99 6.5.3.2p1 13728 // We have an lvalue with a decl. Make sure the decl is not declared 13729 // with the register storage-class specifier. 13730 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13731 // in C++ it is not error to take address of a register 13732 // variable (c++03 7.1.1P3) 13733 if (vd->getStorageClass() == SC_Register && 13734 !getLangOpts().CPlusPlus) { 13735 AddressOfError = AO_Register_Variable; 13736 } 13737 } else if (isa<MSPropertyDecl>(dcl)) { 13738 AddressOfError = AO_Property_Expansion; 13739 } else if (isa<FunctionTemplateDecl>(dcl)) { 13740 return Context.OverloadTy; 13741 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13742 // Okay: we can take the address of a field. 13743 // Could be a pointer to member, though, if there is an explicit 13744 // scope qualifier for the class. 13745 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13746 DeclContext *Ctx = dcl->getDeclContext(); 13747 if (Ctx && Ctx->isRecord()) { 13748 if (dcl->getType()->isReferenceType()) { 13749 Diag(OpLoc, 13750 diag::err_cannot_form_pointer_to_member_of_reference_type) 13751 << dcl->getDeclName() << dcl->getType(); 13752 return QualType(); 13753 } 13754 13755 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13756 Ctx = Ctx->getParent(); 13757 13758 QualType MPTy = Context.getMemberPointerType( 13759 op->getType(), 13760 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13761 // Under the MS ABI, lock down the inheritance model now. 13762 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13763 (void)isCompleteType(OpLoc, MPTy); 13764 return MPTy; 13765 } 13766 } 13767 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13768 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13769 llvm_unreachable("Unknown/unexpected decl type"); 13770 } 13771 13772 if (AddressOfError != AO_No_Error) { 13773 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13774 return QualType(); 13775 } 13776 13777 if (lval == Expr::LV_IncompleteVoidType) { 13778 // Taking the address of a void variable is technically illegal, but we 13779 // allow it in cases which are otherwise valid. 13780 // Example: "extern void x; void* y = &x;". 13781 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13782 } 13783 13784 // If the operand has type "type", the result has type "pointer to type". 13785 if (op->getType()->isObjCObjectType()) 13786 return Context.getObjCObjectPointerType(op->getType()); 13787 13788 CheckAddressOfPackedMember(op); 13789 13790 return Context.getPointerType(op->getType()); 13791 } 13792 13793 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13794 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13795 if (!DRE) 13796 return; 13797 const Decl *D = DRE->getDecl(); 13798 if (!D) 13799 return; 13800 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13801 if (!Param) 13802 return; 13803 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13804 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13805 return; 13806 if (FunctionScopeInfo *FD = S.getCurFunction()) 13807 if (!FD->ModifiedNonNullParams.count(Param)) 13808 FD->ModifiedNonNullParams.insert(Param); 13809 } 13810 13811 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13812 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13813 SourceLocation OpLoc) { 13814 if (Op->isTypeDependent()) 13815 return S.Context.DependentTy; 13816 13817 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13818 if (ConvResult.isInvalid()) 13819 return QualType(); 13820 Op = ConvResult.get(); 13821 QualType OpTy = Op->getType(); 13822 QualType Result; 13823 13824 if (isa<CXXReinterpretCastExpr>(Op)) { 13825 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13826 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13827 Op->getSourceRange()); 13828 } 13829 13830 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13831 { 13832 Result = PT->getPointeeType(); 13833 } 13834 else if (const ObjCObjectPointerType *OPT = 13835 OpTy->getAs<ObjCObjectPointerType>()) 13836 Result = OPT->getPointeeType(); 13837 else { 13838 ExprResult PR = S.CheckPlaceholderExpr(Op); 13839 if (PR.isInvalid()) return QualType(); 13840 if (PR.get() != Op) 13841 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13842 } 13843 13844 if (Result.isNull()) { 13845 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13846 << OpTy << Op->getSourceRange(); 13847 return QualType(); 13848 } 13849 13850 // Note that per both C89 and C99, indirection is always legal, even if Result 13851 // is an incomplete type or void. It would be possible to warn about 13852 // dereferencing a void pointer, but it's completely well-defined, and such a 13853 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13854 // for pointers to 'void' but is fine for any other pointer type: 13855 // 13856 // C++ [expr.unary.op]p1: 13857 // [...] the expression to which [the unary * operator] is applied shall 13858 // be a pointer to an object type, or a pointer to a function type 13859 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13860 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13861 << OpTy << Op->getSourceRange(); 13862 13863 // Dereferences are usually l-values... 13864 VK = VK_LValue; 13865 13866 // ...except that certain expressions are never l-values in C. 13867 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13868 VK = VK_PRValue; 13869 13870 return Result; 13871 } 13872 13873 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13874 BinaryOperatorKind Opc; 13875 switch (Kind) { 13876 default: llvm_unreachable("Unknown binop!"); 13877 case tok::periodstar: Opc = BO_PtrMemD; break; 13878 case tok::arrowstar: Opc = BO_PtrMemI; break; 13879 case tok::star: Opc = BO_Mul; break; 13880 case tok::slash: Opc = BO_Div; break; 13881 case tok::percent: Opc = BO_Rem; break; 13882 case tok::plus: Opc = BO_Add; break; 13883 case tok::minus: Opc = BO_Sub; break; 13884 case tok::lessless: Opc = BO_Shl; break; 13885 case tok::greatergreater: Opc = BO_Shr; break; 13886 case tok::lessequal: Opc = BO_LE; break; 13887 case tok::less: Opc = BO_LT; break; 13888 case tok::greaterequal: Opc = BO_GE; break; 13889 case tok::greater: Opc = BO_GT; break; 13890 case tok::exclaimequal: Opc = BO_NE; break; 13891 case tok::equalequal: Opc = BO_EQ; break; 13892 case tok::spaceship: Opc = BO_Cmp; break; 13893 case tok::amp: Opc = BO_And; break; 13894 case tok::caret: Opc = BO_Xor; break; 13895 case tok::pipe: Opc = BO_Or; break; 13896 case tok::ampamp: Opc = BO_LAnd; break; 13897 case tok::pipepipe: Opc = BO_LOr; break; 13898 case tok::equal: Opc = BO_Assign; break; 13899 case tok::starequal: Opc = BO_MulAssign; break; 13900 case tok::slashequal: Opc = BO_DivAssign; break; 13901 case tok::percentequal: Opc = BO_RemAssign; break; 13902 case tok::plusequal: Opc = BO_AddAssign; break; 13903 case tok::minusequal: Opc = BO_SubAssign; break; 13904 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13905 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13906 case tok::ampequal: Opc = BO_AndAssign; break; 13907 case tok::caretequal: Opc = BO_XorAssign; break; 13908 case tok::pipeequal: Opc = BO_OrAssign; break; 13909 case tok::comma: Opc = BO_Comma; break; 13910 } 13911 return Opc; 13912 } 13913 13914 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13915 tok::TokenKind Kind) { 13916 UnaryOperatorKind Opc; 13917 switch (Kind) { 13918 default: llvm_unreachable("Unknown unary op!"); 13919 case tok::plusplus: Opc = UO_PreInc; break; 13920 case tok::minusminus: Opc = UO_PreDec; break; 13921 case tok::amp: Opc = UO_AddrOf; break; 13922 case tok::star: Opc = UO_Deref; break; 13923 case tok::plus: Opc = UO_Plus; break; 13924 case tok::minus: Opc = UO_Minus; break; 13925 case tok::tilde: Opc = UO_Not; break; 13926 case tok::exclaim: Opc = UO_LNot; break; 13927 case tok::kw___real: Opc = UO_Real; break; 13928 case tok::kw___imag: Opc = UO_Imag; break; 13929 case tok::kw___extension__: Opc = UO_Extension; break; 13930 } 13931 return Opc; 13932 } 13933 13934 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13935 /// This warning suppressed in the event of macro expansions. 13936 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13937 SourceLocation OpLoc, bool IsBuiltin) { 13938 if (S.inTemplateInstantiation()) 13939 return; 13940 if (S.isUnevaluatedContext()) 13941 return; 13942 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13943 return; 13944 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13945 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13946 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13947 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13948 if (!LHSDeclRef || !RHSDeclRef || 13949 LHSDeclRef->getLocation().isMacroID() || 13950 RHSDeclRef->getLocation().isMacroID()) 13951 return; 13952 const ValueDecl *LHSDecl = 13953 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13954 const ValueDecl *RHSDecl = 13955 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13956 if (LHSDecl != RHSDecl) 13957 return; 13958 if (LHSDecl->getType().isVolatileQualified()) 13959 return; 13960 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13961 if (RefTy->getPointeeType().isVolatileQualified()) 13962 return; 13963 13964 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13965 : diag::warn_self_assignment_overloaded) 13966 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13967 << RHSExpr->getSourceRange(); 13968 } 13969 13970 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13971 /// is usually indicative of introspection within the Objective-C pointer. 13972 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13973 SourceLocation OpLoc) { 13974 if (!S.getLangOpts().ObjC) 13975 return; 13976 13977 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13978 const Expr *LHS = L.get(); 13979 const Expr *RHS = R.get(); 13980 13981 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13982 ObjCPointerExpr = LHS; 13983 OtherExpr = RHS; 13984 } 13985 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13986 ObjCPointerExpr = RHS; 13987 OtherExpr = LHS; 13988 } 13989 13990 // This warning is deliberately made very specific to reduce false 13991 // positives with logic that uses '&' for hashing. This logic mainly 13992 // looks for code trying to introspect into tagged pointers, which 13993 // code should generally never do. 13994 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13995 unsigned Diag = diag::warn_objc_pointer_masking; 13996 // Determine if we are introspecting the result of performSelectorXXX. 13997 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13998 // Special case messages to -performSelector and friends, which 13999 // can return non-pointer values boxed in a pointer value. 14000 // Some clients may wish to silence warnings in this subcase. 14001 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14002 Selector S = ME->getSelector(); 14003 StringRef SelArg0 = S.getNameForSlot(0); 14004 if (SelArg0.startswith("performSelector")) 14005 Diag = diag::warn_objc_pointer_masking_performSelector; 14006 } 14007 14008 S.Diag(OpLoc, Diag) 14009 << ObjCPointerExpr->getSourceRange(); 14010 } 14011 } 14012 14013 static NamedDecl *getDeclFromExpr(Expr *E) { 14014 if (!E) 14015 return nullptr; 14016 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14017 return DRE->getDecl(); 14018 if (auto *ME = dyn_cast<MemberExpr>(E)) 14019 return ME->getMemberDecl(); 14020 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14021 return IRE->getDecl(); 14022 return nullptr; 14023 } 14024 14025 // This helper function promotes a binary operator's operands (which are of a 14026 // half vector type) to a vector of floats and then truncates the result to 14027 // a vector of either half or short. 14028 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14029 BinaryOperatorKind Opc, QualType ResultTy, 14030 ExprValueKind VK, ExprObjectKind OK, 14031 bool IsCompAssign, SourceLocation OpLoc, 14032 FPOptionsOverride FPFeatures) { 14033 auto &Context = S.getASTContext(); 14034 assert((isVector(ResultTy, Context.HalfTy) || 14035 isVector(ResultTy, Context.ShortTy)) && 14036 "Result must be a vector of half or short"); 14037 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14038 isVector(RHS.get()->getType(), Context.HalfTy) && 14039 "both operands expected to be a half vector"); 14040 14041 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14042 QualType BinOpResTy = RHS.get()->getType(); 14043 14044 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14045 // change BinOpResTy to a vector of ints. 14046 if (isVector(ResultTy, Context.ShortTy)) 14047 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14048 14049 if (IsCompAssign) 14050 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14051 ResultTy, VK, OK, OpLoc, FPFeatures, 14052 BinOpResTy, BinOpResTy); 14053 14054 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14055 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14056 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14057 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14058 } 14059 14060 static std::pair<ExprResult, ExprResult> 14061 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14062 Expr *RHSExpr) { 14063 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14064 if (!S.Context.isDependenceAllowed()) { 14065 // C cannot handle TypoExpr nodes on either side of a binop because it 14066 // doesn't handle dependent types properly, so make sure any TypoExprs have 14067 // been dealt with before checking the operands. 14068 LHS = S.CorrectDelayedTyposInExpr(LHS); 14069 RHS = S.CorrectDelayedTyposInExpr( 14070 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14071 [Opc, LHS](Expr *E) { 14072 if (Opc != BO_Assign) 14073 return ExprResult(E); 14074 // Avoid correcting the RHS to the same Expr as the LHS. 14075 Decl *D = getDeclFromExpr(E); 14076 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14077 }); 14078 } 14079 return std::make_pair(LHS, RHS); 14080 } 14081 14082 /// Returns true if conversion between vectors of halfs and vectors of floats 14083 /// is needed. 14084 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14085 Expr *E0, Expr *E1 = nullptr) { 14086 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14087 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14088 return false; 14089 14090 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14091 QualType Ty = E->IgnoreImplicit()->getType(); 14092 14093 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14094 // to vectors of floats. Although the element type of the vectors is __fp16, 14095 // the vectors shouldn't be treated as storage-only types. See the 14096 // discussion here: https://reviews.llvm.org/rG825235c140e7 14097 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14098 if (VT->getVectorKind() == VectorType::NeonVector) 14099 return false; 14100 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14101 } 14102 return false; 14103 }; 14104 14105 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14106 } 14107 14108 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14109 /// operator @p Opc at location @c TokLoc. This routine only supports 14110 /// built-in operations; ActOnBinOp handles overloaded operators. 14111 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14112 BinaryOperatorKind Opc, 14113 Expr *LHSExpr, Expr *RHSExpr) { 14114 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14115 // The syntax only allows initializer lists on the RHS of assignment, 14116 // so we don't need to worry about accepting invalid code for 14117 // non-assignment operators. 14118 // C++11 5.17p9: 14119 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14120 // of x = {} is x = T(). 14121 InitializationKind Kind = InitializationKind::CreateDirectList( 14122 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14123 InitializedEntity Entity = 14124 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14125 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14126 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14127 if (Init.isInvalid()) 14128 return Init; 14129 RHSExpr = Init.get(); 14130 } 14131 14132 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14133 QualType ResultTy; // Result type of the binary operator. 14134 // The following two variables are used for compound assignment operators 14135 QualType CompLHSTy; // Type of LHS after promotions for computation 14136 QualType CompResultTy; // Type of computation result 14137 ExprValueKind VK = VK_PRValue; 14138 ExprObjectKind OK = OK_Ordinary; 14139 bool ConvertHalfVec = false; 14140 14141 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14142 if (!LHS.isUsable() || !RHS.isUsable()) 14143 return ExprError(); 14144 14145 if (getLangOpts().OpenCL) { 14146 QualType LHSTy = LHSExpr->getType(); 14147 QualType RHSTy = RHSExpr->getType(); 14148 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14149 // the ATOMIC_VAR_INIT macro. 14150 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14151 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14152 if (BO_Assign == Opc) 14153 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14154 else 14155 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14156 return ExprError(); 14157 } 14158 14159 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14160 // only with a builtin functions and therefore should be disallowed here. 14161 if (LHSTy->isImageType() || RHSTy->isImageType() || 14162 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14163 LHSTy->isPipeType() || RHSTy->isPipeType() || 14164 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14165 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14166 return ExprError(); 14167 } 14168 } 14169 14170 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14171 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14172 14173 switch (Opc) { 14174 case BO_Assign: 14175 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14176 if (getLangOpts().CPlusPlus && 14177 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14178 VK = LHS.get()->getValueKind(); 14179 OK = LHS.get()->getObjectKind(); 14180 } 14181 if (!ResultTy.isNull()) { 14182 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14183 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14184 14185 // Avoid copying a block to the heap if the block is assigned to a local 14186 // auto variable that is declared in the same scope as the block. This 14187 // optimization is unsafe if the local variable is declared in an outer 14188 // scope. For example: 14189 // 14190 // BlockTy b; 14191 // { 14192 // b = ^{...}; 14193 // } 14194 // // It is unsafe to invoke the block here if it wasn't copied to the 14195 // // heap. 14196 // b(); 14197 14198 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14199 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14200 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14201 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14202 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14203 14204 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14205 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14206 NTCUC_Assignment, NTCUK_Copy); 14207 } 14208 RecordModifiableNonNullParam(*this, LHS.get()); 14209 break; 14210 case BO_PtrMemD: 14211 case BO_PtrMemI: 14212 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14213 Opc == BO_PtrMemI); 14214 break; 14215 case BO_Mul: 14216 case BO_Div: 14217 ConvertHalfVec = true; 14218 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14219 Opc == BO_Div); 14220 break; 14221 case BO_Rem: 14222 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14223 break; 14224 case BO_Add: 14225 ConvertHalfVec = true; 14226 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14227 break; 14228 case BO_Sub: 14229 ConvertHalfVec = true; 14230 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14231 break; 14232 case BO_Shl: 14233 case BO_Shr: 14234 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14235 break; 14236 case BO_LE: 14237 case BO_LT: 14238 case BO_GE: 14239 case BO_GT: 14240 ConvertHalfVec = true; 14241 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14242 break; 14243 case BO_EQ: 14244 case BO_NE: 14245 ConvertHalfVec = true; 14246 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14247 break; 14248 case BO_Cmp: 14249 ConvertHalfVec = true; 14250 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14251 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14252 break; 14253 case BO_And: 14254 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14255 LLVM_FALLTHROUGH; 14256 case BO_Xor: 14257 case BO_Or: 14258 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14259 break; 14260 case BO_LAnd: 14261 case BO_LOr: 14262 ConvertHalfVec = true; 14263 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14264 break; 14265 case BO_MulAssign: 14266 case BO_DivAssign: 14267 ConvertHalfVec = true; 14268 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14269 Opc == BO_DivAssign); 14270 CompLHSTy = CompResultTy; 14271 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14272 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14273 break; 14274 case BO_RemAssign: 14275 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14276 CompLHSTy = CompResultTy; 14277 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14278 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14279 break; 14280 case BO_AddAssign: 14281 ConvertHalfVec = true; 14282 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14283 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14284 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14285 break; 14286 case BO_SubAssign: 14287 ConvertHalfVec = true; 14288 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14289 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14290 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14291 break; 14292 case BO_ShlAssign: 14293 case BO_ShrAssign: 14294 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14295 CompLHSTy = CompResultTy; 14296 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14297 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14298 break; 14299 case BO_AndAssign: 14300 case BO_OrAssign: // fallthrough 14301 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14302 LLVM_FALLTHROUGH; 14303 case BO_XorAssign: 14304 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14305 CompLHSTy = CompResultTy; 14306 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14307 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14308 break; 14309 case BO_Comma: 14310 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14311 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14312 VK = RHS.get()->getValueKind(); 14313 OK = RHS.get()->getObjectKind(); 14314 } 14315 break; 14316 } 14317 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14318 return ExprError(); 14319 14320 // Some of the binary operations require promoting operands of half vector to 14321 // float vectors and truncating the result back to half vector. For now, we do 14322 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14323 // arm64). 14324 assert( 14325 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14326 isVector(LHS.get()->getType(), Context.HalfTy)) && 14327 "both sides are half vectors or neither sides are"); 14328 ConvertHalfVec = 14329 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14330 14331 // Check for array bounds violations for both sides of the BinaryOperator 14332 CheckArrayAccess(LHS.get()); 14333 CheckArrayAccess(RHS.get()); 14334 14335 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14336 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14337 &Context.Idents.get("object_setClass"), 14338 SourceLocation(), LookupOrdinaryName); 14339 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14340 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14341 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14342 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14343 "object_setClass(") 14344 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14345 ",") 14346 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14347 } 14348 else 14349 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14350 } 14351 else if (const ObjCIvarRefExpr *OIRE = 14352 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14353 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14354 14355 // Opc is not a compound assignment if CompResultTy is null. 14356 if (CompResultTy.isNull()) { 14357 if (ConvertHalfVec) 14358 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14359 OpLoc, CurFPFeatureOverrides()); 14360 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14361 VK, OK, OpLoc, CurFPFeatureOverrides()); 14362 } 14363 14364 // Handle compound assignments. 14365 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14366 OK_ObjCProperty) { 14367 VK = VK_LValue; 14368 OK = LHS.get()->getObjectKind(); 14369 } 14370 14371 // The LHS is not converted to the result type for fixed-point compound 14372 // assignment as the common type is computed on demand. Reset the CompLHSTy 14373 // to the LHS type we would have gotten after unary conversions. 14374 if (CompResultTy->isFixedPointType()) 14375 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14376 14377 if (ConvertHalfVec) 14378 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14379 OpLoc, CurFPFeatureOverrides()); 14380 14381 return CompoundAssignOperator::Create( 14382 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14383 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14384 } 14385 14386 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14387 /// operators are mixed in a way that suggests that the programmer forgot that 14388 /// comparison operators have higher precedence. The most typical example of 14389 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14390 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14391 SourceLocation OpLoc, Expr *LHSExpr, 14392 Expr *RHSExpr) { 14393 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14394 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14395 14396 // Check that one of the sides is a comparison operator and the other isn't. 14397 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14398 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14399 if (isLeftComp == isRightComp) 14400 return; 14401 14402 // Bitwise operations are sometimes used as eager logical ops. 14403 // Don't diagnose this. 14404 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14405 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14406 if (isLeftBitwise || isRightBitwise) 14407 return; 14408 14409 SourceRange DiagRange = isLeftComp 14410 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14411 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14412 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14413 SourceRange ParensRange = 14414 isLeftComp 14415 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14416 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14417 14418 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14419 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14420 SuggestParentheses(Self, OpLoc, 14421 Self.PDiag(diag::note_precedence_silence) << OpStr, 14422 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14423 SuggestParentheses(Self, OpLoc, 14424 Self.PDiag(diag::note_precedence_bitwise_first) 14425 << BinaryOperator::getOpcodeStr(Opc), 14426 ParensRange); 14427 } 14428 14429 /// It accepts a '&&' expr that is inside a '||' one. 14430 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14431 /// in parentheses. 14432 static void 14433 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14434 BinaryOperator *Bop) { 14435 assert(Bop->getOpcode() == BO_LAnd); 14436 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14437 << Bop->getSourceRange() << OpLoc; 14438 SuggestParentheses(Self, Bop->getOperatorLoc(), 14439 Self.PDiag(diag::note_precedence_silence) 14440 << Bop->getOpcodeStr(), 14441 Bop->getSourceRange()); 14442 } 14443 14444 /// Returns true if the given expression can be evaluated as a constant 14445 /// 'true'. 14446 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14447 bool Res; 14448 return !E->isValueDependent() && 14449 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14450 } 14451 14452 /// Returns true if the given expression can be evaluated as a constant 14453 /// 'false'. 14454 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14455 bool Res; 14456 return !E->isValueDependent() && 14457 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14458 } 14459 14460 /// Look for '&&' in the left hand of a '||' expr. 14461 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14462 Expr *LHSExpr, Expr *RHSExpr) { 14463 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14464 if (Bop->getOpcode() == BO_LAnd) { 14465 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14466 if (EvaluatesAsFalse(S, RHSExpr)) 14467 return; 14468 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14469 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14470 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14471 } else if (Bop->getOpcode() == BO_LOr) { 14472 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14473 // If it's "a || b && 1 || c" we didn't warn earlier for 14474 // "a || b && 1", but warn now. 14475 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14476 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14477 } 14478 } 14479 } 14480 } 14481 14482 /// Look for '&&' in the right hand of a '||' expr. 14483 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14484 Expr *LHSExpr, Expr *RHSExpr) { 14485 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14486 if (Bop->getOpcode() == BO_LAnd) { 14487 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14488 if (EvaluatesAsFalse(S, LHSExpr)) 14489 return; 14490 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14491 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14492 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14493 } 14494 } 14495 } 14496 14497 /// Look for bitwise op in the left or right hand of a bitwise op with 14498 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14499 /// the '&' expression in parentheses. 14500 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14501 SourceLocation OpLoc, Expr *SubExpr) { 14502 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14503 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14504 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14505 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14506 << Bop->getSourceRange() << OpLoc; 14507 SuggestParentheses(S, Bop->getOperatorLoc(), 14508 S.PDiag(diag::note_precedence_silence) 14509 << Bop->getOpcodeStr(), 14510 Bop->getSourceRange()); 14511 } 14512 } 14513 } 14514 14515 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14516 Expr *SubExpr, StringRef Shift) { 14517 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14518 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14519 StringRef Op = Bop->getOpcodeStr(); 14520 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14521 << Bop->getSourceRange() << OpLoc << Shift << Op; 14522 SuggestParentheses(S, Bop->getOperatorLoc(), 14523 S.PDiag(diag::note_precedence_silence) << Op, 14524 Bop->getSourceRange()); 14525 } 14526 } 14527 } 14528 14529 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14530 Expr *LHSExpr, Expr *RHSExpr) { 14531 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14532 if (!OCE) 14533 return; 14534 14535 FunctionDecl *FD = OCE->getDirectCallee(); 14536 if (!FD || !FD->isOverloadedOperator()) 14537 return; 14538 14539 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14540 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14541 return; 14542 14543 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14544 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14545 << (Kind == OO_LessLess); 14546 SuggestParentheses(S, OCE->getOperatorLoc(), 14547 S.PDiag(diag::note_precedence_silence) 14548 << (Kind == OO_LessLess ? "<<" : ">>"), 14549 OCE->getSourceRange()); 14550 SuggestParentheses( 14551 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14552 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14553 } 14554 14555 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14556 /// precedence. 14557 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14558 SourceLocation OpLoc, Expr *LHSExpr, 14559 Expr *RHSExpr){ 14560 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14561 if (BinaryOperator::isBitwiseOp(Opc)) 14562 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14563 14564 // Diagnose "arg1 & arg2 | arg3" 14565 if ((Opc == BO_Or || Opc == BO_Xor) && 14566 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14567 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14568 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14569 } 14570 14571 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14572 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14573 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14574 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14575 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14576 } 14577 14578 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14579 || Opc == BO_Shr) { 14580 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14581 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14582 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14583 } 14584 14585 // Warn on overloaded shift operators and comparisons, such as: 14586 // cout << 5 == 4; 14587 if (BinaryOperator::isComparisonOp(Opc)) 14588 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14589 } 14590 14591 // Binary Operators. 'Tok' is the token for the operator. 14592 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14593 tok::TokenKind Kind, 14594 Expr *LHSExpr, Expr *RHSExpr) { 14595 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14596 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14597 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14598 14599 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14600 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14601 14602 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14603 } 14604 14605 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14606 UnresolvedSetImpl &Functions) { 14607 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14608 if (OverOp != OO_None && OverOp != OO_Equal) 14609 LookupOverloadedOperatorName(OverOp, S, Functions); 14610 14611 // In C++20 onwards, we may have a second operator to look up. 14612 if (getLangOpts().CPlusPlus20) { 14613 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14614 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14615 } 14616 } 14617 14618 /// Build an overloaded binary operator expression in the given scope. 14619 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14620 BinaryOperatorKind Opc, 14621 Expr *LHS, Expr *RHS) { 14622 switch (Opc) { 14623 case BO_Assign: 14624 case BO_DivAssign: 14625 case BO_RemAssign: 14626 case BO_SubAssign: 14627 case BO_AndAssign: 14628 case BO_OrAssign: 14629 case BO_XorAssign: 14630 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14631 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14632 break; 14633 default: 14634 break; 14635 } 14636 14637 // Find all of the overloaded operators visible from this point. 14638 UnresolvedSet<16> Functions; 14639 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14640 14641 // Build the (potentially-overloaded, potentially-dependent) 14642 // binary operation. 14643 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14644 } 14645 14646 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14647 BinaryOperatorKind Opc, 14648 Expr *LHSExpr, Expr *RHSExpr) { 14649 ExprResult LHS, RHS; 14650 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14651 if (!LHS.isUsable() || !RHS.isUsable()) 14652 return ExprError(); 14653 LHSExpr = LHS.get(); 14654 RHSExpr = RHS.get(); 14655 14656 // We want to end up calling one of checkPseudoObjectAssignment 14657 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14658 // both expressions are overloadable or either is type-dependent), 14659 // or CreateBuiltinBinOp (in any other case). We also want to get 14660 // any placeholder types out of the way. 14661 14662 // Handle pseudo-objects in the LHS. 14663 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14664 // Assignments with a pseudo-object l-value need special analysis. 14665 if (pty->getKind() == BuiltinType::PseudoObject && 14666 BinaryOperator::isAssignmentOp(Opc)) 14667 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14668 14669 // Don't resolve overloads if the other type is overloadable. 14670 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14671 // We can't actually test that if we still have a placeholder, 14672 // though. Fortunately, none of the exceptions we see in that 14673 // code below are valid when the LHS is an overload set. Note 14674 // that an overload set can be dependently-typed, but it never 14675 // instantiates to having an overloadable type. 14676 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14677 if (resolvedRHS.isInvalid()) return ExprError(); 14678 RHSExpr = resolvedRHS.get(); 14679 14680 if (RHSExpr->isTypeDependent() || 14681 RHSExpr->getType()->isOverloadableType()) 14682 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14683 } 14684 14685 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14686 // template, diagnose the missing 'template' keyword instead of diagnosing 14687 // an invalid use of a bound member function. 14688 // 14689 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14690 // to C++1z [over.over]/1.4, but we already checked for that case above. 14691 if (Opc == BO_LT && inTemplateInstantiation() && 14692 (pty->getKind() == BuiltinType::BoundMember || 14693 pty->getKind() == BuiltinType::Overload)) { 14694 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14695 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14696 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14697 return isa<FunctionTemplateDecl>(ND); 14698 })) { 14699 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14700 : OE->getNameLoc(), 14701 diag::err_template_kw_missing) 14702 << OE->getName().getAsString() << ""; 14703 return ExprError(); 14704 } 14705 } 14706 14707 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14708 if (LHS.isInvalid()) return ExprError(); 14709 LHSExpr = LHS.get(); 14710 } 14711 14712 // Handle pseudo-objects in the RHS. 14713 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14714 // An overload in the RHS can potentially be resolved by the type 14715 // being assigned to. 14716 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14717 if (getLangOpts().CPlusPlus && 14718 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14719 LHSExpr->getType()->isOverloadableType())) 14720 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14721 14722 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14723 } 14724 14725 // Don't resolve overloads if the other type is overloadable. 14726 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14727 LHSExpr->getType()->isOverloadableType()) 14728 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14729 14730 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14731 if (!resolvedRHS.isUsable()) return ExprError(); 14732 RHSExpr = resolvedRHS.get(); 14733 } 14734 14735 if (getLangOpts().CPlusPlus) { 14736 // If either expression is type-dependent, always build an 14737 // overloaded op. 14738 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14739 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14740 14741 // Otherwise, build an overloaded op if either expression has an 14742 // overloadable type. 14743 if (LHSExpr->getType()->isOverloadableType() || 14744 RHSExpr->getType()->isOverloadableType()) 14745 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14746 } 14747 14748 if (getLangOpts().RecoveryAST && 14749 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14750 assert(!getLangOpts().CPlusPlus); 14751 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14752 "Should only occur in error-recovery path."); 14753 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14754 // C [6.15.16] p3: 14755 // An assignment expression has the value of the left operand after the 14756 // assignment, but is not an lvalue. 14757 return CompoundAssignOperator::Create( 14758 Context, LHSExpr, RHSExpr, Opc, 14759 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14760 OpLoc, CurFPFeatureOverrides()); 14761 QualType ResultType; 14762 switch (Opc) { 14763 case BO_Assign: 14764 ResultType = LHSExpr->getType().getUnqualifiedType(); 14765 break; 14766 case BO_LT: 14767 case BO_GT: 14768 case BO_LE: 14769 case BO_GE: 14770 case BO_EQ: 14771 case BO_NE: 14772 case BO_LAnd: 14773 case BO_LOr: 14774 // These operators have a fixed result type regardless of operands. 14775 ResultType = Context.IntTy; 14776 break; 14777 case BO_Comma: 14778 ResultType = RHSExpr->getType(); 14779 break; 14780 default: 14781 ResultType = Context.DependentTy; 14782 break; 14783 } 14784 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14785 VK_PRValue, OK_Ordinary, OpLoc, 14786 CurFPFeatureOverrides()); 14787 } 14788 14789 // Build a built-in binary operation. 14790 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14791 } 14792 14793 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14794 if (T.isNull() || T->isDependentType()) 14795 return false; 14796 14797 if (!T->isPromotableIntegerType()) 14798 return true; 14799 14800 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14801 } 14802 14803 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14804 UnaryOperatorKind Opc, 14805 Expr *InputExpr) { 14806 ExprResult Input = InputExpr; 14807 ExprValueKind VK = VK_PRValue; 14808 ExprObjectKind OK = OK_Ordinary; 14809 QualType resultType; 14810 bool CanOverflow = false; 14811 14812 bool ConvertHalfVec = false; 14813 if (getLangOpts().OpenCL) { 14814 QualType Ty = InputExpr->getType(); 14815 // The only legal unary operation for atomics is '&'. 14816 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14817 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14818 // only with a builtin functions and therefore should be disallowed here. 14819 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14820 || Ty->isBlockPointerType())) { 14821 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14822 << InputExpr->getType() 14823 << Input.get()->getSourceRange()); 14824 } 14825 } 14826 14827 switch (Opc) { 14828 case UO_PreInc: 14829 case UO_PreDec: 14830 case UO_PostInc: 14831 case UO_PostDec: 14832 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14833 OpLoc, 14834 Opc == UO_PreInc || 14835 Opc == UO_PostInc, 14836 Opc == UO_PreInc || 14837 Opc == UO_PreDec); 14838 CanOverflow = isOverflowingIntegerType(Context, resultType); 14839 break; 14840 case UO_AddrOf: 14841 resultType = CheckAddressOfOperand(Input, OpLoc); 14842 CheckAddressOfNoDeref(InputExpr); 14843 RecordModifiableNonNullParam(*this, InputExpr); 14844 break; 14845 case UO_Deref: { 14846 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14847 if (Input.isInvalid()) return ExprError(); 14848 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14849 break; 14850 } 14851 case UO_Plus: 14852 case UO_Minus: 14853 CanOverflow = Opc == UO_Minus && 14854 isOverflowingIntegerType(Context, Input.get()->getType()); 14855 Input = UsualUnaryConversions(Input.get()); 14856 if (Input.isInvalid()) return ExprError(); 14857 // Unary plus and minus require promoting an operand of half vector to a 14858 // float vector and truncating the result back to a half vector. For now, we 14859 // do this only when HalfArgsAndReturns is set (that is, when the target is 14860 // arm or arm64). 14861 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14862 14863 // If the operand is a half vector, promote it to a float vector. 14864 if (ConvertHalfVec) 14865 Input = convertVector(Input.get(), Context.FloatTy, *this); 14866 resultType = Input.get()->getType(); 14867 if (resultType->isDependentType()) 14868 break; 14869 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14870 break; 14871 else if (resultType->isVectorType() && 14872 // The z vector extensions don't allow + or - with bool vectors. 14873 (!Context.getLangOpts().ZVector || 14874 resultType->castAs<VectorType>()->getVectorKind() != 14875 VectorType::AltiVecBool)) 14876 break; 14877 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14878 Opc == UO_Plus && 14879 resultType->isPointerType()) 14880 break; 14881 14882 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14883 << resultType << Input.get()->getSourceRange()); 14884 14885 case UO_Not: // bitwise complement 14886 Input = UsualUnaryConversions(Input.get()); 14887 if (Input.isInvalid()) 14888 return ExprError(); 14889 resultType = Input.get()->getType(); 14890 if (resultType->isDependentType()) 14891 break; 14892 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14893 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14894 // C99 does not support '~' for complex conjugation. 14895 Diag(OpLoc, diag::ext_integer_complement_complex) 14896 << resultType << Input.get()->getSourceRange(); 14897 else if (resultType->hasIntegerRepresentation()) 14898 break; 14899 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14900 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14901 // on vector float types. 14902 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14903 if (!T->isIntegerType()) 14904 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14905 << resultType << Input.get()->getSourceRange()); 14906 } else { 14907 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14908 << resultType << Input.get()->getSourceRange()); 14909 } 14910 break; 14911 14912 case UO_LNot: // logical negation 14913 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14914 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14915 if (Input.isInvalid()) return ExprError(); 14916 resultType = Input.get()->getType(); 14917 14918 // Though we still have to promote half FP to float... 14919 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14920 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14921 resultType = Context.FloatTy; 14922 } 14923 14924 if (resultType->isDependentType()) 14925 break; 14926 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14927 // C99 6.5.3.3p1: ok, fallthrough; 14928 if (Context.getLangOpts().CPlusPlus) { 14929 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14930 // operand contextually converted to bool. 14931 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14932 ScalarTypeToBooleanCastKind(resultType)); 14933 } else if (Context.getLangOpts().OpenCL && 14934 Context.getLangOpts().OpenCLVersion < 120) { 14935 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14936 // operate on scalar float types. 14937 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14938 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14939 << resultType << Input.get()->getSourceRange()); 14940 } 14941 } else if (resultType->isExtVectorType()) { 14942 if (Context.getLangOpts().OpenCL && 14943 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 14944 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14945 // operate on vector float types. 14946 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14947 if (!T->isIntegerType()) 14948 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14949 << resultType << Input.get()->getSourceRange()); 14950 } 14951 // Vector logical not returns the signed variant of the operand type. 14952 resultType = GetSignedVectorType(resultType); 14953 break; 14954 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14955 const VectorType *VTy = resultType->castAs<VectorType>(); 14956 if (VTy->getVectorKind() != VectorType::GenericVector) 14957 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14958 << resultType << Input.get()->getSourceRange()); 14959 14960 // Vector logical not returns the signed variant of the operand type. 14961 resultType = GetSignedVectorType(resultType); 14962 break; 14963 } else { 14964 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14965 << resultType << Input.get()->getSourceRange()); 14966 } 14967 14968 // LNot always has type int. C99 6.5.3.3p5. 14969 // In C++, it's bool. C++ 5.3.1p8 14970 resultType = Context.getLogicalOperationType(); 14971 break; 14972 case UO_Real: 14973 case UO_Imag: 14974 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14975 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14976 // complex l-values to ordinary l-values and all other values to r-values. 14977 if (Input.isInvalid()) return ExprError(); 14978 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14979 if (Input.get()->isGLValue() && 14980 Input.get()->getObjectKind() == OK_Ordinary) 14981 VK = Input.get()->getValueKind(); 14982 } else if (!getLangOpts().CPlusPlus) { 14983 // In C, a volatile scalar is read by __imag. In C++, it is not. 14984 Input = DefaultLvalueConversion(Input.get()); 14985 } 14986 break; 14987 case UO_Extension: 14988 resultType = Input.get()->getType(); 14989 VK = Input.get()->getValueKind(); 14990 OK = Input.get()->getObjectKind(); 14991 break; 14992 case UO_Coawait: 14993 // It's unnecessary to represent the pass-through operator co_await in the 14994 // AST; just return the input expression instead. 14995 assert(!Input.get()->getType()->isDependentType() && 14996 "the co_await expression must be non-dependant before " 14997 "building operator co_await"); 14998 return Input; 14999 } 15000 if (resultType.isNull() || Input.isInvalid()) 15001 return ExprError(); 15002 15003 // Check for array bounds violations in the operand of the UnaryOperator, 15004 // except for the '*' and '&' operators that have to be handled specially 15005 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15006 // that are explicitly defined as valid by the standard). 15007 if (Opc != UO_AddrOf && Opc != UO_Deref) 15008 CheckArrayAccess(Input.get()); 15009 15010 auto *UO = 15011 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15012 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15013 15014 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15015 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15016 !isUnevaluatedContext()) 15017 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15018 15019 // Convert the result back to a half vector. 15020 if (ConvertHalfVec) 15021 return convertVector(UO, Context.HalfTy, *this); 15022 return UO; 15023 } 15024 15025 /// Determine whether the given expression is a qualified member 15026 /// access expression, of a form that could be turned into a pointer to member 15027 /// with the address-of operator. 15028 bool Sema::isQualifiedMemberAccess(Expr *E) { 15029 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15030 if (!DRE->getQualifier()) 15031 return false; 15032 15033 ValueDecl *VD = DRE->getDecl(); 15034 if (!VD->isCXXClassMember()) 15035 return false; 15036 15037 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15038 return true; 15039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15040 return Method->isInstance(); 15041 15042 return false; 15043 } 15044 15045 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15046 if (!ULE->getQualifier()) 15047 return false; 15048 15049 for (NamedDecl *D : ULE->decls()) { 15050 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15051 if (Method->isInstance()) 15052 return true; 15053 } else { 15054 // Overload set does not contain methods. 15055 break; 15056 } 15057 } 15058 15059 return false; 15060 } 15061 15062 return false; 15063 } 15064 15065 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15066 UnaryOperatorKind Opc, Expr *Input) { 15067 // First things first: handle placeholders so that the 15068 // overloaded-operator check considers the right type. 15069 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15070 // Increment and decrement of pseudo-object references. 15071 if (pty->getKind() == BuiltinType::PseudoObject && 15072 UnaryOperator::isIncrementDecrementOp(Opc)) 15073 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15074 15075 // extension is always a builtin operator. 15076 if (Opc == UO_Extension) 15077 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15078 15079 // & gets special logic for several kinds of placeholder. 15080 // The builtin code knows what to do. 15081 if (Opc == UO_AddrOf && 15082 (pty->getKind() == BuiltinType::Overload || 15083 pty->getKind() == BuiltinType::UnknownAny || 15084 pty->getKind() == BuiltinType::BoundMember)) 15085 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15086 15087 // Anything else needs to be handled now. 15088 ExprResult Result = CheckPlaceholderExpr(Input); 15089 if (Result.isInvalid()) return ExprError(); 15090 Input = Result.get(); 15091 } 15092 15093 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15094 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15095 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15096 // Find all of the overloaded operators visible from this point. 15097 UnresolvedSet<16> Functions; 15098 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15099 if (S && OverOp != OO_None) 15100 LookupOverloadedOperatorName(OverOp, S, Functions); 15101 15102 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15103 } 15104 15105 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15106 } 15107 15108 // Unary Operators. 'Tok' is the token for the operator. 15109 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15110 tok::TokenKind Op, Expr *Input) { 15111 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15112 } 15113 15114 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15115 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15116 LabelDecl *TheDecl) { 15117 TheDecl->markUsed(Context); 15118 // Create the AST node. The address of a label always has type 'void*'. 15119 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15120 Context.getPointerType(Context.VoidTy)); 15121 } 15122 15123 void Sema::ActOnStartStmtExpr() { 15124 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15125 } 15126 15127 void Sema::ActOnStmtExprError() { 15128 // Note that function is also called by TreeTransform when leaving a 15129 // StmtExpr scope without rebuilding anything. 15130 15131 DiscardCleanupsInEvaluationContext(); 15132 PopExpressionEvaluationContext(); 15133 } 15134 15135 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15136 SourceLocation RPLoc) { 15137 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15138 } 15139 15140 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15141 SourceLocation RPLoc, unsigned TemplateDepth) { 15142 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15143 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15144 15145 if (hasAnyUnrecoverableErrorsInThisFunction()) 15146 DiscardCleanupsInEvaluationContext(); 15147 assert(!Cleanup.exprNeedsCleanups() && 15148 "cleanups within StmtExpr not correctly bound!"); 15149 PopExpressionEvaluationContext(); 15150 15151 // FIXME: there are a variety of strange constraints to enforce here, for 15152 // example, it is not possible to goto into a stmt expression apparently. 15153 // More semantic analysis is needed. 15154 15155 // If there are sub-stmts in the compound stmt, take the type of the last one 15156 // as the type of the stmtexpr. 15157 QualType Ty = Context.VoidTy; 15158 bool StmtExprMayBindToTemp = false; 15159 if (!Compound->body_empty()) { 15160 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15161 if (const auto *LastStmt = 15162 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15163 if (const Expr *Value = LastStmt->getExprStmt()) { 15164 StmtExprMayBindToTemp = true; 15165 Ty = Value->getType(); 15166 } 15167 } 15168 } 15169 15170 // FIXME: Check that expression type is complete/non-abstract; statement 15171 // expressions are not lvalues. 15172 Expr *ResStmtExpr = 15173 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15174 if (StmtExprMayBindToTemp) 15175 return MaybeBindToTemporary(ResStmtExpr); 15176 return ResStmtExpr; 15177 } 15178 15179 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15180 if (ER.isInvalid()) 15181 return ExprError(); 15182 15183 // Do function/array conversion on the last expression, but not 15184 // lvalue-to-rvalue. However, initialize an unqualified type. 15185 ER = DefaultFunctionArrayConversion(ER.get()); 15186 if (ER.isInvalid()) 15187 return ExprError(); 15188 Expr *E = ER.get(); 15189 15190 if (E->isTypeDependent()) 15191 return E; 15192 15193 // In ARC, if the final expression ends in a consume, splice 15194 // the consume out and bind it later. In the alternate case 15195 // (when dealing with a retainable type), the result 15196 // initialization will create a produce. In both cases the 15197 // result will be +1, and we'll need to balance that out with 15198 // a bind. 15199 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15200 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15201 return Cast->getSubExpr(); 15202 15203 // FIXME: Provide a better location for the initialization. 15204 return PerformCopyInitialization( 15205 InitializedEntity::InitializeStmtExprResult( 15206 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15207 SourceLocation(), E); 15208 } 15209 15210 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15211 TypeSourceInfo *TInfo, 15212 ArrayRef<OffsetOfComponent> Components, 15213 SourceLocation RParenLoc) { 15214 QualType ArgTy = TInfo->getType(); 15215 bool Dependent = ArgTy->isDependentType(); 15216 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15217 15218 // We must have at least one component that refers to the type, and the first 15219 // one is known to be a field designator. Verify that the ArgTy represents 15220 // a struct/union/class. 15221 if (!Dependent && !ArgTy->isRecordType()) 15222 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15223 << ArgTy << TypeRange); 15224 15225 // Type must be complete per C99 7.17p3 because a declaring a variable 15226 // with an incomplete type would be ill-formed. 15227 if (!Dependent 15228 && RequireCompleteType(BuiltinLoc, ArgTy, 15229 diag::err_offsetof_incomplete_type, TypeRange)) 15230 return ExprError(); 15231 15232 bool DidWarnAboutNonPOD = false; 15233 QualType CurrentType = ArgTy; 15234 SmallVector<OffsetOfNode, 4> Comps; 15235 SmallVector<Expr*, 4> Exprs; 15236 for (const OffsetOfComponent &OC : Components) { 15237 if (OC.isBrackets) { 15238 // Offset of an array sub-field. TODO: Should we allow vector elements? 15239 if (!CurrentType->isDependentType()) { 15240 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15241 if(!AT) 15242 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15243 << CurrentType); 15244 CurrentType = AT->getElementType(); 15245 } else 15246 CurrentType = Context.DependentTy; 15247 15248 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15249 if (IdxRval.isInvalid()) 15250 return ExprError(); 15251 Expr *Idx = IdxRval.get(); 15252 15253 // The expression must be an integral expression. 15254 // FIXME: An integral constant expression? 15255 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15256 !Idx->getType()->isIntegerType()) 15257 return ExprError( 15258 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15259 << Idx->getSourceRange()); 15260 15261 // Record this array index. 15262 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15263 Exprs.push_back(Idx); 15264 continue; 15265 } 15266 15267 // Offset of a field. 15268 if (CurrentType->isDependentType()) { 15269 // We have the offset of a field, but we can't look into the dependent 15270 // type. Just record the identifier of the field. 15271 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15272 CurrentType = Context.DependentTy; 15273 continue; 15274 } 15275 15276 // We need to have a complete type to look into. 15277 if (RequireCompleteType(OC.LocStart, CurrentType, 15278 diag::err_offsetof_incomplete_type)) 15279 return ExprError(); 15280 15281 // Look for the designated field. 15282 const RecordType *RC = CurrentType->getAs<RecordType>(); 15283 if (!RC) 15284 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15285 << CurrentType); 15286 RecordDecl *RD = RC->getDecl(); 15287 15288 // C++ [lib.support.types]p5: 15289 // The macro offsetof accepts a restricted set of type arguments in this 15290 // International Standard. type shall be a POD structure or a POD union 15291 // (clause 9). 15292 // C++11 [support.types]p4: 15293 // If type is not a standard-layout class (Clause 9), the results are 15294 // undefined. 15295 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15296 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15297 unsigned DiagID = 15298 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15299 : diag::ext_offsetof_non_pod_type; 15300 15301 if (!IsSafe && !DidWarnAboutNonPOD && 15302 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15303 PDiag(DiagID) 15304 << SourceRange(Components[0].LocStart, OC.LocEnd) 15305 << CurrentType)) 15306 DidWarnAboutNonPOD = true; 15307 } 15308 15309 // Look for the field. 15310 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15311 LookupQualifiedName(R, RD); 15312 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15313 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15314 if (!MemberDecl) { 15315 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15316 MemberDecl = IndirectMemberDecl->getAnonField(); 15317 } 15318 15319 if (!MemberDecl) 15320 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15321 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15322 OC.LocEnd)); 15323 15324 // C99 7.17p3: 15325 // (If the specified member is a bit-field, the behavior is undefined.) 15326 // 15327 // We diagnose this as an error. 15328 if (MemberDecl->isBitField()) { 15329 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15330 << MemberDecl->getDeclName() 15331 << SourceRange(BuiltinLoc, RParenLoc); 15332 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15333 return ExprError(); 15334 } 15335 15336 RecordDecl *Parent = MemberDecl->getParent(); 15337 if (IndirectMemberDecl) 15338 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15339 15340 // If the member was found in a base class, introduce OffsetOfNodes for 15341 // the base class indirections. 15342 CXXBasePaths Paths; 15343 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15344 Paths)) { 15345 if (Paths.getDetectedVirtual()) { 15346 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15347 << MemberDecl->getDeclName() 15348 << SourceRange(BuiltinLoc, RParenLoc); 15349 return ExprError(); 15350 } 15351 15352 CXXBasePath &Path = Paths.front(); 15353 for (const CXXBasePathElement &B : Path) 15354 Comps.push_back(OffsetOfNode(B.Base)); 15355 } 15356 15357 if (IndirectMemberDecl) { 15358 for (auto *FI : IndirectMemberDecl->chain()) { 15359 assert(isa<FieldDecl>(FI)); 15360 Comps.push_back(OffsetOfNode(OC.LocStart, 15361 cast<FieldDecl>(FI), OC.LocEnd)); 15362 } 15363 } else 15364 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15365 15366 CurrentType = MemberDecl->getType().getNonReferenceType(); 15367 } 15368 15369 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15370 Comps, Exprs, RParenLoc); 15371 } 15372 15373 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15374 SourceLocation BuiltinLoc, 15375 SourceLocation TypeLoc, 15376 ParsedType ParsedArgTy, 15377 ArrayRef<OffsetOfComponent> Components, 15378 SourceLocation RParenLoc) { 15379 15380 TypeSourceInfo *ArgTInfo; 15381 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15382 if (ArgTy.isNull()) 15383 return ExprError(); 15384 15385 if (!ArgTInfo) 15386 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15387 15388 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15389 } 15390 15391 15392 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15393 Expr *CondExpr, 15394 Expr *LHSExpr, Expr *RHSExpr, 15395 SourceLocation RPLoc) { 15396 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15397 15398 ExprValueKind VK = VK_PRValue; 15399 ExprObjectKind OK = OK_Ordinary; 15400 QualType resType; 15401 bool CondIsTrue = false; 15402 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15403 resType = Context.DependentTy; 15404 } else { 15405 // The conditional expression is required to be a constant expression. 15406 llvm::APSInt condEval(32); 15407 ExprResult CondICE = VerifyIntegerConstantExpression( 15408 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15409 if (CondICE.isInvalid()) 15410 return ExprError(); 15411 CondExpr = CondICE.get(); 15412 CondIsTrue = condEval.getZExtValue(); 15413 15414 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15415 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15416 15417 resType = ActiveExpr->getType(); 15418 VK = ActiveExpr->getValueKind(); 15419 OK = ActiveExpr->getObjectKind(); 15420 } 15421 15422 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15423 resType, VK, OK, RPLoc, CondIsTrue); 15424 } 15425 15426 //===----------------------------------------------------------------------===// 15427 // Clang Extensions. 15428 //===----------------------------------------------------------------------===// 15429 15430 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15431 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15432 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15433 15434 if (LangOpts.CPlusPlus) { 15435 MangleNumberingContext *MCtx; 15436 Decl *ManglingContextDecl; 15437 std::tie(MCtx, ManglingContextDecl) = 15438 getCurrentMangleNumberContext(Block->getDeclContext()); 15439 if (MCtx) { 15440 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15441 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15442 } 15443 } 15444 15445 PushBlockScope(CurScope, Block); 15446 CurContext->addDecl(Block); 15447 if (CurScope) 15448 PushDeclContext(CurScope, Block); 15449 else 15450 CurContext = Block; 15451 15452 getCurBlock()->HasImplicitReturnType = true; 15453 15454 // Enter a new evaluation context to insulate the block from any 15455 // cleanups from the enclosing full-expression. 15456 PushExpressionEvaluationContext( 15457 ExpressionEvaluationContext::PotentiallyEvaluated); 15458 } 15459 15460 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15461 Scope *CurScope) { 15462 assert(ParamInfo.getIdentifier() == nullptr && 15463 "block-id should have no identifier!"); 15464 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15465 BlockScopeInfo *CurBlock = getCurBlock(); 15466 15467 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15468 QualType T = Sig->getType(); 15469 15470 // FIXME: We should allow unexpanded parameter packs here, but that would, 15471 // in turn, make the block expression contain unexpanded parameter packs. 15472 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15473 // Drop the parameters. 15474 FunctionProtoType::ExtProtoInfo EPI; 15475 EPI.HasTrailingReturn = false; 15476 EPI.TypeQuals.addConst(); 15477 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15478 Sig = Context.getTrivialTypeSourceInfo(T); 15479 } 15480 15481 // GetTypeForDeclarator always produces a function type for a block 15482 // literal signature. Furthermore, it is always a FunctionProtoType 15483 // unless the function was written with a typedef. 15484 assert(T->isFunctionType() && 15485 "GetTypeForDeclarator made a non-function block signature"); 15486 15487 // Look for an explicit signature in that function type. 15488 FunctionProtoTypeLoc ExplicitSignature; 15489 15490 if ((ExplicitSignature = Sig->getTypeLoc() 15491 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15492 15493 // Check whether that explicit signature was synthesized by 15494 // GetTypeForDeclarator. If so, don't save that as part of the 15495 // written signature. 15496 if (ExplicitSignature.getLocalRangeBegin() == 15497 ExplicitSignature.getLocalRangeEnd()) { 15498 // This would be much cheaper if we stored TypeLocs instead of 15499 // TypeSourceInfos. 15500 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15501 unsigned Size = Result.getFullDataSize(); 15502 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15503 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15504 15505 ExplicitSignature = FunctionProtoTypeLoc(); 15506 } 15507 } 15508 15509 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15510 CurBlock->FunctionType = T; 15511 15512 const auto *Fn = T->castAs<FunctionType>(); 15513 QualType RetTy = Fn->getReturnType(); 15514 bool isVariadic = 15515 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15516 15517 CurBlock->TheDecl->setIsVariadic(isVariadic); 15518 15519 // Context.DependentTy is used as a placeholder for a missing block 15520 // return type. TODO: what should we do with declarators like: 15521 // ^ * { ... } 15522 // If the answer is "apply template argument deduction".... 15523 if (RetTy != Context.DependentTy) { 15524 CurBlock->ReturnType = RetTy; 15525 CurBlock->TheDecl->setBlockMissingReturnType(false); 15526 CurBlock->HasImplicitReturnType = false; 15527 } 15528 15529 // Push block parameters from the declarator if we had them. 15530 SmallVector<ParmVarDecl*, 8> Params; 15531 if (ExplicitSignature) { 15532 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15533 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15534 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15535 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15536 // Diagnose this as an extension in C17 and earlier. 15537 if (!getLangOpts().C2x) 15538 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15539 } 15540 Params.push_back(Param); 15541 } 15542 15543 // Fake up parameter variables if we have a typedef, like 15544 // ^ fntype { ... } 15545 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15546 for (const auto &I : Fn->param_types()) { 15547 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15548 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15549 Params.push_back(Param); 15550 } 15551 } 15552 15553 // Set the parameters on the block decl. 15554 if (!Params.empty()) { 15555 CurBlock->TheDecl->setParams(Params); 15556 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15557 /*CheckParameterNames=*/false); 15558 } 15559 15560 // Finally we can process decl attributes. 15561 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15562 15563 // Put the parameter variables in scope. 15564 for (auto AI : CurBlock->TheDecl->parameters()) { 15565 AI->setOwningFunction(CurBlock->TheDecl); 15566 15567 // If this has an identifier, add it to the scope stack. 15568 if (AI->getIdentifier()) { 15569 CheckShadow(CurBlock->TheScope, AI); 15570 15571 PushOnScopeChains(AI, CurBlock->TheScope); 15572 } 15573 } 15574 } 15575 15576 /// ActOnBlockError - If there is an error parsing a block, this callback 15577 /// is invoked to pop the information about the block from the action impl. 15578 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15579 // Leave the expression-evaluation context. 15580 DiscardCleanupsInEvaluationContext(); 15581 PopExpressionEvaluationContext(); 15582 15583 // Pop off CurBlock, handle nested blocks. 15584 PopDeclContext(); 15585 PopFunctionScopeInfo(); 15586 } 15587 15588 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15589 /// literal was successfully completed. ^(int x){...} 15590 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15591 Stmt *Body, Scope *CurScope) { 15592 // If blocks are disabled, emit an error. 15593 if (!LangOpts.Blocks) 15594 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15595 15596 // Leave the expression-evaluation context. 15597 if (hasAnyUnrecoverableErrorsInThisFunction()) 15598 DiscardCleanupsInEvaluationContext(); 15599 assert(!Cleanup.exprNeedsCleanups() && 15600 "cleanups within block not correctly bound!"); 15601 PopExpressionEvaluationContext(); 15602 15603 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15604 BlockDecl *BD = BSI->TheDecl; 15605 15606 if (BSI->HasImplicitReturnType) 15607 deduceClosureReturnType(*BSI); 15608 15609 QualType RetTy = Context.VoidTy; 15610 if (!BSI->ReturnType.isNull()) 15611 RetTy = BSI->ReturnType; 15612 15613 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15614 QualType BlockTy; 15615 15616 // If the user wrote a function type in some form, try to use that. 15617 if (!BSI->FunctionType.isNull()) { 15618 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15619 15620 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15621 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15622 15623 // Turn protoless block types into nullary block types. 15624 if (isa<FunctionNoProtoType>(FTy)) { 15625 FunctionProtoType::ExtProtoInfo EPI; 15626 EPI.ExtInfo = Ext; 15627 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15628 15629 // Otherwise, if we don't need to change anything about the function type, 15630 // preserve its sugar structure. 15631 } else if (FTy->getReturnType() == RetTy && 15632 (!NoReturn || FTy->getNoReturnAttr())) { 15633 BlockTy = BSI->FunctionType; 15634 15635 // Otherwise, make the minimal modifications to the function type. 15636 } else { 15637 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15638 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15639 EPI.TypeQuals = Qualifiers(); 15640 EPI.ExtInfo = Ext; 15641 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15642 } 15643 15644 // If we don't have a function type, just build one from nothing. 15645 } else { 15646 FunctionProtoType::ExtProtoInfo EPI; 15647 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15648 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15649 } 15650 15651 DiagnoseUnusedParameters(BD->parameters()); 15652 BlockTy = Context.getBlockPointerType(BlockTy); 15653 15654 // If needed, diagnose invalid gotos and switches in the block. 15655 if (getCurFunction()->NeedsScopeChecking() && 15656 !PP.isCodeCompletionEnabled()) 15657 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15658 15659 BD->setBody(cast<CompoundStmt>(Body)); 15660 15661 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15662 DiagnoseUnguardedAvailabilityViolations(BD); 15663 15664 // Try to apply the named return value optimization. We have to check again 15665 // if we can do this, though, because blocks keep return statements around 15666 // to deduce an implicit return type. 15667 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15668 !BD->isDependentContext()) 15669 computeNRVO(Body, BSI); 15670 15671 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15672 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15673 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15674 NTCUK_Destruct|NTCUK_Copy); 15675 15676 PopDeclContext(); 15677 15678 // Set the captured variables on the block. 15679 SmallVector<BlockDecl::Capture, 4> Captures; 15680 for (Capture &Cap : BSI->Captures) { 15681 if (Cap.isInvalid() || Cap.isThisCapture()) 15682 continue; 15683 15684 VarDecl *Var = Cap.getVariable(); 15685 Expr *CopyExpr = nullptr; 15686 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15687 if (const RecordType *Record = 15688 Cap.getCaptureType()->getAs<RecordType>()) { 15689 // The capture logic needs the destructor, so make sure we mark it. 15690 // Usually this is unnecessary because most local variables have 15691 // their destructors marked at declaration time, but parameters are 15692 // an exception because it's technically only the call site that 15693 // actually requires the destructor. 15694 if (isa<ParmVarDecl>(Var)) 15695 FinalizeVarWithDestructor(Var, Record); 15696 15697 // Enter a separate potentially-evaluated context while building block 15698 // initializers to isolate their cleanups from those of the block 15699 // itself. 15700 // FIXME: Is this appropriate even when the block itself occurs in an 15701 // unevaluated operand? 15702 EnterExpressionEvaluationContext EvalContext( 15703 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15704 15705 SourceLocation Loc = Cap.getLocation(); 15706 15707 ExprResult Result = BuildDeclarationNameExpr( 15708 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15709 15710 // According to the blocks spec, the capture of a variable from 15711 // the stack requires a const copy constructor. This is not true 15712 // of the copy/move done to move a __block variable to the heap. 15713 if (!Result.isInvalid() && 15714 !Result.get()->getType().isConstQualified()) { 15715 Result = ImpCastExprToType(Result.get(), 15716 Result.get()->getType().withConst(), 15717 CK_NoOp, VK_LValue); 15718 } 15719 15720 if (!Result.isInvalid()) { 15721 Result = PerformCopyInitialization( 15722 InitializedEntity::InitializeBlock(Var->getLocation(), 15723 Cap.getCaptureType()), 15724 Loc, Result.get()); 15725 } 15726 15727 // Build a full-expression copy expression if initialization 15728 // succeeded and used a non-trivial constructor. Recover from 15729 // errors by pretending that the copy isn't necessary. 15730 if (!Result.isInvalid() && 15731 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15732 ->isTrivial()) { 15733 Result = MaybeCreateExprWithCleanups(Result); 15734 CopyExpr = Result.get(); 15735 } 15736 } 15737 } 15738 15739 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15740 CopyExpr); 15741 Captures.push_back(NewCap); 15742 } 15743 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15744 15745 // Pop the block scope now but keep it alive to the end of this function. 15746 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15747 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15748 15749 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15750 15751 // If the block isn't obviously global, i.e. it captures anything at 15752 // all, then we need to do a few things in the surrounding context: 15753 if (Result->getBlockDecl()->hasCaptures()) { 15754 // First, this expression has a new cleanup object. 15755 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15756 Cleanup.setExprNeedsCleanups(true); 15757 15758 // It also gets a branch-protected scope if any of the captured 15759 // variables needs destruction. 15760 for (const auto &CI : Result->getBlockDecl()->captures()) { 15761 const VarDecl *var = CI.getVariable(); 15762 if (var->getType().isDestructedType() != QualType::DK_none) { 15763 setFunctionHasBranchProtectedScope(); 15764 break; 15765 } 15766 } 15767 } 15768 15769 if (getCurFunction()) 15770 getCurFunction()->addBlock(BD); 15771 15772 return Result; 15773 } 15774 15775 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15776 SourceLocation RPLoc) { 15777 TypeSourceInfo *TInfo; 15778 GetTypeFromParser(Ty, &TInfo); 15779 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15780 } 15781 15782 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15783 Expr *E, TypeSourceInfo *TInfo, 15784 SourceLocation RPLoc) { 15785 Expr *OrigExpr = E; 15786 bool IsMS = false; 15787 15788 // CUDA device code does not support varargs. 15789 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15790 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15791 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15792 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15793 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15794 } 15795 } 15796 15797 // NVPTX does not support va_arg expression. 15798 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15799 Context.getTargetInfo().getTriple().isNVPTX()) 15800 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15801 15802 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15803 // as Microsoft ABI on an actual Microsoft platform, where 15804 // __builtin_ms_va_list and __builtin_va_list are the same.) 15805 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15806 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15807 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15808 if (Context.hasSameType(MSVaListType, E->getType())) { 15809 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15810 return ExprError(); 15811 IsMS = true; 15812 } 15813 } 15814 15815 // Get the va_list type 15816 QualType VaListType = Context.getBuiltinVaListType(); 15817 if (!IsMS) { 15818 if (VaListType->isArrayType()) { 15819 // Deal with implicit array decay; for example, on x86-64, 15820 // va_list is an array, but it's supposed to decay to 15821 // a pointer for va_arg. 15822 VaListType = Context.getArrayDecayedType(VaListType); 15823 // Make sure the input expression also decays appropriately. 15824 ExprResult Result = UsualUnaryConversions(E); 15825 if (Result.isInvalid()) 15826 return ExprError(); 15827 E = Result.get(); 15828 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15829 // If va_list is a record type and we are compiling in C++ mode, 15830 // check the argument using reference binding. 15831 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15832 Context, Context.getLValueReferenceType(VaListType), false); 15833 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15834 if (Init.isInvalid()) 15835 return ExprError(); 15836 E = Init.getAs<Expr>(); 15837 } else { 15838 // Otherwise, the va_list argument must be an l-value because 15839 // it is modified by va_arg. 15840 if (!E->isTypeDependent() && 15841 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15842 return ExprError(); 15843 } 15844 } 15845 15846 if (!IsMS && !E->isTypeDependent() && 15847 !Context.hasSameType(VaListType, E->getType())) 15848 return ExprError( 15849 Diag(E->getBeginLoc(), 15850 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15851 << OrigExpr->getType() << E->getSourceRange()); 15852 15853 if (!TInfo->getType()->isDependentType()) { 15854 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15855 diag::err_second_parameter_to_va_arg_incomplete, 15856 TInfo->getTypeLoc())) 15857 return ExprError(); 15858 15859 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15860 TInfo->getType(), 15861 diag::err_second_parameter_to_va_arg_abstract, 15862 TInfo->getTypeLoc())) 15863 return ExprError(); 15864 15865 if (!TInfo->getType().isPODType(Context)) { 15866 Diag(TInfo->getTypeLoc().getBeginLoc(), 15867 TInfo->getType()->isObjCLifetimeType() 15868 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15869 : diag::warn_second_parameter_to_va_arg_not_pod) 15870 << TInfo->getType() 15871 << TInfo->getTypeLoc().getSourceRange(); 15872 } 15873 15874 // Check for va_arg where arguments of the given type will be promoted 15875 // (i.e. this va_arg is guaranteed to have undefined behavior). 15876 QualType PromoteType; 15877 if (TInfo->getType()->isPromotableIntegerType()) { 15878 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15879 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15880 // and C2x 7.16.1.1p2 says, in part: 15881 // If type is not compatible with the type of the actual next argument 15882 // (as promoted according to the default argument promotions), the 15883 // behavior is undefined, except for the following cases: 15884 // - both types are pointers to qualified or unqualified versions of 15885 // compatible types; 15886 // - one type is a signed integer type, the other type is the 15887 // corresponding unsigned integer type, and the value is 15888 // representable in both types; 15889 // - one type is pointer to qualified or unqualified void and the 15890 // other is a pointer to a qualified or unqualified character type. 15891 // Given that type compatibility is the primary requirement (ignoring 15892 // qualifications), you would think we could call typesAreCompatible() 15893 // directly to test this. However, in C++, that checks for *same type*, 15894 // which causes false positives when passing an enumeration type to 15895 // va_arg. Instead, get the underlying type of the enumeration and pass 15896 // that. 15897 QualType UnderlyingType = TInfo->getType(); 15898 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15899 UnderlyingType = ET->getDecl()->getIntegerType(); 15900 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15901 /*CompareUnqualified*/ true)) 15902 PromoteType = QualType(); 15903 15904 // If the types are still not compatible, we need to test whether the 15905 // promoted type and the underlying type are the same except for 15906 // signedness. Ask the AST for the correctly corresponding type and see 15907 // if that's compatible. 15908 if (!PromoteType.isNull() && 15909 PromoteType->isUnsignedIntegerType() != 15910 UnderlyingType->isUnsignedIntegerType()) { 15911 UnderlyingType = 15912 UnderlyingType->isUnsignedIntegerType() 15913 ? Context.getCorrespondingSignedType(UnderlyingType) 15914 : Context.getCorrespondingUnsignedType(UnderlyingType); 15915 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15916 /*CompareUnqualified*/ true)) 15917 PromoteType = QualType(); 15918 } 15919 } 15920 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15921 PromoteType = Context.DoubleTy; 15922 if (!PromoteType.isNull()) 15923 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15924 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15925 << TInfo->getType() 15926 << PromoteType 15927 << TInfo->getTypeLoc().getSourceRange()); 15928 } 15929 15930 QualType T = TInfo->getType().getNonLValueExprType(Context); 15931 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15932 } 15933 15934 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15935 // The type of __null will be int or long, depending on the size of 15936 // pointers on the target. 15937 QualType Ty; 15938 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15939 if (pw == Context.getTargetInfo().getIntWidth()) 15940 Ty = Context.IntTy; 15941 else if (pw == Context.getTargetInfo().getLongWidth()) 15942 Ty = Context.LongTy; 15943 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15944 Ty = Context.LongLongTy; 15945 else { 15946 llvm_unreachable("I don't know size of pointer!"); 15947 } 15948 15949 return new (Context) GNUNullExpr(Ty, TokenLoc); 15950 } 15951 15952 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15953 SourceLocation BuiltinLoc, 15954 SourceLocation RPLoc) { 15955 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15956 } 15957 15958 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15959 SourceLocation BuiltinLoc, 15960 SourceLocation RPLoc, 15961 DeclContext *ParentContext) { 15962 return new (Context) 15963 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15964 } 15965 15966 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15967 bool Diagnose) { 15968 if (!getLangOpts().ObjC) 15969 return false; 15970 15971 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15972 if (!PT) 15973 return false; 15974 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15975 15976 // Ignore any parens, implicit casts (should only be 15977 // array-to-pointer decays), and not-so-opaque values. The last is 15978 // important for making this trigger for property assignments. 15979 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15980 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15981 if (OV->getSourceExpr()) 15982 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15983 15984 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15985 if (!PT->isObjCIdType() && 15986 !(ID && ID->getIdentifier()->isStr("NSString"))) 15987 return false; 15988 if (!SL->isAscii()) 15989 return false; 15990 15991 if (Diagnose) { 15992 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15993 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15994 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15995 } 15996 return true; 15997 } 15998 15999 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16000 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16001 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16002 !SrcExpr->isNullPointerConstant( 16003 getASTContext(), Expr::NPC_NeverValueDependent)) { 16004 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16005 return false; 16006 if (Diagnose) { 16007 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16008 << /*number*/1 16009 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16010 Expr *NumLit = 16011 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16012 if (NumLit) 16013 Exp = NumLit; 16014 } 16015 return true; 16016 } 16017 16018 return false; 16019 } 16020 16021 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16022 const Expr *SrcExpr) { 16023 if (!DstType->isFunctionPointerType() || 16024 !SrcExpr->getType()->isFunctionType()) 16025 return false; 16026 16027 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16028 if (!DRE) 16029 return false; 16030 16031 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16032 if (!FD) 16033 return false; 16034 16035 return !S.checkAddressOfFunctionIsAvailable(FD, 16036 /*Complain=*/true, 16037 SrcExpr->getBeginLoc()); 16038 } 16039 16040 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16041 SourceLocation Loc, 16042 QualType DstType, QualType SrcType, 16043 Expr *SrcExpr, AssignmentAction Action, 16044 bool *Complained) { 16045 if (Complained) 16046 *Complained = false; 16047 16048 // Decode the result (notice that AST's are still created for extensions). 16049 bool CheckInferredResultType = false; 16050 bool isInvalid = false; 16051 unsigned DiagKind = 0; 16052 ConversionFixItGenerator ConvHints; 16053 bool MayHaveConvFixit = false; 16054 bool MayHaveFunctionDiff = false; 16055 const ObjCInterfaceDecl *IFace = nullptr; 16056 const ObjCProtocolDecl *PDecl = nullptr; 16057 16058 switch (ConvTy) { 16059 case Compatible: 16060 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16061 return false; 16062 16063 case PointerToInt: 16064 if (getLangOpts().CPlusPlus) { 16065 DiagKind = diag::err_typecheck_convert_pointer_int; 16066 isInvalid = true; 16067 } else { 16068 DiagKind = diag::ext_typecheck_convert_pointer_int; 16069 } 16070 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16071 MayHaveConvFixit = true; 16072 break; 16073 case IntToPointer: 16074 if (getLangOpts().CPlusPlus) { 16075 DiagKind = diag::err_typecheck_convert_int_pointer; 16076 isInvalid = true; 16077 } else { 16078 DiagKind = diag::ext_typecheck_convert_int_pointer; 16079 } 16080 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16081 MayHaveConvFixit = true; 16082 break; 16083 case IncompatibleFunctionPointer: 16084 if (getLangOpts().CPlusPlus) { 16085 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16086 isInvalid = true; 16087 } else { 16088 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16089 } 16090 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16091 MayHaveConvFixit = true; 16092 break; 16093 case IncompatiblePointer: 16094 if (Action == AA_Passing_CFAudited) { 16095 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16096 } else if (getLangOpts().CPlusPlus) { 16097 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16098 isInvalid = true; 16099 } else { 16100 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16101 } 16102 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16103 SrcType->isObjCObjectPointerType(); 16104 if (!CheckInferredResultType) { 16105 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16106 } else if (CheckInferredResultType) { 16107 SrcType = SrcType.getUnqualifiedType(); 16108 DstType = DstType.getUnqualifiedType(); 16109 } 16110 MayHaveConvFixit = true; 16111 break; 16112 case IncompatiblePointerSign: 16113 if (getLangOpts().CPlusPlus) { 16114 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16115 isInvalid = true; 16116 } else { 16117 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16118 } 16119 break; 16120 case FunctionVoidPointer: 16121 if (getLangOpts().CPlusPlus) { 16122 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16123 isInvalid = true; 16124 } else { 16125 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16126 } 16127 break; 16128 case IncompatiblePointerDiscardsQualifiers: { 16129 // Perform array-to-pointer decay if necessary. 16130 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16131 16132 isInvalid = true; 16133 16134 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16135 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16136 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16137 DiagKind = diag::err_typecheck_incompatible_address_space; 16138 break; 16139 16140 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16141 DiagKind = diag::err_typecheck_incompatible_ownership; 16142 break; 16143 } 16144 16145 llvm_unreachable("unknown error case for discarding qualifiers!"); 16146 // fallthrough 16147 } 16148 case CompatiblePointerDiscardsQualifiers: 16149 // If the qualifiers lost were because we were applying the 16150 // (deprecated) C++ conversion from a string literal to a char* 16151 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16152 // Ideally, this check would be performed in 16153 // checkPointerTypesForAssignment. However, that would require a 16154 // bit of refactoring (so that the second argument is an 16155 // expression, rather than a type), which should be done as part 16156 // of a larger effort to fix checkPointerTypesForAssignment for 16157 // C++ semantics. 16158 if (getLangOpts().CPlusPlus && 16159 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16160 return false; 16161 if (getLangOpts().CPlusPlus) { 16162 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16163 isInvalid = true; 16164 } else { 16165 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16166 } 16167 16168 break; 16169 case IncompatibleNestedPointerQualifiers: 16170 if (getLangOpts().CPlusPlus) { 16171 isInvalid = true; 16172 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16173 } else { 16174 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16175 } 16176 break; 16177 case IncompatibleNestedPointerAddressSpaceMismatch: 16178 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16179 isInvalid = true; 16180 break; 16181 case IntToBlockPointer: 16182 DiagKind = diag::err_int_to_block_pointer; 16183 isInvalid = true; 16184 break; 16185 case IncompatibleBlockPointer: 16186 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16187 isInvalid = true; 16188 break; 16189 case IncompatibleObjCQualifiedId: { 16190 if (SrcType->isObjCQualifiedIdType()) { 16191 const ObjCObjectPointerType *srcOPT = 16192 SrcType->castAs<ObjCObjectPointerType>(); 16193 for (auto *srcProto : srcOPT->quals()) { 16194 PDecl = srcProto; 16195 break; 16196 } 16197 if (const ObjCInterfaceType *IFaceT = 16198 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16199 IFace = IFaceT->getDecl(); 16200 } 16201 else if (DstType->isObjCQualifiedIdType()) { 16202 const ObjCObjectPointerType *dstOPT = 16203 DstType->castAs<ObjCObjectPointerType>(); 16204 for (auto *dstProto : dstOPT->quals()) { 16205 PDecl = dstProto; 16206 break; 16207 } 16208 if (const ObjCInterfaceType *IFaceT = 16209 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16210 IFace = IFaceT->getDecl(); 16211 } 16212 if (getLangOpts().CPlusPlus) { 16213 DiagKind = diag::err_incompatible_qualified_id; 16214 isInvalid = true; 16215 } else { 16216 DiagKind = diag::warn_incompatible_qualified_id; 16217 } 16218 break; 16219 } 16220 case IncompatibleVectors: 16221 if (getLangOpts().CPlusPlus) { 16222 DiagKind = diag::err_incompatible_vectors; 16223 isInvalid = true; 16224 } else { 16225 DiagKind = diag::warn_incompatible_vectors; 16226 } 16227 break; 16228 case IncompatibleObjCWeakRef: 16229 DiagKind = diag::err_arc_weak_unavailable_assign; 16230 isInvalid = true; 16231 break; 16232 case Incompatible: 16233 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16234 if (Complained) 16235 *Complained = true; 16236 return true; 16237 } 16238 16239 DiagKind = diag::err_typecheck_convert_incompatible; 16240 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16241 MayHaveConvFixit = true; 16242 isInvalid = true; 16243 MayHaveFunctionDiff = true; 16244 break; 16245 } 16246 16247 QualType FirstType, SecondType; 16248 switch (Action) { 16249 case AA_Assigning: 16250 case AA_Initializing: 16251 // The destination type comes first. 16252 FirstType = DstType; 16253 SecondType = SrcType; 16254 break; 16255 16256 case AA_Returning: 16257 case AA_Passing: 16258 case AA_Passing_CFAudited: 16259 case AA_Converting: 16260 case AA_Sending: 16261 case AA_Casting: 16262 // The source type comes first. 16263 FirstType = SrcType; 16264 SecondType = DstType; 16265 break; 16266 } 16267 16268 PartialDiagnostic FDiag = PDiag(DiagKind); 16269 if (Action == AA_Passing_CFAudited) 16270 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16271 else 16272 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16273 16274 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16275 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16276 auto isPlainChar = [](const clang::Type *Type) { 16277 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16278 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16279 }; 16280 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16281 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16282 } 16283 16284 // If we can fix the conversion, suggest the FixIts. 16285 if (!ConvHints.isNull()) { 16286 for (FixItHint &H : ConvHints.Hints) 16287 FDiag << H; 16288 } 16289 16290 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16291 16292 if (MayHaveFunctionDiff) 16293 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16294 16295 Diag(Loc, FDiag); 16296 if ((DiagKind == diag::warn_incompatible_qualified_id || 16297 DiagKind == diag::err_incompatible_qualified_id) && 16298 PDecl && IFace && !IFace->hasDefinition()) 16299 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16300 << IFace << PDecl; 16301 16302 if (SecondType == Context.OverloadTy) 16303 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16304 FirstType, /*TakingAddress=*/true); 16305 16306 if (CheckInferredResultType) 16307 EmitRelatedResultTypeNote(SrcExpr); 16308 16309 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16310 EmitRelatedResultTypeNoteForReturn(DstType); 16311 16312 if (Complained) 16313 *Complained = true; 16314 return isInvalid; 16315 } 16316 16317 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16318 llvm::APSInt *Result, 16319 AllowFoldKind CanFold) { 16320 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16321 public: 16322 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16323 QualType T) override { 16324 return S.Diag(Loc, diag::err_ice_not_integral) 16325 << T << S.LangOpts.CPlusPlus; 16326 } 16327 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16328 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16329 } 16330 } Diagnoser; 16331 16332 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16333 } 16334 16335 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16336 llvm::APSInt *Result, 16337 unsigned DiagID, 16338 AllowFoldKind CanFold) { 16339 class IDDiagnoser : public VerifyICEDiagnoser { 16340 unsigned DiagID; 16341 16342 public: 16343 IDDiagnoser(unsigned DiagID) 16344 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16345 16346 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16347 return S.Diag(Loc, DiagID); 16348 } 16349 } Diagnoser(DiagID); 16350 16351 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16352 } 16353 16354 Sema::SemaDiagnosticBuilder 16355 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16356 QualType T) { 16357 return diagnoseNotICE(S, Loc); 16358 } 16359 16360 Sema::SemaDiagnosticBuilder 16361 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16362 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16363 } 16364 16365 ExprResult 16366 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16367 VerifyICEDiagnoser &Diagnoser, 16368 AllowFoldKind CanFold) { 16369 SourceLocation DiagLoc = E->getBeginLoc(); 16370 16371 if (getLangOpts().CPlusPlus11) { 16372 // C++11 [expr.const]p5: 16373 // If an expression of literal class type is used in a context where an 16374 // integral constant expression is required, then that class type shall 16375 // have a single non-explicit conversion function to an integral or 16376 // unscoped enumeration type 16377 ExprResult Converted; 16378 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16379 VerifyICEDiagnoser &BaseDiagnoser; 16380 public: 16381 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16382 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16383 BaseDiagnoser.Suppress, true), 16384 BaseDiagnoser(BaseDiagnoser) {} 16385 16386 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16387 QualType T) override { 16388 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16389 } 16390 16391 SemaDiagnosticBuilder diagnoseIncomplete( 16392 Sema &S, SourceLocation Loc, QualType T) override { 16393 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16394 } 16395 16396 SemaDiagnosticBuilder diagnoseExplicitConv( 16397 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16398 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16399 } 16400 16401 SemaDiagnosticBuilder noteExplicitConv( 16402 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16403 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16404 << ConvTy->isEnumeralType() << ConvTy; 16405 } 16406 16407 SemaDiagnosticBuilder diagnoseAmbiguous( 16408 Sema &S, SourceLocation Loc, QualType T) override { 16409 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16410 } 16411 16412 SemaDiagnosticBuilder noteAmbiguous( 16413 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16414 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16415 << ConvTy->isEnumeralType() << ConvTy; 16416 } 16417 16418 SemaDiagnosticBuilder diagnoseConversion( 16419 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16420 llvm_unreachable("conversion functions are permitted"); 16421 } 16422 } ConvertDiagnoser(Diagnoser); 16423 16424 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16425 ConvertDiagnoser); 16426 if (Converted.isInvalid()) 16427 return Converted; 16428 E = Converted.get(); 16429 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16430 return ExprError(); 16431 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16432 // An ICE must be of integral or unscoped enumeration type. 16433 if (!Diagnoser.Suppress) 16434 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16435 << E->getSourceRange(); 16436 return ExprError(); 16437 } 16438 16439 ExprResult RValueExpr = DefaultLvalueConversion(E); 16440 if (RValueExpr.isInvalid()) 16441 return ExprError(); 16442 16443 E = RValueExpr.get(); 16444 16445 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16446 // in the non-ICE case. 16447 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16448 if (Result) 16449 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16450 if (!isa<ConstantExpr>(E)) 16451 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16452 : ConstantExpr::Create(Context, E); 16453 return E; 16454 } 16455 16456 Expr::EvalResult EvalResult; 16457 SmallVector<PartialDiagnosticAt, 8> Notes; 16458 EvalResult.Diag = &Notes; 16459 16460 // Try to evaluate the expression, and produce diagnostics explaining why it's 16461 // not a constant expression as a side-effect. 16462 bool Folded = 16463 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16464 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16465 16466 if (!isa<ConstantExpr>(E)) 16467 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16468 16469 // In C++11, we can rely on diagnostics being produced for any expression 16470 // which is not a constant expression. If no diagnostics were produced, then 16471 // this is a constant expression. 16472 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16473 if (Result) 16474 *Result = EvalResult.Val.getInt(); 16475 return E; 16476 } 16477 16478 // If our only note is the usual "invalid subexpression" note, just point 16479 // the caret at its location rather than producing an essentially 16480 // redundant note. 16481 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16482 diag::note_invalid_subexpr_in_const_expr) { 16483 DiagLoc = Notes[0].first; 16484 Notes.clear(); 16485 } 16486 16487 if (!Folded || !CanFold) { 16488 if (!Diagnoser.Suppress) { 16489 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16490 for (const PartialDiagnosticAt &Note : Notes) 16491 Diag(Note.first, Note.second); 16492 } 16493 16494 return ExprError(); 16495 } 16496 16497 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16498 for (const PartialDiagnosticAt &Note : Notes) 16499 Diag(Note.first, Note.second); 16500 16501 if (Result) 16502 *Result = EvalResult.Val.getInt(); 16503 return E; 16504 } 16505 16506 namespace { 16507 // Handle the case where we conclude a expression which we speculatively 16508 // considered to be unevaluated is actually evaluated. 16509 class TransformToPE : public TreeTransform<TransformToPE> { 16510 typedef TreeTransform<TransformToPE> BaseTransform; 16511 16512 public: 16513 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16514 16515 // Make sure we redo semantic analysis 16516 bool AlwaysRebuild() { return true; } 16517 bool ReplacingOriginal() { return true; } 16518 16519 // We need to special-case DeclRefExprs referring to FieldDecls which 16520 // are not part of a member pointer formation; normal TreeTransforming 16521 // doesn't catch this case because of the way we represent them in the AST. 16522 // FIXME: This is a bit ugly; is it really the best way to handle this 16523 // case? 16524 // 16525 // Error on DeclRefExprs referring to FieldDecls. 16526 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16527 if (isa<FieldDecl>(E->getDecl()) && 16528 !SemaRef.isUnevaluatedContext()) 16529 return SemaRef.Diag(E->getLocation(), 16530 diag::err_invalid_non_static_member_use) 16531 << E->getDecl() << E->getSourceRange(); 16532 16533 return BaseTransform::TransformDeclRefExpr(E); 16534 } 16535 16536 // Exception: filter out member pointer formation 16537 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16538 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16539 return E; 16540 16541 return BaseTransform::TransformUnaryOperator(E); 16542 } 16543 16544 // The body of a lambda-expression is in a separate expression evaluation 16545 // context so never needs to be transformed. 16546 // FIXME: Ideally we wouldn't transform the closure type either, and would 16547 // just recreate the capture expressions and lambda expression. 16548 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16549 return SkipLambdaBody(E, Body); 16550 } 16551 }; 16552 } 16553 16554 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16555 assert(isUnevaluatedContext() && 16556 "Should only transform unevaluated expressions"); 16557 ExprEvalContexts.back().Context = 16558 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16559 if (isUnevaluatedContext()) 16560 return E; 16561 return TransformToPE(*this).TransformExpr(E); 16562 } 16563 16564 void 16565 Sema::PushExpressionEvaluationContext( 16566 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16567 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16568 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16569 LambdaContextDecl, ExprContext); 16570 16571 // Discarded statements and immediate contexts nested in other 16572 // discarded statements or immediate context are themselves 16573 // a discarded statement or an immediate context, respectively. 16574 ExprEvalContexts.back().InDiscardedStatement = 16575 ExprEvalContexts[ExprEvalContexts.size() - 2] 16576 .isDiscardedStatementContext(); 16577 ExprEvalContexts.back().InImmediateFunctionContext = 16578 ExprEvalContexts[ExprEvalContexts.size() - 2] 16579 .isImmediateFunctionContext(); 16580 16581 Cleanup.reset(); 16582 if (!MaybeODRUseExprs.empty()) 16583 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16584 } 16585 16586 void 16587 Sema::PushExpressionEvaluationContext( 16588 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16589 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16590 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16591 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16592 } 16593 16594 namespace { 16595 16596 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16597 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16598 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16599 if (E->getOpcode() == UO_Deref) 16600 return CheckPossibleDeref(S, E->getSubExpr()); 16601 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16602 return CheckPossibleDeref(S, E->getBase()); 16603 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16604 return CheckPossibleDeref(S, E->getBase()); 16605 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16606 QualType Inner; 16607 QualType Ty = E->getType(); 16608 if (const auto *Ptr = Ty->getAs<PointerType>()) 16609 Inner = Ptr->getPointeeType(); 16610 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16611 Inner = Arr->getElementType(); 16612 else 16613 return nullptr; 16614 16615 if (Inner->hasAttr(attr::NoDeref)) 16616 return E; 16617 } 16618 return nullptr; 16619 } 16620 16621 } // namespace 16622 16623 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16624 for (const Expr *E : Rec.PossibleDerefs) { 16625 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16626 if (DeclRef) { 16627 const ValueDecl *Decl = DeclRef->getDecl(); 16628 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16629 << Decl->getName() << E->getSourceRange(); 16630 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16631 } else { 16632 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16633 << E->getSourceRange(); 16634 } 16635 } 16636 Rec.PossibleDerefs.clear(); 16637 } 16638 16639 /// Check whether E, which is either a discarded-value expression or an 16640 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16641 /// and if so, remove it from the list of volatile-qualified assignments that 16642 /// we are going to warn are deprecated. 16643 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16644 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16645 return; 16646 16647 // Note: ignoring parens here is not justified by the standard rules, but 16648 // ignoring parentheses seems like a more reasonable approach, and this only 16649 // drives a deprecation warning so doesn't affect conformance. 16650 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16651 if (BO->getOpcode() == BO_Assign) { 16652 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16653 llvm::erase_value(LHSs, BO->getLHS()); 16654 } 16655 } 16656 } 16657 16658 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16659 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16660 !Decl->isConsteval() || isConstantEvaluated() || 16661 RebuildingImmediateInvocation || isImmediateFunctionContext()) 16662 return E; 16663 16664 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16665 /// It's OK if this fails; we'll also remove this in 16666 /// HandleImmediateInvocations, but catching it here allows us to avoid 16667 /// walking the AST looking for it in simple cases. 16668 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16669 if (auto *DeclRef = 16670 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16671 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16672 16673 E = MaybeCreateExprWithCleanups(E); 16674 16675 ConstantExpr *Res = ConstantExpr::Create( 16676 getASTContext(), E.get(), 16677 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16678 getASTContext()), 16679 /*IsImmediateInvocation*/ true); 16680 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16681 return Res; 16682 } 16683 16684 static void EvaluateAndDiagnoseImmediateInvocation( 16685 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16686 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16687 Expr::EvalResult Eval; 16688 Eval.Diag = &Notes; 16689 ConstantExpr *CE = Candidate.getPointer(); 16690 bool Result = CE->EvaluateAsConstantExpr( 16691 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16692 if (!Result || !Notes.empty()) { 16693 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16694 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16695 InnerExpr = FunctionalCast->getSubExpr(); 16696 FunctionDecl *FD = nullptr; 16697 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16698 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16699 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16700 FD = Call->getConstructor(); 16701 else 16702 llvm_unreachable("unhandled decl kind"); 16703 assert(FD->isConsteval()); 16704 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16705 for (auto &Note : Notes) 16706 SemaRef.Diag(Note.first, Note.second); 16707 return; 16708 } 16709 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16710 } 16711 16712 static void RemoveNestedImmediateInvocation( 16713 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16714 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16715 struct ComplexRemove : TreeTransform<ComplexRemove> { 16716 using Base = TreeTransform<ComplexRemove>; 16717 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16718 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16719 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16720 CurrentII; 16721 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16722 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16723 SmallVector<Sema::ImmediateInvocationCandidate, 16724 4>::reverse_iterator Current) 16725 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16726 void RemoveImmediateInvocation(ConstantExpr* E) { 16727 auto It = std::find_if(CurrentII, IISet.rend(), 16728 [E](Sema::ImmediateInvocationCandidate Elem) { 16729 return Elem.getPointer() == E; 16730 }); 16731 assert(It != IISet.rend() && 16732 "ConstantExpr marked IsImmediateInvocation should " 16733 "be present"); 16734 It->setInt(1); // Mark as deleted 16735 } 16736 ExprResult TransformConstantExpr(ConstantExpr *E) { 16737 if (!E->isImmediateInvocation()) 16738 return Base::TransformConstantExpr(E); 16739 RemoveImmediateInvocation(E); 16740 return Base::TransformExpr(E->getSubExpr()); 16741 } 16742 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16743 /// we need to remove its DeclRefExpr from the DRSet. 16744 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16745 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16746 return Base::TransformCXXOperatorCallExpr(E); 16747 } 16748 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16749 /// here. 16750 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16751 if (!Init) 16752 return Init; 16753 /// ConstantExpr are the first layer of implicit node to be removed so if 16754 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16755 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16756 if (CE->isImmediateInvocation()) 16757 RemoveImmediateInvocation(CE); 16758 return Base::TransformInitializer(Init, NotCopyInit); 16759 } 16760 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16761 DRSet.erase(E); 16762 return E; 16763 } 16764 bool AlwaysRebuild() { return false; } 16765 bool ReplacingOriginal() { return true; } 16766 bool AllowSkippingCXXConstructExpr() { 16767 bool Res = AllowSkippingFirstCXXConstructExpr; 16768 AllowSkippingFirstCXXConstructExpr = true; 16769 return Res; 16770 } 16771 bool AllowSkippingFirstCXXConstructExpr = true; 16772 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16773 Rec.ImmediateInvocationCandidates, It); 16774 16775 /// CXXConstructExpr with a single argument are getting skipped by 16776 /// TreeTransform in some situtation because they could be implicit. This 16777 /// can only occur for the top-level CXXConstructExpr because it is used 16778 /// nowhere in the expression being transformed therefore will not be rebuilt. 16779 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16780 /// skipping the first CXXConstructExpr. 16781 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16782 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16783 16784 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16785 assert(Res.isUsable()); 16786 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16787 It->getPointer()->setSubExpr(Res.get()); 16788 } 16789 16790 static void 16791 HandleImmediateInvocations(Sema &SemaRef, 16792 Sema::ExpressionEvaluationContextRecord &Rec) { 16793 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16794 Rec.ReferenceToConsteval.size() == 0) || 16795 SemaRef.RebuildingImmediateInvocation) 16796 return; 16797 16798 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16799 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16800 /// need to remove ReferenceToConsteval in the immediate invocation. 16801 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16802 16803 /// Prevent sema calls during the tree transform from adding pointers that 16804 /// are already in the sets. 16805 llvm::SaveAndRestore<bool> DisableIITracking( 16806 SemaRef.RebuildingImmediateInvocation, true); 16807 16808 /// Prevent diagnostic during tree transfrom as they are duplicates 16809 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16810 16811 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16812 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16813 if (!It->getInt()) 16814 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16815 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16816 Rec.ReferenceToConsteval.size()) { 16817 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16818 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16819 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16820 bool VisitDeclRefExpr(DeclRefExpr *E) { 16821 DRSet.erase(E); 16822 return DRSet.size(); 16823 } 16824 } Visitor(Rec.ReferenceToConsteval); 16825 Visitor.TraverseStmt( 16826 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16827 } 16828 for (auto CE : Rec.ImmediateInvocationCandidates) 16829 if (!CE.getInt()) 16830 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16831 for (auto DR : Rec.ReferenceToConsteval) { 16832 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16833 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16834 << FD; 16835 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16836 } 16837 } 16838 16839 void Sema::PopExpressionEvaluationContext() { 16840 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16841 unsigned NumTypos = Rec.NumTypos; 16842 16843 if (!Rec.Lambdas.empty()) { 16844 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16845 if (!getLangOpts().CPlusPlus20 && 16846 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16847 Rec.isUnevaluated() || 16848 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16849 unsigned D; 16850 if (Rec.isUnevaluated()) { 16851 // C++11 [expr.prim.lambda]p2: 16852 // A lambda-expression shall not appear in an unevaluated operand 16853 // (Clause 5). 16854 D = diag::err_lambda_unevaluated_operand; 16855 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16856 // C++1y [expr.const]p2: 16857 // A conditional-expression e is a core constant expression unless the 16858 // evaluation of e, following the rules of the abstract machine, would 16859 // evaluate [...] a lambda-expression. 16860 D = diag::err_lambda_in_constant_expression; 16861 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16862 // C++17 [expr.prim.lamda]p2: 16863 // A lambda-expression shall not appear [...] in a template-argument. 16864 D = diag::err_lambda_in_invalid_context; 16865 } else 16866 llvm_unreachable("Couldn't infer lambda error message."); 16867 16868 for (const auto *L : Rec.Lambdas) 16869 Diag(L->getBeginLoc(), D); 16870 } 16871 } 16872 16873 WarnOnPendingNoDerefs(Rec); 16874 HandleImmediateInvocations(*this, Rec); 16875 16876 // Warn on any volatile-qualified simple-assignments that are not discarded- 16877 // value expressions nor unevaluated operands (those cases get removed from 16878 // this list by CheckUnusedVolatileAssignment). 16879 for (auto *BO : Rec.VolatileAssignmentLHSs) 16880 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16881 << BO->getType(); 16882 16883 // When are coming out of an unevaluated context, clear out any 16884 // temporaries that we may have created as part of the evaluation of 16885 // the expression in that context: they aren't relevant because they 16886 // will never be constructed. 16887 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16888 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16889 ExprCleanupObjects.end()); 16890 Cleanup = Rec.ParentCleanup; 16891 CleanupVarDeclMarking(); 16892 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16893 // Otherwise, merge the contexts together. 16894 } else { 16895 Cleanup.mergeFrom(Rec.ParentCleanup); 16896 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16897 Rec.SavedMaybeODRUseExprs.end()); 16898 } 16899 16900 // Pop the current expression evaluation context off the stack. 16901 ExprEvalContexts.pop_back(); 16902 16903 // The global expression evaluation context record is never popped. 16904 ExprEvalContexts.back().NumTypos += NumTypos; 16905 } 16906 16907 void Sema::DiscardCleanupsInEvaluationContext() { 16908 ExprCleanupObjects.erase( 16909 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16910 ExprCleanupObjects.end()); 16911 Cleanup.reset(); 16912 MaybeODRUseExprs.clear(); 16913 } 16914 16915 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16916 ExprResult Result = CheckPlaceholderExpr(E); 16917 if (Result.isInvalid()) 16918 return ExprError(); 16919 E = Result.get(); 16920 if (!E->getType()->isVariablyModifiedType()) 16921 return E; 16922 return TransformToPotentiallyEvaluated(E); 16923 } 16924 16925 /// Are we in a context that is potentially constant evaluated per C++20 16926 /// [expr.const]p12? 16927 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16928 /// C++2a [expr.const]p12: 16929 // An expression or conversion is potentially constant evaluated if it is 16930 switch (SemaRef.ExprEvalContexts.back().Context) { 16931 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16932 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 16933 16934 // -- a manifestly constant-evaluated expression, 16935 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16936 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16937 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16938 // -- a potentially-evaluated expression, 16939 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16940 // -- an immediate subexpression of a braced-init-list, 16941 16942 // -- [FIXME] an expression of the form & cast-expression that occurs 16943 // within a templated entity 16944 // -- a subexpression of one of the above that is not a subexpression of 16945 // a nested unevaluated operand. 16946 return true; 16947 16948 case Sema::ExpressionEvaluationContext::Unevaluated: 16949 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16950 // Expressions in this context are never evaluated. 16951 return false; 16952 } 16953 llvm_unreachable("Invalid context"); 16954 } 16955 16956 /// Return true if this function has a calling convention that requires mangling 16957 /// in the size of the parameter pack. 16958 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16959 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16960 // we don't need parameter type sizes. 16961 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16962 if (!TT.isOSWindows() || !TT.isX86()) 16963 return false; 16964 16965 // If this is C++ and this isn't an extern "C" function, parameters do not 16966 // need to be complete. In this case, C++ mangling will apply, which doesn't 16967 // use the size of the parameters. 16968 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16969 return false; 16970 16971 // Stdcall, fastcall, and vectorcall need this special treatment. 16972 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16973 switch (CC) { 16974 case CC_X86StdCall: 16975 case CC_X86FastCall: 16976 case CC_X86VectorCall: 16977 return true; 16978 default: 16979 break; 16980 } 16981 return false; 16982 } 16983 16984 /// Require that all of the parameter types of function be complete. Normally, 16985 /// parameter types are only required to be complete when a function is called 16986 /// or defined, but to mangle functions with certain calling conventions, the 16987 /// mangler needs to know the size of the parameter list. In this situation, 16988 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16989 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16990 /// result in a linker error. Clang doesn't implement this behavior, and instead 16991 /// attempts to error at compile time. 16992 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16993 SourceLocation Loc) { 16994 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16995 FunctionDecl *FD; 16996 ParmVarDecl *Param; 16997 16998 public: 16999 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 17000 : FD(FD), Param(Param) {} 17001 17002 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17003 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17004 StringRef CCName; 17005 switch (CC) { 17006 case CC_X86StdCall: 17007 CCName = "stdcall"; 17008 break; 17009 case CC_X86FastCall: 17010 CCName = "fastcall"; 17011 break; 17012 case CC_X86VectorCall: 17013 CCName = "vectorcall"; 17014 break; 17015 default: 17016 llvm_unreachable("CC does not need mangling"); 17017 } 17018 17019 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17020 << Param->getDeclName() << FD->getDeclName() << CCName; 17021 } 17022 }; 17023 17024 for (ParmVarDecl *Param : FD->parameters()) { 17025 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17026 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17027 } 17028 } 17029 17030 namespace { 17031 enum class OdrUseContext { 17032 /// Declarations in this context are not odr-used. 17033 None, 17034 /// Declarations in this context are formally odr-used, but this is a 17035 /// dependent context. 17036 Dependent, 17037 /// Declarations in this context are odr-used but not actually used (yet). 17038 FormallyOdrUsed, 17039 /// Declarations in this context are used. 17040 Used 17041 }; 17042 } 17043 17044 /// Are we within a context in which references to resolved functions or to 17045 /// variables result in odr-use? 17046 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17047 OdrUseContext Result; 17048 17049 switch (SemaRef.ExprEvalContexts.back().Context) { 17050 case Sema::ExpressionEvaluationContext::Unevaluated: 17051 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17052 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17053 return OdrUseContext::None; 17054 17055 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17056 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17057 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17058 Result = OdrUseContext::Used; 17059 break; 17060 17061 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17062 Result = OdrUseContext::FormallyOdrUsed; 17063 break; 17064 17065 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17066 // A default argument formally results in odr-use, but doesn't actually 17067 // result in a use in any real sense until it itself is used. 17068 Result = OdrUseContext::FormallyOdrUsed; 17069 break; 17070 } 17071 17072 if (SemaRef.CurContext->isDependentContext()) 17073 return OdrUseContext::Dependent; 17074 17075 return Result; 17076 } 17077 17078 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17079 if (!Func->isConstexpr()) 17080 return false; 17081 17082 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17083 return true; 17084 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17085 return CCD && CCD->getInheritedConstructor(); 17086 } 17087 17088 /// Mark a function referenced, and check whether it is odr-used 17089 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17090 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17091 bool MightBeOdrUse) { 17092 assert(Func && "No function?"); 17093 17094 Func->setReferenced(); 17095 17096 // Recursive functions aren't really used until they're used from some other 17097 // context. 17098 bool IsRecursiveCall = CurContext == Func; 17099 17100 // C++11 [basic.def.odr]p3: 17101 // A function whose name appears as a potentially-evaluated expression is 17102 // odr-used if it is the unique lookup result or the selected member of a 17103 // set of overloaded functions [...]. 17104 // 17105 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17106 // can just check that here. 17107 OdrUseContext OdrUse = 17108 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17109 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17110 OdrUse = OdrUseContext::FormallyOdrUsed; 17111 17112 // Trivial default constructors and destructors are never actually used. 17113 // FIXME: What about other special members? 17114 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17115 OdrUse == OdrUseContext::Used) { 17116 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17117 if (Constructor->isDefaultConstructor()) 17118 OdrUse = OdrUseContext::FormallyOdrUsed; 17119 if (isa<CXXDestructorDecl>(Func)) 17120 OdrUse = OdrUseContext::FormallyOdrUsed; 17121 } 17122 17123 // C++20 [expr.const]p12: 17124 // A function [...] is needed for constant evaluation if it is [...] a 17125 // constexpr function that is named by an expression that is potentially 17126 // constant evaluated 17127 bool NeededForConstantEvaluation = 17128 isPotentiallyConstantEvaluatedContext(*this) && 17129 isImplicitlyDefinableConstexprFunction(Func); 17130 17131 // Determine whether we require a function definition to exist, per 17132 // C++11 [temp.inst]p3: 17133 // Unless a function template specialization has been explicitly 17134 // instantiated or explicitly specialized, the function template 17135 // specialization is implicitly instantiated when the specialization is 17136 // referenced in a context that requires a function definition to exist. 17137 // C++20 [temp.inst]p7: 17138 // The existence of a definition of a [...] function is considered to 17139 // affect the semantics of the program if the [...] function is needed for 17140 // constant evaluation by an expression 17141 // C++20 [basic.def.odr]p10: 17142 // Every program shall contain exactly one definition of every non-inline 17143 // function or variable that is odr-used in that program outside of a 17144 // discarded statement 17145 // C++20 [special]p1: 17146 // The implementation will implicitly define [defaulted special members] 17147 // if they are odr-used or needed for constant evaluation. 17148 // 17149 // Note that we skip the implicit instantiation of templates that are only 17150 // used in unused default arguments or by recursive calls to themselves. 17151 // This is formally non-conforming, but seems reasonable in practice. 17152 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17153 NeededForConstantEvaluation); 17154 17155 // C++14 [temp.expl.spec]p6: 17156 // If a template [...] is explicitly specialized then that specialization 17157 // shall be declared before the first use of that specialization that would 17158 // cause an implicit instantiation to take place, in every translation unit 17159 // in which such a use occurs 17160 if (NeedDefinition && 17161 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17162 Func->getMemberSpecializationInfo())) 17163 checkSpecializationVisibility(Loc, Func); 17164 17165 if (getLangOpts().CUDA) 17166 CheckCUDACall(Loc, Func); 17167 17168 if (getLangOpts().SYCLIsDevice) 17169 checkSYCLDeviceFunction(Loc, Func); 17170 17171 // If we need a definition, try to create one. 17172 if (NeedDefinition && !Func->getBody()) { 17173 runWithSufficientStackSpace(Loc, [&] { 17174 if (CXXConstructorDecl *Constructor = 17175 dyn_cast<CXXConstructorDecl>(Func)) { 17176 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17177 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17178 if (Constructor->isDefaultConstructor()) { 17179 if (Constructor->isTrivial() && 17180 !Constructor->hasAttr<DLLExportAttr>()) 17181 return; 17182 DefineImplicitDefaultConstructor(Loc, Constructor); 17183 } else if (Constructor->isCopyConstructor()) { 17184 DefineImplicitCopyConstructor(Loc, Constructor); 17185 } else if (Constructor->isMoveConstructor()) { 17186 DefineImplicitMoveConstructor(Loc, Constructor); 17187 } 17188 } else if (Constructor->getInheritedConstructor()) { 17189 DefineInheritingConstructor(Loc, Constructor); 17190 } 17191 } else if (CXXDestructorDecl *Destructor = 17192 dyn_cast<CXXDestructorDecl>(Func)) { 17193 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17194 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17195 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17196 return; 17197 DefineImplicitDestructor(Loc, Destructor); 17198 } 17199 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17200 MarkVTableUsed(Loc, Destructor->getParent()); 17201 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17202 if (MethodDecl->isOverloadedOperator() && 17203 MethodDecl->getOverloadedOperator() == OO_Equal) { 17204 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17205 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17206 if (MethodDecl->isCopyAssignmentOperator()) 17207 DefineImplicitCopyAssignment(Loc, MethodDecl); 17208 else if (MethodDecl->isMoveAssignmentOperator()) 17209 DefineImplicitMoveAssignment(Loc, MethodDecl); 17210 } 17211 } else if (isa<CXXConversionDecl>(MethodDecl) && 17212 MethodDecl->getParent()->isLambda()) { 17213 CXXConversionDecl *Conversion = 17214 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17215 if (Conversion->isLambdaToBlockPointerConversion()) 17216 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17217 else 17218 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17219 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17220 MarkVTableUsed(Loc, MethodDecl->getParent()); 17221 } 17222 17223 if (Func->isDefaulted() && !Func->isDeleted()) { 17224 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17225 if (DCK != DefaultedComparisonKind::None) 17226 DefineDefaultedComparison(Loc, Func, DCK); 17227 } 17228 17229 // Implicit instantiation of function templates and member functions of 17230 // class templates. 17231 if (Func->isImplicitlyInstantiable()) { 17232 TemplateSpecializationKind TSK = 17233 Func->getTemplateSpecializationKindForInstantiation(); 17234 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17235 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17236 if (FirstInstantiation) { 17237 PointOfInstantiation = Loc; 17238 if (auto *MSI = Func->getMemberSpecializationInfo()) 17239 MSI->setPointOfInstantiation(Loc); 17240 // FIXME: Notify listener. 17241 else 17242 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17243 } else if (TSK != TSK_ImplicitInstantiation) { 17244 // Use the point of use as the point of instantiation, instead of the 17245 // point of explicit instantiation (which we track as the actual point 17246 // of instantiation). This gives better backtraces in diagnostics. 17247 PointOfInstantiation = Loc; 17248 } 17249 17250 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17251 Func->isConstexpr()) { 17252 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17253 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17254 CodeSynthesisContexts.size()) 17255 PendingLocalImplicitInstantiations.push_back( 17256 std::make_pair(Func, PointOfInstantiation)); 17257 else if (Func->isConstexpr()) 17258 // Do not defer instantiations of constexpr functions, to avoid the 17259 // expression evaluator needing to call back into Sema if it sees a 17260 // call to such a function. 17261 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17262 else { 17263 Func->setInstantiationIsPending(true); 17264 PendingInstantiations.push_back( 17265 std::make_pair(Func, PointOfInstantiation)); 17266 // Notify the consumer that a function was implicitly instantiated. 17267 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17268 } 17269 } 17270 } else { 17271 // Walk redefinitions, as some of them may be instantiable. 17272 for (auto i : Func->redecls()) { 17273 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17274 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17275 } 17276 } 17277 }); 17278 } 17279 17280 // C++14 [except.spec]p17: 17281 // An exception-specification is considered to be needed when: 17282 // - the function is odr-used or, if it appears in an unevaluated operand, 17283 // would be odr-used if the expression were potentially-evaluated; 17284 // 17285 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17286 // function is a pure virtual function we're calling, and in that case the 17287 // function was selected by overload resolution and we need to resolve its 17288 // exception specification for a different reason. 17289 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17290 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17291 ResolveExceptionSpec(Loc, FPT); 17292 17293 // If this is the first "real" use, act on that. 17294 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17295 // Keep track of used but undefined functions. 17296 if (!Func->isDefined()) { 17297 if (mightHaveNonExternalLinkage(Func)) 17298 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17299 else if (Func->getMostRecentDecl()->isInlined() && 17300 !LangOpts.GNUInline && 17301 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17302 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17303 else if (isExternalWithNoLinkageType(Func)) 17304 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17305 } 17306 17307 // Some x86 Windows calling conventions mangle the size of the parameter 17308 // pack into the name. Computing the size of the parameters requires the 17309 // parameter types to be complete. Check that now. 17310 if (funcHasParameterSizeMangling(*this, Func)) 17311 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17312 17313 // In the MS C++ ABI, the compiler emits destructor variants where they are 17314 // used. If the destructor is used here but defined elsewhere, mark the 17315 // virtual base destructors referenced. If those virtual base destructors 17316 // are inline, this will ensure they are defined when emitting the complete 17317 // destructor variant. This checking may be redundant if the destructor is 17318 // provided later in this TU. 17319 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17320 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17321 CXXRecordDecl *Parent = Dtor->getParent(); 17322 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17323 CheckCompleteDestructorVariant(Loc, Dtor); 17324 } 17325 } 17326 17327 Func->markUsed(Context); 17328 } 17329 } 17330 17331 /// Directly mark a variable odr-used. Given a choice, prefer to use 17332 /// MarkVariableReferenced since it does additional checks and then 17333 /// calls MarkVarDeclODRUsed. 17334 /// If the variable must be captured: 17335 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17336 /// - else capture it in the DeclContext that maps to the 17337 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17338 static void 17339 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17340 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17341 // Keep track of used but undefined variables. 17342 // FIXME: We shouldn't suppress this warning for static data members. 17343 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17344 (!Var->isExternallyVisible() || Var->isInline() || 17345 SemaRef.isExternalWithNoLinkageType(Var)) && 17346 !(Var->isStaticDataMember() && Var->hasInit())) { 17347 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17348 if (old.isInvalid()) 17349 old = Loc; 17350 } 17351 QualType CaptureType, DeclRefType; 17352 if (SemaRef.LangOpts.OpenMP) 17353 SemaRef.tryCaptureOpenMPLambdas(Var); 17354 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17355 /*EllipsisLoc*/ SourceLocation(), 17356 /*BuildAndDiagnose*/ true, 17357 CaptureType, DeclRefType, 17358 FunctionScopeIndexToStopAt); 17359 17360 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17361 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17362 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17363 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17364 if (VarTarget == Sema::CVT_Host && 17365 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17366 UserTarget == Sema::CFT_Global)) { 17367 // Diagnose ODR-use of host global variables in device functions. 17368 // Reference of device global variables in host functions is allowed 17369 // through shadow variables therefore it is not diagnosed. 17370 if (SemaRef.LangOpts.CUDAIsDevice) { 17371 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17372 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17373 SemaRef.targetDiag(Var->getLocation(), 17374 Var->getType().isConstQualified() 17375 ? diag::note_cuda_const_var_unpromoted 17376 : diag::note_cuda_host_var); 17377 } 17378 } else if (VarTarget == Sema::CVT_Device && 17379 (UserTarget == Sema::CFT_Host || 17380 UserTarget == Sema::CFT_HostDevice) && 17381 !Var->hasExternalStorage()) { 17382 // Record a CUDA/HIP device side variable if it is ODR-used 17383 // by host code. This is done conservatively, when the variable is 17384 // referenced in any of the following contexts: 17385 // - a non-function context 17386 // - a host function 17387 // - a host device function 17388 // This makes the ODR-use of the device side variable by host code to 17389 // be visible in the device compilation for the compiler to be able to 17390 // emit template variables instantiated by host code only and to 17391 // externalize the static device side variable ODR-used by host code. 17392 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17393 } 17394 } 17395 17396 Var->markUsed(SemaRef.Context); 17397 } 17398 17399 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17400 SourceLocation Loc, 17401 unsigned CapturingScopeIndex) { 17402 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17403 } 17404 17405 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17406 ValueDecl *var) { 17407 DeclContext *VarDC = var->getDeclContext(); 17408 17409 // If the parameter still belongs to the translation unit, then 17410 // we're actually just using one parameter in the declaration of 17411 // the next. 17412 if (isa<ParmVarDecl>(var) && 17413 isa<TranslationUnitDecl>(VarDC)) 17414 return; 17415 17416 // For C code, don't diagnose about capture if we're not actually in code 17417 // right now; it's impossible to write a non-constant expression outside of 17418 // function context, so we'll get other (more useful) diagnostics later. 17419 // 17420 // For C++, things get a bit more nasty... it would be nice to suppress this 17421 // diagnostic for certain cases like using a local variable in an array bound 17422 // for a member of a local class, but the correct predicate is not obvious. 17423 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17424 return; 17425 17426 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17427 unsigned ContextKind = 3; // unknown 17428 if (isa<CXXMethodDecl>(VarDC) && 17429 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17430 ContextKind = 2; 17431 } else if (isa<FunctionDecl>(VarDC)) { 17432 ContextKind = 0; 17433 } else if (isa<BlockDecl>(VarDC)) { 17434 ContextKind = 1; 17435 } 17436 17437 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17438 << var << ValueKind << ContextKind << VarDC; 17439 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17440 << var; 17441 17442 // FIXME: Add additional diagnostic info about class etc. which prevents 17443 // capture. 17444 } 17445 17446 17447 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17448 bool &SubCapturesAreNested, 17449 QualType &CaptureType, 17450 QualType &DeclRefType) { 17451 // Check whether we've already captured it. 17452 if (CSI->CaptureMap.count(Var)) { 17453 // If we found a capture, any subcaptures are nested. 17454 SubCapturesAreNested = true; 17455 17456 // Retrieve the capture type for this variable. 17457 CaptureType = CSI->getCapture(Var).getCaptureType(); 17458 17459 // Compute the type of an expression that refers to this variable. 17460 DeclRefType = CaptureType.getNonReferenceType(); 17461 17462 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17463 // are mutable in the sense that user can change their value - they are 17464 // private instances of the captured declarations. 17465 const Capture &Cap = CSI->getCapture(Var); 17466 if (Cap.isCopyCapture() && 17467 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17468 !(isa<CapturedRegionScopeInfo>(CSI) && 17469 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17470 DeclRefType.addConst(); 17471 return true; 17472 } 17473 return false; 17474 } 17475 17476 // Only block literals, captured statements, and lambda expressions can 17477 // capture; other scopes don't work. 17478 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17479 SourceLocation Loc, 17480 const bool Diagnose, Sema &S) { 17481 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17482 return getLambdaAwareParentOfDeclContext(DC); 17483 else if (Var->hasLocalStorage()) { 17484 if (Diagnose) 17485 diagnoseUncapturableValueReference(S, Loc, Var); 17486 } 17487 return nullptr; 17488 } 17489 17490 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17491 // certain types of variables (unnamed, variably modified types etc.) 17492 // so check for eligibility. 17493 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17494 SourceLocation Loc, 17495 const bool Diagnose, Sema &S) { 17496 17497 bool IsBlock = isa<BlockScopeInfo>(CSI); 17498 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17499 17500 // Lambdas are not allowed to capture unnamed variables 17501 // (e.g. anonymous unions). 17502 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17503 // assuming that's the intent. 17504 if (IsLambda && !Var->getDeclName()) { 17505 if (Diagnose) { 17506 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17507 S.Diag(Var->getLocation(), diag::note_declared_at); 17508 } 17509 return false; 17510 } 17511 17512 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17513 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17514 if (Diagnose) { 17515 S.Diag(Loc, diag::err_ref_vm_type); 17516 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17517 } 17518 return false; 17519 } 17520 // Prohibit structs with flexible array members too. 17521 // We cannot capture what is in the tail end of the struct. 17522 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17523 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17524 if (Diagnose) { 17525 if (IsBlock) 17526 S.Diag(Loc, diag::err_ref_flexarray_type); 17527 else 17528 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17529 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17530 } 17531 return false; 17532 } 17533 } 17534 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17535 // Lambdas and captured statements are not allowed to capture __block 17536 // variables; they don't support the expected semantics. 17537 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17538 if (Diagnose) { 17539 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17540 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17541 } 17542 return false; 17543 } 17544 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17545 if (S.getLangOpts().OpenCL && IsBlock && 17546 Var->getType()->isBlockPointerType()) { 17547 if (Diagnose) 17548 S.Diag(Loc, diag::err_opencl_block_ref_block); 17549 return false; 17550 } 17551 17552 return true; 17553 } 17554 17555 // Returns true if the capture by block was successful. 17556 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17557 SourceLocation Loc, 17558 const bool BuildAndDiagnose, 17559 QualType &CaptureType, 17560 QualType &DeclRefType, 17561 const bool Nested, 17562 Sema &S, bool Invalid) { 17563 bool ByRef = false; 17564 17565 // Blocks are not allowed to capture arrays, excepting OpenCL. 17566 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17567 // (decayed to pointers). 17568 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17569 if (BuildAndDiagnose) { 17570 S.Diag(Loc, diag::err_ref_array_type); 17571 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17572 Invalid = true; 17573 } else { 17574 return false; 17575 } 17576 } 17577 17578 // Forbid the block-capture of autoreleasing variables. 17579 if (!Invalid && 17580 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17581 if (BuildAndDiagnose) { 17582 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17583 << /*block*/ 0; 17584 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17585 Invalid = true; 17586 } else { 17587 return false; 17588 } 17589 } 17590 17591 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17592 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17593 QualType PointeeTy = PT->getPointeeType(); 17594 17595 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17596 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17597 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17598 if (BuildAndDiagnose) { 17599 SourceLocation VarLoc = Var->getLocation(); 17600 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17601 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17602 } 17603 } 17604 } 17605 17606 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17607 if (HasBlocksAttr || CaptureType->isReferenceType() || 17608 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17609 // Block capture by reference does not change the capture or 17610 // declaration reference types. 17611 ByRef = true; 17612 } else { 17613 // Block capture by copy introduces 'const'. 17614 CaptureType = CaptureType.getNonReferenceType().withConst(); 17615 DeclRefType = CaptureType; 17616 } 17617 17618 // Actually capture the variable. 17619 if (BuildAndDiagnose) 17620 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17621 CaptureType, Invalid); 17622 17623 return !Invalid; 17624 } 17625 17626 17627 /// Capture the given variable in the captured region. 17628 static bool captureInCapturedRegion( 17629 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17630 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17631 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17632 bool IsTopScope, Sema &S, bool Invalid) { 17633 // By default, capture variables by reference. 17634 bool ByRef = true; 17635 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17636 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17637 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17638 // Using an LValue reference type is consistent with Lambdas (see below). 17639 if (S.isOpenMPCapturedDecl(Var)) { 17640 bool HasConst = DeclRefType.isConstQualified(); 17641 DeclRefType = DeclRefType.getUnqualifiedType(); 17642 // Don't lose diagnostics about assignments to const. 17643 if (HasConst) 17644 DeclRefType.addConst(); 17645 } 17646 // Do not capture firstprivates in tasks. 17647 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17648 OMPC_unknown) 17649 return true; 17650 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17651 RSI->OpenMPCaptureLevel); 17652 } 17653 17654 if (ByRef) 17655 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17656 else 17657 CaptureType = DeclRefType; 17658 17659 // Actually capture the variable. 17660 if (BuildAndDiagnose) 17661 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17662 Loc, SourceLocation(), CaptureType, Invalid); 17663 17664 return !Invalid; 17665 } 17666 17667 /// Capture the given variable in the lambda. 17668 static bool captureInLambda(LambdaScopeInfo *LSI, 17669 VarDecl *Var, 17670 SourceLocation Loc, 17671 const bool BuildAndDiagnose, 17672 QualType &CaptureType, 17673 QualType &DeclRefType, 17674 const bool RefersToCapturedVariable, 17675 const Sema::TryCaptureKind Kind, 17676 SourceLocation EllipsisLoc, 17677 const bool IsTopScope, 17678 Sema &S, bool Invalid) { 17679 // Determine whether we are capturing by reference or by value. 17680 bool ByRef = false; 17681 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17682 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17683 } else { 17684 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17685 } 17686 17687 // Compute the type of the field that will capture this variable. 17688 if (ByRef) { 17689 // C++11 [expr.prim.lambda]p15: 17690 // An entity is captured by reference if it is implicitly or 17691 // explicitly captured but not captured by copy. It is 17692 // unspecified whether additional unnamed non-static data 17693 // members are declared in the closure type for entities 17694 // captured by reference. 17695 // 17696 // FIXME: It is not clear whether we want to build an lvalue reference 17697 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17698 // to do the former, while EDG does the latter. Core issue 1249 will 17699 // clarify, but for now we follow GCC because it's a more permissive and 17700 // easily defensible position. 17701 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17702 } else { 17703 // C++11 [expr.prim.lambda]p14: 17704 // For each entity captured by copy, an unnamed non-static 17705 // data member is declared in the closure type. The 17706 // declaration order of these members is unspecified. The type 17707 // of such a data member is the type of the corresponding 17708 // captured entity if the entity is not a reference to an 17709 // object, or the referenced type otherwise. [Note: If the 17710 // captured entity is a reference to a function, the 17711 // corresponding data member is also a reference to a 17712 // function. - end note ] 17713 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17714 if (!RefType->getPointeeType()->isFunctionType()) 17715 CaptureType = RefType->getPointeeType(); 17716 } 17717 17718 // Forbid the lambda copy-capture of autoreleasing variables. 17719 if (!Invalid && 17720 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17721 if (BuildAndDiagnose) { 17722 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17723 S.Diag(Var->getLocation(), diag::note_previous_decl) 17724 << Var->getDeclName(); 17725 Invalid = true; 17726 } else { 17727 return false; 17728 } 17729 } 17730 17731 // Make sure that by-copy captures are of a complete and non-abstract type. 17732 if (!Invalid && BuildAndDiagnose) { 17733 if (!CaptureType->isDependentType() && 17734 S.RequireCompleteSizedType( 17735 Loc, CaptureType, 17736 diag::err_capture_of_incomplete_or_sizeless_type, 17737 Var->getDeclName())) 17738 Invalid = true; 17739 else if (S.RequireNonAbstractType(Loc, CaptureType, 17740 diag::err_capture_of_abstract_type)) 17741 Invalid = true; 17742 } 17743 } 17744 17745 // Compute the type of a reference to this captured variable. 17746 if (ByRef) 17747 DeclRefType = CaptureType.getNonReferenceType(); 17748 else { 17749 // C++ [expr.prim.lambda]p5: 17750 // The closure type for a lambda-expression has a public inline 17751 // function call operator [...]. This function call operator is 17752 // declared const (9.3.1) if and only if the lambda-expression's 17753 // parameter-declaration-clause is not followed by mutable. 17754 DeclRefType = CaptureType.getNonReferenceType(); 17755 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17756 DeclRefType.addConst(); 17757 } 17758 17759 // Add the capture. 17760 if (BuildAndDiagnose) 17761 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17762 Loc, EllipsisLoc, CaptureType, Invalid); 17763 17764 return !Invalid; 17765 } 17766 17767 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17768 // Offer a Copy fix even if the type is dependent. 17769 if (Var->getType()->isDependentType()) 17770 return true; 17771 QualType T = Var->getType().getNonReferenceType(); 17772 if (T.isTriviallyCopyableType(Context)) 17773 return true; 17774 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17775 17776 if (!(RD = RD->getDefinition())) 17777 return false; 17778 if (RD->hasSimpleCopyConstructor()) 17779 return true; 17780 if (RD->hasUserDeclaredCopyConstructor()) 17781 for (CXXConstructorDecl *Ctor : RD->ctors()) 17782 if (Ctor->isCopyConstructor()) 17783 return !Ctor->isDeleted(); 17784 } 17785 return false; 17786 } 17787 17788 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17789 /// default capture. Fixes may be omitted if they aren't allowed by the 17790 /// standard, for example we can't emit a default copy capture fix-it if we 17791 /// already explicitly copy capture capture another variable. 17792 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17793 VarDecl *Var) { 17794 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17795 // Don't offer Capture by copy of default capture by copy fixes if Var is 17796 // known not to be copy constructible. 17797 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17798 17799 SmallString<32> FixBuffer; 17800 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17801 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17802 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17803 if (ShouldOfferCopyFix) { 17804 // Offer fixes to insert an explicit capture for the variable. 17805 // [] -> [VarName] 17806 // [OtherCapture] -> [OtherCapture, VarName] 17807 FixBuffer.assign({Separator, Var->getName()}); 17808 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17809 << Var << /*value*/ 0 17810 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17811 } 17812 // As above but capture by reference. 17813 FixBuffer.assign({Separator, "&", Var->getName()}); 17814 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17815 << Var << /*reference*/ 1 17816 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17817 } 17818 17819 // Only try to offer default capture if there are no captures excluding this 17820 // and init captures. 17821 // [this]: OK. 17822 // [X = Y]: OK. 17823 // [&A, &B]: Don't offer. 17824 // [A, B]: Don't offer. 17825 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17826 return !C.isThisCapture() && !C.isInitCapture(); 17827 })) 17828 return; 17829 17830 // The default capture specifiers, '=' or '&', must appear first in the 17831 // capture body. 17832 SourceLocation DefaultInsertLoc = 17833 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17834 17835 if (ShouldOfferCopyFix) { 17836 bool CanDefaultCopyCapture = true; 17837 // [=, *this] OK since c++17 17838 // [=, this] OK since c++20 17839 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17840 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17841 ? LSI->getCXXThisCapture().isCopyCapture() 17842 : false; 17843 // We can't use default capture by copy if any captures already specified 17844 // capture by copy. 17845 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17846 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17847 })) { 17848 FixBuffer.assign({"=", Separator}); 17849 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17850 << /*value*/ 0 17851 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17852 } 17853 } 17854 17855 // We can't use default capture by reference if any captures already specified 17856 // capture by reference. 17857 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17858 return !C.isInitCapture() && C.isReferenceCapture() && 17859 !C.isThisCapture(); 17860 })) { 17861 FixBuffer.assign({"&", Separator}); 17862 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17863 << /*reference*/ 1 17864 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17865 } 17866 } 17867 17868 bool Sema::tryCaptureVariable( 17869 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17870 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17871 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17872 // An init-capture is notionally from the context surrounding its 17873 // declaration, but its parent DC is the lambda class. 17874 DeclContext *VarDC = Var->getDeclContext(); 17875 if (Var->isInitCapture()) 17876 VarDC = VarDC->getParent(); 17877 17878 DeclContext *DC = CurContext; 17879 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17880 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17881 // We need to sync up the Declaration Context with the 17882 // FunctionScopeIndexToStopAt 17883 if (FunctionScopeIndexToStopAt) { 17884 unsigned FSIndex = FunctionScopes.size() - 1; 17885 while (FSIndex != MaxFunctionScopesIndex) { 17886 DC = getLambdaAwareParentOfDeclContext(DC); 17887 --FSIndex; 17888 } 17889 } 17890 17891 17892 // If the variable is declared in the current context, there is no need to 17893 // capture it. 17894 if (VarDC == DC) return true; 17895 17896 // Capture global variables if it is required to use private copy of this 17897 // variable. 17898 bool IsGlobal = !Var->hasLocalStorage(); 17899 if (IsGlobal && 17900 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17901 MaxFunctionScopesIndex))) 17902 return true; 17903 Var = Var->getCanonicalDecl(); 17904 17905 // Walk up the stack to determine whether we can capture the variable, 17906 // performing the "simple" checks that don't depend on type. We stop when 17907 // we've either hit the declared scope of the variable or find an existing 17908 // capture of that variable. We start from the innermost capturing-entity 17909 // (the DC) and ensure that all intervening capturing-entities 17910 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17911 // declcontext can either capture the variable or have already captured 17912 // the variable. 17913 CaptureType = Var->getType(); 17914 DeclRefType = CaptureType.getNonReferenceType(); 17915 bool Nested = false; 17916 bool Explicit = (Kind != TryCapture_Implicit); 17917 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17918 do { 17919 // Only block literals, captured statements, and lambda expressions can 17920 // capture; other scopes don't work. 17921 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17922 ExprLoc, 17923 BuildAndDiagnose, 17924 *this); 17925 // We need to check for the parent *first* because, if we *have* 17926 // private-captured a global variable, we need to recursively capture it in 17927 // intermediate blocks, lambdas, etc. 17928 if (!ParentDC) { 17929 if (IsGlobal) { 17930 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17931 break; 17932 } 17933 return true; 17934 } 17935 17936 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17937 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17938 17939 17940 // Check whether we've already captured it. 17941 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17942 DeclRefType)) { 17943 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17944 break; 17945 } 17946 // If we are instantiating a generic lambda call operator body, 17947 // we do not want to capture new variables. What was captured 17948 // during either a lambdas transformation or initial parsing 17949 // should be used. 17950 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17951 if (BuildAndDiagnose) { 17952 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17953 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17954 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17955 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17956 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17957 buildLambdaCaptureFixit(*this, LSI, Var); 17958 } else 17959 diagnoseUncapturableValueReference(*this, ExprLoc, Var); 17960 } 17961 return true; 17962 } 17963 17964 // Try to capture variable-length arrays types. 17965 if (Var->getType()->isVariablyModifiedType()) { 17966 // We're going to walk down into the type and look for VLA 17967 // expressions. 17968 QualType QTy = Var->getType(); 17969 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17970 QTy = PVD->getOriginalType(); 17971 captureVariablyModifiedType(Context, QTy, CSI); 17972 } 17973 17974 if (getLangOpts().OpenMP) { 17975 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17976 // OpenMP private variables should not be captured in outer scope, so 17977 // just break here. Similarly, global variables that are captured in a 17978 // target region should not be captured outside the scope of the region. 17979 if (RSI->CapRegionKind == CR_OpenMP) { 17980 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17981 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17982 // If the variable is private (i.e. not captured) and has variably 17983 // modified type, we still need to capture the type for correct 17984 // codegen in all regions, associated with the construct. Currently, 17985 // it is captured in the innermost captured region only. 17986 if (IsOpenMPPrivateDecl != OMPC_unknown && 17987 Var->getType()->isVariablyModifiedType()) { 17988 QualType QTy = Var->getType(); 17989 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17990 QTy = PVD->getOriginalType(); 17991 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17992 I < E; ++I) { 17993 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17994 FunctionScopes[FunctionScopesIndex - I]); 17995 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17996 "Wrong number of captured regions associated with the " 17997 "OpenMP construct."); 17998 captureVariablyModifiedType(Context, QTy, OuterRSI); 17999 } 18000 } 18001 bool IsTargetCap = 18002 IsOpenMPPrivateDecl != OMPC_private && 18003 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 18004 RSI->OpenMPCaptureLevel); 18005 // Do not capture global if it is not privatized in outer regions. 18006 bool IsGlobalCap = 18007 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 18008 RSI->OpenMPCaptureLevel); 18009 18010 // When we detect target captures we are looking from inside the 18011 // target region, therefore we need to propagate the capture from the 18012 // enclosing region. Therefore, the capture is not initially nested. 18013 if (IsTargetCap) 18014 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18015 18016 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18017 (IsGlobal && !IsGlobalCap)) { 18018 Nested = !IsTargetCap; 18019 bool HasConst = DeclRefType.isConstQualified(); 18020 DeclRefType = DeclRefType.getUnqualifiedType(); 18021 // Don't lose diagnostics about assignments to const. 18022 if (HasConst) 18023 DeclRefType.addConst(); 18024 CaptureType = Context.getLValueReferenceType(DeclRefType); 18025 break; 18026 } 18027 } 18028 } 18029 } 18030 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18031 // No capture-default, and this is not an explicit capture 18032 // so cannot capture this variable. 18033 if (BuildAndDiagnose) { 18034 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18035 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18036 auto *LSI = cast<LambdaScopeInfo>(CSI); 18037 if (LSI->Lambda) { 18038 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18039 buildLambdaCaptureFixit(*this, LSI, Var); 18040 } 18041 // FIXME: If we error out because an outer lambda can not implicitly 18042 // capture a variable that an inner lambda explicitly captures, we 18043 // should have the inner lambda do the explicit capture - because 18044 // it makes for cleaner diagnostics later. This would purely be done 18045 // so that the diagnostic does not misleadingly claim that a variable 18046 // can not be captured by a lambda implicitly even though it is captured 18047 // explicitly. Suggestion: 18048 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18049 // at the function head 18050 // - cache the StartingDeclContext - this must be a lambda 18051 // - captureInLambda in the innermost lambda the variable. 18052 } 18053 return true; 18054 } 18055 18056 FunctionScopesIndex--; 18057 DC = ParentDC; 18058 Explicit = false; 18059 } while (!VarDC->Equals(DC)); 18060 18061 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18062 // computing the type of the capture at each step, checking type-specific 18063 // requirements, and adding captures if requested. 18064 // If the variable had already been captured previously, we start capturing 18065 // at the lambda nested within that one. 18066 bool Invalid = false; 18067 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18068 ++I) { 18069 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18070 18071 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18072 // certain types of variables (unnamed, variably modified types etc.) 18073 // so check for eligibility. 18074 if (!Invalid) 18075 Invalid = 18076 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18077 18078 // After encountering an error, if we're actually supposed to capture, keep 18079 // capturing in nested contexts to suppress any follow-on diagnostics. 18080 if (Invalid && !BuildAndDiagnose) 18081 return true; 18082 18083 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18084 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18085 DeclRefType, Nested, *this, Invalid); 18086 Nested = true; 18087 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18088 Invalid = !captureInCapturedRegion( 18089 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18090 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18091 Nested = true; 18092 } else { 18093 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18094 Invalid = 18095 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18096 DeclRefType, Nested, Kind, EllipsisLoc, 18097 /*IsTopScope*/ I == N - 1, *this, Invalid); 18098 Nested = true; 18099 } 18100 18101 if (Invalid && !BuildAndDiagnose) 18102 return true; 18103 } 18104 return Invalid; 18105 } 18106 18107 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18108 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18109 QualType CaptureType; 18110 QualType DeclRefType; 18111 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18112 /*BuildAndDiagnose=*/true, CaptureType, 18113 DeclRefType, nullptr); 18114 } 18115 18116 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18117 QualType CaptureType; 18118 QualType DeclRefType; 18119 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18120 /*BuildAndDiagnose=*/false, CaptureType, 18121 DeclRefType, nullptr); 18122 } 18123 18124 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18125 QualType CaptureType; 18126 QualType DeclRefType; 18127 18128 // Determine whether we can capture this variable. 18129 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18130 /*BuildAndDiagnose=*/false, CaptureType, 18131 DeclRefType, nullptr)) 18132 return QualType(); 18133 18134 return DeclRefType; 18135 } 18136 18137 namespace { 18138 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18139 // The produced TemplateArgumentListInfo* points to data stored within this 18140 // object, so should only be used in contexts where the pointer will not be 18141 // used after the CopiedTemplateArgs object is destroyed. 18142 class CopiedTemplateArgs { 18143 bool HasArgs; 18144 TemplateArgumentListInfo TemplateArgStorage; 18145 public: 18146 template<typename RefExpr> 18147 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18148 if (HasArgs) 18149 E->copyTemplateArgumentsInto(TemplateArgStorage); 18150 } 18151 operator TemplateArgumentListInfo*() 18152 #ifdef __has_cpp_attribute 18153 #if __has_cpp_attribute(clang::lifetimebound) 18154 [[clang::lifetimebound]] 18155 #endif 18156 #endif 18157 { 18158 return HasArgs ? &TemplateArgStorage : nullptr; 18159 } 18160 }; 18161 } 18162 18163 /// Walk the set of potential results of an expression and mark them all as 18164 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18165 /// 18166 /// \return A new expression if we found any potential results, ExprEmpty() if 18167 /// not, and ExprError() if we diagnosed an error. 18168 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18169 NonOdrUseReason NOUR) { 18170 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18171 // an object that satisfies the requirements for appearing in a 18172 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18173 // is immediately applied." This function handles the lvalue-to-rvalue 18174 // conversion part. 18175 // 18176 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18177 // transform it into the relevant kind of non-odr-use node and rebuild the 18178 // tree of nodes leading to it. 18179 // 18180 // This is a mini-TreeTransform that only transforms a restricted subset of 18181 // nodes (and only certain operands of them). 18182 18183 // Rebuild a subexpression. 18184 auto Rebuild = [&](Expr *Sub) { 18185 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18186 }; 18187 18188 // Check whether a potential result satisfies the requirements of NOUR. 18189 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18190 // Any entity other than a VarDecl is always odr-used whenever it's named 18191 // in a potentially-evaluated expression. 18192 auto *VD = dyn_cast<VarDecl>(D); 18193 if (!VD) 18194 return true; 18195 18196 // C++2a [basic.def.odr]p4: 18197 // A variable x whose name appears as a potentially-evalauted expression 18198 // e is odr-used by e unless 18199 // -- x is a reference that is usable in constant expressions, or 18200 // -- x is a variable of non-reference type that is usable in constant 18201 // expressions and has no mutable subobjects, and e is an element of 18202 // the set of potential results of an expression of 18203 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18204 // conversion is applied, or 18205 // -- x is a variable of non-reference type, and e is an element of the 18206 // set of potential results of a discarded-value expression to which 18207 // the lvalue-to-rvalue conversion is not applied 18208 // 18209 // We check the first bullet and the "potentially-evaluated" condition in 18210 // BuildDeclRefExpr. We check the type requirements in the second bullet 18211 // in CheckLValueToRValueConversionOperand below. 18212 switch (NOUR) { 18213 case NOUR_None: 18214 case NOUR_Unevaluated: 18215 llvm_unreachable("unexpected non-odr-use-reason"); 18216 18217 case NOUR_Constant: 18218 // Constant references were handled when they were built. 18219 if (VD->getType()->isReferenceType()) 18220 return true; 18221 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18222 if (RD->hasMutableFields()) 18223 return true; 18224 if (!VD->isUsableInConstantExpressions(S.Context)) 18225 return true; 18226 break; 18227 18228 case NOUR_Discarded: 18229 if (VD->getType()->isReferenceType()) 18230 return true; 18231 break; 18232 } 18233 return false; 18234 }; 18235 18236 // Mark that this expression does not constitute an odr-use. 18237 auto MarkNotOdrUsed = [&] { 18238 S.MaybeODRUseExprs.remove(E); 18239 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18240 LSI->markVariableExprAsNonODRUsed(E); 18241 }; 18242 18243 // C++2a [basic.def.odr]p2: 18244 // The set of potential results of an expression e is defined as follows: 18245 switch (E->getStmtClass()) { 18246 // -- If e is an id-expression, ... 18247 case Expr::DeclRefExprClass: { 18248 auto *DRE = cast<DeclRefExpr>(E); 18249 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18250 break; 18251 18252 // Rebuild as a non-odr-use DeclRefExpr. 18253 MarkNotOdrUsed(); 18254 return DeclRefExpr::Create( 18255 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18256 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18257 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18258 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18259 } 18260 18261 case Expr::FunctionParmPackExprClass: { 18262 auto *FPPE = cast<FunctionParmPackExpr>(E); 18263 // If any of the declarations in the pack is odr-used, then the expression 18264 // as a whole constitutes an odr-use. 18265 for (VarDecl *D : *FPPE) 18266 if (IsPotentialResultOdrUsed(D)) 18267 return ExprEmpty(); 18268 18269 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18270 // nothing cares about whether we marked this as an odr-use, but it might 18271 // be useful for non-compiler tools. 18272 MarkNotOdrUsed(); 18273 break; 18274 } 18275 18276 // -- If e is a subscripting operation with an array operand... 18277 case Expr::ArraySubscriptExprClass: { 18278 auto *ASE = cast<ArraySubscriptExpr>(E); 18279 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18280 if (!OldBase->getType()->isArrayType()) 18281 break; 18282 ExprResult Base = Rebuild(OldBase); 18283 if (!Base.isUsable()) 18284 return Base; 18285 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18286 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18287 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18288 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18289 ASE->getRBracketLoc()); 18290 } 18291 18292 case Expr::MemberExprClass: { 18293 auto *ME = cast<MemberExpr>(E); 18294 // -- If e is a class member access expression [...] naming a non-static 18295 // data member... 18296 if (isa<FieldDecl>(ME->getMemberDecl())) { 18297 ExprResult Base = Rebuild(ME->getBase()); 18298 if (!Base.isUsable()) 18299 return Base; 18300 return MemberExpr::Create( 18301 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18302 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18303 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18304 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18305 ME->getObjectKind(), ME->isNonOdrUse()); 18306 } 18307 18308 if (ME->getMemberDecl()->isCXXInstanceMember()) 18309 break; 18310 18311 // -- If e is a class member access expression naming a static data member, 18312 // ... 18313 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18314 break; 18315 18316 // Rebuild as a non-odr-use MemberExpr. 18317 MarkNotOdrUsed(); 18318 return MemberExpr::Create( 18319 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18320 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18321 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18322 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18323 } 18324 18325 case Expr::BinaryOperatorClass: { 18326 auto *BO = cast<BinaryOperator>(E); 18327 Expr *LHS = BO->getLHS(); 18328 Expr *RHS = BO->getRHS(); 18329 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18330 if (BO->getOpcode() == BO_PtrMemD) { 18331 ExprResult Sub = Rebuild(LHS); 18332 if (!Sub.isUsable()) 18333 return Sub; 18334 LHS = Sub.get(); 18335 // -- If e is a comma expression, ... 18336 } else if (BO->getOpcode() == BO_Comma) { 18337 ExprResult Sub = Rebuild(RHS); 18338 if (!Sub.isUsable()) 18339 return Sub; 18340 RHS = Sub.get(); 18341 } else { 18342 break; 18343 } 18344 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18345 LHS, RHS); 18346 } 18347 18348 // -- If e has the form (e1)... 18349 case Expr::ParenExprClass: { 18350 auto *PE = cast<ParenExpr>(E); 18351 ExprResult Sub = Rebuild(PE->getSubExpr()); 18352 if (!Sub.isUsable()) 18353 return Sub; 18354 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18355 } 18356 18357 // -- If e is a glvalue conditional expression, ... 18358 // We don't apply this to a binary conditional operator. FIXME: Should we? 18359 case Expr::ConditionalOperatorClass: { 18360 auto *CO = cast<ConditionalOperator>(E); 18361 ExprResult LHS = Rebuild(CO->getLHS()); 18362 if (LHS.isInvalid()) 18363 return ExprError(); 18364 ExprResult RHS = Rebuild(CO->getRHS()); 18365 if (RHS.isInvalid()) 18366 return ExprError(); 18367 if (!LHS.isUsable() && !RHS.isUsable()) 18368 return ExprEmpty(); 18369 if (!LHS.isUsable()) 18370 LHS = CO->getLHS(); 18371 if (!RHS.isUsable()) 18372 RHS = CO->getRHS(); 18373 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18374 CO->getCond(), LHS.get(), RHS.get()); 18375 } 18376 18377 // [Clang extension] 18378 // -- If e has the form __extension__ e1... 18379 case Expr::UnaryOperatorClass: { 18380 auto *UO = cast<UnaryOperator>(E); 18381 if (UO->getOpcode() != UO_Extension) 18382 break; 18383 ExprResult Sub = Rebuild(UO->getSubExpr()); 18384 if (!Sub.isUsable()) 18385 return Sub; 18386 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18387 Sub.get()); 18388 } 18389 18390 // [Clang extension] 18391 // -- If e has the form _Generic(...), the set of potential results is the 18392 // union of the sets of potential results of the associated expressions. 18393 case Expr::GenericSelectionExprClass: { 18394 auto *GSE = cast<GenericSelectionExpr>(E); 18395 18396 SmallVector<Expr *, 4> AssocExprs; 18397 bool AnyChanged = false; 18398 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18399 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18400 if (AssocExpr.isInvalid()) 18401 return ExprError(); 18402 if (AssocExpr.isUsable()) { 18403 AssocExprs.push_back(AssocExpr.get()); 18404 AnyChanged = true; 18405 } else { 18406 AssocExprs.push_back(OrigAssocExpr); 18407 } 18408 } 18409 18410 return AnyChanged ? S.CreateGenericSelectionExpr( 18411 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18412 GSE->getRParenLoc(), GSE->getControllingExpr(), 18413 GSE->getAssocTypeSourceInfos(), AssocExprs) 18414 : ExprEmpty(); 18415 } 18416 18417 // [Clang extension] 18418 // -- If e has the form __builtin_choose_expr(...), the set of potential 18419 // results is the union of the sets of potential results of the 18420 // second and third subexpressions. 18421 case Expr::ChooseExprClass: { 18422 auto *CE = cast<ChooseExpr>(E); 18423 18424 ExprResult LHS = Rebuild(CE->getLHS()); 18425 if (LHS.isInvalid()) 18426 return ExprError(); 18427 18428 ExprResult RHS = Rebuild(CE->getLHS()); 18429 if (RHS.isInvalid()) 18430 return ExprError(); 18431 18432 if (!LHS.get() && !RHS.get()) 18433 return ExprEmpty(); 18434 if (!LHS.isUsable()) 18435 LHS = CE->getLHS(); 18436 if (!RHS.isUsable()) 18437 RHS = CE->getRHS(); 18438 18439 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18440 RHS.get(), CE->getRParenLoc()); 18441 } 18442 18443 // Step through non-syntactic nodes. 18444 case Expr::ConstantExprClass: { 18445 auto *CE = cast<ConstantExpr>(E); 18446 ExprResult Sub = Rebuild(CE->getSubExpr()); 18447 if (!Sub.isUsable()) 18448 return Sub; 18449 return ConstantExpr::Create(S.Context, Sub.get()); 18450 } 18451 18452 // We could mostly rely on the recursive rebuilding to rebuild implicit 18453 // casts, but not at the top level, so rebuild them here. 18454 case Expr::ImplicitCastExprClass: { 18455 auto *ICE = cast<ImplicitCastExpr>(E); 18456 // Only step through the narrow set of cast kinds we expect to encounter. 18457 // Anything else suggests we've left the region in which potential results 18458 // can be found. 18459 switch (ICE->getCastKind()) { 18460 case CK_NoOp: 18461 case CK_DerivedToBase: 18462 case CK_UncheckedDerivedToBase: { 18463 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18464 if (!Sub.isUsable()) 18465 return Sub; 18466 CXXCastPath Path(ICE->path()); 18467 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18468 ICE->getValueKind(), &Path); 18469 } 18470 18471 default: 18472 break; 18473 } 18474 break; 18475 } 18476 18477 default: 18478 break; 18479 } 18480 18481 // Can't traverse through this node. Nothing to do. 18482 return ExprEmpty(); 18483 } 18484 18485 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18486 // Check whether the operand is or contains an object of non-trivial C union 18487 // type. 18488 if (E->getType().isVolatileQualified() && 18489 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18490 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18491 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18492 Sema::NTCUC_LValueToRValueVolatile, 18493 NTCUK_Destruct|NTCUK_Copy); 18494 18495 // C++2a [basic.def.odr]p4: 18496 // [...] an expression of non-volatile-qualified non-class type to which 18497 // the lvalue-to-rvalue conversion is applied [...] 18498 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18499 return E; 18500 18501 ExprResult Result = 18502 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18503 if (Result.isInvalid()) 18504 return ExprError(); 18505 return Result.get() ? Result : E; 18506 } 18507 18508 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18509 Res = CorrectDelayedTyposInExpr(Res); 18510 18511 if (!Res.isUsable()) 18512 return Res; 18513 18514 // If a constant-expression is a reference to a variable where we delay 18515 // deciding whether it is an odr-use, just assume we will apply the 18516 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18517 // (a non-type template argument), we have special handling anyway. 18518 return CheckLValueToRValueConversionOperand(Res.get()); 18519 } 18520 18521 void Sema::CleanupVarDeclMarking() { 18522 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18523 // call. 18524 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18525 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18526 18527 for (Expr *E : LocalMaybeODRUseExprs) { 18528 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18529 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18530 DRE->getLocation(), *this); 18531 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18532 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18533 *this); 18534 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18535 for (VarDecl *VD : *FP) 18536 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18537 } else { 18538 llvm_unreachable("Unexpected expression"); 18539 } 18540 } 18541 18542 assert(MaybeODRUseExprs.empty() && 18543 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18544 } 18545 18546 static void DoMarkVarDeclReferenced( 18547 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18548 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18549 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18550 isa<FunctionParmPackExpr>(E)) && 18551 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18552 Var->setReferenced(); 18553 18554 if (Var->isInvalidDecl()) 18555 return; 18556 18557 auto *MSI = Var->getMemberSpecializationInfo(); 18558 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18559 : Var->getTemplateSpecializationKind(); 18560 18561 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18562 bool UsableInConstantExpr = 18563 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18564 18565 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18566 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18567 } 18568 18569 // C++20 [expr.const]p12: 18570 // A variable [...] is needed for constant evaluation if it is [...] a 18571 // variable whose name appears as a potentially constant evaluated 18572 // expression that is either a contexpr variable or is of non-volatile 18573 // const-qualified integral type or of reference type 18574 bool NeededForConstantEvaluation = 18575 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18576 18577 bool NeedDefinition = 18578 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18579 18580 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18581 "Can't instantiate a partial template specialization."); 18582 18583 // If this might be a member specialization of a static data member, check 18584 // the specialization is visible. We already did the checks for variable 18585 // template specializations when we created them. 18586 if (NeedDefinition && TSK != TSK_Undeclared && 18587 !isa<VarTemplateSpecializationDecl>(Var)) 18588 SemaRef.checkSpecializationVisibility(Loc, Var); 18589 18590 // Perform implicit instantiation of static data members, static data member 18591 // templates of class templates, and variable template specializations. Delay 18592 // instantiations of variable templates, except for those that could be used 18593 // in a constant expression. 18594 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18595 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18596 // instantiation declaration if a variable is usable in a constant 18597 // expression (among other cases). 18598 bool TryInstantiating = 18599 TSK == TSK_ImplicitInstantiation || 18600 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18601 18602 if (TryInstantiating) { 18603 SourceLocation PointOfInstantiation = 18604 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18605 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18606 if (FirstInstantiation) { 18607 PointOfInstantiation = Loc; 18608 if (MSI) 18609 MSI->setPointOfInstantiation(PointOfInstantiation); 18610 // FIXME: Notify listener. 18611 else 18612 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18613 } 18614 18615 if (UsableInConstantExpr) { 18616 // Do not defer instantiations of variables that could be used in a 18617 // constant expression. 18618 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18619 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18620 }); 18621 18622 // Re-set the member to trigger a recomputation of the dependence bits 18623 // for the expression. 18624 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18625 DRE->setDecl(DRE->getDecl()); 18626 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18627 ME->setMemberDecl(ME->getMemberDecl()); 18628 } else if (FirstInstantiation || 18629 isa<VarTemplateSpecializationDecl>(Var)) { 18630 // FIXME: For a specialization of a variable template, we don't 18631 // distinguish between "declaration and type implicitly instantiated" 18632 // and "implicit instantiation of definition requested", so we have 18633 // no direct way to avoid enqueueing the pending instantiation 18634 // multiple times. 18635 SemaRef.PendingInstantiations 18636 .push_back(std::make_pair(Var, PointOfInstantiation)); 18637 } 18638 } 18639 } 18640 18641 // C++2a [basic.def.odr]p4: 18642 // A variable x whose name appears as a potentially-evaluated expression e 18643 // is odr-used by e unless 18644 // -- x is a reference that is usable in constant expressions 18645 // -- x is a variable of non-reference type that is usable in constant 18646 // expressions and has no mutable subobjects [FIXME], and e is an 18647 // element of the set of potential results of an expression of 18648 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18649 // conversion is applied 18650 // -- x is a variable of non-reference type, and e is an element of the set 18651 // of potential results of a discarded-value expression to which the 18652 // lvalue-to-rvalue conversion is not applied [FIXME] 18653 // 18654 // We check the first part of the second bullet here, and 18655 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18656 // FIXME: To get the third bullet right, we need to delay this even for 18657 // variables that are not usable in constant expressions. 18658 18659 // If we already know this isn't an odr-use, there's nothing more to do. 18660 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18661 if (DRE->isNonOdrUse()) 18662 return; 18663 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18664 if (ME->isNonOdrUse()) 18665 return; 18666 18667 switch (OdrUse) { 18668 case OdrUseContext::None: 18669 assert((!E || isa<FunctionParmPackExpr>(E)) && 18670 "missing non-odr-use marking for unevaluated decl ref"); 18671 break; 18672 18673 case OdrUseContext::FormallyOdrUsed: 18674 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18675 // behavior. 18676 break; 18677 18678 case OdrUseContext::Used: 18679 // If we might later find that this expression isn't actually an odr-use, 18680 // delay the marking. 18681 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18682 SemaRef.MaybeODRUseExprs.insert(E); 18683 else 18684 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18685 break; 18686 18687 case OdrUseContext::Dependent: 18688 // If this is a dependent context, we don't need to mark variables as 18689 // odr-used, but we may still need to track them for lambda capture. 18690 // FIXME: Do we also need to do this inside dependent typeid expressions 18691 // (which are modeled as unevaluated at this point)? 18692 const bool RefersToEnclosingScope = 18693 (SemaRef.CurContext != Var->getDeclContext() && 18694 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18695 if (RefersToEnclosingScope) { 18696 LambdaScopeInfo *const LSI = 18697 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18698 if (LSI && (!LSI->CallOperator || 18699 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18700 // If a variable could potentially be odr-used, defer marking it so 18701 // until we finish analyzing the full expression for any 18702 // lvalue-to-rvalue 18703 // or discarded value conversions that would obviate odr-use. 18704 // Add it to the list of potential captures that will be analyzed 18705 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18706 // unless the variable is a reference that was initialized by a constant 18707 // expression (this will never need to be captured or odr-used). 18708 // 18709 // FIXME: We can simplify this a lot after implementing P0588R1. 18710 assert(E && "Capture variable should be used in an expression."); 18711 if (!Var->getType()->isReferenceType() || 18712 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18713 LSI->addPotentialCapture(E->IgnoreParens()); 18714 } 18715 } 18716 break; 18717 } 18718 } 18719 18720 /// Mark a variable referenced, and check whether it is odr-used 18721 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18722 /// used directly for normal expressions referring to VarDecl. 18723 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18724 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18725 } 18726 18727 static void 18728 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18729 bool MightBeOdrUse, 18730 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18731 if (SemaRef.isInOpenMPDeclareTargetContext()) 18732 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18733 18734 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18735 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18736 return; 18737 } 18738 18739 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18740 18741 // If this is a call to a method via a cast, also mark the method in the 18742 // derived class used in case codegen can devirtualize the call. 18743 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18744 if (!ME) 18745 return; 18746 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18747 if (!MD) 18748 return; 18749 // Only attempt to devirtualize if this is truly a virtual call. 18750 bool IsVirtualCall = MD->isVirtual() && 18751 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18752 if (!IsVirtualCall) 18753 return; 18754 18755 // If it's possible to devirtualize the call, mark the called function 18756 // referenced. 18757 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18758 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18759 if (DM) 18760 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18761 } 18762 18763 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18764 /// 18765 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18766 /// handled with care if the DeclRefExpr is not newly-created. 18767 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18768 // TODO: update this with DR# once a defect report is filed. 18769 // C++11 defect. The address of a pure member should not be an ODR use, even 18770 // if it's a qualified reference. 18771 bool OdrUse = true; 18772 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18773 if (Method->isVirtual() && 18774 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18775 OdrUse = false; 18776 18777 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18778 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18779 FD->isConsteval() && !RebuildingImmediateInvocation) 18780 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18781 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18782 RefsMinusAssignments); 18783 } 18784 18785 /// Perform reference-marking and odr-use handling for a MemberExpr. 18786 void Sema::MarkMemberReferenced(MemberExpr *E) { 18787 // C++11 [basic.def.odr]p2: 18788 // A non-overloaded function whose name appears as a potentially-evaluated 18789 // expression or a member of a set of candidate functions, if selected by 18790 // overload resolution when referred to from a potentially-evaluated 18791 // expression, is odr-used, unless it is a pure virtual function and its 18792 // name is not explicitly qualified. 18793 bool MightBeOdrUse = true; 18794 if (E->performsVirtualDispatch(getLangOpts())) { 18795 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18796 if (Method->isPure()) 18797 MightBeOdrUse = false; 18798 } 18799 SourceLocation Loc = 18800 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18801 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18802 RefsMinusAssignments); 18803 } 18804 18805 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18806 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18807 for (VarDecl *VD : *E) 18808 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18809 RefsMinusAssignments); 18810 } 18811 18812 /// Perform marking for a reference to an arbitrary declaration. It 18813 /// marks the declaration referenced, and performs odr-use checking for 18814 /// functions and variables. This method should not be used when building a 18815 /// normal expression which refers to a variable. 18816 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18817 bool MightBeOdrUse) { 18818 if (MightBeOdrUse) { 18819 if (auto *VD = dyn_cast<VarDecl>(D)) { 18820 MarkVariableReferenced(Loc, VD); 18821 return; 18822 } 18823 } 18824 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18825 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18826 return; 18827 } 18828 D->setReferenced(); 18829 } 18830 18831 namespace { 18832 // Mark all of the declarations used by a type as referenced. 18833 // FIXME: Not fully implemented yet! We need to have a better understanding 18834 // of when we're entering a context we should not recurse into. 18835 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18836 // TreeTransforms rebuilding the type in a new context. Rather than 18837 // duplicating the TreeTransform logic, we should consider reusing it here. 18838 // Currently that causes problems when rebuilding LambdaExprs. 18839 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18840 Sema &S; 18841 SourceLocation Loc; 18842 18843 public: 18844 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18845 18846 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18847 18848 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18849 }; 18850 } 18851 18852 bool MarkReferencedDecls::TraverseTemplateArgument( 18853 const TemplateArgument &Arg) { 18854 { 18855 // A non-type template argument is a constant-evaluated context. 18856 EnterExpressionEvaluationContext Evaluated( 18857 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18858 if (Arg.getKind() == TemplateArgument::Declaration) { 18859 if (Decl *D = Arg.getAsDecl()) 18860 S.MarkAnyDeclReferenced(Loc, D, true); 18861 } else if (Arg.getKind() == TemplateArgument::Expression) { 18862 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18863 } 18864 } 18865 18866 return Inherited::TraverseTemplateArgument(Arg); 18867 } 18868 18869 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18870 MarkReferencedDecls Marker(*this, Loc); 18871 Marker.TraverseType(T); 18872 } 18873 18874 namespace { 18875 /// Helper class that marks all of the declarations referenced by 18876 /// potentially-evaluated subexpressions as "referenced". 18877 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18878 public: 18879 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18880 bool SkipLocalVariables; 18881 ArrayRef<const Expr *> StopAt; 18882 18883 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 18884 ArrayRef<const Expr *> StopAt) 18885 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 18886 18887 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18888 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18889 } 18890 18891 void Visit(Expr *E) { 18892 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end()) 18893 return; 18894 Inherited::Visit(E); 18895 } 18896 18897 void VisitDeclRefExpr(DeclRefExpr *E) { 18898 // If we were asked not to visit local variables, don't. 18899 if (SkipLocalVariables) { 18900 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18901 if (VD->hasLocalStorage()) 18902 return; 18903 } 18904 18905 // FIXME: This can trigger the instantiation of the initializer of a 18906 // variable, which can cause the expression to become value-dependent 18907 // or error-dependent. Do we need to propagate the new dependence bits? 18908 S.MarkDeclRefReferenced(E); 18909 } 18910 18911 void VisitMemberExpr(MemberExpr *E) { 18912 S.MarkMemberReferenced(E); 18913 Visit(E->getBase()); 18914 } 18915 }; 18916 } // namespace 18917 18918 /// Mark any declarations that appear within this expression or any 18919 /// potentially-evaluated subexpressions as "referenced". 18920 /// 18921 /// \param SkipLocalVariables If true, don't mark local variables as 18922 /// 'referenced'. 18923 /// \param StopAt Subexpressions that we shouldn't recurse into. 18924 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18925 bool SkipLocalVariables, 18926 ArrayRef<const Expr*> StopAt) { 18927 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 18928 } 18929 18930 /// Emit a diagnostic when statements are reachable. 18931 /// FIXME: check for reachability even in expressions for which we don't build a 18932 /// CFG (eg, in the initializer of a global or in a constant expression). 18933 /// For example, 18934 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 18935 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 18936 const PartialDiagnostic &PD) { 18937 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18938 if (!FunctionScopes.empty()) 18939 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 18940 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18941 return true; 18942 } 18943 18944 // The initializer of a constexpr variable or of the first declaration of a 18945 // static data member is not syntactically a constant evaluated constant, 18946 // but nonetheless is always required to be a constant expression, so we 18947 // can skip diagnosing. 18948 // FIXME: Using the mangling context here is a hack. 18949 if (auto *VD = dyn_cast_or_null<VarDecl>( 18950 ExprEvalContexts.back().ManglingContextDecl)) { 18951 if (VD->isConstexpr() || 18952 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18953 return false; 18954 // FIXME: For any other kind of variable, we should build a CFG for its 18955 // initializer and check whether the context in question is reachable. 18956 } 18957 18958 Diag(Loc, PD); 18959 return true; 18960 } 18961 18962 /// Emit a diagnostic that describes an effect on the run-time behavior 18963 /// of the program being compiled. 18964 /// 18965 /// This routine emits the given diagnostic when the code currently being 18966 /// type-checked is "potentially evaluated", meaning that there is a 18967 /// possibility that the code will actually be executable. Code in sizeof() 18968 /// expressions, code used only during overload resolution, etc., are not 18969 /// potentially evaluated. This routine will suppress such diagnostics or, 18970 /// in the absolutely nutty case of potentially potentially evaluated 18971 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18972 /// later. 18973 /// 18974 /// This routine should be used for all diagnostics that describe the run-time 18975 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18976 /// Failure to do so will likely result in spurious diagnostics or failures 18977 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18978 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18979 const PartialDiagnostic &PD) { 18980 18981 if (ExprEvalContexts.back().isDiscardedStatementContext()) 18982 return false; 18983 18984 switch (ExprEvalContexts.back().Context) { 18985 case ExpressionEvaluationContext::Unevaluated: 18986 case ExpressionEvaluationContext::UnevaluatedList: 18987 case ExpressionEvaluationContext::UnevaluatedAbstract: 18988 case ExpressionEvaluationContext::DiscardedStatement: 18989 // The argument will never be evaluated, so don't complain. 18990 break; 18991 18992 case ExpressionEvaluationContext::ConstantEvaluated: 18993 case ExpressionEvaluationContext::ImmediateFunctionContext: 18994 // Relevant diagnostics should be produced by constant evaluation. 18995 break; 18996 18997 case ExpressionEvaluationContext::PotentiallyEvaluated: 18998 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18999 return DiagIfReachable(Loc, Stmts, PD); 19000 } 19001 19002 return false; 19003 } 19004 19005 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 19006 const PartialDiagnostic &PD) { 19007 return DiagRuntimeBehavior( 19008 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 19009 } 19010 19011 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 19012 CallExpr *CE, FunctionDecl *FD) { 19013 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 19014 return false; 19015 19016 // If we're inside a decltype's expression, don't check for a valid return 19017 // type or construct temporaries until we know whether this is the last call. 19018 if (ExprEvalContexts.back().ExprContext == 19019 ExpressionEvaluationContextRecord::EK_Decltype) { 19020 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 19021 return false; 19022 } 19023 19024 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19025 FunctionDecl *FD; 19026 CallExpr *CE; 19027 19028 public: 19029 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19030 : FD(FD), CE(CE) { } 19031 19032 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19033 if (!FD) { 19034 S.Diag(Loc, diag::err_call_incomplete_return) 19035 << T << CE->getSourceRange(); 19036 return; 19037 } 19038 19039 S.Diag(Loc, diag::err_call_function_incomplete_return) 19040 << CE->getSourceRange() << FD << T; 19041 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19042 << FD->getDeclName(); 19043 } 19044 } Diagnoser(FD, CE); 19045 19046 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19047 return true; 19048 19049 return false; 19050 } 19051 19052 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19053 // will prevent this condition from triggering, which is what we want. 19054 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19055 SourceLocation Loc; 19056 19057 unsigned diagnostic = diag::warn_condition_is_assignment; 19058 bool IsOrAssign = false; 19059 19060 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19061 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19062 return; 19063 19064 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19065 19066 // Greylist some idioms by putting them into a warning subcategory. 19067 if (ObjCMessageExpr *ME 19068 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19069 Selector Sel = ME->getSelector(); 19070 19071 // self = [<foo> init...] 19072 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19073 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19074 19075 // <foo> = [<bar> nextObject] 19076 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19077 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19078 } 19079 19080 Loc = Op->getOperatorLoc(); 19081 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19082 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19083 return; 19084 19085 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19086 Loc = Op->getOperatorLoc(); 19087 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19088 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19089 else { 19090 // Not an assignment. 19091 return; 19092 } 19093 19094 Diag(Loc, diagnostic) << E->getSourceRange(); 19095 19096 SourceLocation Open = E->getBeginLoc(); 19097 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19098 Diag(Loc, diag::note_condition_assign_silence) 19099 << FixItHint::CreateInsertion(Open, "(") 19100 << FixItHint::CreateInsertion(Close, ")"); 19101 19102 if (IsOrAssign) 19103 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19104 << FixItHint::CreateReplacement(Loc, "!="); 19105 else 19106 Diag(Loc, diag::note_condition_assign_to_comparison) 19107 << FixItHint::CreateReplacement(Loc, "=="); 19108 } 19109 19110 /// Redundant parentheses over an equality comparison can indicate 19111 /// that the user intended an assignment used as condition. 19112 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19113 // Don't warn if the parens came from a macro. 19114 SourceLocation parenLoc = ParenE->getBeginLoc(); 19115 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19116 return; 19117 // Don't warn for dependent expressions. 19118 if (ParenE->isTypeDependent()) 19119 return; 19120 19121 Expr *E = ParenE->IgnoreParens(); 19122 19123 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19124 if (opE->getOpcode() == BO_EQ && 19125 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19126 == Expr::MLV_Valid) { 19127 SourceLocation Loc = opE->getOperatorLoc(); 19128 19129 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19130 SourceRange ParenERange = ParenE->getSourceRange(); 19131 Diag(Loc, diag::note_equality_comparison_silence) 19132 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19133 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19134 Diag(Loc, diag::note_equality_comparison_to_assign) 19135 << FixItHint::CreateReplacement(Loc, "="); 19136 } 19137 } 19138 19139 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19140 bool IsConstexpr) { 19141 DiagnoseAssignmentAsCondition(E); 19142 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19143 DiagnoseEqualityWithExtraParens(parenE); 19144 19145 ExprResult result = CheckPlaceholderExpr(E); 19146 if (result.isInvalid()) return ExprError(); 19147 E = result.get(); 19148 19149 if (!E->isTypeDependent()) { 19150 if (getLangOpts().CPlusPlus) 19151 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19152 19153 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19154 if (ERes.isInvalid()) 19155 return ExprError(); 19156 E = ERes.get(); 19157 19158 QualType T = E->getType(); 19159 if (!T->isScalarType()) { // C99 6.8.4.1p1 19160 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19161 << T << E->getSourceRange(); 19162 return ExprError(); 19163 } 19164 CheckBoolLikeConversion(E, Loc); 19165 } 19166 19167 return E; 19168 } 19169 19170 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19171 Expr *SubExpr, ConditionKind CK) { 19172 // Empty conditions are valid in for-statements. 19173 if (!SubExpr) 19174 return ConditionResult(); 19175 19176 ExprResult Cond; 19177 switch (CK) { 19178 case ConditionKind::Boolean: 19179 Cond = CheckBooleanCondition(Loc, SubExpr); 19180 break; 19181 19182 case ConditionKind::ConstexprIf: 19183 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19184 break; 19185 19186 case ConditionKind::Switch: 19187 Cond = CheckSwitchCondition(Loc, SubExpr); 19188 break; 19189 } 19190 if (Cond.isInvalid()) { 19191 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19192 {SubExpr}); 19193 if (!Cond.get()) 19194 return ConditionError(); 19195 } 19196 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19197 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19198 if (!FullExpr.get()) 19199 return ConditionError(); 19200 19201 return ConditionResult(*this, nullptr, FullExpr, 19202 CK == ConditionKind::ConstexprIf); 19203 } 19204 19205 namespace { 19206 /// A visitor for rebuilding a call to an __unknown_any expression 19207 /// to have an appropriate type. 19208 struct RebuildUnknownAnyFunction 19209 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19210 19211 Sema &S; 19212 19213 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19214 19215 ExprResult VisitStmt(Stmt *S) { 19216 llvm_unreachable("unexpected statement!"); 19217 } 19218 19219 ExprResult VisitExpr(Expr *E) { 19220 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19221 << E->getSourceRange(); 19222 return ExprError(); 19223 } 19224 19225 /// Rebuild an expression which simply semantically wraps another 19226 /// expression which it shares the type and value kind of. 19227 template <class T> ExprResult rebuildSugarExpr(T *E) { 19228 ExprResult SubResult = Visit(E->getSubExpr()); 19229 if (SubResult.isInvalid()) return ExprError(); 19230 19231 Expr *SubExpr = SubResult.get(); 19232 E->setSubExpr(SubExpr); 19233 E->setType(SubExpr->getType()); 19234 E->setValueKind(SubExpr->getValueKind()); 19235 assert(E->getObjectKind() == OK_Ordinary); 19236 return E; 19237 } 19238 19239 ExprResult VisitParenExpr(ParenExpr *E) { 19240 return rebuildSugarExpr(E); 19241 } 19242 19243 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19244 return rebuildSugarExpr(E); 19245 } 19246 19247 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19248 ExprResult SubResult = Visit(E->getSubExpr()); 19249 if (SubResult.isInvalid()) return ExprError(); 19250 19251 Expr *SubExpr = SubResult.get(); 19252 E->setSubExpr(SubExpr); 19253 E->setType(S.Context.getPointerType(SubExpr->getType())); 19254 assert(E->isPRValue()); 19255 assert(E->getObjectKind() == OK_Ordinary); 19256 return E; 19257 } 19258 19259 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19260 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19261 19262 E->setType(VD->getType()); 19263 19264 assert(E->isPRValue()); 19265 if (S.getLangOpts().CPlusPlus && 19266 !(isa<CXXMethodDecl>(VD) && 19267 cast<CXXMethodDecl>(VD)->isInstance())) 19268 E->setValueKind(VK_LValue); 19269 19270 return E; 19271 } 19272 19273 ExprResult VisitMemberExpr(MemberExpr *E) { 19274 return resolveDecl(E, E->getMemberDecl()); 19275 } 19276 19277 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19278 return resolveDecl(E, E->getDecl()); 19279 } 19280 }; 19281 } 19282 19283 /// Given a function expression of unknown-any type, try to rebuild it 19284 /// to have a function type. 19285 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19286 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19287 if (Result.isInvalid()) return ExprError(); 19288 return S.DefaultFunctionArrayConversion(Result.get()); 19289 } 19290 19291 namespace { 19292 /// A visitor for rebuilding an expression of type __unknown_anytype 19293 /// into one which resolves the type directly on the referring 19294 /// expression. Strict preservation of the original source 19295 /// structure is not a goal. 19296 struct RebuildUnknownAnyExpr 19297 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19298 19299 Sema &S; 19300 19301 /// The current destination type. 19302 QualType DestType; 19303 19304 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19305 : S(S), DestType(CastType) {} 19306 19307 ExprResult VisitStmt(Stmt *S) { 19308 llvm_unreachable("unexpected statement!"); 19309 } 19310 19311 ExprResult VisitExpr(Expr *E) { 19312 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19313 << E->getSourceRange(); 19314 return ExprError(); 19315 } 19316 19317 ExprResult VisitCallExpr(CallExpr *E); 19318 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19319 19320 /// Rebuild an expression which simply semantically wraps another 19321 /// expression which it shares the type and value kind of. 19322 template <class T> ExprResult rebuildSugarExpr(T *E) { 19323 ExprResult SubResult = Visit(E->getSubExpr()); 19324 if (SubResult.isInvalid()) return ExprError(); 19325 Expr *SubExpr = SubResult.get(); 19326 E->setSubExpr(SubExpr); 19327 E->setType(SubExpr->getType()); 19328 E->setValueKind(SubExpr->getValueKind()); 19329 assert(E->getObjectKind() == OK_Ordinary); 19330 return E; 19331 } 19332 19333 ExprResult VisitParenExpr(ParenExpr *E) { 19334 return rebuildSugarExpr(E); 19335 } 19336 19337 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19338 return rebuildSugarExpr(E); 19339 } 19340 19341 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19342 const PointerType *Ptr = DestType->getAs<PointerType>(); 19343 if (!Ptr) { 19344 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19345 << E->getSourceRange(); 19346 return ExprError(); 19347 } 19348 19349 if (isa<CallExpr>(E->getSubExpr())) { 19350 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19351 << E->getSourceRange(); 19352 return ExprError(); 19353 } 19354 19355 assert(E->isPRValue()); 19356 assert(E->getObjectKind() == OK_Ordinary); 19357 E->setType(DestType); 19358 19359 // Build the sub-expression as if it were an object of the pointee type. 19360 DestType = Ptr->getPointeeType(); 19361 ExprResult SubResult = Visit(E->getSubExpr()); 19362 if (SubResult.isInvalid()) return ExprError(); 19363 E->setSubExpr(SubResult.get()); 19364 return E; 19365 } 19366 19367 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19368 19369 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19370 19371 ExprResult VisitMemberExpr(MemberExpr *E) { 19372 return resolveDecl(E, E->getMemberDecl()); 19373 } 19374 19375 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19376 return resolveDecl(E, E->getDecl()); 19377 } 19378 }; 19379 } 19380 19381 /// Rebuilds a call expression which yielded __unknown_anytype. 19382 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19383 Expr *CalleeExpr = E->getCallee(); 19384 19385 enum FnKind { 19386 FK_MemberFunction, 19387 FK_FunctionPointer, 19388 FK_BlockPointer 19389 }; 19390 19391 FnKind Kind; 19392 QualType CalleeType = CalleeExpr->getType(); 19393 if (CalleeType == S.Context.BoundMemberTy) { 19394 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19395 Kind = FK_MemberFunction; 19396 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19397 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19398 CalleeType = Ptr->getPointeeType(); 19399 Kind = FK_FunctionPointer; 19400 } else { 19401 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19402 Kind = FK_BlockPointer; 19403 } 19404 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19405 19406 // Verify that this is a legal result type of a function. 19407 if (DestType->isArrayType() || DestType->isFunctionType()) { 19408 unsigned diagID = diag::err_func_returning_array_function; 19409 if (Kind == FK_BlockPointer) 19410 diagID = diag::err_block_returning_array_function; 19411 19412 S.Diag(E->getExprLoc(), diagID) 19413 << DestType->isFunctionType() << DestType; 19414 return ExprError(); 19415 } 19416 19417 // Otherwise, go ahead and set DestType as the call's result. 19418 E->setType(DestType.getNonLValueExprType(S.Context)); 19419 E->setValueKind(Expr::getValueKindForType(DestType)); 19420 assert(E->getObjectKind() == OK_Ordinary); 19421 19422 // Rebuild the function type, replacing the result type with DestType. 19423 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19424 if (Proto) { 19425 // __unknown_anytype(...) is a special case used by the debugger when 19426 // it has no idea what a function's signature is. 19427 // 19428 // We want to build this call essentially under the K&R 19429 // unprototyped rules, but making a FunctionNoProtoType in C++ 19430 // would foul up all sorts of assumptions. However, we cannot 19431 // simply pass all arguments as variadic arguments, nor can we 19432 // portably just call the function under a non-variadic type; see 19433 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19434 // However, it turns out that in practice it is generally safe to 19435 // call a function declared as "A foo(B,C,D);" under the prototype 19436 // "A foo(B,C,D,...);". The only known exception is with the 19437 // Windows ABI, where any variadic function is implicitly cdecl 19438 // regardless of its normal CC. Therefore we change the parameter 19439 // types to match the types of the arguments. 19440 // 19441 // This is a hack, but it is far superior to moving the 19442 // corresponding target-specific code from IR-gen to Sema/AST. 19443 19444 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19445 SmallVector<QualType, 8> ArgTypes; 19446 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19447 ArgTypes.reserve(E->getNumArgs()); 19448 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19449 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19450 } 19451 ParamTypes = ArgTypes; 19452 } 19453 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19454 Proto->getExtProtoInfo()); 19455 } else { 19456 DestType = S.Context.getFunctionNoProtoType(DestType, 19457 FnType->getExtInfo()); 19458 } 19459 19460 // Rebuild the appropriate pointer-to-function type. 19461 switch (Kind) { 19462 case FK_MemberFunction: 19463 // Nothing to do. 19464 break; 19465 19466 case FK_FunctionPointer: 19467 DestType = S.Context.getPointerType(DestType); 19468 break; 19469 19470 case FK_BlockPointer: 19471 DestType = S.Context.getBlockPointerType(DestType); 19472 break; 19473 } 19474 19475 // Finally, we can recurse. 19476 ExprResult CalleeResult = Visit(CalleeExpr); 19477 if (!CalleeResult.isUsable()) return ExprError(); 19478 E->setCallee(CalleeResult.get()); 19479 19480 // Bind a temporary if necessary. 19481 return S.MaybeBindToTemporary(E); 19482 } 19483 19484 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19485 // Verify that this is a legal result type of a call. 19486 if (DestType->isArrayType() || DestType->isFunctionType()) { 19487 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19488 << DestType->isFunctionType() << DestType; 19489 return ExprError(); 19490 } 19491 19492 // Rewrite the method result type if available. 19493 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19494 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19495 Method->setReturnType(DestType); 19496 } 19497 19498 // Change the type of the message. 19499 E->setType(DestType.getNonReferenceType()); 19500 E->setValueKind(Expr::getValueKindForType(DestType)); 19501 19502 return S.MaybeBindToTemporary(E); 19503 } 19504 19505 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19506 // The only case we should ever see here is a function-to-pointer decay. 19507 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19508 assert(E->isPRValue()); 19509 assert(E->getObjectKind() == OK_Ordinary); 19510 19511 E->setType(DestType); 19512 19513 // Rebuild the sub-expression as the pointee (function) type. 19514 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19515 19516 ExprResult Result = Visit(E->getSubExpr()); 19517 if (!Result.isUsable()) return ExprError(); 19518 19519 E->setSubExpr(Result.get()); 19520 return E; 19521 } else if (E->getCastKind() == CK_LValueToRValue) { 19522 assert(E->isPRValue()); 19523 assert(E->getObjectKind() == OK_Ordinary); 19524 19525 assert(isa<BlockPointerType>(E->getType())); 19526 19527 E->setType(DestType); 19528 19529 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19530 DestType = S.Context.getLValueReferenceType(DestType); 19531 19532 ExprResult Result = Visit(E->getSubExpr()); 19533 if (!Result.isUsable()) return ExprError(); 19534 19535 E->setSubExpr(Result.get()); 19536 return E; 19537 } else { 19538 llvm_unreachable("Unhandled cast type!"); 19539 } 19540 } 19541 19542 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19543 ExprValueKind ValueKind = VK_LValue; 19544 QualType Type = DestType; 19545 19546 // We know how to make this work for certain kinds of decls: 19547 19548 // - functions 19549 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19550 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19551 DestType = Ptr->getPointeeType(); 19552 ExprResult Result = resolveDecl(E, VD); 19553 if (Result.isInvalid()) return ExprError(); 19554 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19555 VK_PRValue); 19556 } 19557 19558 if (!Type->isFunctionType()) { 19559 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19560 << VD << E->getSourceRange(); 19561 return ExprError(); 19562 } 19563 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19564 // We must match the FunctionDecl's type to the hack introduced in 19565 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19566 // type. See the lengthy commentary in that routine. 19567 QualType FDT = FD->getType(); 19568 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19569 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19570 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19571 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19572 SourceLocation Loc = FD->getLocation(); 19573 FunctionDecl *NewFD = FunctionDecl::Create( 19574 S.Context, FD->getDeclContext(), Loc, Loc, 19575 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19576 SC_None, S.getCurFPFeatures().isFPConstrained(), 19577 false /*isInlineSpecified*/, FD->hasPrototype(), 19578 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19579 19580 if (FD->getQualifier()) 19581 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19582 19583 SmallVector<ParmVarDecl*, 16> Params; 19584 for (const auto &AI : FT->param_types()) { 19585 ParmVarDecl *Param = 19586 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19587 Param->setScopeInfo(0, Params.size()); 19588 Params.push_back(Param); 19589 } 19590 NewFD->setParams(Params); 19591 DRE->setDecl(NewFD); 19592 VD = DRE->getDecl(); 19593 } 19594 } 19595 19596 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19597 if (MD->isInstance()) { 19598 ValueKind = VK_PRValue; 19599 Type = S.Context.BoundMemberTy; 19600 } 19601 19602 // Function references aren't l-values in C. 19603 if (!S.getLangOpts().CPlusPlus) 19604 ValueKind = VK_PRValue; 19605 19606 // - variables 19607 } else if (isa<VarDecl>(VD)) { 19608 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19609 Type = RefTy->getPointeeType(); 19610 } else if (Type->isFunctionType()) { 19611 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19612 << VD << E->getSourceRange(); 19613 return ExprError(); 19614 } 19615 19616 // - nothing else 19617 } else { 19618 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19619 << VD << E->getSourceRange(); 19620 return ExprError(); 19621 } 19622 19623 // Modifying the declaration like this is friendly to IR-gen but 19624 // also really dangerous. 19625 VD->setType(DestType); 19626 E->setType(Type); 19627 E->setValueKind(ValueKind); 19628 return E; 19629 } 19630 19631 /// Check a cast of an unknown-any type. We intentionally only 19632 /// trigger this for C-style casts. 19633 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19634 Expr *CastExpr, CastKind &CastKind, 19635 ExprValueKind &VK, CXXCastPath &Path) { 19636 // The type we're casting to must be either void or complete. 19637 if (!CastType->isVoidType() && 19638 RequireCompleteType(TypeRange.getBegin(), CastType, 19639 diag::err_typecheck_cast_to_incomplete)) 19640 return ExprError(); 19641 19642 // Rewrite the casted expression from scratch. 19643 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19644 if (!result.isUsable()) return ExprError(); 19645 19646 CastExpr = result.get(); 19647 VK = CastExpr->getValueKind(); 19648 CastKind = CK_NoOp; 19649 19650 return CastExpr; 19651 } 19652 19653 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19654 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19655 } 19656 19657 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19658 Expr *arg, QualType ¶mType) { 19659 // If the syntactic form of the argument is not an explicit cast of 19660 // any sort, just do default argument promotion. 19661 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19662 if (!castArg) { 19663 ExprResult result = DefaultArgumentPromotion(arg); 19664 if (result.isInvalid()) return ExprError(); 19665 paramType = result.get()->getType(); 19666 return result; 19667 } 19668 19669 // Otherwise, use the type that was written in the explicit cast. 19670 assert(!arg->hasPlaceholderType()); 19671 paramType = castArg->getTypeAsWritten(); 19672 19673 // Copy-initialize a parameter of that type. 19674 InitializedEntity entity = 19675 InitializedEntity::InitializeParameter(Context, paramType, 19676 /*consumed*/ false); 19677 return PerformCopyInitialization(entity, callLoc, arg); 19678 } 19679 19680 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19681 Expr *orig = E; 19682 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19683 while (true) { 19684 E = E->IgnoreParenImpCasts(); 19685 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19686 E = call->getCallee(); 19687 diagID = diag::err_uncasted_call_of_unknown_any; 19688 } else { 19689 break; 19690 } 19691 } 19692 19693 SourceLocation loc; 19694 NamedDecl *d; 19695 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19696 loc = ref->getLocation(); 19697 d = ref->getDecl(); 19698 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19699 loc = mem->getMemberLoc(); 19700 d = mem->getMemberDecl(); 19701 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19702 diagID = diag::err_uncasted_call_of_unknown_any; 19703 loc = msg->getSelectorStartLoc(); 19704 d = msg->getMethodDecl(); 19705 if (!d) { 19706 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19707 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19708 << orig->getSourceRange(); 19709 return ExprError(); 19710 } 19711 } else { 19712 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19713 << E->getSourceRange(); 19714 return ExprError(); 19715 } 19716 19717 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19718 19719 // Never recoverable. 19720 return ExprError(); 19721 } 19722 19723 /// Check for operands with placeholder types and complain if found. 19724 /// Returns ExprError() if there was an error and no recovery was possible. 19725 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19726 if (!Context.isDependenceAllowed()) { 19727 // C cannot handle TypoExpr nodes on either side of a binop because it 19728 // doesn't handle dependent types properly, so make sure any TypoExprs have 19729 // been dealt with before checking the operands. 19730 ExprResult Result = CorrectDelayedTyposInExpr(E); 19731 if (!Result.isUsable()) return ExprError(); 19732 E = Result.get(); 19733 } 19734 19735 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19736 if (!placeholderType) return E; 19737 19738 switch (placeholderType->getKind()) { 19739 19740 // Overloaded expressions. 19741 case BuiltinType::Overload: { 19742 // Try to resolve a single function template specialization. 19743 // This is obligatory. 19744 ExprResult Result = E; 19745 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19746 return Result; 19747 19748 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19749 // leaves Result unchanged on failure. 19750 Result = E; 19751 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19752 return Result; 19753 19754 // If that failed, try to recover with a call. 19755 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19756 /*complain*/ true); 19757 return Result; 19758 } 19759 19760 // Bound member functions. 19761 case BuiltinType::BoundMember: { 19762 ExprResult result = E; 19763 const Expr *BME = E->IgnoreParens(); 19764 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19765 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19766 if (isa<CXXPseudoDestructorExpr>(BME)) { 19767 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19768 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19769 if (ME->getMemberNameInfo().getName().getNameKind() == 19770 DeclarationName::CXXDestructorName) 19771 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19772 } 19773 tryToRecoverWithCall(result, PD, 19774 /*complain*/ true); 19775 return result; 19776 } 19777 19778 // ARC unbridged casts. 19779 case BuiltinType::ARCUnbridgedCast: { 19780 Expr *realCast = stripARCUnbridgedCast(E); 19781 diagnoseARCUnbridgedCast(realCast); 19782 return realCast; 19783 } 19784 19785 // Expressions of unknown type. 19786 case BuiltinType::UnknownAny: 19787 return diagnoseUnknownAnyExpr(*this, E); 19788 19789 // Pseudo-objects. 19790 case BuiltinType::PseudoObject: 19791 return checkPseudoObjectRValue(E); 19792 19793 case BuiltinType::BuiltinFn: { 19794 // Accept __noop without parens by implicitly converting it to a call expr. 19795 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19796 if (DRE) { 19797 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19798 if (FD->getBuiltinID() == Builtin::BI__noop) { 19799 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19800 CK_BuiltinFnToFnPtr) 19801 .get(); 19802 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19803 VK_PRValue, SourceLocation(), 19804 FPOptionsOverride()); 19805 } 19806 } 19807 19808 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19809 return ExprError(); 19810 } 19811 19812 case BuiltinType::IncompleteMatrixIdx: 19813 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19814 ->getRowIdx() 19815 ->getBeginLoc(), 19816 diag::err_matrix_incomplete_index); 19817 return ExprError(); 19818 19819 // Expressions of unknown type. 19820 case BuiltinType::OMPArraySection: 19821 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19822 return ExprError(); 19823 19824 // Expressions of unknown type. 19825 case BuiltinType::OMPArrayShaping: 19826 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19827 19828 case BuiltinType::OMPIterator: 19829 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19830 19831 // Everything else should be impossible. 19832 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19833 case BuiltinType::Id: 19834 #include "clang/Basic/OpenCLImageTypes.def" 19835 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19836 case BuiltinType::Id: 19837 #include "clang/Basic/OpenCLExtensionTypes.def" 19838 #define SVE_TYPE(Name, Id, SingletonId) \ 19839 case BuiltinType::Id: 19840 #include "clang/Basic/AArch64SVEACLETypes.def" 19841 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19842 case BuiltinType::Id: 19843 #include "clang/Basic/PPCTypes.def" 19844 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19845 #include "clang/Basic/RISCVVTypes.def" 19846 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19847 #define PLACEHOLDER_TYPE(Id, SingletonId) 19848 #include "clang/AST/BuiltinTypes.def" 19849 break; 19850 } 19851 19852 llvm_unreachable("invalid placeholder type!"); 19853 } 19854 19855 bool Sema::CheckCaseExpression(Expr *E) { 19856 if (E->isTypeDependent()) 19857 return true; 19858 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19859 return E->getType()->isIntegralOrEnumerationType(); 19860 return false; 19861 } 19862 19863 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19864 ExprResult 19865 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19866 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19867 "Unknown Objective-C Boolean value!"); 19868 QualType BoolT = Context.ObjCBuiltinBoolTy; 19869 if (!Context.getBOOLDecl()) { 19870 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19871 Sema::LookupOrdinaryName); 19872 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19873 NamedDecl *ND = Result.getFoundDecl(); 19874 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19875 Context.setBOOLDecl(TD); 19876 } 19877 } 19878 if (Context.getBOOLDecl()) 19879 BoolT = Context.getBOOLType(); 19880 return new (Context) 19881 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19882 } 19883 19884 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19885 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19886 SourceLocation RParen) { 19887 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19888 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19889 return Spec.getPlatform() == Platform; 19890 }); 19891 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19892 // for "maccatalyst" if "maccatalyst" is not specified. 19893 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19894 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19895 return Spec.getPlatform() == "ios"; 19896 }); 19897 } 19898 if (Spec == AvailSpecs.end()) 19899 return None; 19900 return Spec->getVersion(); 19901 }; 19902 19903 VersionTuple Version; 19904 if (auto MaybeVersion = 19905 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19906 Version = *MaybeVersion; 19907 19908 // The use of `@available` in the enclosing context should be analyzed to 19909 // warn when it's used inappropriately (i.e. not if(@available)). 19910 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19911 Context->HasPotentialAvailabilityViolations = true; 19912 19913 return new (Context) 19914 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19915 } 19916 19917 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19918 ArrayRef<Expr *> SubExprs, QualType T) { 19919 if (!Context.getLangOpts().RecoveryAST) 19920 return ExprError(); 19921 19922 if (isSFINAEContext()) 19923 return ExprError(); 19924 19925 if (T.isNull() || T->isUndeducedType() || 19926 !Context.getLangOpts().RecoveryASTType) 19927 // We don't know the concrete type, fallback to dependent type. 19928 T = Context.DependentTy; 19929 19930 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19931 } 19932