1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/OperationKinds.h" 28 #include "clang/AST/ParentMapContext.h" 29 #include "clang/AST/RecursiveASTVisitor.h" 30 #include "clang/AST/TypeLoc.h" 31 #include "clang/Basic/Builtins.h" 32 #include "clang/Basic/DiagnosticSema.h" 33 #include "clang/Basic/PartialDiagnostic.h" 34 #include "clang/Basic/SourceManager.h" 35 #include "clang/Basic/TargetInfo.h" 36 #include "clang/Lex/LiteralSupport.h" 37 #include "clang/Lex/Preprocessor.h" 38 #include "clang/Sema/AnalysisBasedWarnings.h" 39 #include "clang/Sema/DeclSpec.h" 40 #include "clang/Sema/DelayedDiagnostic.h" 41 #include "clang/Sema/Designator.h" 42 #include "clang/Sema/Initialization.h" 43 #include "clang/Sema/Lookup.h" 44 #include "clang/Sema/Overload.h" 45 #include "clang/Sema/ParsedTemplate.h" 46 #include "clang/Sema/Scope.h" 47 #include "clang/Sema/ScopeInfo.h" 48 #include "clang/Sema/SemaFixItUtils.h" 49 #include "clang/Sema/SemaInternal.h" 50 #include "clang/Sema/Template.h" 51 #include "llvm/ADT/STLExtras.h" 52 #include "llvm/ADT/StringExtras.h" 53 #include "llvm/Support/ConvertUTF.h" 54 #include "llvm/Support/SaveAndRestore.h" 55 56 using namespace clang; 57 using namespace sema; 58 59 /// Determine whether the use of this declaration is valid, without 60 /// emitting diagnostics. 61 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 62 // See if this is an auto-typed variable whose initializer we are parsing. 63 if (ParsingInitForAutoVars.count(D)) 64 return false; 65 66 // See if this is a deleted function. 67 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 68 if (FD->isDeleted()) 69 return false; 70 71 // If the function has a deduced return type, and we can't deduce it, 72 // then we can't use it either. 73 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 74 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 75 return false; 76 77 // See if this is an aligned allocation/deallocation function that is 78 // unavailable. 79 if (TreatUnavailableAsInvalid && 80 isUnavailableAlignedAllocationFunction(*FD)) 81 return false; 82 } 83 84 // See if this function is unavailable. 85 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 86 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 87 return false; 88 89 if (isa<UnresolvedUsingIfExistsDecl>(D)) 90 return false; 91 92 return true; 93 } 94 95 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 96 // Warn if this is used but marked unused. 97 if (const auto *A = D->getAttr<UnusedAttr>()) { 98 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 99 // should diagnose them. 100 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 101 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 102 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 103 if (DC && !DC->hasAttr<UnusedAttr>()) 104 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 105 } 106 } 107 } 108 109 /// Emit a note explaining that this function is deleted. 110 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 111 assert(Decl && Decl->isDeleted()); 112 113 if (Decl->isDefaulted()) { 114 // If the method was explicitly defaulted, point at that declaration. 115 if (!Decl->isImplicit()) 116 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 117 118 // Try to diagnose why this special member function was implicitly 119 // deleted. This might fail, if that reason no longer applies. 120 DiagnoseDeletedDefaultedFunction(Decl); 121 return; 122 } 123 124 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 125 if (Ctor && Ctor->isInheritingConstructor()) 126 return NoteDeletedInheritingConstructor(Ctor); 127 128 Diag(Decl->getLocation(), diag::note_availability_specified_here) 129 << Decl << 1; 130 } 131 132 /// Determine whether a FunctionDecl was ever declared with an 133 /// explicit storage class. 134 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 135 for (auto I : D->redecls()) { 136 if (I->getStorageClass() != SC_None) 137 return true; 138 } 139 return false; 140 } 141 142 /// Check whether we're in an extern inline function and referring to a 143 /// variable or function with internal linkage (C11 6.7.4p3). 144 /// 145 /// This is only a warning because we used to silently accept this code, but 146 /// in many cases it will not behave correctly. This is not enabled in C++ mode 147 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 148 /// and so while there may still be user mistakes, most of the time we can't 149 /// prove that there are errors. 150 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 151 const NamedDecl *D, 152 SourceLocation Loc) { 153 // This is disabled under C++; there are too many ways for this to fire in 154 // contexts where the warning is a false positive, or where it is technically 155 // correct but benign. 156 if (S.getLangOpts().CPlusPlus) 157 return; 158 159 // Check if this is an inlined function or method. 160 FunctionDecl *Current = S.getCurFunctionDecl(); 161 if (!Current) 162 return; 163 if (!Current->isInlined()) 164 return; 165 if (!Current->isExternallyVisible()) 166 return; 167 168 // Check if the decl has internal linkage. 169 if (D->getFormalLinkage() != InternalLinkage) 170 return; 171 172 // Downgrade from ExtWarn to Extension if 173 // (1) the supposedly external inline function is in the main file, 174 // and probably won't be included anywhere else. 175 // (2) the thing we're referencing is a pure function. 176 // (3) the thing we're referencing is another inline function. 177 // This last can give us false negatives, but it's better than warning on 178 // wrappers for simple C library functions. 179 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 180 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 181 if (!DowngradeWarning && UsedFn) 182 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 183 184 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 185 : diag::ext_internal_in_extern_inline) 186 << /*IsVar=*/!UsedFn << D; 187 188 S.MaybeSuggestAddingStaticToDecl(Current); 189 190 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 191 << D; 192 } 193 194 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 195 const FunctionDecl *First = Cur->getFirstDecl(); 196 197 // Suggest "static" on the function, if possible. 198 if (!hasAnyExplicitStorageClass(First)) { 199 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 200 Diag(DeclBegin, diag::note_convert_inline_to_static) 201 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 202 } 203 } 204 205 /// Determine whether the use of this declaration is valid, and 206 /// emit any corresponding diagnostics. 207 /// 208 /// This routine diagnoses various problems with referencing 209 /// declarations that can occur when using a declaration. For example, 210 /// it might warn if a deprecated or unavailable declaration is being 211 /// used, or produce an error (and return true) if a C++0x deleted 212 /// function is being used. 213 /// 214 /// \returns true if there was an error (this declaration cannot be 215 /// referenced), false otherwise. 216 /// 217 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 218 const ObjCInterfaceDecl *UnknownObjCClass, 219 bool ObjCPropertyAccess, 220 bool AvoidPartialAvailabilityChecks, 221 ObjCInterfaceDecl *ClassReceiver) { 222 SourceLocation Loc = Locs.front(); 223 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 224 // If there were any diagnostics suppressed by template argument deduction, 225 // emit them now. 226 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 227 if (Pos != SuppressedDiagnostics.end()) { 228 for (const PartialDiagnosticAt &Suppressed : Pos->second) 229 Diag(Suppressed.first, Suppressed.second); 230 231 // Clear out the list of suppressed diagnostics, so that we don't emit 232 // them again for this specialization. However, we don't obsolete this 233 // entry from the table, because we want to avoid ever emitting these 234 // diagnostics again. 235 Pos->second.clear(); 236 } 237 238 // C++ [basic.start.main]p3: 239 // The function 'main' shall not be used within a program. 240 if (cast<FunctionDecl>(D)->isMain()) 241 Diag(Loc, diag::ext_main_used); 242 243 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 244 } 245 246 // See if this is an auto-typed variable whose initializer we are parsing. 247 if (ParsingInitForAutoVars.count(D)) { 248 if (isa<BindingDecl>(D)) { 249 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 250 << D->getDeclName(); 251 } else { 252 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 253 << D->getDeclName() << cast<VarDecl>(D)->getType(); 254 } 255 return true; 256 } 257 258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 259 // See if this is a deleted function. 260 if (FD->isDeleted()) { 261 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 262 if (Ctor && Ctor->isInheritingConstructor()) 263 Diag(Loc, diag::err_deleted_inherited_ctor_use) 264 << Ctor->getParent() 265 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 266 else 267 Diag(Loc, diag::err_deleted_function_use); 268 NoteDeletedFunction(FD); 269 return true; 270 } 271 272 // [expr.prim.id]p4 273 // A program that refers explicitly or implicitly to a function with a 274 // trailing requires-clause whose constraint-expression is not satisfied, 275 // other than to declare it, is ill-formed. [...] 276 // 277 // See if this is a function with constraints that need to be satisfied. 278 // Check this before deducing the return type, as it might instantiate the 279 // definition. 280 if (FD->getTrailingRequiresClause()) { 281 ConstraintSatisfaction Satisfaction; 282 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 283 // A diagnostic will have already been generated (non-constant 284 // constraint expression, for example) 285 return true; 286 if (!Satisfaction.IsSatisfied) { 287 Diag(Loc, 288 diag::err_reference_to_function_with_unsatisfied_constraints) 289 << D; 290 DiagnoseUnsatisfiedConstraint(Satisfaction); 291 return true; 292 } 293 } 294 295 // If the function has a deduced return type, and we can't deduce it, 296 // then we can't use it either. 297 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 298 DeduceReturnType(FD, Loc)) 299 return true; 300 301 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 302 return true; 303 304 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 305 return true; 306 } 307 308 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 309 // Lambdas are only default-constructible or assignable in C++2a onwards. 310 if (MD->getParent()->isLambda() && 311 ((isa<CXXConstructorDecl>(MD) && 312 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 313 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 314 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 315 << !isa<CXXConstructorDecl>(MD); 316 } 317 } 318 319 auto getReferencedObjCProp = [](const NamedDecl *D) -> 320 const ObjCPropertyDecl * { 321 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 322 return MD->findPropertyDecl(); 323 return nullptr; 324 }; 325 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 326 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 327 return true; 328 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 329 return true; 330 } 331 332 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 333 // Only the variables omp_in and omp_out are allowed in the combiner. 334 // Only the variables omp_priv and omp_orig are allowed in the 335 // initializer-clause. 336 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 337 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 338 isa<VarDecl>(D)) { 339 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 340 << getCurFunction()->HasOMPDeclareReductionCombiner; 341 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 342 return true; 343 } 344 345 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 346 // List-items in map clauses on this construct may only refer to the declared 347 // variable var and entities that could be referenced by a procedure defined 348 // at the same location 349 if (LangOpts.OpenMP && isa<VarDecl>(D) && 350 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 351 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 352 << getOpenMPDeclareMapperVarName(); 353 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 354 return true; 355 } 356 357 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 358 Diag(Loc, diag::err_use_of_empty_using_if_exists); 359 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 360 return true; 361 } 362 363 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 364 AvoidPartialAvailabilityChecks, ClassReceiver); 365 366 DiagnoseUnusedOfDecl(*this, D, Loc); 367 368 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 369 370 if (auto *VD = dyn_cast<ValueDecl>(D)) 371 checkTypeSupport(VD->getType(), Loc, VD); 372 373 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 374 if (!Context.getTargetInfo().isTLSSupported()) 375 if (const auto *VD = dyn_cast<VarDecl>(D)) 376 if (VD->getTLSKind() != VarDecl::TLS_None) 377 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 378 } 379 380 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 381 !isUnevaluatedContext()) { 382 // C++ [expr.prim.req.nested] p3 383 // A local parameter shall only appear as an unevaluated operand 384 // (Clause 8) within the constraint-expression. 385 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 386 << D; 387 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 388 return true; 389 } 390 391 return false; 392 } 393 394 /// DiagnoseSentinelCalls - This routine checks whether a call or 395 /// message-send is to a declaration with the sentinel attribute, and 396 /// if so, it checks that the requirements of the sentinel are 397 /// satisfied. 398 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 399 ArrayRef<Expr *> Args) { 400 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 401 if (!attr) 402 return; 403 404 // The number of formal parameters of the declaration. 405 unsigned numFormalParams; 406 407 // The kind of declaration. This is also an index into a %select in 408 // the diagnostic. 409 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 410 411 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 412 numFormalParams = MD->param_size(); 413 calleeType = CT_Method; 414 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 415 numFormalParams = FD->param_size(); 416 calleeType = CT_Function; 417 } else if (isa<VarDecl>(D)) { 418 QualType type = cast<ValueDecl>(D)->getType(); 419 const FunctionType *fn = nullptr; 420 if (const PointerType *ptr = type->getAs<PointerType>()) { 421 fn = ptr->getPointeeType()->getAs<FunctionType>(); 422 if (!fn) return; 423 calleeType = CT_Function; 424 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 425 fn = ptr->getPointeeType()->castAs<FunctionType>(); 426 calleeType = CT_Block; 427 } else { 428 return; 429 } 430 431 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 432 numFormalParams = proto->getNumParams(); 433 } else { 434 numFormalParams = 0; 435 } 436 } else { 437 return; 438 } 439 440 // "nullPos" is the number of formal parameters at the end which 441 // effectively count as part of the variadic arguments. This is 442 // useful if you would prefer to not have *any* formal parameters, 443 // but the language forces you to have at least one. 444 unsigned nullPos = attr->getNullPos(); 445 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 446 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 447 448 // The number of arguments which should follow the sentinel. 449 unsigned numArgsAfterSentinel = attr->getSentinel(); 450 451 // If there aren't enough arguments for all the formal parameters, 452 // the sentinel, and the args after the sentinel, complain. 453 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 454 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 455 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 456 return; 457 } 458 459 // Otherwise, find the sentinel expression. 460 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 461 if (!sentinelExpr) return; 462 if (sentinelExpr->isValueDependent()) return; 463 if (Context.isSentinelNullExpr(sentinelExpr)) return; 464 465 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 466 // or 'NULL' if those are actually defined in the context. Only use 467 // 'nil' for ObjC methods, where it's much more likely that the 468 // variadic arguments form a list of object pointers. 469 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 470 std::string NullValue; 471 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 472 NullValue = "nil"; 473 else if (getLangOpts().CPlusPlus11) 474 NullValue = "nullptr"; 475 else if (PP.isMacroDefined("NULL")) 476 NullValue = "NULL"; 477 else 478 NullValue = "(void*) 0"; 479 480 if (MissingNilLoc.isInvalid()) 481 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 482 else 483 Diag(MissingNilLoc, diag::warn_missing_sentinel) 484 << int(calleeType) 485 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 486 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 487 } 488 489 SourceRange Sema::getExprRange(Expr *E) const { 490 return E ? E->getSourceRange() : SourceRange(); 491 } 492 493 //===----------------------------------------------------------------------===// 494 // Standard Promotions and Conversions 495 //===----------------------------------------------------------------------===// 496 497 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 498 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 499 // Handle any placeholder expressions which made it here. 500 if (E->getType()->isPlaceholderType()) { 501 ExprResult result = CheckPlaceholderExpr(E); 502 if (result.isInvalid()) return ExprError(); 503 E = result.get(); 504 } 505 506 QualType Ty = E->getType(); 507 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 508 509 if (Ty->isFunctionType()) { 510 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 511 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 512 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 513 return ExprError(); 514 515 E = ImpCastExprToType(E, Context.getPointerType(Ty), 516 CK_FunctionToPointerDecay).get(); 517 } else if (Ty->isArrayType()) { 518 // In C90 mode, arrays only promote to pointers if the array expression is 519 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 520 // type 'array of type' is converted to an expression that has type 'pointer 521 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 522 // that has type 'array of type' ...". The relevant change is "an lvalue" 523 // (C90) to "an expression" (C99). 524 // 525 // C++ 4.2p1: 526 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 527 // T" can be converted to an rvalue of type "pointer to T". 528 // 529 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 530 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 531 CK_ArrayToPointerDecay); 532 if (Res.isInvalid()) 533 return ExprError(); 534 E = Res.get(); 535 } 536 } 537 return E; 538 } 539 540 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 541 // Check to see if we are dereferencing a null pointer. If so, 542 // and if not volatile-qualified, this is undefined behavior that the 543 // optimizer will delete, so warn about it. People sometimes try to use this 544 // to get a deterministic trap and are surprised by clang's behavior. This 545 // only handles the pattern "*null", which is a very syntactic check. 546 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 547 if (UO && UO->getOpcode() == UO_Deref && 548 UO->getSubExpr()->getType()->isPointerType()) { 549 const LangAS AS = 550 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 551 if ((!isTargetAddressSpace(AS) || 552 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 553 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 554 S.Context, Expr::NPC_ValueDependentIsNotNull) && 555 !UO->getType().isVolatileQualified()) { 556 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 557 S.PDiag(diag::warn_indirection_through_null) 558 << UO->getSubExpr()->getSourceRange()); 559 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 560 S.PDiag(diag::note_indirection_through_null)); 561 } 562 } 563 } 564 565 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 566 SourceLocation AssignLoc, 567 const Expr* RHS) { 568 const ObjCIvarDecl *IV = OIRE->getDecl(); 569 if (!IV) 570 return; 571 572 DeclarationName MemberName = IV->getDeclName(); 573 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 574 if (!Member || !Member->isStr("isa")) 575 return; 576 577 const Expr *Base = OIRE->getBase(); 578 QualType BaseType = Base->getType(); 579 if (OIRE->isArrow()) 580 BaseType = BaseType->getPointeeType(); 581 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 582 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 583 ObjCInterfaceDecl *ClassDeclared = nullptr; 584 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 585 if (!ClassDeclared->getSuperClass() 586 && (*ClassDeclared->ivar_begin()) == IV) { 587 if (RHS) { 588 NamedDecl *ObjectSetClass = 589 S.LookupSingleName(S.TUScope, 590 &S.Context.Idents.get("object_setClass"), 591 SourceLocation(), S.LookupOrdinaryName); 592 if (ObjectSetClass) { 593 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 594 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 595 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 596 "object_setClass(") 597 << FixItHint::CreateReplacement( 598 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 599 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 600 } 601 else 602 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 603 } else { 604 NamedDecl *ObjectGetClass = 605 S.LookupSingleName(S.TUScope, 606 &S.Context.Idents.get("object_getClass"), 607 SourceLocation(), S.LookupOrdinaryName); 608 if (ObjectGetClass) 609 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 610 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 611 "object_getClass(") 612 << FixItHint::CreateReplacement( 613 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 614 else 615 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 616 } 617 S.Diag(IV->getLocation(), diag::note_ivar_decl); 618 } 619 } 620 } 621 622 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 623 // Handle any placeholder expressions which made it here. 624 if (E->getType()->isPlaceholderType()) { 625 ExprResult result = CheckPlaceholderExpr(E); 626 if (result.isInvalid()) return ExprError(); 627 E = result.get(); 628 } 629 630 // C++ [conv.lval]p1: 631 // A glvalue of a non-function, non-array type T can be 632 // converted to a prvalue. 633 if (!E->isGLValue()) return E; 634 635 QualType T = E->getType(); 636 assert(!T.isNull() && "r-value conversion on typeless expression?"); 637 638 // lvalue-to-rvalue conversion cannot be applied to function or array types. 639 if (T->isFunctionType() || T->isArrayType()) 640 return E; 641 642 // We don't want to throw lvalue-to-rvalue casts on top of 643 // expressions of certain types in C++. 644 if (getLangOpts().CPlusPlus && 645 (E->getType() == Context.OverloadTy || 646 T->isDependentType() || 647 T->isRecordType())) 648 return E; 649 650 // The C standard is actually really unclear on this point, and 651 // DR106 tells us what the result should be but not why. It's 652 // generally best to say that void types just doesn't undergo 653 // lvalue-to-rvalue at all. Note that expressions of unqualified 654 // 'void' type are never l-values, but qualified void can be. 655 if (T->isVoidType()) 656 return E; 657 658 // OpenCL usually rejects direct accesses to values of 'half' type. 659 if (getLangOpts().OpenCL && 660 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 661 T->isHalfType()) { 662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 663 << 0 << T; 664 return ExprError(); 665 } 666 667 CheckForNullPointerDereference(*this, E); 668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 670 &Context.Idents.get("object_getClass"), 671 SourceLocation(), LookupOrdinaryName); 672 if (ObjectGetClass) 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 674 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 675 << FixItHint::CreateReplacement( 676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 677 else 678 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 679 } 680 else if (const ObjCIvarRefExpr *OIRE = 681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 683 684 // C++ [conv.lval]p1: 685 // [...] If T is a non-class type, the type of the prvalue is the 686 // cv-unqualified version of T. Otherwise, the type of the 687 // rvalue is T. 688 // 689 // C99 6.3.2.1p2: 690 // If the lvalue has qualified type, the value has the unqualified 691 // version of the type of the lvalue; otherwise, the value has the 692 // type of the lvalue. 693 if (T.hasQualifiers()) 694 T = T.getUnqualifiedType(); 695 696 // Under the MS ABI, lock down the inheritance model now. 697 if (T->isMemberPointerType() && 698 Context.getTargetInfo().getCXXABI().isMicrosoft()) 699 (void)isCompleteType(E->getExprLoc(), T); 700 701 ExprResult Res = CheckLValueToRValueConversionOperand(E); 702 if (Res.isInvalid()) 703 return Res; 704 E = Res.get(); 705 706 // Loading a __weak object implicitly retains the value, so we need a cleanup to 707 // balance that. 708 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 709 Cleanup.setExprNeedsCleanups(true); 710 711 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 712 Cleanup.setExprNeedsCleanups(true); 713 714 // C++ [conv.lval]p3: 715 // If T is cv std::nullptr_t, the result is a null pointer constant. 716 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 717 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 718 CurFPFeatureOverrides()); 719 720 // C11 6.3.2.1p2: 721 // ... if the lvalue has atomic type, the value has the non-atomic version 722 // of the type of the lvalue ... 723 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 724 T = Atomic->getValueType().getUnqualifiedType(); 725 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 726 nullptr, VK_PRValue, FPOptionsOverride()); 727 } 728 729 return Res; 730 } 731 732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 733 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 734 if (Res.isInvalid()) 735 return ExprError(); 736 Res = DefaultLvalueConversion(Res.get()); 737 if (Res.isInvalid()) 738 return ExprError(); 739 return Res; 740 } 741 742 /// CallExprUnaryConversions - a special case of an unary conversion 743 /// performed on a function designator of a call expression. 744 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 745 QualType Ty = E->getType(); 746 ExprResult Res = E; 747 // Only do implicit cast for a function type, but not for a pointer 748 // to function type. 749 if (Ty->isFunctionType()) { 750 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 751 CK_FunctionToPointerDecay); 752 if (Res.isInvalid()) 753 return ExprError(); 754 } 755 Res = DefaultLvalueConversion(Res.get()); 756 if (Res.isInvalid()) 757 return ExprError(); 758 return Res.get(); 759 } 760 761 /// UsualUnaryConversions - Performs various conversions that are common to most 762 /// operators (C99 6.3). The conversions of array and function types are 763 /// sometimes suppressed. For example, the array->pointer conversion doesn't 764 /// apply if the array is an argument to the sizeof or address (&) operators. 765 /// In these instances, this routine should *not* be called. 766 ExprResult Sema::UsualUnaryConversions(Expr *E) { 767 // First, convert to an r-value. 768 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 769 if (Res.isInvalid()) 770 return ExprError(); 771 E = Res.get(); 772 773 QualType Ty = E->getType(); 774 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 775 776 // Half FP have to be promoted to float unless it is natively supported 777 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 778 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 779 780 // Try to perform integral promotions if the object has a theoretically 781 // promotable type. 782 if (Ty->isIntegralOrUnscopedEnumerationType()) { 783 // C99 6.3.1.1p2: 784 // 785 // The following may be used in an expression wherever an int or 786 // unsigned int may be used: 787 // - an object or expression with an integer type whose integer 788 // conversion rank is less than or equal to the rank of int 789 // and unsigned int. 790 // - A bit-field of type _Bool, int, signed int, or unsigned int. 791 // 792 // If an int can represent all values of the original type, the 793 // value is converted to an int; otherwise, it is converted to an 794 // unsigned int. These are called the integer promotions. All 795 // other types are unchanged by the integer promotions. 796 797 QualType PTy = Context.isPromotableBitField(E); 798 if (!PTy.isNull()) { 799 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 800 return E; 801 } 802 if (Ty->isPromotableIntegerType()) { 803 QualType PT = Context.getPromotedIntegerType(Ty); 804 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 805 return E; 806 } 807 } 808 return E; 809 } 810 811 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 812 /// do not have a prototype. Arguments that have type float or __fp16 813 /// are promoted to double. All other argument types are converted by 814 /// UsualUnaryConversions(). 815 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 816 QualType Ty = E->getType(); 817 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 818 819 ExprResult Res = UsualUnaryConversions(E); 820 if (Res.isInvalid()) 821 return ExprError(); 822 E = Res.get(); 823 824 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 825 // promote to double. 826 // Note that default argument promotion applies only to float (and 827 // half/fp16); it does not apply to _Float16. 828 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 829 if (BTy && (BTy->getKind() == BuiltinType::Half || 830 BTy->getKind() == BuiltinType::Float)) { 831 if (getLangOpts().OpenCL && 832 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 833 if (BTy->getKind() == BuiltinType::Half) { 834 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 835 } 836 } else { 837 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 838 } 839 } 840 if (BTy && 841 getLangOpts().getExtendIntArgs() == 842 LangOptions::ExtendArgsKind::ExtendTo64 && 843 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 844 Context.getTypeSizeInChars(BTy) < 845 Context.getTypeSizeInChars(Context.LongLongTy)) { 846 E = (Ty->isUnsignedIntegerType()) 847 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 848 .get() 849 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 850 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 851 "Unexpected typesize for LongLongTy"); 852 } 853 854 // C++ performs lvalue-to-rvalue conversion as a default argument 855 // promotion, even on class types, but note: 856 // C++11 [conv.lval]p2: 857 // When an lvalue-to-rvalue conversion occurs in an unevaluated 858 // operand or a subexpression thereof the value contained in the 859 // referenced object is not accessed. Otherwise, if the glvalue 860 // has a class type, the conversion copy-initializes a temporary 861 // of type T from the glvalue and the result of the conversion 862 // is a prvalue for the temporary. 863 // FIXME: add some way to gate this entire thing for correctness in 864 // potentially potentially evaluated contexts. 865 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 866 ExprResult Temp = PerformCopyInitialization( 867 InitializedEntity::InitializeTemporary(E->getType()), 868 E->getExprLoc(), E); 869 if (Temp.isInvalid()) 870 return ExprError(); 871 E = Temp.get(); 872 } 873 874 return E; 875 } 876 877 /// Determine the degree of POD-ness for an expression. 878 /// Incomplete types are considered POD, since this check can be performed 879 /// when we're in an unevaluated context. 880 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 881 if (Ty->isIncompleteType()) { 882 // C++11 [expr.call]p7: 883 // After these conversions, if the argument does not have arithmetic, 884 // enumeration, pointer, pointer to member, or class type, the program 885 // is ill-formed. 886 // 887 // Since we've already performed array-to-pointer and function-to-pointer 888 // decay, the only such type in C++ is cv void. This also handles 889 // initializer lists as variadic arguments. 890 if (Ty->isVoidType()) 891 return VAK_Invalid; 892 893 if (Ty->isObjCObjectType()) 894 return VAK_Invalid; 895 return VAK_Valid; 896 } 897 898 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 899 return VAK_Invalid; 900 901 if (Ty.isCXX98PODType(Context)) 902 return VAK_Valid; 903 904 // C++11 [expr.call]p7: 905 // Passing a potentially-evaluated argument of class type (Clause 9) 906 // having a non-trivial copy constructor, a non-trivial move constructor, 907 // or a non-trivial destructor, with no corresponding parameter, 908 // is conditionally-supported with implementation-defined semantics. 909 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 910 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 911 if (!Record->hasNonTrivialCopyConstructor() && 912 !Record->hasNonTrivialMoveConstructor() && 913 !Record->hasNonTrivialDestructor()) 914 return VAK_ValidInCXX11; 915 916 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 917 return VAK_Valid; 918 919 if (Ty->isObjCObjectType()) 920 return VAK_Invalid; 921 922 if (getLangOpts().MSVCCompat) 923 return VAK_MSVCUndefined; 924 925 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 926 // permitted to reject them. We should consider doing so. 927 return VAK_Undefined; 928 } 929 930 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 931 // Don't allow one to pass an Objective-C interface to a vararg. 932 const QualType &Ty = E->getType(); 933 VarArgKind VAK = isValidVarArgType(Ty); 934 935 // Complain about passing non-POD types through varargs. 936 switch (VAK) { 937 case VAK_ValidInCXX11: 938 DiagRuntimeBehavior( 939 E->getBeginLoc(), nullptr, 940 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 941 LLVM_FALLTHROUGH; 942 case VAK_Valid: 943 if (Ty->isRecordType()) { 944 // This is unlikely to be what the user intended. If the class has a 945 // 'c_str' member function, the user probably meant to call that. 946 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 947 PDiag(diag::warn_pass_class_arg_to_vararg) 948 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 949 } 950 break; 951 952 case VAK_Undefined: 953 case VAK_MSVCUndefined: 954 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 955 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 956 << getLangOpts().CPlusPlus11 << Ty << CT); 957 break; 958 959 case VAK_Invalid: 960 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 961 Diag(E->getBeginLoc(), 962 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 963 << Ty << CT; 964 else if (Ty->isObjCObjectType()) 965 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 966 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 967 << Ty << CT); 968 else 969 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 970 << isa<InitListExpr>(E) << Ty << CT; 971 break; 972 } 973 } 974 975 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 976 /// will create a trap if the resulting type is not a POD type. 977 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 978 FunctionDecl *FDecl) { 979 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 980 // Strip the unbridged-cast placeholder expression off, if applicable. 981 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 982 (CT == VariadicMethod || 983 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 984 E = stripARCUnbridgedCast(E); 985 986 // Otherwise, do normal placeholder checking. 987 } else { 988 ExprResult ExprRes = CheckPlaceholderExpr(E); 989 if (ExprRes.isInvalid()) 990 return ExprError(); 991 E = ExprRes.get(); 992 } 993 } 994 995 ExprResult ExprRes = DefaultArgumentPromotion(E); 996 if (ExprRes.isInvalid()) 997 return ExprError(); 998 999 // Copy blocks to the heap. 1000 if (ExprRes.get()->getType()->isBlockPointerType()) 1001 maybeExtendBlockObject(ExprRes); 1002 1003 E = ExprRes.get(); 1004 1005 // Diagnostics regarding non-POD argument types are 1006 // emitted along with format string checking in Sema::CheckFunctionCall(). 1007 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1008 // Turn this into a trap. 1009 CXXScopeSpec SS; 1010 SourceLocation TemplateKWLoc; 1011 UnqualifiedId Name; 1012 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1013 E->getBeginLoc()); 1014 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1015 /*HasTrailingLParen=*/true, 1016 /*IsAddressOfOperand=*/false); 1017 if (TrapFn.isInvalid()) 1018 return ExprError(); 1019 1020 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1021 None, E->getEndLoc()); 1022 if (Call.isInvalid()) 1023 return ExprError(); 1024 1025 ExprResult Comma = 1026 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1027 if (Comma.isInvalid()) 1028 return ExprError(); 1029 return Comma.get(); 1030 } 1031 1032 if (!getLangOpts().CPlusPlus && 1033 RequireCompleteType(E->getExprLoc(), E->getType(), 1034 diag::err_call_incomplete_argument)) 1035 return ExprError(); 1036 1037 return E; 1038 } 1039 1040 /// Converts an integer to complex float type. Helper function of 1041 /// UsualArithmeticConversions() 1042 /// 1043 /// \return false if the integer expression is an integer type and is 1044 /// successfully converted to the complex type. 1045 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1046 ExprResult &ComplexExpr, 1047 QualType IntTy, 1048 QualType ComplexTy, 1049 bool SkipCast) { 1050 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1051 if (SkipCast) return false; 1052 if (IntTy->isIntegerType()) { 1053 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1055 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1056 CK_FloatingRealToComplex); 1057 } else { 1058 assert(IntTy->isComplexIntegerType()); 1059 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1060 CK_IntegralComplexToFloatingComplex); 1061 } 1062 return false; 1063 } 1064 1065 /// Handle arithmetic conversion with complex types. Helper function of 1066 /// UsualArithmeticConversions() 1067 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1068 ExprResult &RHS, QualType LHSType, 1069 QualType RHSType, 1070 bool IsCompAssign) { 1071 // if we have an integer operand, the result is the complex type. 1072 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1073 /*skipCast*/false)) 1074 return LHSType; 1075 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1076 /*skipCast*/IsCompAssign)) 1077 return RHSType; 1078 1079 // This handles complex/complex, complex/float, or float/complex. 1080 // When both operands are complex, the shorter operand is converted to the 1081 // type of the longer, and that is the type of the result. This corresponds 1082 // to what is done when combining two real floating-point operands. 1083 // The fun begins when size promotion occur across type domains. 1084 // From H&S 6.3.4: When one operand is complex and the other is a real 1085 // floating-point type, the less precise type is converted, within it's 1086 // real or complex domain, to the precision of the other type. For example, 1087 // when combining a "long double" with a "double _Complex", the 1088 // "double _Complex" is promoted to "long double _Complex". 1089 1090 // Compute the rank of the two types, regardless of whether they are complex. 1091 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1092 1093 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1094 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1095 QualType LHSElementType = 1096 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1097 QualType RHSElementType = 1098 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1099 1100 QualType ResultType = S.Context.getComplexType(LHSElementType); 1101 if (Order < 0) { 1102 // Promote the precision of the LHS if not an assignment. 1103 ResultType = S.Context.getComplexType(RHSElementType); 1104 if (!IsCompAssign) { 1105 if (LHSComplexType) 1106 LHS = 1107 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1108 else 1109 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1110 } 1111 } else if (Order > 0) { 1112 // Promote the precision of the RHS. 1113 if (RHSComplexType) 1114 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1115 else 1116 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1117 } 1118 return ResultType; 1119 } 1120 1121 /// Handle arithmetic conversion from integer to float. Helper function 1122 /// of UsualArithmeticConversions() 1123 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1124 ExprResult &IntExpr, 1125 QualType FloatTy, QualType IntTy, 1126 bool ConvertFloat, bool ConvertInt) { 1127 if (IntTy->isIntegerType()) { 1128 if (ConvertInt) 1129 // Convert intExpr to the lhs floating point type. 1130 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1131 CK_IntegralToFloating); 1132 return FloatTy; 1133 } 1134 1135 // Convert both sides to the appropriate complex float. 1136 assert(IntTy->isComplexIntegerType()); 1137 QualType result = S.Context.getComplexType(FloatTy); 1138 1139 // _Complex int -> _Complex float 1140 if (ConvertInt) 1141 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1142 CK_IntegralComplexToFloatingComplex); 1143 1144 // float -> _Complex float 1145 if (ConvertFloat) 1146 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1147 CK_FloatingRealToComplex); 1148 1149 return result; 1150 } 1151 1152 /// Handle arithmethic conversion with floating point types. Helper 1153 /// function of UsualArithmeticConversions() 1154 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1155 ExprResult &RHS, QualType LHSType, 1156 QualType RHSType, bool IsCompAssign) { 1157 bool LHSFloat = LHSType->isRealFloatingType(); 1158 bool RHSFloat = RHSType->isRealFloatingType(); 1159 1160 // N1169 4.1.4: If one of the operands has a floating type and the other 1161 // operand has a fixed-point type, the fixed-point operand 1162 // is converted to the floating type [...] 1163 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1164 if (LHSFloat) 1165 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1166 else if (!IsCompAssign) 1167 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1168 return LHSFloat ? LHSType : RHSType; 1169 } 1170 1171 // If we have two real floating types, convert the smaller operand 1172 // to the bigger result. 1173 if (LHSFloat && RHSFloat) { 1174 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1175 if (order > 0) { 1176 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1177 return LHSType; 1178 } 1179 1180 assert(order < 0 && "illegal float comparison"); 1181 if (!IsCompAssign) 1182 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1183 return RHSType; 1184 } 1185 1186 if (LHSFloat) { 1187 // Half FP has to be promoted to float unless it is natively supported 1188 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1189 LHSType = S.Context.FloatTy; 1190 1191 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1192 /*ConvertFloat=*/!IsCompAssign, 1193 /*ConvertInt=*/ true); 1194 } 1195 assert(RHSFloat); 1196 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1197 /*ConvertFloat=*/ true, 1198 /*ConvertInt=*/!IsCompAssign); 1199 } 1200 1201 /// Diagnose attempts to convert between __float128, __ibm128 and 1202 /// long double if there is no support for such conversion. 1203 /// Helper function of UsualArithmeticConversions(). 1204 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1205 QualType RHSType) { 1206 // No issue if either is not a floating point type. 1207 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1208 return false; 1209 1210 // No issue if both have the same 128-bit float semantics. 1211 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1212 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1213 1214 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1215 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1216 1217 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1218 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1219 1220 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1221 &RHSSem != &llvm::APFloat::IEEEquad()) && 1222 (&LHSSem != &llvm::APFloat::IEEEquad() || 1223 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1224 return false; 1225 1226 return true; 1227 } 1228 1229 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1230 1231 namespace { 1232 /// These helper callbacks are placed in an anonymous namespace to 1233 /// permit their use as function template parameters. 1234 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1235 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1236 } 1237 1238 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1239 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1240 CK_IntegralComplexCast); 1241 } 1242 } 1243 1244 /// Handle integer arithmetic conversions. Helper function of 1245 /// UsualArithmeticConversions() 1246 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1247 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1248 ExprResult &RHS, QualType LHSType, 1249 QualType RHSType, bool IsCompAssign) { 1250 // The rules for this case are in C99 6.3.1.8 1251 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1252 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1253 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1254 if (LHSSigned == RHSSigned) { 1255 // Same signedness; use the higher-ranked type 1256 if (order >= 0) { 1257 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1258 return LHSType; 1259 } else if (!IsCompAssign) 1260 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1261 return RHSType; 1262 } else if (order != (LHSSigned ? 1 : -1)) { 1263 // The unsigned type has greater than or equal rank to the 1264 // signed type, so use the unsigned type 1265 if (RHSSigned) { 1266 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1267 return LHSType; 1268 } else if (!IsCompAssign) 1269 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1270 return RHSType; 1271 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1272 // The two types are different widths; if we are here, that 1273 // means the signed type is larger than the unsigned type, so 1274 // use the signed type. 1275 if (LHSSigned) { 1276 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1277 return LHSType; 1278 } else if (!IsCompAssign) 1279 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1280 return RHSType; 1281 } else { 1282 // The signed type is higher-ranked than the unsigned type, 1283 // but isn't actually any bigger (like unsigned int and long 1284 // on most 32-bit systems). Use the unsigned type corresponding 1285 // to the signed type. 1286 QualType result = 1287 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1288 RHS = (*doRHSCast)(S, RHS.get(), result); 1289 if (!IsCompAssign) 1290 LHS = (*doLHSCast)(S, LHS.get(), result); 1291 return result; 1292 } 1293 } 1294 1295 /// Handle conversions with GCC complex int extension. Helper function 1296 /// of UsualArithmeticConversions() 1297 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1298 ExprResult &RHS, QualType LHSType, 1299 QualType RHSType, 1300 bool IsCompAssign) { 1301 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1302 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1303 1304 if (LHSComplexInt && RHSComplexInt) { 1305 QualType LHSEltType = LHSComplexInt->getElementType(); 1306 QualType RHSEltType = RHSComplexInt->getElementType(); 1307 QualType ScalarType = 1308 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1309 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1310 1311 return S.Context.getComplexType(ScalarType); 1312 } 1313 1314 if (LHSComplexInt) { 1315 QualType LHSEltType = LHSComplexInt->getElementType(); 1316 QualType ScalarType = 1317 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1318 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1319 QualType ComplexType = S.Context.getComplexType(ScalarType); 1320 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1321 CK_IntegralRealToComplex); 1322 1323 return ComplexType; 1324 } 1325 1326 assert(RHSComplexInt); 1327 1328 QualType RHSEltType = RHSComplexInt->getElementType(); 1329 QualType ScalarType = 1330 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1331 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1332 QualType ComplexType = S.Context.getComplexType(ScalarType); 1333 1334 if (!IsCompAssign) 1335 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1336 CK_IntegralRealToComplex); 1337 return ComplexType; 1338 } 1339 1340 /// Return the rank of a given fixed point or integer type. The value itself 1341 /// doesn't matter, but the values must be increasing with proper increasing 1342 /// rank as described in N1169 4.1.1. 1343 static unsigned GetFixedPointRank(QualType Ty) { 1344 const auto *BTy = Ty->getAs<BuiltinType>(); 1345 assert(BTy && "Expected a builtin type."); 1346 1347 switch (BTy->getKind()) { 1348 case BuiltinType::ShortFract: 1349 case BuiltinType::UShortFract: 1350 case BuiltinType::SatShortFract: 1351 case BuiltinType::SatUShortFract: 1352 return 1; 1353 case BuiltinType::Fract: 1354 case BuiltinType::UFract: 1355 case BuiltinType::SatFract: 1356 case BuiltinType::SatUFract: 1357 return 2; 1358 case BuiltinType::LongFract: 1359 case BuiltinType::ULongFract: 1360 case BuiltinType::SatLongFract: 1361 case BuiltinType::SatULongFract: 1362 return 3; 1363 case BuiltinType::ShortAccum: 1364 case BuiltinType::UShortAccum: 1365 case BuiltinType::SatShortAccum: 1366 case BuiltinType::SatUShortAccum: 1367 return 4; 1368 case BuiltinType::Accum: 1369 case BuiltinType::UAccum: 1370 case BuiltinType::SatAccum: 1371 case BuiltinType::SatUAccum: 1372 return 5; 1373 case BuiltinType::LongAccum: 1374 case BuiltinType::ULongAccum: 1375 case BuiltinType::SatLongAccum: 1376 case BuiltinType::SatULongAccum: 1377 return 6; 1378 default: 1379 if (BTy->isInteger()) 1380 return 0; 1381 llvm_unreachable("Unexpected fixed point or integer type"); 1382 } 1383 } 1384 1385 /// handleFixedPointConversion - Fixed point operations between fixed 1386 /// point types and integers or other fixed point types do not fall under 1387 /// usual arithmetic conversion since these conversions could result in loss 1388 /// of precsision (N1169 4.1.4). These operations should be calculated with 1389 /// the full precision of their result type (N1169 4.1.6.2.1). 1390 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1391 QualType RHSTy) { 1392 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1393 "Expected at least one of the operands to be a fixed point type"); 1394 assert((LHSTy->isFixedPointOrIntegerType() || 1395 RHSTy->isFixedPointOrIntegerType()) && 1396 "Special fixed point arithmetic operation conversions are only " 1397 "applied to ints or other fixed point types"); 1398 1399 // If one operand has signed fixed-point type and the other operand has 1400 // unsigned fixed-point type, then the unsigned fixed-point operand is 1401 // converted to its corresponding signed fixed-point type and the resulting 1402 // type is the type of the converted operand. 1403 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1404 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1405 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1406 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1407 1408 // The result type is the type with the highest rank, whereby a fixed-point 1409 // conversion rank is always greater than an integer conversion rank; if the 1410 // type of either of the operands is a saturating fixedpoint type, the result 1411 // type shall be the saturating fixed-point type corresponding to the type 1412 // with the highest rank; the resulting value is converted (taking into 1413 // account rounding and overflow) to the precision of the resulting type. 1414 // Same ranks between signed and unsigned types are resolved earlier, so both 1415 // types are either signed or both unsigned at this point. 1416 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1417 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1418 1419 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1420 1421 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1422 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1423 1424 return ResultTy; 1425 } 1426 1427 /// Check that the usual arithmetic conversions can be performed on this pair of 1428 /// expressions that might be of enumeration type. 1429 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1430 SourceLocation Loc, 1431 Sema::ArithConvKind ACK) { 1432 // C++2a [expr.arith.conv]p1: 1433 // If one operand is of enumeration type and the other operand is of a 1434 // different enumeration type or a floating-point type, this behavior is 1435 // deprecated ([depr.arith.conv.enum]). 1436 // 1437 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1438 // Eventually we will presumably reject these cases (in C++23 onwards?). 1439 QualType L = LHS->getType(), R = RHS->getType(); 1440 bool LEnum = L->isUnscopedEnumerationType(), 1441 REnum = R->isUnscopedEnumerationType(); 1442 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1443 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1444 (REnum && L->isFloatingType())) { 1445 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1446 ? diag::warn_arith_conv_enum_float_cxx20 1447 : diag::warn_arith_conv_enum_float) 1448 << LHS->getSourceRange() << RHS->getSourceRange() 1449 << (int)ACK << LEnum << L << R; 1450 } else if (!IsCompAssign && LEnum && REnum && 1451 !S.Context.hasSameUnqualifiedType(L, R)) { 1452 unsigned DiagID; 1453 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1454 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1455 // If either enumeration type is unnamed, it's less likely that the 1456 // user cares about this, but this situation is still deprecated in 1457 // C++2a. Use a different warning group. 1458 DiagID = S.getLangOpts().CPlusPlus20 1459 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1460 : diag::warn_arith_conv_mixed_anon_enum_types; 1461 } else if (ACK == Sema::ACK_Conditional) { 1462 // Conditional expressions are separated out because they have 1463 // historically had a different warning flag. 1464 DiagID = S.getLangOpts().CPlusPlus20 1465 ? diag::warn_conditional_mixed_enum_types_cxx20 1466 : diag::warn_conditional_mixed_enum_types; 1467 } else if (ACK == Sema::ACK_Comparison) { 1468 // Comparison expressions are separated out because they have 1469 // historically had a different warning flag. 1470 DiagID = S.getLangOpts().CPlusPlus20 1471 ? diag::warn_comparison_mixed_enum_types_cxx20 1472 : diag::warn_comparison_mixed_enum_types; 1473 } else { 1474 DiagID = S.getLangOpts().CPlusPlus20 1475 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1476 : diag::warn_arith_conv_mixed_enum_types; 1477 } 1478 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1479 << (int)ACK << L << R; 1480 } 1481 } 1482 1483 /// UsualArithmeticConversions - Performs various conversions that are common to 1484 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1485 /// routine returns the first non-arithmetic type found. The client is 1486 /// responsible for emitting appropriate error diagnostics. 1487 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1488 SourceLocation Loc, 1489 ArithConvKind ACK) { 1490 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1491 1492 if (ACK != ACK_CompAssign) { 1493 LHS = UsualUnaryConversions(LHS.get()); 1494 if (LHS.isInvalid()) 1495 return QualType(); 1496 } 1497 1498 RHS = UsualUnaryConversions(RHS.get()); 1499 if (RHS.isInvalid()) 1500 return QualType(); 1501 1502 // For conversion purposes, we ignore any qualifiers. 1503 // For example, "const float" and "float" are equivalent. 1504 QualType LHSType = 1505 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1506 QualType RHSType = 1507 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1508 1509 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1510 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1511 LHSType = AtomicLHS->getValueType(); 1512 1513 // If both types are identical, no conversion is needed. 1514 if (LHSType == RHSType) 1515 return LHSType; 1516 1517 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1518 // The caller can deal with this (e.g. pointer + int). 1519 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1520 return QualType(); 1521 1522 // Apply unary and bitfield promotions to the LHS's type. 1523 QualType LHSUnpromotedType = LHSType; 1524 if (LHSType->isPromotableIntegerType()) 1525 LHSType = Context.getPromotedIntegerType(LHSType); 1526 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1527 if (!LHSBitfieldPromoteTy.isNull()) 1528 LHSType = LHSBitfieldPromoteTy; 1529 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1530 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1531 1532 // If both types are identical, no conversion is needed. 1533 if (LHSType == RHSType) 1534 return LHSType; 1535 1536 // At this point, we have two different arithmetic types. 1537 1538 // Diagnose attempts to convert between __ibm128, __float128 and long double 1539 // where such conversions currently can't be handled. 1540 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1541 return QualType(); 1542 1543 // Handle complex types first (C99 6.3.1.8p1). 1544 if (LHSType->isComplexType() || RHSType->isComplexType()) 1545 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1546 ACK == ACK_CompAssign); 1547 1548 // Now handle "real" floating types (i.e. float, double, long double). 1549 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1550 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1551 ACK == ACK_CompAssign); 1552 1553 // Handle GCC complex int extension. 1554 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1555 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1556 ACK == ACK_CompAssign); 1557 1558 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1559 return handleFixedPointConversion(*this, LHSType, RHSType); 1560 1561 // Finally, we have two differing integer types. 1562 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1563 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1564 } 1565 1566 //===----------------------------------------------------------------------===// 1567 // Semantic Analysis for various Expression Types 1568 //===----------------------------------------------------------------------===// 1569 1570 1571 ExprResult 1572 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1573 SourceLocation DefaultLoc, 1574 SourceLocation RParenLoc, 1575 Expr *ControllingExpr, 1576 ArrayRef<ParsedType> ArgTypes, 1577 ArrayRef<Expr *> ArgExprs) { 1578 unsigned NumAssocs = ArgTypes.size(); 1579 assert(NumAssocs == ArgExprs.size()); 1580 1581 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1582 for (unsigned i = 0; i < NumAssocs; ++i) { 1583 if (ArgTypes[i]) 1584 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1585 else 1586 Types[i] = nullptr; 1587 } 1588 1589 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1590 ControllingExpr, 1591 llvm::makeArrayRef(Types, NumAssocs), 1592 ArgExprs); 1593 delete [] Types; 1594 return ER; 1595 } 1596 1597 ExprResult 1598 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1599 SourceLocation DefaultLoc, 1600 SourceLocation RParenLoc, 1601 Expr *ControllingExpr, 1602 ArrayRef<TypeSourceInfo *> Types, 1603 ArrayRef<Expr *> Exprs) { 1604 unsigned NumAssocs = Types.size(); 1605 assert(NumAssocs == Exprs.size()); 1606 1607 // Decay and strip qualifiers for the controlling expression type, and handle 1608 // placeholder type replacement. See committee discussion from WG14 DR423. 1609 { 1610 EnterExpressionEvaluationContext Unevaluated( 1611 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1612 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1613 if (R.isInvalid()) 1614 return ExprError(); 1615 ControllingExpr = R.get(); 1616 } 1617 1618 // The controlling expression is an unevaluated operand, so side effects are 1619 // likely unintended. 1620 if (!inTemplateInstantiation() && 1621 ControllingExpr->HasSideEffects(Context, false)) 1622 Diag(ControllingExpr->getExprLoc(), 1623 diag::warn_side_effects_unevaluated_context); 1624 1625 bool TypeErrorFound = false, 1626 IsResultDependent = ControllingExpr->isTypeDependent(), 1627 ContainsUnexpandedParameterPack 1628 = ControllingExpr->containsUnexpandedParameterPack(); 1629 1630 for (unsigned i = 0; i < NumAssocs; ++i) { 1631 if (Exprs[i]->containsUnexpandedParameterPack()) 1632 ContainsUnexpandedParameterPack = true; 1633 1634 if (Types[i]) { 1635 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1636 ContainsUnexpandedParameterPack = true; 1637 1638 if (Types[i]->getType()->isDependentType()) { 1639 IsResultDependent = true; 1640 } else { 1641 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1642 // complete object type other than a variably modified type." 1643 unsigned D = 0; 1644 if (Types[i]->getType()->isIncompleteType()) 1645 D = diag::err_assoc_type_incomplete; 1646 else if (!Types[i]->getType()->isObjectType()) 1647 D = diag::err_assoc_type_nonobject; 1648 else if (Types[i]->getType()->isVariablyModifiedType()) 1649 D = diag::err_assoc_type_variably_modified; 1650 1651 if (D != 0) { 1652 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1653 << Types[i]->getTypeLoc().getSourceRange() 1654 << Types[i]->getType(); 1655 TypeErrorFound = true; 1656 } 1657 1658 // C11 6.5.1.1p2 "No two generic associations in the same generic 1659 // selection shall specify compatible types." 1660 for (unsigned j = i+1; j < NumAssocs; ++j) 1661 if (Types[j] && !Types[j]->getType()->isDependentType() && 1662 Context.typesAreCompatible(Types[i]->getType(), 1663 Types[j]->getType())) { 1664 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1665 diag::err_assoc_compatible_types) 1666 << Types[j]->getTypeLoc().getSourceRange() 1667 << Types[j]->getType() 1668 << Types[i]->getType(); 1669 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1670 diag::note_compat_assoc) 1671 << Types[i]->getTypeLoc().getSourceRange() 1672 << Types[i]->getType(); 1673 TypeErrorFound = true; 1674 } 1675 } 1676 } 1677 } 1678 if (TypeErrorFound) 1679 return ExprError(); 1680 1681 // If we determined that the generic selection is result-dependent, don't 1682 // try to compute the result expression. 1683 if (IsResultDependent) 1684 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1685 Exprs, DefaultLoc, RParenLoc, 1686 ContainsUnexpandedParameterPack); 1687 1688 SmallVector<unsigned, 1> CompatIndices; 1689 unsigned DefaultIndex = -1U; 1690 for (unsigned i = 0; i < NumAssocs; ++i) { 1691 if (!Types[i]) 1692 DefaultIndex = i; 1693 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1694 Types[i]->getType())) 1695 CompatIndices.push_back(i); 1696 } 1697 1698 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1699 // type compatible with at most one of the types named in its generic 1700 // association list." 1701 if (CompatIndices.size() > 1) { 1702 // We strip parens here because the controlling expression is typically 1703 // parenthesized in macro definitions. 1704 ControllingExpr = ControllingExpr->IgnoreParens(); 1705 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1706 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1707 << (unsigned)CompatIndices.size(); 1708 for (unsigned I : CompatIndices) { 1709 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1710 diag::note_compat_assoc) 1711 << Types[I]->getTypeLoc().getSourceRange() 1712 << Types[I]->getType(); 1713 } 1714 return ExprError(); 1715 } 1716 1717 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1718 // its controlling expression shall have type compatible with exactly one of 1719 // the types named in its generic association list." 1720 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1721 // We strip parens here because the controlling expression is typically 1722 // parenthesized in macro definitions. 1723 ControllingExpr = ControllingExpr->IgnoreParens(); 1724 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1725 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1726 return ExprError(); 1727 } 1728 1729 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1730 // type name that is compatible with the type of the controlling expression, 1731 // then the result expression of the generic selection is the expression 1732 // in that generic association. Otherwise, the result expression of the 1733 // generic selection is the expression in the default generic association." 1734 unsigned ResultIndex = 1735 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1736 1737 return GenericSelectionExpr::Create( 1738 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1739 ContainsUnexpandedParameterPack, ResultIndex); 1740 } 1741 1742 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1743 /// location of the token and the offset of the ud-suffix within it. 1744 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1745 unsigned Offset) { 1746 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1747 S.getLangOpts()); 1748 } 1749 1750 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1751 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1752 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1753 IdentifierInfo *UDSuffix, 1754 SourceLocation UDSuffixLoc, 1755 ArrayRef<Expr*> Args, 1756 SourceLocation LitEndLoc) { 1757 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1758 1759 QualType ArgTy[2]; 1760 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1761 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1762 if (ArgTy[ArgIdx]->isArrayType()) 1763 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1764 } 1765 1766 DeclarationName OpName = 1767 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1768 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1769 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1770 1771 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1772 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1773 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1774 /*AllowStringTemplatePack*/ false, 1775 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1776 return ExprError(); 1777 1778 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1779 } 1780 1781 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1782 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1783 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1784 /// multiple tokens. However, the common case is that StringToks points to one 1785 /// string. 1786 /// 1787 ExprResult 1788 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1789 assert(!StringToks.empty() && "Must have at least one string!"); 1790 1791 StringLiteralParser Literal(StringToks, PP); 1792 if (Literal.hadError) 1793 return ExprError(); 1794 1795 SmallVector<SourceLocation, 4> StringTokLocs; 1796 for (const Token &Tok : StringToks) 1797 StringTokLocs.push_back(Tok.getLocation()); 1798 1799 QualType CharTy = Context.CharTy; 1800 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1801 if (Literal.isWide()) { 1802 CharTy = Context.getWideCharType(); 1803 Kind = StringLiteral::Wide; 1804 } else if (Literal.isUTF8()) { 1805 if (getLangOpts().Char8) 1806 CharTy = Context.Char8Ty; 1807 Kind = StringLiteral::UTF8; 1808 } else if (Literal.isUTF16()) { 1809 CharTy = Context.Char16Ty; 1810 Kind = StringLiteral::UTF16; 1811 } else if (Literal.isUTF32()) { 1812 CharTy = Context.Char32Ty; 1813 Kind = StringLiteral::UTF32; 1814 } else if (Literal.isPascal()) { 1815 CharTy = Context.UnsignedCharTy; 1816 } 1817 1818 // Warn on initializing an array of char from a u8 string literal; this 1819 // becomes ill-formed in C++2a. 1820 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1821 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1822 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1823 1824 // Create removals for all 'u8' prefixes in the string literal(s). This 1825 // ensures C++2a compatibility (but may change the program behavior when 1826 // built by non-Clang compilers for which the execution character set is 1827 // not always UTF-8). 1828 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1829 SourceLocation RemovalDiagLoc; 1830 for (const Token &Tok : StringToks) { 1831 if (Tok.getKind() == tok::utf8_string_literal) { 1832 if (RemovalDiagLoc.isInvalid()) 1833 RemovalDiagLoc = Tok.getLocation(); 1834 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1835 Tok.getLocation(), 1836 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1837 getSourceManager(), getLangOpts()))); 1838 } 1839 } 1840 Diag(RemovalDiagLoc, RemovalDiag); 1841 } 1842 1843 QualType StrTy = 1844 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1845 1846 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1847 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1848 Kind, Literal.Pascal, StrTy, 1849 &StringTokLocs[0], 1850 StringTokLocs.size()); 1851 if (Literal.getUDSuffix().empty()) 1852 return Lit; 1853 1854 // We're building a user-defined literal. 1855 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1856 SourceLocation UDSuffixLoc = 1857 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1858 Literal.getUDSuffixOffset()); 1859 1860 // Make sure we're allowed user-defined literals here. 1861 if (!UDLScope) 1862 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1863 1864 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1865 // operator "" X (str, len) 1866 QualType SizeType = Context.getSizeType(); 1867 1868 DeclarationName OpName = 1869 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1870 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1871 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1872 1873 QualType ArgTy[] = { 1874 Context.getArrayDecayedType(StrTy), SizeType 1875 }; 1876 1877 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1878 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1879 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1880 /*AllowStringTemplatePack*/ true, 1881 /*DiagnoseMissing*/ true, Lit)) { 1882 1883 case LOLR_Cooked: { 1884 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1885 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1886 StringTokLocs[0]); 1887 Expr *Args[] = { Lit, LenArg }; 1888 1889 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1890 } 1891 1892 case LOLR_Template: { 1893 TemplateArgumentListInfo ExplicitArgs; 1894 TemplateArgument Arg(Lit); 1895 TemplateArgumentLocInfo ArgInfo(Lit); 1896 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1897 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1898 &ExplicitArgs); 1899 } 1900 1901 case LOLR_StringTemplatePack: { 1902 TemplateArgumentListInfo ExplicitArgs; 1903 1904 unsigned CharBits = Context.getIntWidth(CharTy); 1905 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1906 llvm::APSInt Value(CharBits, CharIsUnsigned); 1907 1908 TemplateArgument TypeArg(CharTy); 1909 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1910 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1911 1912 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1913 Value = Lit->getCodeUnit(I); 1914 TemplateArgument Arg(Context, Value, CharTy); 1915 TemplateArgumentLocInfo ArgInfo; 1916 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1917 } 1918 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1919 &ExplicitArgs); 1920 } 1921 case LOLR_Raw: 1922 case LOLR_ErrorNoDiagnostic: 1923 llvm_unreachable("unexpected literal operator lookup result"); 1924 case LOLR_Error: 1925 return ExprError(); 1926 } 1927 llvm_unreachable("unexpected literal operator lookup result"); 1928 } 1929 1930 DeclRefExpr * 1931 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1932 SourceLocation Loc, 1933 const CXXScopeSpec *SS) { 1934 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1935 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1936 } 1937 1938 DeclRefExpr * 1939 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1940 const DeclarationNameInfo &NameInfo, 1941 const CXXScopeSpec *SS, NamedDecl *FoundD, 1942 SourceLocation TemplateKWLoc, 1943 const TemplateArgumentListInfo *TemplateArgs) { 1944 NestedNameSpecifierLoc NNS = 1945 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1946 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1947 TemplateArgs); 1948 } 1949 1950 // CUDA/HIP: Check whether a captured reference variable is referencing a 1951 // host variable in a device or host device lambda. 1952 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1953 VarDecl *VD) { 1954 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1955 return false; 1956 assert(VD->getType()->isReferenceType()); 1957 1958 // Check whether the reference variable is referencing a host variable. 1959 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1960 if (!DRE) 1961 return false; 1962 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1963 if (!Referee || !Referee->hasGlobalStorage() || 1964 Referee->hasAttr<CUDADeviceAttr>()) 1965 return false; 1966 1967 // Check whether the current function is a device or host device lambda. 1968 // Check whether the reference variable is a capture by getDeclContext() 1969 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1970 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1971 if (MD && MD->getParent()->isLambda() && 1972 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1973 VD->getDeclContext() != MD) 1974 return true; 1975 1976 return false; 1977 } 1978 1979 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1980 // A declaration named in an unevaluated operand never constitutes an odr-use. 1981 if (isUnevaluatedContext()) 1982 return NOUR_Unevaluated; 1983 1984 // C++2a [basic.def.odr]p4: 1985 // A variable x whose name appears as a potentially-evaluated expression e 1986 // is odr-used by e unless [...] x is a reference that is usable in 1987 // constant expressions. 1988 // CUDA/HIP: 1989 // If a reference variable referencing a host variable is captured in a 1990 // device or host device lambda, the value of the referee must be copied 1991 // to the capture and the reference variable must be treated as odr-use 1992 // since the value of the referee is not known at compile time and must 1993 // be loaded from the captured. 1994 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1995 if (VD->getType()->isReferenceType() && 1996 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1997 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 1998 VD->isUsableInConstantExpressions(Context)) 1999 return NOUR_Constant; 2000 } 2001 2002 // All remaining non-variable cases constitute an odr-use. For variables, we 2003 // need to wait and see how the expression is used. 2004 return NOUR_None; 2005 } 2006 2007 /// BuildDeclRefExpr - Build an expression that references a 2008 /// declaration that does not require a closure capture. 2009 DeclRefExpr * 2010 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2011 const DeclarationNameInfo &NameInfo, 2012 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2013 SourceLocation TemplateKWLoc, 2014 const TemplateArgumentListInfo *TemplateArgs) { 2015 bool RefersToCapturedVariable = 2016 isa<VarDecl>(D) && 2017 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2018 2019 DeclRefExpr *E = DeclRefExpr::Create( 2020 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2021 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2022 MarkDeclRefReferenced(E); 2023 2024 // C++ [except.spec]p17: 2025 // An exception-specification is considered to be needed when: 2026 // - in an expression, the function is the unique lookup result or 2027 // the selected member of a set of overloaded functions. 2028 // 2029 // We delay doing this until after we've built the function reference and 2030 // marked it as used so that: 2031 // a) if the function is defaulted, we get errors from defining it before / 2032 // instead of errors from computing its exception specification, and 2033 // b) if the function is a defaulted comparison, we can use the body we 2034 // build when defining it as input to the exception specification 2035 // computation rather than computing a new body. 2036 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2037 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2038 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2039 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2040 } 2041 } 2042 2043 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2044 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2045 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2046 getCurFunction()->recordUseOfWeak(E); 2047 2048 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2049 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2050 FD = IFD->getAnonField(); 2051 if (FD) { 2052 UnusedPrivateFields.remove(FD); 2053 // Just in case we're building an illegal pointer-to-member. 2054 if (FD->isBitField()) 2055 E->setObjectKind(OK_BitField); 2056 } 2057 2058 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2059 // designates a bit-field. 2060 if (auto *BD = dyn_cast<BindingDecl>(D)) 2061 if (auto *BE = BD->getBinding()) 2062 E->setObjectKind(BE->getObjectKind()); 2063 2064 return E; 2065 } 2066 2067 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2068 /// possibly a list of template arguments. 2069 /// 2070 /// If this produces template arguments, it is permitted to call 2071 /// DecomposeTemplateName. 2072 /// 2073 /// This actually loses a lot of source location information for 2074 /// non-standard name kinds; we should consider preserving that in 2075 /// some way. 2076 void 2077 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2078 TemplateArgumentListInfo &Buffer, 2079 DeclarationNameInfo &NameInfo, 2080 const TemplateArgumentListInfo *&TemplateArgs) { 2081 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2082 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2083 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2084 2085 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2086 Id.TemplateId->NumArgs); 2087 translateTemplateArguments(TemplateArgsPtr, Buffer); 2088 2089 TemplateName TName = Id.TemplateId->Template.get(); 2090 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2091 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2092 TemplateArgs = &Buffer; 2093 } else { 2094 NameInfo = GetNameFromUnqualifiedId(Id); 2095 TemplateArgs = nullptr; 2096 } 2097 } 2098 2099 static void emitEmptyLookupTypoDiagnostic( 2100 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2101 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2102 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2103 DeclContext *Ctx = 2104 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2105 if (!TC) { 2106 // Emit a special diagnostic for failed member lookups. 2107 // FIXME: computing the declaration context might fail here (?) 2108 if (Ctx) 2109 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2110 << SS.getRange(); 2111 else 2112 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2113 return; 2114 } 2115 2116 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2117 bool DroppedSpecifier = 2118 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2119 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2120 ? diag::note_implicit_param_decl 2121 : diag::note_previous_decl; 2122 if (!Ctx) 2123 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2124 SemaRef.PDiag(NoteID)); 2125 else 2126 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2127 << Typo << Ctx << DroppedSpecifier 2128 << SS.getRange(), 2129 SemaRef.PDiag(NoteID)); 2130 } 2131 2132 /// Diagnose a lookup that found results in an enclosing class during error 2133 /// recovery. This usually indicates that the results were found in a dependent 2134 /// base class that could not be searched as part of a template definition. 2135 /// Always issues a diagnostic (though this may be only a warning in MS 2136 /// compatibility mode). 2137 /// 2138 /// Return \c true if the error is unrecoverable, or \c false if the caller 2139 /// should attempt to recover using these lookup results. 2140 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2141 // During a default argument instantiation the CurContext points 2142 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2143 // function parameter list, hence add an explicit check. 2144 bool isDefaultArgument = 2145 !CodeSynthesisContexts.empty() && 2146 CodeSynthesisContexts.back().Kind == 2147 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2148 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2149 bool isInstance = CurMethod && CurMethod->isInstance() && 2150 R.getNamingClass() == CurMethod->getParent() && 2151 !isDefaultArgument; 2152 2153 // There are two ways we can find a class-scope declaration during template 2154 // instantiation that we did not find in the template definition: if it is a 2155 // member of a dependent base class, or if it is declared after the point of 2156 // use in the same class. Distinguish these by comparing the class in which 2157 // the member was found to the naming class of the lookup. 2158 unsigned DiagID = diag::err_found_in_dependent_base; 2159 unsigned NoteID = diag::note_member_declared_at; 2160 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2161 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2162 : diag::err_found_later_in_class; 2163 } else if (getLangOpts().MSVCCompat) { 2164 DiagID = diag::ext_found_in_dependent_base; 2165 NoteID = diag::note_dependent_member_use; 2166 } 2167 2168 if (isInstance) { 2169 // Give a code modification hint to insert 'this->'. 2170 Diag(R.getNameLoc(), DiagID) 2171 << R.getLookupName() 2172 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2173 CheckCXXThisCapture(R.getNameLoc()); 2174 } else { 2175 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2176 // they're not shadowed). 2177 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2178 } 2179 2180 for (NamedDecl *D : R) 2181 Diag(D->getLocation(), NoteID); 2182 2183 // Return true if we are inside a default argument instantiation 2184 // and the found name refers to an instance member function, otherwise 2185 // the caller will try to create an implicit member call and this is wrong 2186 // for default arguments. 2187 // 2188 // FIXME: Is this special case necessary? We could allow the caller to 2189 // diagnose this. 2190 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2191 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2192 return true; 2193 } 2194 2195 // Tell the callee to try to recover. 2196 return false; 2197 } 2198 2199 /// Diagnose an empty lookup. 2200 /// 2201 /// \return false if new lookup candidates were found 2202 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2203 CorrectionCandidateCallback &CCC, 2204 TemplateArgumentListInfo *ExplicitTemplateArgs, 2205 ArrayRef<Expr *> Args, TypoExpr **Out) { 2206 DeclarationName Name = R.getLookupName(); 2207 2208 unsigned diagnostic = diag::err_undeclared_var_use; 2209 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2210 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2211 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2212 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2213 diagnostic = diag::err_undeclared_use; 2214 diagnostic_suggest = diag::err_undeclared_use_suggest; 2215 } 2216 2217 // If the original lookup was an unqualified lookup, fake an 2218 // unqualified lookup. This is useful when (for example) the 2219 // original lookup would not have found something because it was a 2220 // dependent name. 2221 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2222 while (DC) { 2223 if (isa<CXXRecordDecl>(DC)) { 2224 LookupQualifiedName(R, DC); 2225 2226 if (!R.empty()) { 2227 // Don't give errors about ambiguities in this lookup. 2228 R.suppressDiagnostics(); 2229 2230 // If there's a best viable function among the results, only mention 2231 // that one in the notes. 2232 OverloadCandidateSet Candidates(R.getNameLoc(), 2233 OverloadCandidateSet::CSK_Normal); 2234 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2235 OverloadCandidateSet::iterator Best; 2236 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2237 OR_Success) { 2238 R.clear(); 2239 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2240 R.resolveKind(); 2241 } 2242 2243 return DiagnoseDependentMemberLookup(R); 2244 } 2245 2246 R.clear(); 2247 } 2248 2249 DC = DC->getLookupParent(); 2250 } 2251 2252 // We didn't find anything, so try to correct for a typo. 2253 TypoCorrection Corrected; 2254 if (S && Out) { 2255 SourceLocation TypoLoc = R.getNameLoc(); 2256 assert(!ExplicitTemplateArgs && 2257 "Diagnosing an empty lookup with explicit template args!"); 2258 *Out = CorrectTypoDelayed( 2259 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2260 [=](const TypoCorrection &TC) { 2261 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2262 diagnostic, diagnostic_suggest); 2263 }, 2264 nullptr, CTK_ErrorRecovery); 2265 if (*Out) 2266 return true; 2267 } else if (S && 2268 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2269 S, &SS, CCC, CTK_ErrorRecovery))) { 2270 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2271 bool DroppedSpecifier = 2272 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2273 R.setLookupName(Corrected.getCorrection()); 2274 2275 bool AcceptableWithRecovery = false; 2276 bool AcceptableWithoutRecovery = false; 2277 NamedDecl *ND = Corrected.getFoundDecl(); 2278 if (ND) { 2279 if (Corrected.isOverloaded()) { 2280 OverloadCandidateSet OCS(R.getNameLoc(), 2281 OverloadCandidateSet::CSK_Normal); 2282 OverloadCandidateSet::iterator Best; 2283 for (NamedDecl *CD : Corrected) { 2284 if (FunctionTemplateDecl *FTD = 2285 dyn_cast<FunctionTemplateDecl>(CD)) 2286 AddTemplateOverloadCandidate( 2287 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2288 Args, OCS); 2289 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2290 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2291 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2292 Args, OCS); 2293 } 2294 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2295 case OR_Success: 2296 ND = Best->FoundDecl; 2297 Corrected.setCorrectionDecl(ND); 2298 break; 2299 default: 2300 // FIXME: Arbitrarily pick the first declaration for the note. 2301 Corrected.setCorrectionDecl(ND); 2302 break; 2303 } 2304 } 2305 R.addDecl(ND); 2306 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2307 CXXRecordDecl *Record = nullptr; 2308 if (Corrected.getCorrectionSpecifier()) { 2309 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2310 Record = Ty->getAsCXXRecordDecl(); 2311 } 2312 if (!Record) 2313 Record = cast<CXXRecordDecl>( 2314 ND->getDeclContext()->getRedeclContext()); 2315 R.setNamingClass(Record); 2316 } 2317 2318 auto *UnderlyingND = ND->getUnderlyingDecl(); 2319 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2320 isa<FunctionTemplateDecl>(UnderlyingND); 2321 // FIXME: If we ended up with a typo for a type name or 2322 // Objective-C class name, we're in trouble because the parser 2323 // is in the wrong place to recover. Suggest the typo 2324 // correction, but don't make it a fix-it since we're not going 2325 // to recover well anyway. 2326 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2327 getAsTypeTemplateDecl(UnderlyingND) || 2328 isa<ObjCInterfaceDecl>(UnderlyingND); 2329 } else { 2330 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2331 // because we aren't able to recover. 2332 AcceptableWithoutRecovery = true; 2333 } 2334 2335 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2336 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2337 ? diag::note_implicit_param_decl 2338 : diag::note_previous_decl; 2339 if (SS.isEmpty()) 2340 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2341 PDiag(NoteID), AcceptableWithRecovery); 2342 else 2343 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2344 << Name << computeDeclContext(SS, false) 2345 << DroppedSpecifier << SS.getRange(), 2346 PDiag(NoteID), AcceptableWithRecovery); 2347 2348 // Tell the callee whether to try to recover. 2349 return !AcceptableWithRecovery; 2350 } 2351 } 2352 R.clear(); 2353 2354 // Emit a special diagnostic for failed member lookups. 2355 // FIXME: computing the declaration context might fail here (?) 2356 if (!SS.isEmpty()) { 2357 Diag(R.getNameLoc(), diag::err_no_member) 2358 << Name << computeDeclContext(SS, false) 2359 << SS.getRange(); 2360 return true; 2361 } 2362 2363 // Give up, we can't recover. 2364 Diag(R.getNameLoc(), diagnostic) << Name; 2365 return true; 2366 } 2367 2368 /// In Microsoft mode, if we are inside a template class whose parent class has 2369 /// dependent base classes, and we can't resolve an unqualified identifier, then 2370 /// assume the identifier is a member of a dependent base class. We can only 2371 /// recover successfully in static methods, instance methods, and other contexts 2372 /// where 'this' is available. This doesn't precisely match MSVC's 2373 /// instantiation model, but it's close enough. 2374 static Expr * 2375 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2376 DeclarationNameInfo &NameInfo, 2377 SourceLocation TemplateKWLoc, 2378 const TemplateArgumentListInfo *TemplateArgs) { 2379 // Only try to recover from lookup into dependent bases in static methods or 2380 // contexts where 'this' is available. 2381 QualType ThisType = S.getCurrentThisType(); 2382 const CXXRecordDecl *RD = nullptr; 2383 if (!ThisType.isNull()) 2384 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2385 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2386 RD = MD->getParent(); 2387 if (!RD || !RD->hasAnyDependentBases()) 2388 return nullptr; 2389 2390 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2391 // is available, suggest inserting 'this->' as a fixit. 2392 SourceLocation Loc = NameInfo.getLoc(); 2393 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2394 DB << NameInfo.getName() << RD; 2395 2396 if (!ThisType.isNull()) { 2397 DB << FixItHint::CreateInsertion(Loc, "this->"); 2398 return CXXDependentScopeMemberExpr::Create( 2399 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2400 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2401 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2402 } 2403 2404 // Synthesize a fake NNS that points to the derived class. This will 2405 // perform name lookup during template instantiation. 2406 CXXScopeSpec SS; 2407 auto *NNS = 2408 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2409 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2410 return DependentScopeDeclRefExpr::Create( 2411 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2412 TemplateArgs); 2413 } 2414 2415 ExprResult 2416 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2417 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2418 bool HasTrailingLParen, bool IsAddressOfOperand, 2419 CorrectionCandidateCallback *CCC, 2420 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2421 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2422 "cannot be direct & operand and have a trailing lparen"); 2423 if (SS.isInvalid()) 2424 return ExprError(); 2425 2426 TemplateArgumentListInfo TemplateArgsBuffer; 2427 2428 // Decompose the UnqualifiedId into the following data. 2429 DeclarationNameInfo NameInfo; 2430 const TemplateArgumentListInfo *TemplateArgs; 2431 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2432 2433 DeclarationName Name = NameInfo.getName(); 2434 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2435 SourceLocation NameLoc = NameInfo.getLoc(); 2436 2437 if (II && II->isEditorPlaceholder()) { 2438 // FIXME: When typed placeholders are supported we can create a typed 2439 // placeholder expression node. 2440 return ExprError(); 2441 } 2442 2443 // C++ [temp.dep.expr]p3: 2444 // An id-expression is type-dependent if it contains: 2445 // -- an identifier that was declared with a dependent type, 2446 // (note: handled after lookup) 2447 // -- a template-id that is dependent, 2448 // (note: handled in BuildTemplateIdExpr) 2449 // -- a conversion-function-id that specifies a dependent type, 2450 // -- a nested-name-specifier that contains a class-name that 2451 // names a dependent type. 2452 // Determine whether this is a member of an unknown specialization; 2453 // we need to handle these differently. 2454 bool DependentID = false; 2455 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2456 Name.getCXXNameType()->isDependentType()) { 2457 DependentID = true; 2458 } else if (SS.isSet()) { 2459 if (DeclContext *DC = computeDeclContext(SS, false)) { 2460 if (RequireCompleteDeclContext(SS, DC)) 2461 return ExprError(); 2462 } else { 2463 DependentID = true; 2464 } 2465 } 2466 2467 if (DependentID) 2468 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2469 IsAddressOfOperand, TemplateArgs); 2470 2471 // Perform the required lookup. 2472 LookupResult R(*this, NameInfo, 2473 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2474 ? LookupObjCImplicitSelfParam 2475 : LookupOrdinaryName); 2476 if (TemplateKWLoc.isValid() || TemplateArgs) { 2477 // Lookup the template name again to correctly establish the context in 2478 // which it was found. This is really unfortunate as we already did the 2479 // lookup to determine that it was a template name in the first place. If 2480 // this becomes a performance hit, we can work harder to preserve those 2481 // results until we get here but it's likely not worth it. 2482 bool MemberOfUnknownSpecialization; 2483 AssumedTemplateKind AssumedTemplate; 2484 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2485 MemberOfUnknownSpecialization, TemplateKWLoc, 2486 &AssumedTemplate)) 2487 return ExprError(); 2488 2489 if (MemberOfUnknownSpecialization || 2490 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2491 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2492 IsAddressOfOperand, TemplateArgs); 2493 } else { 2494 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2495 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2496 2497 // If the result might be in a dependent base class, this is a dependent 2498 // id-expression. 2499 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2500 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2501 IsAddressOfOperand, TemplateArgs); 2502 2503 // If this reference is in an Objective-C method, then we need to do 2504 // some special Objective-C lookup, too. 2505 if (IvarLookupFollowUp) { 2506 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2507 if (E.isInvalid()) 2508 return ExprError(); 2509 2510 if (Expr *Ex = E.getAs<Expr>()) 2511 return Ex; 2512 } 2513 } 2514 2515 if (R.isAmbiguous()) 2516 return ExprError(); 2517 2518 // This could be an implicitly declared function reference (legal in C90, 2519 // extension in C99, forbidden in C++). 2520 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2521 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2522 if (D) R.addDecl(D); 2523 } 2524 2525 // Determine whether this name might be a candidate for 2526 // argument-dependent lookup. 2527 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2528 2529 if (R.empty() && !ADL) { 2530 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2531 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2532 TemplateKWLoc, TemplateArgs)) 2533 return E; 2534 } 2535 2536 // Don't diagnose an empty lookup for inline assembly. 2537 if (IsInlineAsmIdentifier) 2538 return ExprError(); 2539 2540 // If this name wasn't predeclared and if this is not a function 2541 // call, diagnose the problem. 2542 TypoExpr *TE = nullptr; 2543 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2544 : nullptr); 2545 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2546 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2547 "Typo correction callback misconfigured"); 2548 if (CCC) { 2549 // Make sure the callback knows what the typo being diagnosed is. 2550 CCC->setTypoName(II); 2551 if (SS.isValid()) 2552 CCC->setTypoNNS(SS.getScopeRep()); 2553 } 2554 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2555 // a template name, but we happen to have always already looked up the name 2556 // before we get here if it must be a template name. 2557 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2558 None, &TE)) { 2559 if (TE && KeywordReplacement) { 2560 auto &State = getTypoExprState(TE); 2561 auto BestTC = State.Consumer->getNextCorrection(); 2562 if (BestTC.isKeyword()) { 2563 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2564 if (State.DiagHandler) 2565 State.DiagHandler(BestTC); 2566 KeywordReplacement->startToken(); 2567 KeywordReplacement->setKind(II->getTokenID()); 2568 KeywordReplacement->setIdentifierInfo(II); 2569 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2570 // Clean up the state associated with the TypoExpr, since it has 2571 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2572 clearDelayedTypo(TE); 2573 // Signal that a correction to a keyword was performed by returning a 2574 // valid-but-null ExprResult. 2575 return (Expr*)nullptr; 2576 } 2577 State.Consumer->resetCorrectionStream(); 2578 } 2579 return TE ? TE : ExprError(); 2580 } 2581 2582 assert(!R.empty() && 2583 "DiagnoseEmptyLookup returned false but added no results"); 2584 2585 // If we found an Objective-C instance variable, let 2586 // LookupInObjCMethod build the appropriate expression to 2587 // reference the ivar. 2588 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2589 R.clear(); 2590 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2591 // In a hopelessly buggy code, Objective-C instance variable 2592 // lookup fails and no expression will be built to reference it. 2593 if (!E.isInvalid() && !E.get()) 2594 return ExprError(); 2595 return E; 2596 } 2597 } 2598 2599 // This is guaranteed from this point on. 2600 assert(!R.empty() || ADL); 2601 2602 // Check whether this might be a C++ implicit instance member access. 2603 // C++ [class.mfct.non-static]p3: 2604 // When an id-expression that is not part of a class member access 2605 // syntax and not used to form a pointer to member is used in the 2606 // body of a non-static member function of class X, if name lookup 2607 // resolves the name in the id-expression to a non-static non-type 2608 // member of some class C, the id-expression is transformed into a 2609 // class member access expression using (*this) as the 2610 // postfix-expression to the left of the . operator. 2611 // 2612 // But we don't actually need to do this for '&' operands if R 2613 // resolved to a function or overloaded function set, because the 2614 // expression is ill-formed if it actually works out to be a 2615 // non-static member function: 2616 // 2617 // C++ [expr.ref]p4: 2618 // Otherwise, if E1.E2 refers to a non-static member function. . . 2619 // [t]he expression can be used only as the left-hand operand of a 2620 // member function call. 2621 // 2622 // There are other safeguards against such uses, but it's important 2623 // to get this right here so that we don't end up making a 2624 // spuriously dependent expression if we're inside a dependent 2625 // instance method. 2626 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2627 bool MightBeImplicitMember; 2628 if (!IsAddressOfOperand) 2629 MightBeImplicitMember = true; 2630 else if (!SS.isEmpty()) 2631 MightBeImplicitMember = false; 2632 else if (R.isOverloadedResult()) 2633 MightBeImplicitMember = false; 2634 else if (R.isUnresolvableResult()) 2635 MightBeImplicitMember = true; 2636 else 2637 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2638 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2639 isa<MSPropertyDecl>(R.getFoundDecl()); 2640 2641 if (MightBeImplicitMember) 2642 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2643 R, TemplateArgs, S); 2644 } 2645 2646 if (TemplateArgs || TemplateKWLoc.isValid()) { 2647 2648 // In C++1y, if this is a variable template id, then check it 2649 // in BuildTemplateIdExpr(). 2650 // The single lookup result must be a variable template declaration. 2651 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2652 Id.TemplateId->Kind == TNK_Var_template) { 2653 assert(R.getAsSingle<VarTemplateDecl>() && 2654 "There should only be one declaration found."); 2655 } 2656 2657 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2658 } 2659 2660 return BuildDeclarationNameExpr(SS, R, ADL); 2661 } 2662 2663 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2664 /// declaration name, generally during template instantiation. 2665 /// There's a large number of things which don't need to be done along 2666 /// this path. 2667 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2668 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2669 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2670 DeclContext *DC = computeDeclContext(SS, false); 2671 if (!DC) 2672 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2673 NameInfo, /*TemplateArgs=*/nullptr); 2674 2675 if (RequireCompleteDeclContext(SS, DC)) 2676 return ExprError(); 2677 2678 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2679 LookupQualifiedName(R, DC); 2680 2681 if (R.isAmbiguous()) 2682 return ExprError(); 2683 2684 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2685 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2686 NameInfo, /*TemplateArgs=*/nullptr); 2687 2688 if (R.empty()) { 2689 // Don't diagnose problems with invalid record decl, the secondary no_member 2690 // diagnostic during template instantiation is likely bogus, e.g. if a class 2691 // is invalid because it's derived from an invalid base class, then missing 2692 // members were likely supposed to be inherited. 2693 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2694 if (CD->isInvalidDecl()) 2695 return ExprError(); 2696 Diag(NameInfo.getLoc(), diag::err_no_member) 2697 << NameInfo.getName() << DC << SS.getRange(); 2698 return ExprError(); 2699 } 2700 2701 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2702 // Diagnose a missing typename if this resolved unambiguously to a type in 2703 // a dependent context. If we can recover with a type, downgrade this to 2704 // a warning in Microsoft compatibility mode. 2705 unsigned DiagID = diag::err_typename_missing; 2706 if (RecoveryTSI && getLangOpts().MSVCCompat) 2707 DiagID = diag::ext_typename_missing; 2708 SourceLocation Loc = SS.getBeginLoc(); 2709 auto D = Diag(Loc, DiagID); 2710 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2711 << SourceRange(Loc, NameInfo.getEndLoc()); 2712 2713 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2714 // context. 2715 if (!RecoveryTSI) 2716 return ExprError(); 2717 2718 // Only issue the fixit if we're prepared to recover. 2719 D << FixItHint::CreateInsertion(Loc, "typename "); 2720 2721 // Recover by pretending this was an elaborated type. 2722 QualType Ty = Context.getTypeDeclType(TD); 2723 TypeLocBuilder TLB; 2724 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2725 2726 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2727 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2728 QTL.setElaboratedKeywordLoc(SourceLocation()); 2729 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2730 2731 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2732 2733 return ExprEmpty(); 2734 } 2735 2736 // Defend against this resolving to an implicit member access. We usually 2737 // won't get here if this might be a legitimate a class member (we end up in 2738 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2739 // a pointer-to-member or in an unevaluated context in C++11. 2740 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2741 return BuildPossibleImplicitMemberExpr(SS, 2742 /*TemplateKWLoc=*/SourceLocation(), 2743 R, /*TemplateArgs=*/nullptr, S); 2744 2745 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2746 } 2747 2748 /// The parser has read a name in, and Sema has detected that we're currently 2749 /// inside an ObjC method. Perform some additional checks and determine if we 2750 /// should form a reference to an ivar. 2751 /// 2752 /// Ideally, most of this would be done by lookup, but there's 2753 /// actually quite a lot of extra work involved. 2754 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2755 IdentifierInfo *II) { 2756 SourceLocation Loc = Lookup.getNameLoc(); 2757 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2758 2759 // Check for error condition which is already reported. 2760 if (!CurMethod) 2761 return DeclResult(true); 2762 2763 // There are two cases to handle here. 1) scoped lookup could have failed, 2764 // in which case we should look for an ivar. 2) scoped lookup could have 2765 // found a decl, but that decl is outside the current instance method (i.e. 2766 // a global variable). In these two cases, we do a lookup for an ivar with 2767 // this name, if the lookup sucedes, we replace it our current decl. 2768 2769 // If we're in a class method, we don't normally want to look for 2770 // ivars. But if we don't find anything else, and there's an 2771 // ivar, that's an error. 2772 bool IsClassMethod = CurMethod->isClassMethod(); 2773 2774 bool LookForIvars; 2775 if (Lookup.empty()) 2776 LookForIvars = true; 2777 else if (IsClassMethod) 2778 LookForIvars = false; 2779 else 2780 LookForIvars = (Lookup.isSingleResult() && 2781 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2782 ObjCInterfaceDecl *IFace = nullptr; 2783 if (LookForIvars) { 2784 IFace = CurMethod->getClassInterface(); 2785 ObjCInterfaceDecl *ClassDeclared; 2786 ObjCIvarDecl *IV = nullptr; 2787 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2788 // Diagnose using an ivar in a class method. 2789 if (IsClassMethod) { 2790 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2791 return DeclResult(true); 2792 } 2793 2794 // Diagnose the use of an ivar outside of the declaring class. 2795 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2796 !declaresSameEntity(ClassDeclared, IFace) && 2797 !getLangOpts().DebuggerSupport) 2798 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2799 2800 // Success. 2801 return IV; 2802 } 2803 } else if (CurMethod->isInstanceMethod()) { 2804 // We should warn if a local variable hides an ivar. 2805 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2806 ObjCInterfaceDecl *ClassDeclared; 2807 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2808 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2809 declaresSameEntity(IFace, ClassDeclared)) 2810 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2811 } 2812 } 2813 } else if (Lookup.isSingleResult() && 2814 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2815 // If accessing a stand-alone ivar in a class method, this is an error. 2816 if (const ObjCIvarDecl *IV = 2817 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2818 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2819 return DeclResult(true); 2820 } 2821 } 2822 2823 // Didn't encounter an error, didn't find an ivar. 2824 return DeclResult(false); 2825 } 2826 2827 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2828 ObjCIvarDecl *IV) { 2829 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2830 assert(CurMethod && CurMethod->isInstanceMethod() && 2831 "should not reference ivar from this context"); 2832 2833 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2834 assert(IFace && "should not reference ivar from this context"); 2835 2836 // If we're referencing an invalid decl, just return this as a silent 2837 // error node. The error diagnostic was already emitted on the decl. 2838 if (IV->isInvalidDecl()) 2839 return ExprError(); 2840 2841 // Check if referencing a field with __attribute__((deprecated)). 2842 if (DiagnoseUseOfDecl(IV, Loc)) 2843 return ExprError(); 2844 2845 // FIXME: This should use a new expr for a direct reference, don't 2846 // turn this into Self->ivar, just return a BareIVarExpr or something. 2847 IdentifierInfo &II = Context.Idents.get("self"); 2848 UnqualifiedId SelfName; 2849 SelfName.setImplicitSelfParam(&II); 2850 CXXScopeSpec SelfScopeSpec; 2851 SourceLocation TemplateKWLoc; 2852 ExprResult SelfExpr = 2853 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2854 /*HasTrailingLParen=*/false, 2855 /*IsAddressOfOperand=*/false); 2856 if (SelfExpr.isInvalid()) 2857 return ExprError(); 2858 2859 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2860 if (SelfExpr.isInvalid()) 2861 return ExprError(); 2862 2863 MarkAnyDeclReferenced(Loc, IV, true); 2864 2865 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2866 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2867 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2868 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2869 2870 ObjCIvarRefExpr *Result = new (Context) 2871 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2872 IV->getLocation(), SelfExpr.get(), true, true); 2873 2874 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2875 if (!isUnevaluatedContext() && 2876 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2877 getCurFunction()->recordUseOfWeak(Result); 2878 } 2879 if (getLangOpts().ObjCAutoRefCount) 2880 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2881 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2882 2883 return Result; 2884 } 2885 2886 /// The parser has read a name in, and Sema has detected that we're currently 2887 /// inside an ObjC method. Perform some additional checks and determine if we 2888 /// should form a reference to an ivar. If so, build an expression referencing 2889 /// that ivar. 2890 ExprResult 2891 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2892 IdentifierInfo *II, bool AllowBuiltinCreation) { 2893 // FIXME: Integrate this lookup step into LookupParsedName. 2894 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2895 if (Ivar.isInvalid()) 2896 return ExprError(); 2897 if (Ivar.isUsable()) 2898 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2899 cast<ObjCIvarDecl>(Ivar.get())); 2900 2901 if (Lookup.empty() && II && AllowBuiltinCreation) 2902 LookupBuiltin(Lookup); 2903 2904 // Sentinel value saying that we didn't do anything special. 2905 return ExprResult(false); 2906 } 2907 2908 /// Cast a base object to a member's actual type. 2909 /// 2910 /// There are two relevant checks: 2911 /// 2912 /// C++ [class.access.base]p7: 2913 /// 2914 /// If a class member access operator [...] is used to access a non-static 2915 /// data member or non-static member function, the reference is ill-formed if 2916 /// the left operand [...] cannot be implicitly converted to a pointer to the 2917 /// naming class of the right operand. 2918 /// 2919 /// C++ [expr.ref]p7: 2920 /// 2921 /// If E2 is a non-static data member or a non-static member function, the 2922 /// program is ill-formed if the class of which E2 is directly a member is an 2923 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2924 /// 2925 /// Note that the latter check does not consider access; the access of the 2926 /// "real" base class is checked as appropriate when checking the access of the 2927 /// member name. 2928 ExprResult 2929 Sema::PerformObjectMemberConversion(Expr *From, 2930 NestedNameSpecifier *Qualifier, 2931 NamedDecl *FoundDecl, 2932 NamedDecl *Member) { 2933 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2934 if (!RD) 2935 return From; 2936 2937 QualType DestRecordType; 2938 QualType DestType; 2939 QualType FromRecordType; 2940 QualType FromType = From->getType(); 2941 bool PointerConversions = false; 2942 if (isa<FieldDecl>(Member)) { 2943 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2944 auto FromPtrType = FromType->getAs<PointerType>(); 2945 DestRecordType = Context.getAddrSpaceQualType( 2946 DestRecordType, FromPtrType 2947 ? FromType->getPointeeType().getAddressSpace() 2948 : FromType.getAddressSpace()); 2949 2950 if (FromPtrType) { 2951 DestType = Context.getPointerType(DestRecordType); 2952 FromRecordType = FromPtrType->getPointeeType(); 2953 PointerConversions = true; 2954 } else { 2955 DestType = DestRecordType; 2956 FromRecordType = FromType; 2957 } 2958 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2959 if (Method->isStatic()) 2960 return From; 2961 2962 DestType = Method->getThisType(); 2963 DestRecordType = DestType->getPointeeType(); 2964 2965 if (FromType->getAs<PointerType>()) { 2966 FromRecordType = FromType->getPointeeType(); 2967 PointerConversions = true; 2968 } else { 2969 FromRecordType = FromType; 2970 DestType = DestRecordType; 2971 } 2972 2973 LangAS FromAS = FromRecordType.getAddressSpace(); 2974 LangAS DestAS = DestRecordType.getAddressSpace(); 2975 if (FromAS != DestAS) { 2976 QualType FromRecordTypeWithoutAS = 2977 Context.removeAddrSpaceQualType(FromRecordType); 2978 QualType FromTypeWithDestAS = 2979 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2980 if (PointerConversions) 2981 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2982 From = ImpCastExprToType(From, FromTypeWithDestAS, 2983 CK_AddressSpaceConversion, From->getValueKind()) 2984 .get(); 2985 } 2986 } else { 2987 // No conversion necessary. 2988 return From; 2989 } 2990 2991 if (DestType->isDependentType() || FromType->isDependentType()) 2992 return From; 2993 2994 // If the unqualified types are the same, no conversion is necessary. 2995 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2996 return From; 2997 2998 SourceRange FromRange = From->getSourceRange(); 2999 SourceLocation FromLoc = FromRange.getBegin(); 3000 3001 ExprValueKind VK = From->getValueKind(); 3002 3003 // C++ [class.member.lookup]p8: 3004 // [...] Ambiguities can often be resolved by qualifying a name with its 3005 // class name. 3006 // 3007 // If the member was a qualified name and the qualified referred to a 3008 // specific base subobject type, we'll cast to that intermediate type 3009 // first and then to the object in which the member is declared. That allows 3010 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3011 // 3012 // class Base { public: int x; }; 3013 // class Derived1 : public Base { }; 3014 // class Derived2 : public Base { }; 3015 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3016 // 3017 // void VeryDerived::f() { 3018 // x = 17; // error: ambiguous base subobjects 3019 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3020 // } 3021 if (Qualifier && Qualifier->getAsType()) { 3022 QualType QType = QualType(Qualifier->getAsType(), 0); 3023 assert(QType->isRecordType() && "lookup done with non-record type"); 3024 3025 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3026 3027 // In C++98, the qualifier type doesn't actually have to be a base 3028 // type of the object type, in which case we just ignore it. 3029 // Otherwise build the appropriate casts. 3030 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3031 CXXCastPath BasePath; 3032 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3033 FromLoc, FromRange, &BasePath)) 3034 return ExprError(); 3035 3036 if (PointerConversions) 3037 QType = Context.getPointerType(QType); 3038 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3039 VK, &BasePath).get(); 3040 3041 FromType = QType; 3042 FromRecordType = QRecordType; 3043 3044 // If the qualifier type was the same as the destination type, 3045 // we're done. 3046 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3047 return From; 3048 } 3049 } 3050 3051 CXXCastPath BasePath; 3052 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3053 FromLoc, FromRange, &BasePath, 3054 /*IgnoreAccess=*/true)) 3055 return ExprError(); 3056 3057 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3058 VK, &BasePath); 3059 } 3060 3061 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3062 const LookupResult &R, 3063 bool HasTrailingLParen) { 3064 // Only when used directly as the postfix-expression of a call. 3065 if (!HasTrailingLParen) 3066 return false; 3067 3068 // Never if a scope specifier was provided. 3069 if (SS.isSet()) 3070 return false; 3071 3072 // Only in C++ or ObjC++. 3073 if (!getLangOpts().CPlusPlus) 3074 return false; 3075 3076 // Turn off ADL when we find certain kinds of declarations during 3077 // normal lookup: 3078 for (NamedDecl *D : R) { 3079 // C++0x [basic.lookup.argdep]p3: 3080 // -- a declaration of a class member 3081 // Since using decls preserve this property, we check this on the 3082 // original decl. 3083 if (D->isCXXClassMember()) 3084 return false; 3085 3086 // C++0x [basic.lookup.argdep]p3: 3087 // -- a block-scope function declaration that is not a 3088 // using-declaration 3089 // NOTE: we also trigger this for function templates (in fact, we 3090 // don't check the decl type at all, since all other decl types 3091 // turn off ADL anyway). 3092 if (isa<UsingShadowDecl>(D)) 3093 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3094 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3095 return false; 3096 3097 // C++0x [basic.lookup.argdep]p3: 3098 // -- a declaration that is neither a function or a function 3099 // template 3100 // And also for builtin functions. 3101 if (isa<FunctionDecl>(D)) { 3102 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3103 3104 // But also builtin functions. 3105 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3106 return false; 3107 } else if (!isa<FunctionTemplateDecl>(D)) 3108 return false; 3109 } 3110 3111 return true; 3112 } 3113 3114 3115 /// Diagnoses obvious problems with the use of the given declaration 3116 /// as an expression. This is only actually called for lookups that 3117 /// were not overloaded, and it doesn't promise that the declaration 3118 /// will in fact be used. 3119 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3120 if (D->isInvalidDecl()) 3121 return true; 3122 3123 if (isa<TypedefNameDecl>(D)) { 3124 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3125 return true; 3126 } 3127 3128 if (isa<ObjCInterfaceDecl>(D)) { 3129 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3130 return true; 3131 } 3132 3133 if (isa<NamespaceDecl>(D)) { 3134 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3135 return true; 3136 } 3137 3138 return false; 3139 } 3140 3141 // Certain multiversion types should be treated as overloaded even when there is 3142 // only one result. 3143 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3144 assert(R.isSingleResult() && "Expected only a single result"); 3145 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3146 return FD && 3147 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3148 } 3149 3150 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3151 LookupResult &R, bool NeedsADL, 3152 bool AcceptInvalidDecl) { 3153 // If this is a single, fully-resolved result and we don't need ADL, 3154 // just build an ordinary singleton decl ref. 3155 if (!NeedsADL && R.isSingleResult() && 3156 !R.getAsSingle<FunctionTemplateDecl>() && 3157 !ShouldLookupResultBeMultiVersionOverload(R)) 3158 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3159 R.getRepresentativeDecl(), nullptr, 3160 AcceptInvalidDecl); 3161 3162 // We only need to check the declaration if there's exactly one 3163 // result, because in the overloaded case the results can only be 3164 // functions and function templates. 3165 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3166 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3167 return ExprError(); 3168 3169 // Otherwise, just build an unresolved lookup expression. Suppress 3170 // any lookup-related diagnostics; we'll hash these out later, when 3171 // we've picked a target. 3172 R.suppressDiagnostics(); 3173 3174 UnresolvedLookupExpr *ULE 3175 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3176 SS.getWithLocInContext(Context), 3177 R.getLookupNameInfo(), 3178 NeedsADL, R.isOverloadedResult(), 3179 R.begin(), R.end()); 3180 3181 return ULE; 3182 } 3183 3184 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3185 ValueDecl *var); 3186 3187 /// Complete semantic analysis for a reference to the given declaration. 3188 ExprResult Sema::BuildDeclarationNameExpr( 3189 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3190 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3191 bool AcceptInvalidDecl) { 3192 assert(D && "Cannot refer to a NULL declaration"); 3193 assert(!isa<FunctionTemplateDecl>(D) && 3194 "Cannot refer unambiguously to a function template"); 3195 3196 SourceLocation Loc = NameInfo.getLoc(); 3197 if (CheckDeclInExpr(*this, Loc, D)) 3198 return ExprError(); 3199 3200 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3201 // Specifically diagnose references to class templates that are missing 3202 // a template argument list. 3203 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3204 return ExprError(); 3205 } 3206 3207 // Make sure that we're referring to a value. 3208 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3209 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3210 Diag(D->getLocation(), diag::note_declared_at); 3211 return ExprError(); 3212 } 3213 3214 // Check whether this declaration can be used. Note that we suppress 3215 // this check when we're going to perform argument-dependent lookup 3216 // on this function name, because this might not be the function 3217 // that overload resolution actually selects. 3218 if (DiagnoseUseOfDecl(D, Loc)) 3219 return ExprError(); 3220 3221 auto *VD = cast<ValueDecl>(D); 3222 3223 // Only create DeclRefExpr's for valid Decl's. 3224 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3225 return ExprError(); 3226 3227 // Handle members of anonymous structs and unions. If we got here, 3228 // and the reference is to a class member indirect field, then this 3229 // must be the subject of a pointer-to-member expression. 3230 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3231 if (!indirectField->isCXXClassMember()) 3232 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3233 indirectField); 3234 3235 QualType type = VD->getType(); 3236 if (type.isNull()) 3237 return ExprError(); 3238 ExprValueKind valueKind = VK_PRValue; 3239 3240 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3241 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3242 // is expanded by some outer '...' in the context of the use. 3243 type = type.getNonPackExpansionType(); 3244 3245 switch (D->getKind()) { 3246 // Ignore all the non-ValueDecl kinds. 3247 #define ABSTRACT_DECL(kind) 3248 #define VALUE(type, base) 3249 #define DECL(type, base) case Decl::type: 3250 #include "clang/AST/DeclNodes.inc" 3251 llvm_unreachable("invalid value decl kind"); 3252 3253 // These shouldn't make it here. 3254 case Decl::ObjCAtDefsField: 3255 llvm_unreachable("forming non-member reference to ivar?"); 3256 3257 // Enum constants are always r-values and never references. 3258 // Unresolved using declarations are dependent. 3259 case Decl::EnumConstant: 3260 case Decl::UnresolvedUsingValue: 3261 case Decl::OMPDeclareReduction: 3262 case Decl::OMPDeclareMapper: 3263 valueKind = VK_PRValue; 3264 break; 3265 3266 // Fields and indirect fields that got here must be for 3267 // pointer-to-member expressions; we just call them l-values for 3268 // internal consistency, because this subexpression doesn't really 3269 // exist in the high-level semantics. 3270 case Decl::Field: 3271 case Decl::IndirectField: 3272 case Decl::ObjCIvar: 3273 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3274 3275 // These can't have reference type in well-formed programs, but 3276 // for internal consistency we do this anyway. 3277 type = type.getNonReferenceType(); 3278 valueKind = VK_LValue; 3279 break; 3280 3281 // Non-type template parameters are either l-values or r-values 3282 // depending on the type. 3283 case Decl::NonTypeTemplateParm: { 3284 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3285 type = reftype->getPointeeType(); 3286 valueKind = VK_LValue; // even if the parameter is an r-value reference 3287 break; 3288 } 3289 3290 // [expr.prim.id.unqual]p2: 3291 // If the entity is a template parameter object for a template 3292 // parameter of type T, the type of the expression is const T. 3293 // [...] The expression is an lvalue if the entity is a [...] template 3294 // parameter object. 3295 if (type->isRecordType()) { 3296 type = type.getUnqualifiedType().withConst(); 3297 valueKind = VK_LValue; 3298 break; 3299 } 3300 3301 // For non-references, we need to strip qualifiers just in case 3302 // the template parameter was declared as 'const int' or whatever. 3303 valueKind = VK_PRValue; 3304 type = type.getUnqualifiedType(); 3305 break; 3306 } 3307 3308 case Decl::Var: 3309 case Decl::VarTemplateSpecialization: 3310 case Decl::VarTemplatePartialSpecialization: 3311 case Decl::Decomposition: 3312 case Decl::OMPCapturedExpr: 3313 // In C, "extern void blah;" is valid and is an r-value. 3314 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3315 type->isVoidType()) { 3316 valueKind = VK_PRValue; 3317 break; 3318 } 3319 LLVM_FALLTHROUGH; 3320 3321 case Decl::ImplicitParam: 3322 case Decl::ParmVar: { 3323 // These are always l-values. 3324 valueKind = VK_LValue; 3325 type = type.getNonReferenceType(); 3326 3327 // FIXME: Does the addition of const really only apply in 3328 // potentially-evaluated contexts? Since the variable isn't actually 3329 // captured in an unevaluated context, it seems that the answer is no. 3330 if (!isUnevaluatedContext()) { 3331 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3332 if (!CapturedType.isNull()) 3333 type = CapturedType; 3334 } 3335 3336 break; 3337 } 3338 3339 case Decl::Binding: { 3340 // These are always lvalues. 3341 valueKind = VK_LValue; 3342 type = type.getNonReferenceType(); 3343 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3344 // decides how that's supposed to work. 3345 auto *BD = cast<BindingDecl>(VD); 3346 if (BD->getDeclContext() != CurContext) { 3347 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3348 if (DD && DD->hasLocalStorage()) 3349 diagnoseUncapturableValueReference(*this, Loc, BD); 3350 } 3351 break; 3352 } 3353 3354 case Decl::Function: { 3355 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3356 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3357 type = Context.BuiltinFnTy; 3358 valueKind = VK_PRValue; 3359 break; 3360 } 3361 } 3362 3363 const FunctionType *fty = type->castAs<FunctionType>(); 3364 3365 // If we're referring to a function with an __unknown_anytype 3366 // result type, make the entire expression __unknown_anytype. 3367 if (fty->getReturnType() == Context.UnknownAnyTy) { 3368 type = Context.UnknownAnyTy; 3369 valueKind = VK_PRValue; 3370 break; 3371 } 3372 3373 // Functions are l-values in C++. 3374 if (getLangOpts().CPlusPlus) { 3375 valueKind = VK_LValue; 3376 break; 3377 } 3378 3379 // C99 DR 316 says that, if a function type comes from a 3380 // function definition (without a prototype), that type is only 3381 // used for checking compatibility. Therefore, when referencing 3382 // the function, we pretend that we don't have the full function 3383 // type. 3384 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3385 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3386 fty->getExtInfo()); 3387 3388 // Functions are r-values in C. 3389 valueKind = VK_PRValue; 3390 break; 3391 } 3392 3393 case Decl::CXXDeductionGuide: 3394 llvm_unreachable("building reference to deduction guide"); 3395 3396 case Decl::MSProperty: 3397 case Decl::MSGuid: 3398 case Decl::TemplateParamObject: 3399 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3400 // capture in OpenMP, or duplicated between host and device? 3401 valueKind = VK_LValue; 3402 break; 3403 3404 case Decl::CXXMethod: 3405 // If we're referring to a method with an __unknown_anytype 3406 // result type, make the entire expression __unknown_anytype. 3407 // This should only be possible with a type written directly. 3408 if (const FunctionProtoType *proto = 3409 dyn_cast<FunctionProtoType>(VD->getType())) 3410 if (proto->getReturnType() == Context.UnknownAnyTy) { 3411 type = Context.UnknownAnyTy; 3412 valueKind = VK_PRValue; 3413 break; 3414 } 3415 3416 // C++ methods are l-values if static, r-values if non-static. 3417 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3418 valueKind = VK_LValue; 3419 break; 3420 } 3421 LLVM_FALLTHROUGH; 3422 3423 case Decl::CXXConversion: 3424 case Decl::CXXDestructor: 3425 case Decl::CXXConstructor: 3426 valueKind = VK_PRValue; 3427 break; 3428 } 3429 3430 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3431 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3432 TemplateArgs); 3433 } 3434 3435 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3436 SmallString<32> &Target) { 3437 Target.resize(CharByteWidth * (Source.size() + 1)); 3438 char *ResultPtr = &Target[0]; 3439 const llvm::UTF8 *ErrorPtr; 3440 bool success = 3441 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3442 (void)success; 3443 assert(success); 3444 Target.resize(ResultPtr - &Target[0]); 3445 } 3446 3447 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3448 PredefinedExpr::IdentKind IK) { 3449 // Pick the current block, lambda, captured statement or function. 3450 Decl *currentDecl = nullptr; 3451 if (const BlockScopeInfo *BSI = getCurBlock()) 3452 currentDecl = BSI->TheDecl; 3453 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3454 currentDecl = LSI->CallOperator; 3455 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3456 currentDecl = CSI->TheCapturedDecl; 3457 else 3458 currentDecl = getCurFunctionOrMethodDecl(); 3459 3460 if (!currentDecl) { 3461 Diag(Loc, diag::ext_predef_outside_function); 3462 currentDecl = Context.getTranslationUnitDecl(); 3463 } 3464 3465 QualType ResTy; 3466 StringLiteral *SL = nullptr; 3467 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3468 ResTy = Context.DependentTy; 3469 else { 3470 // Pre-defined identifiers are of type char[x], where x is the length of 3471 // the string. 3472 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3473 unsigned Length = Str.length(); 3474 3475 llvm::APInt LengthI(32, Length + 1); 3476 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3477 ResTy = 3478 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3479 SmallString<32> RawChars; 3480 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3481 Str, RawChars); 3482 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3483 ArrayType::Normal, 3484 /*IndexTypeQuals*/ 0); 3485 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3486 /*Pascal*/ false, ResTy, Loc); 3487 } else { 3488 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3489 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3490 ArrayType::Normal, 3491 /*IndexTypeQuals*/ 0); 3492 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3493 /*Pascal*/ false, ResTy, Loc); 3494 } 3495 } 3496 3497 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3498 } 3499 3500 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3501 SourceLocation LParen, 3502 SourceLocation RParen, 3503 TypeSourceInfo *TSI) { 3504 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3505 } 3506 3507 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3508 SourceLocation LParen, 3509 SourceLocation RParen, 3510 ParsedType ParsedTy) { 3511 TypeSourceInfo *TSI = nullptr; 3512 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3513 3514 if (Ty.isNull()) 3515 return ExprError(); 3516 if (!TSI) 3517 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3518 3519 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3520 } 3521 3522 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3523 PredefinedExpr::IdentKind IK; 3524 3525 switch (Kind) { 3526 default: llvm_unreachable("Unknown simple primary expr!"); 3527 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3528 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3529 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3530 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3531 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3532 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3533 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3534 } 3535 3536 return BuildPredefinedExpr(Loc, IK); 3537 } 3538 3539 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3540 SmallString<16> CharBuffer; 3541 bool Invalid = false; 3542 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3543 if (Invalid) 3544 return ExprError(); 3545 3546 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3547 PP, Tok.getKind()); 3548 if (Literal.hadError()) 3549 return ExprError(); 3550 3551 QualType Ty; 3552 if (Literal.isWide()) 3553 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3554 else if (Literal.isUTF8() && getLangOpts().Char8) 3555 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3556 else if (Literal.isUTF16()) 3557 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3558 else if (Literal.isUTF32()) 3559 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3560 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3561 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3562 else 3563 Ty = Context.CharTy; // 'x' -> char in C++ 3564 3565 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3566 if (Literal.isWide()) 3567 Kind = CharacterLiteral::Wide; 3568 else if (Literal.isUTF16()) 3569 Kind = CharacterLiteral::UTF16; 3570 else if (Literal.isUTF32()) 3571 Kind = CharacterLiteral::UTF32; 3572 else if (Literal.isUTF8()) 3573 Kind = CharacterLiteral::UTF8; 3574 3575 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3576 Tok.getLocation()); 3577 3578 if (Literal.getUDSuffix().empty()) 3579 return Lit; 3580 3581 // We're building a user-defined literal. 3582 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3583 SourceLocation UDSuffixLoc = 3584 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3585 3586 // Make sure we're allowed user-defined literals here. 3587 if (!UDLScope) 3588 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3589 3590 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3591 // operator "" X (ch) 3592 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3593 Lit, Tok.getLocation()); 3594 } 3595 3596 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3597 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3598 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3599 Context.IntTy, Loc); 3600 } 3601 3602 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3603 QualType Ty, SourceLocation Loc) { 3604 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3605 3606 using llvm::APFloat; 3607 APFloat Val(Format); 3608 3609 APFloat::opStatus result = Literal.GetFloatValue(Val); 3610 3611 // Overflow is always an error, but underflow is only an error if 3612 // we underflowed to zero (APFloat reports denormals as underflow). 3613 if ((result & APFloat::opOverflow) || 3614 ((result & APFloat::opUnderflow) && Val.isZero())) { 3615 unsigned diagnostic; 3616 SmallString<20> buffer; 3617 if (result & APFloat::opOverflow) { 3618 diagnostic = diag::warn_float_overflow; 3619 APFloat::getLargest(Format).toString(buffer); 3620 } else { 3621 diagnostic = diag::warn_float_underflow; 3622 APFloat::getSmallest(Format).toString(buffer); 3623 } 3624 3625 S.Diag(Loc, diagnostic) 3626 << Ty 3627 << StringRef(buffer.data(), buffer.size()); 3628 } 3629 3630 bool isExact = (result == APFloat::opOK); 3631 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3632 } 3633 3634 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3635 assert(E && "Invalid expression"); 3636 3637 if (E->isValueDependent()) 3638 return false; 3639 3640 QualType QT = E->getType(); 3641 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3642 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3643 return true; 3644 } 3645 3646 llvm::APSInt ValueAPS; 3647 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3648 3649 if (R.isInvalid()) 3650 return true; 3651 3652 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3653 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3654 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3655 << toString(ValueAPS, 10) << ValueIsPositive; 3656 return true; 3657 } 3658 3659 return false; 3660 } 3661 3662 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3663 // Fast path for a single digit (which is quite common). A single digit 3664 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3665 if (Tok.getLength() == 1) { 3666 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3667 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3668 } 3669 3670 SmallString<128> SpellingBuffer; 3671 // NumericLiteralParser wants to overread by one character. Add padding to 3672 // the buffer in case the token is copied to the buffer. If getSpelling() 3673 // returns a StringRef to the memory buffer, it should have a null char at 3674 // the EOF, so it is also safe. 3675 SpellingBuffer.resize(Tok.getLength() + 1); 3676 3677 // Get the spelling of the token, which eliminates trigraphs, etc. 3678 bool Invalid = false; 3679 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3680 if (Invalid) 3681 return ExprError(); 3682 3683 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3684 PP.getSourceManager(), PP.getLangOpts(), 3685 PP.getTargetInfo(), PP.getDiagnostics()); 3686 if (Literal.hadError) 3687 return ExprError(); 3688 3689 if (Literal.hasUDSuffix()) { 3690 // We're building a user-defined literal. 3691 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3692 SourceLocation UDSuffixLoc = 3693 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3694 3695 // Make sure we're allowed user-defined literals here. 3696 if (!UDLScope) 3697 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3698 3699 QualType CookedTy; 3700 if (Literal.isFloatingLiteral()) { 3701 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3702 // long double, the literal is treated as a call of the form 3703 // operator "" X (f L) 3704 CookedTy = Context.LongDoubleTy; 3705 } else { 3706 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3707 // unsigned long long, the literal is treated as a call of the form 3708 // operator "" X (n ULL) 3709 CookedTy = Context.UnsignedLongLongTy; 3710 } 3711 3712 DeclarationName OpName = 3713 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3714 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3715 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3716 3717 SourceLocation TokLoc = Tok.getLocation(); 3718 3719 // Perform literal operator lookup to determine if we're building a raw 3720 // literal or a cooked one. 3721 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3722 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3723 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3724 /*AllowStringTemplatePack*/ false, 3725 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3726 case LOLR_ErrorNoDiagnostic: 3727 // Lookup failure for imaginary constants isn't fatal, there's still the 3728 // GNU extension producing _Complex types. 3729 break; 3730 case LOLR_Error: 3731 return ExprError(); 3732 case LOLR_Cooked: { 3733 Expr *Lit; 3734 if (Literal.isFloatingLiteral()) { 3735 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3736 } else { 3737 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3738 if (Literal.GetIntegerValue(ResultVal)) 3739 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3740 << /* Unsigned */ 1; 3741 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3742 Tok.getLocation()); 3743 } 3744 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3745 } 3746 3747 case LOLR_Raw: { 3748 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3749 // literal is treated as a call of the form 3750 // operator "" X ("n") 3751 unsigned Length = Literal.getUDSuffixOffset(); 3752 QualType StrTy = Context.getConstantArrayType( 3753 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3754 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3755 Expr *Lit = StringLiteral::Create( 3756 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3757 /*Pascal*/false, StrTy, &TokLoc, 1); 3758 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3759 } 3760 3761 case LOLR_Template: { 3762 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3763 // template), L is treated as a call fo the form 3764 // operator "" X <'c1', 'c2', ... 'ck'>() 3765 // where n is the source character sequence c1 c2 ... ck. 3766 TemplateArgumentListInfo ExplicitArgs; 3767 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3768 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3769 llvm::APSInt Value(CharBits, CharIsUnsigned); 3770 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3771 Value = TokSpelling[I]; 3772 TemplateArgument Arg(Context, Value, Context.CharTy); 3773 TemplateArgumentLocInfo ArgInfo; 3774 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3775 } 3776 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3777 &ExplicitArgs); 3778 } 3779 case LOLR_StringTemplatePack: 3780 llvm_unreachable("unexpected literal operator lookup result"); 3781 } 3782 } 3783 3784 Expr *Res; 3785 3786 if (Literal.isFixedPointLiteral()) { 3787 QualType Ty; 3788 3789 if (Literal.isAccum) { 3790 if (Literal.isHalf) { 3791 Ty = Context.ShortAccumTy; 3792 } else if (Literal.isLong) { 3793 Ty = Context.LongAccumTy; 3794 } else { 3795 Ty = Context.AccumTy; 3796 } 3797 } else if (Literal.isFract) { 3798 if (Literal.isHalf) { 3799 Ty = Context.ShortFractTy; 3800 } else if (Literal.isLong) { 3801 Ty = Context.LongFractTy; 3802 } else { 3803 Ty = Context.FractTy; 3804 } 3805 } 3806 3807 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3808 3809 bool isSigned = !Literal.isUnsigned; 3810 unsigned scale = Context.getFixedPointScale(Ty); 3811 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3812 3813 llvm::APInt Val(bit_width, 0, isSigned); 3814 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3815 bool ValIsZero = Val.isZero() && !Overflowed; 3816 3817 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3818 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3819 // Clause 6.4.4 - The value of a constant shall be in the range of 3820 // representable values for its type, with exception for constants of a 3821 // fract type with a value of exactly 1; such a constant shall denote 3822 // the maximal value for the type. 3823 --Val; 3824 else if (Val.ugt(MaxVal) || Overflowed) 3825 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3826 3827 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3828 Tok.getLocation(), scale); 3829 } else if (Literal.isFloatingLiteral()) { 3830 QualType Ty; 3831 if (Literal.isHalf){ 3832 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3833 Ty = Context.HalfTy; 3834 else { 3835 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3836 return ExprError(); 3837 } 3838 } else if (Literal.isFloat) 3839 Ty = Context.FloatTy; 3840 else if (Literal.isLong) 3841 Ty = Context.LongDoubleTy; 3842 else if (Literal.isFloat16) 3843 Ty = Context.Float16Ty; 3844 else if (Literal.isFloat128) 3845 Ty = Context.Float128Ty; 3846 else 3847 Ty = Context.DoubleTy; 3848 3849 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3850 3851 if (Ty == Context.DoubleTy) { 3852 if (getLangOpts().SinglePrecisionConstants) { 3853 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3854 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3855 } 3856 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3857 "cl_khr_fp64", getLangOpts())) { 3858 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3859 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3860 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3861 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3862 } 3863 } 3864 } else if (!Literal.isIntegerLiteral()) { 3865 return ExprError(); 3866 } else { 3867 QualType Ty; 3868 3869 // 'long long' is a C99 or C++11 feature. 3870 if (!getLangOpts().C99 && Literal.isLongLong) { 3871 if (getLangOpts().CPlusPlus) 3872 Diag(Tok.getLocation(), 3873 getLangOpts().CPlusPlus11 ? 3874 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3875 else 3876 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3877 } 3878 3879 // 'z/uz' literals are a C++2b feature. 3880 if (Literal.isSizeT) 3881 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3882 ? getLangOpts().CPlusPlus2b 3883 ? diag::warn_cxx20_compat_size_t_suffix 3884 : diag::ext_cxx2b_size_t_suffix 3885 : diag::err_cxx2b_size_t_suffix); 3886 3887 // Get the value in the widest-possible width. 3888 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3889 llvm::APInt ResultVal(MaxWidth, 0); 3890 3891 if (Literal.GetIntegerValue(ResultVal)) { 3892 // If this value didn't fit into uintmax_t, error and force to ull. 3893 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3894 << /* Unsigned */ 1; 3895 Ty = Context.UnsignedLongLongTy; 3896 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3897 "long long is not intmax_t?"); 3898 } else { 3899 // If this value fits into a ULL, try to figure out what else it fits into 3900 // according to the rules of C99 6.4.4.1p5. 3901 3902 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3903 // be an unsigned int. 3904 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3905 3906 // Check from smallest to largest, picking the smallest type we can. 3907 unsigned Width = 0; 3908 3909 // Microsoft specific integer suffixes are explicitly sized. 3910 if (Literal.MicrosoftInteger) { 3911 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3912 Width = 8; 3913 Ty = Context.CharTy; 3914 } else { 3915 Width = Literal.MicrosoftInteger; 3916 Ty = Context.getIntTypeForBitwidth(Width, 3917 /*Signed=*/!Literal.isUnsigned); 3918 } 3919 } 3920 3921 // Check C++2b size_t literals. 3922 if (Literal.isSizeT) { 3923 assert(!Literal.MicrosoftInteger && 3924 "size_t literals can't be Microsoft literals"); 3925 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3926 Context.getTargetInfo().getSizeType()); 3927 3928 // Does it fit in size_t? 3929 if (ResultVal.isIntN(SizeTSize)) { 3930 // Does it fit in ssize_t? 3931 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3932 Ty = Context.getSignedSizeType(); 3933 else if (AllowUnsigned) 3934 Ty = Context.getSizeType(); 3935 Width = SizeTSize; 3936 } 3937 } 3938 3939 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3940 !Literal.isSizeT) { 3941 // Are int/unsigned possibilities? 3942 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3943 3944 // Does it fit in a unsigned int? 3945 if (ResultVal.isIntN(IntSize)) { 3946 // Does it fit in a signed int? 3947 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3948 Ty = Context.IntTy; 3949 else if (AllowUnsigned) 3950 Ty = Context.UnsignedIntTy; 3951 Width = IntSize; 3952 } 3953 } 3954 3955 // Are long/unsigned long possibilities? 3956 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3957 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3958 3959 // Does it fit in a unsigned long? 3960 if (ResultVal.isIntN(LongSize)) { 3961 // Does it fit in a signed long? 3962 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3963 Ty = Context.LongTy; 3964 else if (AllowUnsigned) 3965 Ty = Context.UnsignedLongTy; 3966 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3967 // is compatible. 3968 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3969 const unsigned LongLongSize = 3970 Context.getTargetInfo().getLongLongWidth(); 3971 Diag(Tok.getLocation(), 3972 getLangOpts().CPlusPlus 3973 ? Literal.isLong 3974 ? diag::warn_old_implicitly_unsigned_long_cxx 3975 : /*C++98 UB*/ diag:: 3976 ext_old_implicitly_unsigned_long_cxx 3977 : diag::warn_old_implicitly_unsigned_long) 3978 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3979 : /*will be ill-formed*/ 1); 3980 Ty = Context.UnsignedLongTy; 3981 } 3982 Width = LongSize; 3983 } 3984 } 3985 3986 // Check long long if needed. 3987 if (Ty.isNull() && !Literal.isSizeT) { 3988 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3989 3990 // Does it fit in a unsigned long long? 3991 if (ResultVal.isIntN(LongLongSize)) { 3992 // Does it fit in a signed long long? 3993 // To be compatible with MSVC, hex integer literals ending with the 3994 // LL or i64 suffix are always signed in Microsoft mode. 3995 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3996 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3997 Ty = Context.LongLongTy; 3998 else if (AllowUnsigned) 3999 Ty = Context.UnsignedLongLongTy; 4000 Width = LongLongSize; 4001 } 4002 } 4003 4004 // If we still couldn't decide a type, we either have 'size_t' literal 4005 // that is out of range, or a decimal literal that does not fit in a 4006 // signed long long and has no U suffix. 4007 if (Ty.isNull()) { 4008 if (Literal.isSizeT) 4009 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4010 << Literal.isUnsigned; 4011 else 4012 Diag(Tok.getLocation(), 4013 diag::ext_integer_literal_too_large_for_signed); 4014 Ty = Context.UnsignedLongLongTy; 4015 Width = Context.getTargetInfo().getLongLongWidth(); 4016 } 4017 4018 if (ResultVal.getBitWidth() != Width) 4019 ResultVal = ResultVal.trunc(Width); 4020 } 4021 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4022 } 4023 4024 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4025 if (Literal.isImaginary) { 4026 Res = new (Context) ImaginaryLiteral(Res, 4027 Context.getComplexType(Res->getType())); 4028 4029 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4030 } 4031 return Res; 4032 } 4033 4034 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4035 assert(E && "ActOnParenExpr() missing expr"); 4036 QualType ExprTy = E->getType(); 4037 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4038 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4039 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4040 return new (Context) ParenExpr(L, R, E); 4041 } 4042 4043 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4044 SourceLocation Loc, 4045 SourceRange ArgRange) { 4046 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4047 // scalar or vector data type argument..." 4048 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4049 // type (C99 6.2.5p18) or void. 4050 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4051 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4052 << T << ArgRange; 4053 return true; 4054 } 4055 4056 assert((T->isVoidType() || !T->isIncompleteType()) && 4057 "Scalar types should always be complete"); 4058 return false; 4059 } 4060 4061 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4062 SourceLocation Loc, 4063 SourceRange ArgRange, 4064 UnaryExprOrTypeTrait TraitKind) { 4065 // Invalid types must be hard errors for SFINAE in C++. 4066 if (S.LangOpts.CPlusPlus) 4067 return true; 4068 4069 // C99 6.5.3.4p1: 4070 if (T->isFunctionType() && 4071 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4072 TraitKind == UETT_PreferredAlignOf)) { 4073 // sizeof(function)/alignof(function) is allowed as an extension. 4074 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4075 << getTraitSpelling(TraitKind) << ArgRange; 4076 return false; 4077 } 4078 4079 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4080 // this is an error (OpenCL v1.1 s6.3.k) 4081 if (T->isVoidType()) { 4082 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4083 : diag::ext_sizeof_alignof_void_type; 4084 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4085 return false; 4086 } 4087 4088 return true; 4089 } 4090 4091 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4092 SourceLocation Loc, 4093 SourceRange ArgRange, 4094 UnaryExprOrTypeTrait TraitKind) { 4095 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4096 // runtime doesn't allow it. 4097 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4098 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4099 << T << (TraitKind == UETT_SizeOf) 4100 << ArgRange; 4101 return true; 4102 } 4103 4104 return false; 4105 } 4106 4107 /// Check whether E is a pointer from a decayed array type (the decayed 4108 /// pointer type is equal to T) and emit a warning if it is. 4109 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4110 Expr *E) { 4111 // Don't warn if the operation changed the type. 4112 if (T != E->getType()) 4113 return; 4114 4115 // Now look for array decays. 4116 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4117 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4118 return; 4119 4120 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4121 << ICE->getType() 4122 << ICE->getSubExpr()->getType(); 4123 } 4124 4125 /// Check the constraints on expression operands to unary type expression 4126 /// and type traits. 4127 /// 4128 /// Completes any types necessary and validates the constraints on the operand 4129 /// expression. The logic mostly mirrors the type-based overload, but may modify 4130 /// the expression as it completes the type for that expression through template 4131 /// instantiation, etc. 4132 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4133 UnaryExprOrTypeTrait ExprKind) { 4134 QualType ExprTy = E->getType(); 4135 assert(!ExprTy->isReferenceType()); 4136 4137 bool IsUnevaluatedOperand = 4138 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4139 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4140 if (IsUnevaluatedOperand) { 4141 ExprResult Result = CheckUnevaluatedOperand(E); 4142 if (Result.isInvalid()) 4143 return true; 4144 E = Result.get(); 4145 } 4146 4147 // The operand for sizeof and alignof is in an unevaluated expression context, 4148 // so side effects could result in unintended consequences. 4149 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4150 // used to build SFINAE gadgets. 4151 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4152 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4153 !E->isInstantiationDependent() && 4154 E->HasSideEffects(Context, false)) 4155 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4156 4157 if (ExprKind == UETT_VecStep) 4158 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4159 E->getSourceRange()); 4160 4161 // Explicitly list some types as extensions. 4162 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4163 E->getSourceRange(), ExprKind)) 4164 return false; 4165 4166 // 'alignof' applied to an expression only requires the base element type of 4167 // the expression to be complete. 'sizeof' requires the expression's type to 4168 // be complete (and will attempt to complete it if it's an array of unknown 4169 // bound). 4170 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4171 if (RequireCompleteSizedType( 4172 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4173 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4174 getTraitSpelling(ExprKind), E->getSourceRange())) 4175 return true; 4176 } else { 4177 if (RequireCompleteSizedExprType( 4178 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4179 getTraitSpelling(ExprKind), E->getSourceRange())) 4180 return true; 4181 } 4182 4183 // Completing the expression's type may have changed it. 4184 ExprTy = E->getType(); 4185 assert(!ExprTy->isReferenceType()); 4186 4187 if (ExprTy->isFunctionType()) { 4188 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4189 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4190 return true; 4191 } 4192 4193 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4194 E->getSourceRange(), ExprKind)) 4195 return true; 4196 4197 if (ExprKind == UETT_SizeOf) { 4198 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4199 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4200 QualType OType = PVD->getOriginalType(); 4201 QualType Type = PVD->getType(); 4202 if (Type->isPointerType() && OType->isArrayType()) { 4203 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4204 << Type << OType; 4205 Diag(PVD->getLocation(), diag::note_declared_at); 4206 } 4207 } 4208 } 4209 4210 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4211 // decays into a pointer and returns an unintended result. This is most 4212 // likely a typo for "sizeof(array) op x". 4213 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4214 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4215 BO->getLHS()); 4216 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4217 BO->getRHS()); 4218 } 4219 } 4220 4221 return false; 4222 } 4223 4224 /// Check the constraints on operands to unary expression and type 4225 /// traits. 4226 /// 4227 /// This will complete any types necessary, and validate the various constraints 4228 /// on those operands. 4229 /// 4230 /// The UsualUnaryConversions() function is *not* called by this routine. 4231 /// C99 6.3.2.1p[2-4] all state: 4232 /// Except when it is the operand of the sizeof operator ... 4233 /// 4234 /// C++ [expr.sizeof]p4 4235 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4236 /// standard conversions are not applied to the operand of sizeof. 4237 /// 4238 /// This policy is followed for all of the unary trait expressions. 4239 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4240 SourceLocation OpLoc, 4241 SourceRange ExprRange, 4242 UnaryExprOrTypeTrait ExprKind) { 4243 if (ExprType->isDependentType()) 4244 return false; 4245 4246 // C++ [expr.sizeof]p2: 4247 // When applied to a reference or a reference type, the result 4248 // is the size of the referenced type. 4249 // C++11 [expr.alignof]p3: 4250 // When alignof is applied to a reference type, the result 4251 // shall be the alignment of the referenced type. 4252 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4253 ExprType = Ref->getPointeeType(); 4254 4255 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4256 // When alignof or _Alignof is applied to an array type, the result 4257 // is the alignment of the element type. 4258 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4259 ExprKind == UETT_OpenMPRequiredSimdAlign) 4260 ExprType = Context.getBaseElementType(ExprType); 4261 4262 if (ExprKind == UETT_VecStep) 4263 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4264 4265 // Explicitly list some types as extensions. 4266 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4267 ExprKind)) 4268 return false; 4269 4270 if (RequireCompleteSizedType( 4271 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4272 getTraitSpelling(ExprKind), ExprRange)) 4273 return true; 4274 4275 if (ExprType->isFunctionType()) { 4276 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4277 << getTraitSpelling(ExprKind) << ExprRange; 4278 return true; 4279 } 4280 4281 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4282 ExprKind)) 4283 return true; 4284 4285 return false; 4286 } 4287 4288 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4289 // Cannot know anything else if the expression is dependent. 4290 if (E->isTypeDependent()) 4291 return false; 4292 4293 if (E->getObjectKind() == OK_BitField) { 4294 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4295 << 1 << E->getSourceRange(); 4296 return true; 4297 } 4298 4299 ValueDecl *D = nullptr; 4300 Expr *Inner = E->IgnoreParens(); 4301 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4302 D = DRE->getDecl(); 4303 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4304 D = ME->getMemberDecl(); 4305 } 4306 4307 // If it's a field, require the containing struct to have a 4308 // complete definition so that we can compute the layout. 4309 // 4310 // This can happen in C++11 onwards, either by naming the member 4311 // in a way that is not transformed into a member access expression 4312 // (in an unevaluated operand, for instance), or by naming the member 4313 // in a trailing-return-type. 4314 // 4315 // For the record, since __alignof__ on expressions is a GCC 4316 // extension, GCC seems to permit this but always gives the 4317 // nonsensical answer 0. 4318 // 4319 // We don't really need the layout here --- we could instead just 4320 // directly check for all the appropriate alignment-lowing 4321 // attributes --- but that would require duplicating a lot of 4322 // logic that just isn't worth duplicating for such a marginal 4323 // use-case. 4324 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4325 // Fast path this check, since we at least know the record has a 4326 // definition if we can find a member of it. 4327 if (!FD->getParent()->isCompleteDefinition()) { 4328 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4329 << E->getSourceRange(); 4330 return true; 4331 } 4332 4333 // Otherwise, if it's a field, and the field doesn't have 4334 // reference type, then it must have a complete type (or be a 4335 // flexible array member, which we explicitly want to 4336 // white-list anyway), which makes the following checks trivial. 4337 if (!FD->getType()->isReferenceType()) 4338 return false; 4339 } 4340 4341 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4342 } 4343 4344 bool Sema::CheckVecStepExpr(Expr *E) { 4345 E = E->IgnoreParens(); 4346 4347 // Cannot know anything else if the expression is dependent. 4348 if (E->isTypeDependent()) 4349 return false; 4350 4351 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4352 } 4353 4354 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4355 CapturingScopeInfo *CSI) { 4356 assert(T->isVariablyModifiedType()); 4357 assert(CSI != nullptr); 4358 4359 // We're going to walk down into the type and look for VLA expressions. 4360 do { 4361 const Type *Ty = T.getTypePtr(); 4362 switch (Ty->getTypeClass()) { 4363 #define TYPE(Class, Base) 4364 #define ABSTRACT_TYPE(Class, Base) 4365 #define NON_CANONICAL_TYPE(Class, Base) 4366 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4367 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4368 #include "clang/AST/TypeNodes.inc" 4369 T = QualType(); 4370 break; 4371 // These types are never variably-modified. 4372 case Type::Builtin: 4373 case Type::Complex: 4374 case Type::Vector: 4375 case Type::ExtVector: 4376 case Type::ConstantMatrix: 4377 case Type::Record: 4378 case Type::Enum: 4379 case Type::Elaborated: 4380 case Type::TemplateSpecialization: 4381 case Type::ObjCObject: 4382 case Type::ObjCInterface: 4383 case Type::ObjCObjectPointer: 4384 case Type::ObjCTypeParam: 4385 case Type::Pipe: 4386 case Type::BitInt: 4387 llvm_unreachable("type class is never variably-modified!"); 4388 case Type::Adjusted: 4389 T = cast<AdjustedType>(Ty)->getOriginalType(); 4390 break; 4391 case Type::Decayed: 4392 T = cast<DecayedType>(Ty)->getPointeeType(); 4393 break; 4394 case Type::Pointer: 4395 T = cast<PointerType>(Ty)->getPointeeType(); 4396 break; 4397 case Type::BlockPointer: 4398 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4399 break; 4400 case Type::LValueReference: 4401 case Type::RValueReference: 4402 T = cast<ReferenceType>(Ty)->getPointeeType(); 4403 break; 4404 case Type::MemberPointer: 4405 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4406 break; 4407 case Type::ConstantArray: 4408 case Type::IncompleteArray: 4409 // Losing element qualification here is fine. 4410 T = cast<ArrayType>(Ty)->getElementType(); 4411 break; 4412 case Type::VariableArray: { 4413 // Losing element qualification here is fine. 4414 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4415 4416 // Unknown size indication requires no size computation. 4417 // Otherwise, evaluate and record it. 4418 auto Size = VAT->getSizeExpr(); 4419 if (Size && !CSI->isVLATypeCaptured(VAT) && 4420 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4421 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4422 4423 T = VAT->getElementType(); 4424 break; 4425 } 4426 case Type::FunctionProto: 4427 case Type::FunctionNoProto: 4428 T = cast<FunctionType>(Ty)->getReturnType(); 4429 break; 4430 case Type::Paren: 4431 case Type::TypeOf: 4432 case Type::UnaryTransform: 4433 case Type::Attributed: 4434 case Type::SubstTemplateTypeParm: 4435 case Type::MacroQualified: 4436 // Keep walking after single level desugaring. 4437 T = T.getSingleStepDesugaredType(Context); 4438 break; 4439 case Type::Typedef: 4440 T = cast<TypedefType>(Ty)->desugar(); 4441 break; 4442 case Type::Decltype: 4443 T = cast<DecltypeType>(Ty)->desugar(); 4444 break; 4445 case Type::Using: 4446 T = cast<UsingType>(Ty)->desugar(); 4447 break; 4448 case Type::Auto: 4449 case Type::DeducedTemplateSpecialization: 4450 T = cast<DeducedType>(Ty)->getDeducedType(); 4451 break; 4452 case Type::TypeOfExpr: 4453 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4454 break; 4455 case Type::Atomic: 4456 T = cast<AtomicType>(Ty)->getValueType(); 4457 break; 4458 } 4459 } while (!T.isNull() && T->isVariablyModifiedType()); 4460 } 4461 4462 /// Build a sizeof or alignof expression given a type operand. 4463 ExprResult 4464 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4465 SourceLocation OpLoc, 4466 UnaryExprOrTypeTrait ExprKind, 4467 SourceRange R) { 4468 if (!TInfo) 4469 return ExprError(); 4470 4471 QualType T = TInfo->getType(); 4472 4473 if (!T->isDependentType() && 4474 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4475 return ExprError(); 4476 4477 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4478 if (auto *TT = T->getAs<TypedefType>()) { 4479 for (auto I = FunctionScopes.rbegin(), 4480 E = std::prev(FunctionScopes.rend()); 4481 I != E; ++I) { 4482 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4483 if (CSI == nullptr) 4484 break; 4485 DeclContext *DC = nullptr; 4486 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4487 DC = LSI->CallOperator; 4488 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4489 DC = CRSI->TheCapturedDecl; 4490 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4491 DC = BSI->TheDecl; 4492 if (DC) { 4493 if (DC->containsDecl(TT->getDecl())) 4494 break; 4495 captureVariablyModifiedType(Context, T, CSI); 4496 } 4497 } 4498 } 4499 } 4500 4501 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4502 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && 4503 TInfo->getType()->isVariablyModifiedType()) 4504 TInfo = TransformToPotentiallyEvaluated(TInfo); 4505 4506 return new (Context) UnaryExprOrTypeTraitExpr( 4507 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4508 } 4509 4510 /// Build a sizeof or alignof expression given an expression 4511 /// operand. 4512 ExprResult 4513 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4514 UnaryExprOrTypeTrait ExprKind) { 4515 ExprResult PE = CheckPlaceholderExpr(E); 4516 if (PE.isInvalid()) 4517 return ExprError(); 4518 4519 E = PE.get(); 4520 4521 // Verify that the operand is valid. 4522 bool isInvalid = false; 4523 if (E->isTypeDependent()) { 4524 // Delay type-checking for type-dependent expressions. 4525 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4526 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4527 } else if (ExprKind == UETT_VecStep) { 4528 isInvalid = CheckVecStepExpr(E); 4529 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4530 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4531 isInvalid = true; 4532 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4533 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4534 isInvalid = true; 4535 } else { 4536 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4537 } 4538 4539 if (isInvalid) 4540 return ExprError(); 4541 4542 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4543 PE = TransformToPotentiallyEvaluated(E); 4544 if (PE.isInvalid()) return ExprError(); 4545 E = PE.get(); 4546 } 4547 4548 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4549 return new (Context) UnaryExprOrTypeTraitExpr( 4550 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4551 } 4552 4553 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4554 /// expr and the same for @c alignof and @c __alignof 4555 /// Note that the ArgRange is invalid if isType is false. 4556 ExprResult 4557 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4558 UnaryExprOrTypeTrait ExprKind, bool IsType, 4559 void *TyOrEx, SourceRange ArgRange) { 4560 // If error parsing type, ignore. 4561 if (!TyOrEx) return ExprError(); 4562 4563 if (IsType) { 4564 TypeSourceInfo *TInfo; 4565 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4566 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4567 } 4568 4569 Expr *ArgEx = (Expr *)TyOrEx; 4570 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4571 return Result; 4572 } 4573 4574 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4575 bool IsReal) { 4576 if (V.get()->isTypeDependent()) 4577 return S.Context.DependentTy; 4578 4579 // _Real and _Imag are only l-values for normal l-values. 4580 if (V.get()->getObjectKind() != OK_Ordinary) { 4581 V = S.DefaultLvalueConversion(V.get()); 4582 if (V.isInvalid()) 4583 return QualType(); 4584 } 4585 4586 // These operators return the element type of a complex type. 4587 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4588 return CT->getElementType(); 4589 4590 // Otherwise they pass through real integer and floating point types here. 4591 if (V.get()->getType()->isArithmeticType()) 4592 return V.get()->getType(); 4593 4594 // Test for placeholders. 4595 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4596 if (PR.isInvalid()) return QualType(); 4597 if (PR.get() != V.get()) { 4598 V = PR; 4599 return CheckRealImagOperand(S, V, Loc, IsReal); 4600 } 4601 4602 // Reject anything else. 4603 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4604 << (IsReal ? "__real" : "__imag"); 4605 return QualType(); 4606 } 4607 4608 4609 4610 ExprResult 4611 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4612 tok::TokenKind Kind, Expr *Input) { 4613 UnaryOperatorKind Opc; 4614 switch (Kind) { 4615 default: llvm_unreachable("Unknown unary op!"); 4616 case tok::plusplus: Opc = UO_PostInc; break; 4617 case tok::minusminus: Opc = UO_PostDec; break; 4618 } 4619 4620 // Since this might is a postfix expression, get rid of ParenListExprs. 4621 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4622 if (Result.isInvalid()) return ExprError(); 4623 Input = Result.get(); 4624 4625 return BuildUnaryOp(S, OpLoc, Opc, Input); 4626 } 4627 4628 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4629 /// 4630 /// \return true on error 4631 static bool checkArithmeticOnObjCPointer(Sema &S, 4632 SourceLocation opLoc, 4633 Expr *op) { 4634 assert(op->getType()->isObjCObjectPointerType()); 4635 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4636 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4637 return false; 4638 4639 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4640 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4641 << op->getSourceRange(); 4642 return true; 4643 } 4644 4645 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4646 auto *BaseNoParens = Base->IgnoreParens(); 4647 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4648 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4649 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4650 } 4651 4652 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. 4653 // Typically this is DependentTy, but can sometimes be more precise. 4654 // 4655 // There are cases when we could determine a non-dependent type: 4656 // - LHS and RHS may have non-dependent types despite being type-dependent 4657 // (e.g. unbounded array static members of the current instantiation) 4658 // - one may be a dependent-sized array with known element type 4659 // - one may be a dependent-typed valid index (enum in current instantiation) 4660 // 4661 // We *always* return a dependent type, in such cases it is DependentTy. 4662 // This avoids creating type-dependent expressions with non-dependent types. 4663 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 4664 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, 4665 const ASTContext &Ctx) { 4666 assert(LHS->isTypeDependent() || RHS->isTypeDependent()); 4667 QualType LTy = LHS->getType(), RTy = RHS->getType(); 4668 QualType Result = Ctx.DependentTy; 4669 if (RTy->isIntegralOrUnscopedEnumerationType()) { 4670 if (const PointerType *PT = LTy->getAs<PointerType>()) 4671 Result = PT->getPointeeType(); 4672 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) 4673 Result = AT->getElementType(); 4674 } else if (LTy->isIntegralOrUnscopedEnumerationType()) { 4675 if (const PointerType *PT = RTy->getAs<PointerType>()) 4676 Result = PT->getPointeeType(); 4677 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) 4678 Result = AT->getElementType(); 4679 } 4680 // Ensure we return a dependent type. 4681 return Result->isDependentType() ? Result : Ctx.DependentTy; 4682 } 4683 4684 ExprResult 4685 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4686 Expr *idx, SourceLocation rbLoc) { 4687 if (base && !base->getType().isNull() && 4688 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4689 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4690 SourceLocation(), /*Length*/ nullptr, 4691 /*Stride=*/nullptr, rbLoc); 4692 4693 // Since this might be a postfix expression, get rid of ParenListExprs. 4694 if (isa<ParenListExpr>(base)) { 4695 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4696 if (result.isInvalid()) return ExprError(); 4697 base = result.get(); 4698 } 4699 4700 // Check if base and idx form a MatrixSubscriptExpr. 4701 // 4702 // Helper to check for comma expressions, which are not allowed as indices for 4703 // matrix subscript expressions. 4704 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4705 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4706 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4707 << SourceRange(base->getBeginLoc(), rbLoc); 4708 return true; 4709 } 4710 return false; 4711 }; 4712 // The matrix subscript operator ([][])is considered a single operator. 4713 // Separating the index expressions by parenthesis is not allowed. 4714 if (base->getType()->isSpecificPlaceholderType( 4715 BuiltinType::IncompleteMatrixIdx) && 4716 !isa<MatrixSubscriptExpr>(base)) { 4717 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4718 << SourceRange(base->getBeginLoc(), rbLoc); 4719 return ExprError(); 4720 } 4721 // If the base is a MatrixSubscriptExpr, try to create a new 4722 // MatrixSubscriptExpr. 4723 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4724 if (matSubscriptE) { 4725 if (CheckAndReportCommaError(idx)) 4726 return ExprError(); 4727 4728 assert(matSubscriptE->isIncomplete() && 4729 "base has to be an incomplete matrix subscript"); 4730 return CreateBuiltinMatrixSubscriptExpr( 4731 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4732 } 4733 4734 // Handle any non-overload placeholder types in the base and index 4735 // expressions. We can't handle overloads here because the other 4736 // operand might be an overloadable type, in which case the overload 4737 // resolution for the operator overload should get the first crack 4738 // at the overload. 4739 bool IsMSPropertySubscript = false; 4740 if (base->getType()->isNonOverloadPlaceholderType()) { 4741 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4742 if (!IsMSPropertySubscript) { 4743 ExprResult result = CheckPlaceholderExpr(base); 4744 if (result.isInvalid()) 4745 return ExprError(); 4746 base = result.get(); 4747 } 4748 } 4749 4750 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4751 if (base->getType()->isMatrixType()) { 4752 if (CheckAndReportCommaError(idx)) 4753 return ExprError(); 4754 4755 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4756 } 4757 4758 // A comma-expression as the index is deprecated in C++2a onwards. 4759 if (getLangOpts().CPlusPlus20 && 4760 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4761 (isa<CXXOperatorCallExpr>(idx) && 4762 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4763 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4764 << SourceRange(base->getBeginLoc(), rbLoc); 4765 } 4766 4767 if (idx->getType()->isNonOverloadPlaceholderType()) { 4768 ExprResult result = CheckPlaceholderExpr(idx); 4769 if (result.isInvalid()) return ExprError(); 4770 idx = result.get(); 4771 } 4772 4773 // Build an unanalyzed expression if either operand is type-dependent. 4774 if (getLangOpts().CPlusPlus && 4775 (base->isTypeDependent() || idx->isTypeDependent())) { 4776 return new (Context) ArraySubscriptExpr( 4777 base, idx, getDependentArraySubscriptType(base, idx, getASTContext()), 4778 VK_LValue, OK_Ordinary, rbLoc); 4779 } 4780 4781 // MSDN, property (C++) 4782 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4783 // This attribute can also be used in the declaration of an empty array in a 4784 // class or structure definition. For example: 4785 // __declspec(property(get=GetX, put=PutX)) int x[]; 4786 // The above statement indicates that x[] can be used with one or more array 4787 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4788 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4789 if (IsMSPropertySubscript) { 4790 // Build MS property subscript expression if base is MS property reference 4791 // or MS property subscript. 4792 return new (Context) MSPropertySubscriptExpr( 4793 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4794 } 4795 4796 // Use C++ overloaded-operator rules if either operand has record 4797 // type. The spec says to do this if either type is *overloadable*, 4798 // but enum types can't declare subscript operators or conversion 4799 // operators, so there's nothing interesting for overload resolution 4800 // to do if there aren't any record types involved. 4801 // 4802 // ObjC pointers have their own subscripting logic that is not tied 4803 // to overload resolution and so should not take this path. 4804 if (getLangOpts().CPlusPlus && 4805 (base->getType()->isRecordType() || 4806 (!base->getType()->isObjCObjectPointerType() && 4807 idx->getType()->isRecordType()))) { 4808 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4809 } 4810 4811 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4812 4813 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4814 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4815 4816 return Res; 4817 } 4818 4819 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4820 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4821 InitializationKind Kind = 4822 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4823 InitializationSequence InitSeq(*this, Entity, Kind, E); 4824 return InitSeq.Perform(*this, Entity, Kind, E); 4825 } 4826 4827 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4828 Expr *ColumnIdx, 4829 SourceLocation RBLoc) { 4830 ExprResult BaseR = CheckPlaceholderExpr(Base); 4831 if (BaseR.isInvalid()) 4832 return BaseR; 4833 Base = BaseR.get(); 4834 4835 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4836 if (RowR.isInvalid()) 4837 return RowR; 4838 RowIdx = RowR.get(); 4839 4840 if (!ColumnIdx) 4841 return new (Context) MatrixSubscriptExpr( 4842 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4843 4844 // Build an unanalyzed expression if any of the operands is type-dependent. 4845 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4846 ColumnIdx->isTypeDependent()) 4847 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4848 Context.DependentTy, RBLoc); 4849 4850 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4851 if (ColumnR.isInvalid()) 4852 return ColumnR; 4853 ColumnIdx = ColumnR.get(); 4854 4855 // Check that IndexExpr is an integer expression. If it is a constant 4856 // expression, check that it is less than Dim (= the number of elements in the 4857 // corresponding dimension). 4858 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4859 bool IsColumnIdx) -> Expr * { 4860 if (!IndexExpr->getType()->isIntegerType() && 4861 !IndexExpr->isTypeDependent()) { 4862 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4863 << IsColumnIdx; 4864 return nullptr; 4865 } 4866 4867 if (Optional<llvm::APSInt> Idx = 4868 IndexExpr->getIntegerConstantExpr(Context)) { 4869 if ((*Idx < 0 || *Idx >= Dim)) { 4870 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4871 << IsColumnIdx << Dim; 4872 return nullptr; 4873 } 4874 } 4875 4876 ExprResult ConvExpr = 4877 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4878 assert(!ConvExpr.isInvalid() && 4879 "should be able to convert any integer type to size type"); 4880 return ConvExpr.get(); 4881 }; 4882 4883 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4884 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4885 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4886 if (!RowIdx || !ColumnIdx) 4887 return ExprError(); 4888 4889 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4890 MTy->getElementType(), RBLoc); 4891 } 4892 4893 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4894 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4895 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4896 4897 // For expressions like `&(*s).b`, the base is recorded and what should be 4898 // checked. 4899 const MemberExpr *Member = nullptr; 4900 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4901 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4902 4903 LastRecord.PossibleDerefs.erase(StrippedExpr); 4904 } 4905 4906 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4907 if (isUnevaluatedContext()) 4908 return; 4909 4910 QualType ResultTy = E->getType(); 4911 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4912 4913 // Bail if the element is an array since it is not memory access. 4914 if (isa<ArrayType>(ResultTy)) 4915 return; 4916 4917 if (ResultTy->hasAttr(attr::NoDeref)) { 4918 LastRecord.PossibleDerefs.insert(E); 4919 return; 4920 } 4921 4922 // Check if the base type is a pointer to a member access of a struct 4923 // marked with noderef. 4924 const Expr *Base = E->getBase(); 4925 QualType BaseTy = Base->getType(); 4926 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4927 // Not a pointer access 4928 return; 4929 4930 const MemberExpr *Member = nullptr; 4931 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4932 Member->isArrow()) 4933 Base = Member->getBase(); 4934 4935 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4936 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4937 LastRecord.PossibleDerefs.insert(E); 4938 } 4939 } 4940 4941 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4942 Expr *LowerBound, 4943 SourceLocation ColonLocFirst, 4944 SourceLocation ColonLocSecond, 4945 Expr *Length, Expr *Stride, 4946 SourceLocation RBLoc) { 4947 if (Base->getType()->isPlaceholderType() && 4948 !Base->getType()->isSpecificPlaceholderType( 4949 BuiltinType::OMPArraySection)) { 4950 ExprResult Result = CheckPlaceholderExpr(Base); 4951 if (Result.isInvalid()) 4952 return ExprError(); 4953 Base = Result.get(); 4954 } 4955 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4956 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4957 if (Result.isInvalid()) 4958 return ExprError(); 4959 Result = DefaultLvalueConversion(Result.get()); 4960 if (Result.isInvalid()) 4961 return ExprError(); 4962 LowerBound = Result.get(); 4963 } 4964 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4965 ExprResult Result = CheckPlaceholderExpr(Length); 4966 if (Result.isInvalid()) 4967 return ExprError(); 4968 Result = DefaultLvalueConversion(Result.get()); 4969 if (Result.isInvalid()) 4970 return ExprError(); 4971 Length = Result.get(); 4972 } 4973 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4974 ExprResult Result = CheckPlaceholderExpr(Stride); 4975 if (Result.isInvalid()) 4976 return ExprError(); 4977 Result = DefaultLvalueConversion(Result.get()); 4978 if (Result.isInvalid()) 4979 return ExprError(); 4980 Stride = Result.get(); 4981 } 4982 4983 // Build an unanalyzed expression if either operand is type-dependent. 4984 if (Base->isTypeDependent() || 4985 (LowerBound && 4986 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4987 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4988 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4989 return new (Context) OMPArraySectionExpr( 4990 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4991 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4992 } 4993 4994 // Perform default conversions. 4995 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4996 QualType ResultTy; 4997 if (OriginalTy->isAnyPointerType()) { 4998 ResultTy = OriginalTy->getPointeeType(); 4999 } else if (OriginalTy->isArrayType()) { 5000 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 5001 } else { 5002 return ExprError( 5003 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 5004 << Base->getSourceRange()); 5005 } 5006 // C99 6.5.2.1p1 5007 if (LowerBound) { 5008 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 5009 LowerBound); 5010 if (Res.isInvalid()) 5011 return ExprError(Diag(LowerBound->getExprLoc(), 5012 diag::err_omp_typecheck_section_not_integer) 5013 << 0 << LowerBound->getSourceRange()); 5014 LowerBound = Res.get(); 5015 5016 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5017 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5018 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5019 << 0 << LowerBound->getSourceRange(); 5020 } 5021 if (Length) { 5022 auto Res = 5023 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5024 if (Res.isInvalid()) 5025 return ExprError(Diag(Length->getExprLoc(), 5026 diag::err_omp_typecheck_section_not_integer) 5027 << 1 << Length->getSourceRange()); 5028 Length = Res.get(); 5029 5030 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5031 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5032 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5033 << 1 << Length->getSourceRange(); 5034 } 5035 if (Stride) { 5036 ExprResult Res = 5037 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5038 if (Res.isInvalid()) 5039 return ExprError(Diag(Stride->getExprLoc(), 5040 diag::err_omp_typecheck_section_not_integer) 5041 << 1 << Stride->getSourceRange()); 5042 Stride = Res.get(); 5043 5044 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5045 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5046 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5047 << 1 << Stride->getSourceRange(); 5048 } 5049 5050 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5051 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5052 // type. Note that functions are not objects, and that (in C99 parlance) 5053 // incomplete types are not object types. 5054 if (ResultTy->isFunctionType()) { 5055 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5056 << ResultTy << Base->getSourceRange(); 5057 return ExprError(); 5058 } 5059 5060 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5061 diag::err_omp_section_incomplete_type, Base)) 5062 return ExprError(); 5063 5064 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5065 Expr::EvalResult Result; 5066 if (LowerBound->EvaluateAsInt(Result, Context)) { 5067 // OpenMP 5.0, [2.1.5 Array Sections] 5068 // The array section must be a subset of the original array. 5069 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5070 if (LowerBoundValue.isNegative()) { 5071 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5072 << LowerBound->getSourceRange(); 5073 return ExprError(); 5074 } 5075 } 5076 } 5077 5078 if (Length) { 5079 Expr::EvalResult Result; 5080 if (Length->EvaluateAsInt(Result, Context)) { 5081 // OpenMP 5.0, [2.1.5 Array Sections] 5082 // The length must evaluate to non-negative integers. 5083 llvm::APSInt LengthValue = Result.Val.getInt(); 5084 if (LengthValue.isNegative()) { 5085 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5086 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5087 << Length->getSourceRange(); 5088 return ExprError(); 5089 } 5090 } 5091 } else if (ColonLocFirst.isValid() && 5092 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5093 !OriginalTy->isVariableArrayType()))) { 5094 // OpenMP 5.0, [2.1.5 Array Sections] 5095 // When the size of the array dimension is not known, the length must be 5096 // specified explicitly. 5097 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5098 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5099 return ExprError(); 5100 } 5101 5102 if (Stride) { 5103 Expr::EvalResult Result; 5104 if (Stride->EvaluateAsInt(Result, Context)) { 5105 // OpenMP 5.0, [2.1.5 Array Sections] 5106 // The stride must evaluate to a positive integer. 5107 llvm::APSInt StrideValue = Result.Val.getInt(); 5108 if (!StrideValue.isStrictlyPositive()) { 5109 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5110 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5111 << Stride->getSourceRange(); 5112 return ExprError(); 5113 } 5114 } 5115 } 5116 5117 if (!Base->getType()->isSpecificPlaceholderType( 5118 BuiltinType::OMPArraySection)) { 5119 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5120 if (Result.isInvalid()) 5121 return ExprError(); 5122 Base = Result.get(); 5123 } 5124 return new (Context) OMPArraySectionExpr( 5125 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5126 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5127 } 5128 5129 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5130 SourceLocation RParenLoc, 5131 ArrayRef<Expr *> Dims, 5132 ArrayRef<SourceRange> Brackets) { 5133 if (Base->getType()->isPlaceholderType()) { 5134 ExprResult Result = CheckPlaceholderExpr(Base); 5135 if (Result.isInvalid()) 5136 return ExprError(); 5137 Result = DefaultLvalueConversion(Result.get()); 5138 if (Result.isInvalid()) 5139 return ExprError(); 5140 Base = Result.get(); 5141 } 5142 QualType BaseTy = Base->getType(); 5143 // Delay analysis of the types/expressions if instantiation/specialization is 5144 // required. 5145 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5146 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5147 LParenLoc, RParenLoc, Dims, Brackets); 5148 if (!BaseTy->isPointerType() || 5149 (!Base->isTypeDependent() && 5150 BaseTy->getPointeeType()->isIncompleteType())) 5151 return ExprError(Diag(Base->getExprLoc(), 5152 diag::err_omp_non_pointer_type_array_shaping_base) 5153 << Base->getSourceRange()); 5154 5155 SmallVector<Expr *, 4> NewDims; 5156 bool ErrorFound = false; 5157 for (Expr *Dim : Dims) { 5158 if (Dim->getType()->isPlaceholderType()) { 5159 ExprResult Result = CheckPlaceholderExpr(Dim); 5160 if (Result.isInvalid()) { 5161 ErrorFound = true; 5162 continue; 5163 } 5164 Result = DefaultLvalueConversion(Result.get()); 5165 if (Result.isInvalid()) { 5166 ErrorFound = true; 5167 continue; 5168 } 5169 Dim = Result.get(); 5170 } 5171 if (!Dim->isTypeDependent()) { 5172 ExprResult Result = 5173 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5174 if (Result.isInvalid()) { 5175 ErrorFound = true; 5176 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5177 << Dim->getSourceRange(); 5178 continue; 5179 } 5180 Dim = Result.get(); 5181 Expr::EvalResult EvResult; 5182 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5183 // OpenMP 5.0, [2.1.4 Array Shaping] 5184 // Each si is an integral type expression that must evaluate to a 5185 // positive integer. 5186 llvm::APSInt Value = EvResult.Val.getInt(); 5187 if (!Value.isStrictlyPositive()) { 5188 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5189 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5190 << Dim->getSourceRange(); 5191 ErrorFound = true; 5192 continue; 5193 } 5194 } 5195 } 5196 NewDims.push_back(Dim); 5197 } 5198 if (ErrorFound) 5199 return ExprError(); 5200 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5201 LParenLoc, RParenLoc, NewDims, Brackets); 5202 } 5203 5204 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5205 SourceLocation LLoc, SourceLocation RLoc, 5206 ArrayRef<OMPIteratorData> Data) { 5207 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5208 bool IsCorrect = true; 5209 for (const OMPIteratorData &D : Data) { 5210 TypeSourceInfo *TInfo = nullptr; 5211 SourceLocation StartLoc; 5212 QualType DeclTy; 5213 if (!D.Type.getAsOpaquePtr()) { 5214 // OpenMP 5.0, 2.1.6 Iterators 5215 // In an iterator-specifier, if the iterator-type is not specified then 5216 // the type of that iterator is of int type. 5217 DeclTy = Context.IntTy; 5218 StartLoc = D.DeclIdentLoc; 5219 } else { 5220 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5221 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5222 } 5223 5224 bool IsDeclTyDependent = DeclTy->isDependentType() || 5225 DeclTy->containsUnexpandedParameterPack() || 5226 DeclTy->isInstantiationDependentType(); 5227 if (!IsDeclTyDependent) { 5228 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5229 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5230 // The iterator-type must be an integral or pointer type. 5231 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5232 << DeclTy; 5233 IsCorrect = false; 5234 continue; 5235 } 5236 if (DeclTy.isConstant(Context)) { 5237 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5238 // The iterator-type must not be const qualified. 5239 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5240 << DeclTy; 5241 IsCorrect = false; 5242 continue; 5243 } 5244 } 5245 5246 // Iterator declaration. 5247 assert(D.DeclIdent && "Identifier expected."); 5248 // Always try to create iterator declarator to avoid extra error messages 5249 // about unknown declarations use. 5250 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5251 D.DeclIdent, DeclTy, TInfo, SC_None); 5252 VD->setImplicit(); 5253 if (S) { 5254 // Check for conflicting previous declaration. 5255 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5256 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5257 ForVisibleRedeclaration); 5258 Previous.suppressDiagnostics(); 5259 LookupName(Previous, S); 5260 5261 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5262 /*AllowInlineNamespace=*/false); 5263 if (!Previous.empty()) { 5264 NamedDecl *Old = Previous.getRepresentativeDecl(); 5265 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5266 Diag(Old->getLocation(), diag::note_previous_definition); 5267 } else { 5268 PushOnScopeChains(VD, S); 5269 } 5270 } else { 5271 CurContext->addDecl(VD); 5272 } 5273 Expr *Begin = D.Range.Begin; 5274 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5275 ExprResult BeginRes = 5276 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5277 Begin = BeginRes.get(); 5278 } 5279 Expr *End = D.Range.End; 5280 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5281 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5282 End = EndRes.get(); 5283 } 5284 Expr *Step = D.Range.Step; 5285 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5286 if (!Step->getType()->isIntegralType(Context)) { 5287 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5288 << Step << Step->getSourceRange(); 5289 IsCorrect = false; 5290 continue; 5291 } 5292 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5293 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5294 // If the step expression of a range-specification equals zero, the 5295 // behavior is unspecified. 5296 if (Result && Result->isZero()) { 5297 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5298 << Step << Step->getSourceRange(); 5299 IsCorrect = false; 5300 continue; 5301 } 5302 } 5303 if (!Begin || !End || !IsCorrect) { 5304 IsCorrect = false; 5305 continue; 5306 } 5307 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5308 IDElem.IteratorDecl = VD; 5309 IDElem.AssignmentLoc = D.AssignLoc; 5310 IDElem.Range.Begin = Begin; 5311 IDElem.Range.End = End; 5312 IDElem.Range.Step = Step; 5313 IDElem.ColonLoc = D.ColonLoc; 5314 IDElem.SecondColonLoc = D.SecColonLoc; 5315 } 5316 if (!IsCorrect) { 5317 // Invalidate all created iterator declarations if error is found. 5318 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5319 if (Decl *ID = D.IteratorDecl) 5320 ID->setInvalidDecl(); 5321 } 5322 return ExprError(); 5323 } 5324 SmallVector<OMPIteratorHelperData, 4> Helpers; 5325 if (!CurContext->isDependentContext()) { 5326 // Build number of ityeration for each iteration range. 5327 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5328 // ((Begini-Stepi-1-Endi) / -Stepi); 5329 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5330 // (Endi - Begini) 5331 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5332 D.Range.Begin); 5333 if(!Res.isUsable()) { 5334 IsCorrect = false; 5335 continue; 5336 } 5337 ExprResult St, St1; 5338 if (D.Range.Step) { 5339 St = D.Range.Step; 5340 // (Endi - Begini) + Stepi 5341 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5342 if (!Res.isUsable()) { 5343 IsCorrect = false; 5344 continue; 5345 } 5346 // (Endi - Begini) + Stepi - 1 5347 Res = 5348 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5349 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5350 if (!Res.isUsable()) { 5351 IsCorrect = false; 5352 continue; 5353 } 5354 // ((Endi - Begini) + Stepi - 1) / Stepi 5355 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5356 if (!Res.isUsable()) { 5357 IsCorrect = false; 5358 continue; 5359 } 5360 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5361 // (Begini - Endi) 5362 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5363 D.Range.Begin, D.Range.End); 5364 if (!Res1.isUsable()) { 5365 IsCorrect = false; 5366 continue; 5367 } 5368 // (Begini - Endi) - Stepi 5369 Res1 = 5370 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5371 if (!Res1.isUsable()) { 5372 IsCorrect = false; 5373 continue; 5374 } 5375 // (Begini - Endi) - Stepi - 1 5376 Res1 = 5377 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5378 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5379 if (!Res1.isUsable()) { 5380 IsCorrect = false; 5381 continue; 5382 } 5383 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5384 Res1 = 5385 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5386 if (!Res1.isUsable()) { 5387 IsCorrect = false; 5388 continue; 5389 } 5390 // Stepi > 0. 5391 ExprResult CmpRes = 5392 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5393 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5394 if (!CmpRes.isUsable()) { 5395 IsCorrect = false; 5396 continue; 5397 } 5398 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5399 Res.get(), Res1.get()); 5400 if (!Res.isUsable()) { 5401 IsCorrect = false; 5402 continue; 5403 } 5404 } 5405 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5406 if (!Res.isUsable()) { 5407 IsCorrect = false; 5408 continue; 5409 } 5410 5411 // Build counter update. 5412 // Build counter. 5413 auto *CounterVD = 5414 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5415 D.IteratorDecl->getBeginLoc(), nullptr, 5416 Res.get()->getType(), nullptr, SC_None); 5417 CounterVD->setImplicit(); 5418 ExprResult RefRes = 5419 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5420 D.IteratorDecl->getBeginLoc()); 5421 // Build counter update. 5422 // I = Begini + counter * Stepi; 5423 ExprResult UpdateRes; 5424 if (D.Range.Step) { 5425 UpdateRes = CreateBuiltinBinOp( 5426 D.AssignmentLoc, BO_Mul, 5427 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5428 } else { 5429 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5430 } 5431 if (!UpdateRes.isUsable()) { 5432 IsCorrect = false; 5433 continue; 5434 } 5435 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5436 UpdateRes.get()); 5437 if (!UpdateRes.isUsable()) { 5438 IsCorrect = false; 5439 continue; 5440 } 5441 ExprResult VDRes = 5442 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5443 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5444 D.IteratorDecl->getBeginLoc()); 5445 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5446 UpdateRes.get()); 5447 if (!UpdateRes.isUsable()) { 5448 IsCorrect = false; 5449 continue; 5450 } 5451 UpdateRes = 5452 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5453 if (!UpdateRes.isUsable()) { 5454 IsCorrect = false; 5455 continue; 5456 } 5457 ExprResult CounterUpdateRes = 5458 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5459 if (!CounterUpdateRes.isUsable()) { 5460 IsCorrect = false; 5461 continue; 5462 } 5463 CounterUpdateRes = 5464 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5465 if (!CounterUpdateRes.isUsable()) { 5466 IsCorrect = false; 5467 continue; 5468 } 5469 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5470 HD.CounterVD = CounterVD; 5471 HD.Upper = Res.get(); 5472 HD.Update = UpdateRes.get(); 5473 HD.CounterUpdate = CounterUpdateRes.get(); 5474 } 5475 } else { 5476 Helpers.assign(ID.size(), {}); 5477 } 5478 if (!IsCorrect) { 5479 // Invalidate all created iterator declarations if error is found. 5480 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5481 if (Decl *ID = D.IteratorDecl) 5482 ID->setInvalidDecl(); 5483 } 5484 return ExprError(); 5485 } 5486 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5487 LLoc, RLoc, ID, Helpers); 5488 } 5489 5490 ExprResult 5491 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5492 Expr *Idx, SourceLocation RLoc) { 5493 Expr *LHSExp = Base; 5494 Expr *RHSExp = Idx; 5495 5496 ExprValueKind VK = VK_LValue; 5497 ExprObjectKind OK = OK_Ordinary; 5498 5499 // Per C++ core issue 1213, the result is an xvalue if either operand is 5500 // a non-lvalue array, and an lvalue otherwise. 5501 if (getLangOpts().CPlusPlus11) { 5502 for (auto *Op : {LHSExp, RHSExp}) { 5503 Op = Op->IgnoreImplicit(); 5504 if (Op->getType()->isArrayType() && !Op->isLValue()) 5505 VK = VK_XValue; 5506 } 5507 } 5508 5509 // Perform default conversions. 5510 if (!LHSExp->getType()->getAs<VectorType>()) { 5511 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5512 if (Result.isInvalid()) 5513 return ExprError(); 5514 LHSExp = Result.get(); 5515 } 5516 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5517 if (Result.isInvalid()) 5518 return ExprError(); 5519 RHSExp = Result.get(); 5520 5521 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5522 5523 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5524 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5525 // in the subscript position. As a result, we need to derive the array base 5526 // and index from the expression types. 5527 Expr *BaseExpr, *IndexExpr; 5528 QualType ResultType; 5529 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5530 BaseExpr = LHSExp; 5531 IndexExpr = RHSExp; 5532 ResultType = 5533 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); 5534 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5535 BaseExpr = LHSExp; 5536 IndexExpr = RHSExp; 5537 ResultType = PTy->getPointeeType(); 5538 } else if (const ObjCObjectPointerType *PTy = 5539 LHSTy->getAs<ObjCObjectPointerType>()) { 5540 BaseExpr = LHSExp; 5541 IndexExpr = RHSExp; 5542 5543 // Use custom logic if this should be the pseudo-object subscript 5544 // expression. 5545 if (!LangOpts.isSubscriptPointerArithmetic()) 5546 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5547 nullptr); 5548 5549 ResultType = PTy->getPointeeType(); 5550 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5551 // Handle the uncommon case of "123[Ptr]". 5552 BaseExpr = RHSExp; 5553 IndexExpr = LHSExp; 5554 ResultType = PTy->getPointeeType(); 5555 } else if (const ObjCObjectPointerType *PTy = 5556 RHSTy->getAs<ObjCObjectPointerType>()) { 5557 // Handle the uncommon case of "123[Ptr]". 5558 BaseExpr = RHSExp; 5559 IndexExpr = LHSExp; 5560 ResultType = PTy->getPointeeType(); 5561 if (!LangOpts.isSubscriptPointerArithmetic()) { 5562 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5563 << ResultType << BaseExpr->getSourceRange(); 5564 return ExprError(); 5565 } 5566 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5567 BaseExpr = LHSExp; // vectors: V[123] 5568 IndexExpr = RHSExp; 5569 // We apply C++ DR1213 to vector subscripting too. 5570 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5571 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5572 if (Materialized.isInvalid()) 5573 return ExprError(); 5574 LHSExp = Materialized.get(); 5575 } 5576 VK = LHSExp->getValueKind(); 5577 if (VK != VK_PRValue) 5578 OK = OK_VectorComponent; 5579 5580 ResultType = VTy->getElementType(); 5581 QualType BaseType = BaseExpr->getType(); 5582 Qualifiers BaseQuals = BaseType.getQualifiers(); 5583 Qualifiers MemberQuals = ResultType.getQualifiers(); 5584 Qualifiers Combined = BaseQuals + MemberQuals; 5585 if (Combined != MemberQuals) 5586 ResultType = Context.getQualifiedType(ResultType, Combined); 5587 } else if (LHSTy->isArrayType()) { 5588 // If we see an array that wasn't promoted by 5589 // DefaultFunctionArrayLvalueConversion, it must be an array that 5590 // wasn't promoted because of the C90 rule that doesn't 5591 // allow promoting non-lvalue arrays. Warn, then 5592 // force the promotion here. 5593 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5594 << LHSExp->getSourceRange(); 5595 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5596 CK_ArrayToPointerDecay).get(); 5597 LHSTy = LHSExp->getType(); 5598 5599 BaseExpr = LHSExp; 5600 IndexExpr = RHSExp; 5601 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5602 } else if (RHSTy->isArrayType()) { 5603 // Same as previous, except for 123[f().a] case 5604 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5605 << RHSExp->getSourceRange(); 5606 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5607 CK_ArrayToPointerDecay).get(); 5608 RHSTy = RHSExp->getType(); 5609 5610 BaseExpr = RHSExp; 5611 IndexExpr = LHSExp; 5612 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5613 } else { 5614 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5615 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5616 } 5617 // C99 6.5.2.1p1 5618 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5619 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5620 << IndexExpr->getSourceRange()); 5621 5622 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5623 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5624 && !IndexExpr->isTypeDependent()) 5625 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5626 5627 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5628 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5629 // type. Note that Functions are not objects, and that (in C99 parlance) 5630 // incomplete types are not object types. 5631 if (ResultType->isFunctionType()) { 5632 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5633 << ResultType << BaseExpr->getSourceRange(); 5634 return ExprError(); 5635 } 5636 5637 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5638 // GNU extension: subscripting on pointer to void 5639 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5640 << BaseExpr->getSourceRange(); 5641 5642 // C forbids expressions of unqualified void type from being l-values. 5643 // See IsCForbiddenLValueType. 5644 if (!ResultType.hasQualifiers()) 5645 VK = VK_PRValue; 5646 } else if (!ResultType->isDependentType() && 5647 RequireCompleteSizedType( 5648 LLoc, ResultType, 5649 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5650 return ExprError(); 5651 5652 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5653 !ResultType.isCForbiddenLValueType()); 5654 5655 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5656 FunctionScopes.size() > 1) { 5657 if (auto *TT = 5658 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5659 for (auto I = FunctionScopes.rbegin(), 5660 E = std::prev(FunctionScopes.rend()); 5661 I != E; ++I) { 5662 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5663 if (CSI == nullptr) 5664 break; 5665 DeclContext *DC = nullptr; 5666 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5667 DC = LSI->CallOperator; 5668 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5669 DC = CRSI->TheCapturedDecl; 5670 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5671 DC = BSI->TheDecl; 5672 if (DC) { 5673 if (DC->containsDecl(TT->getDecl())) 5674 break; 5675 captureVariablyModifiedType( 5676 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5677 } 5678 } 5679 } 5680 } 5681 5682 return new (Context) 5683 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5684 } 5685 5686 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5687 ParmVarDecl *Param) { 5688 if (Param->hasUnparsedDefaultArg()) { 5689 // If we've already cleared out the location for the default argument, 5690 // that means we're parsing it right now. 5691 if (!UnparsedDefaultArgLocs.count(Param)) { 5692 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5693 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5694 Param->setInvalidDecl(); 5695 return true; 5696 } 5697 5698 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5699 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5700 Diag(UnparsedDefaultArgLocs[Param], 5701 diag::note_default_argument_declared_here); 5702 return true; 5703 } 5704 5705 if (Param->hasUninstantiatedDefaultArg() && 5706 InstantiateDefaultArgument(CallLoc, FD, Param)) 5707 return true; 5708 5709 assert(Param->hasInit() && "default argument but no initializer?"); 5710 5711 // If the default expression creates temporaries, we need to 5712 // push them to the current stack of expression temporaries so they'll 5713 // be properly destroyed. 5714 // FIXME: We should really be rebuilding the default argument with new 5715 // bound temporaries; see the comment in PR5810. 5716 // We don't need to do that with block decls, though, because 5717 // blocks in default argument expression can never capture anything. 5718 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5719 // Set the "needs cleanups" bit regardless of whether there are 5720 // any explicit objects. 5721 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5722 5723 // Append all the objects to the cleanup list. Right now, this 5724 // should always be a no-op, because blocks in default argument 5725 // expressions should never be able to capture anything. 5726 assert(!Init->getNumObjects() && 5727 "default argument expression has capturing blocks?"); 5728 } 5729 5730 // We already type-checked the argument, so we know it works. 5731 // Just mark all of the declarations in this potentially-evaluated expression 5732 // as being "referenced". 5733 EnterExpressionEvaluationContext EvalContext( 5734 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5735 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5736 /*SkipLocalVariables=*/true); 5737 return false; 5738 } 5739 5740 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5741 FunctionDecl *FD, ParmVarDecl *Param) { 5742 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5743 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5744 return ExprError(); 5745 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5746 } 5747 5748 Sema::VariadicCallType 5749 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5750 Expr *Fn) { 5751 if (Proto && Proto->isVariadic()) { 5752 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 5753 return VariadicConstructor; 5754 else if (Fn && Fn->getType()->isBlockPointerType()) 5755 return VariadicBlock; 5756 else if (FDecl) { 5757 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5758 if (Method->isInstance()) 5759 return VariadicMethod; 5760 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5761 return VariadicMethod; 5762 return VariadicFunction; 5763 } 5764 return VariadicDoesNotApply; 5765 } 5766 5767 namespace { 5768 class FunctionCallCCC final : public FunctionCallFilterCCC { 5769 public: 5770 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5771 unsigned NumArgs, MemberExpr *ME) 5772 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5773 FunctionName(FuncName) {} 5774 5775 bool ValidateCandidate(const TypoCorrection &candidate) override { 5776 if (!candidate.getCorrectionSpecifier() || 5777 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5778 return false; 5779 } 5780 5781 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5782 } 5783 5784 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5785 return std::make_unique<FunctionCallCCC>(*this); 5786 } 5787 5788 private: 5789 const IdentifierInfo *const FunctionName; 5790 }; 5791 } 5792 5793 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5794 FunctionDecl *FDecl, 5795 ArrayRef<Expr *> Args) { 5796 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5797 DeclarationName FuncName = FDecl->getDeclName(); 5798 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5799 5800 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5801 if (TypoCorrection Corrected = S.CorrectTypo( 5802 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5803 S.getScopeForContext(S.CurContext), nullptr, CCC, 5804 Sema::CTK_ErrorRecovery)) { 5805 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5806 if (Corrected.isOverloaded()) { 5807 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5808 OverloadCandidateSet::iterator Best; 5809 for (NamedDecl *CD : Corrected) { 5810 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5811 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5812 OCS); 5813 } 5814 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5815 case OR_Success: 5816 ND = Best->FoundDecl; 5817 Corrected.setCorrectionDecl(ND); 5818 break; 5819 default: 5820 break; 5821 } 5822 } 5823 ND = ND->getUnderlyingDecl(); 5824 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5825 return Corrected; 5826 } 5827 } 5828 return TypoCorrection(); 5829 } 5830 5831 /// ConvertArgumentsForCall - Converts the arguments specified in 5832 /// Args/NumArgs to the parameter types of the function FDecl with 5833 /// function prototype Proto. Call is the call expression itself, and 5834 /// Fn is the function expression. For a C++ member function, this 5835 /// routine does not attempt to convert the object argument. Returns 5836 /// true if the call is ill-formed. 5837 bool 5838 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5839 FunctionDecl *FDecl, 5840 const FunctionProtoType *Proto, 5841 ArrayRef<Expr *> Args, 5842 SourceLocation RParenLoc, 5843 bool IsExecConfig) { 5844 // Bail out early if calling a builtin with custom typechecking. 5845 if (FDecl) 5846 if (unsigned ID = FDecl->getBuiltinID()) 5847 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5848 return false; 5849 5850 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5851 // assignment, to the types of the corresponding parameter, ... 5852 unsigned NumParams = Proto->getNumParams(); 5853 bool Invalid = false; 5854 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5855 unsigned FnKind = Fn->getType()->isBlockPointerType() 5856 ? 1 /* block */ 5857 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5858 : 0 /* function */); 5859 5860 // If too few arguments are available (and we don't have default 5861 // arguments for the remaining parameters), don't make the call. 5862 if (Args.size() < NumParams) { 5863 if (Args.size() < MinArgs) { 5864 TypoCorrection TC; 5865 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5866 unsigned diag_id = 5867 MinArgs == NumParams && !Proto->isVariadic() 5868 ? diag::err_typecheck_call_too_few_args_suggest 5869 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5870 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5871 << static_cast<unsigned>(Args.size()) 5872 << TC.getCorrectionRange()); 5873 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5874 Diag(RParenLoc, 5875 MinArgs == NumParams && !Proto->isVariadic() 5876 ? diag::err_typecheck_call_too_few_args_one 5877 : diag::err_typecheck_call_too_few_args_at_least_one) 5878 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5879 else 5880 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5881 ? diag::err_typecheck_call_too_few_args 5882 : diag::err_typecheck_call_too_few_args_at_least) 5883 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5884 << Fn->getSourceRange(); 5885 5886 // Emit the location of the prototype. 5887 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5888 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5889 5890 return true; 5891 } 5892 // We reserve space for the default arguments when we create 5893 // the call expression, before calling ConvertArgumentsForCall. 5894 assert((Call->getNumArgs() == NumParams) && 5895 "We should have reserved space for the default arguments before!"); 5896 } 5897 5898 // If too many are passed and not variadic, error on the extras and drop 5899 // them. 5900 if (Args.size() > NumParams) { 5901 if (!Proto->isVariadic()) { 5902 TypoCorrection TC; 5903 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5904 unsigned diag_id = 5905 MinArgs == NumParams && !Proto->isVariadic() 5906 ? diag::err_typecheck_call_too_many_args_suggest 5907 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5908 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5909 << static_cast<unsigned>(Args.size()) 5910 << TC.getCorrectionRange()); 5911 } else if (NumParams == 1 && FDecl && 5912 FDecl->getParamDecl(0)->getDeclName()) 5913 Diag(Args[NumParams]->getBeginLoc(), 5914 MinArgs == NumParams 5915 ? diag::err_typecheck_call_too_many_args_one 5916 : diag::err_typecheck_call_too_many_args_at_most_one) 5917 << FnKind << FDecl->getParamDecl(0) 5918 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5919 << SourceRange(Args[NumParams]->getBeginLoc(), 5920 Args.back()->getEndLoc()); 5921 else 5922 Diag(Args[NumParams]->getBeginLoc(), 5923 MinArgs == NumParams 5924 ? diag::err_typecheck_call_too_many_args 5925 : diag::err_typecheck_call_too_many_args_at_most) 5926 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5927 << Fn->getSourceRange() 5928 << SourceRange(Args[NumParams]->getBeginLoc(), 5929 Args.back()->getEndLoc()); 5930 5931 // Emit the location of the prototype. 5932 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5933 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5934 5935 // This deletes the extra arguments. 5936 Call->shrinkNumArgs(NumParams); 5937 return true; 5938 } 5939 } 5940 SmallVector<Expr *, 8> AllArgs; 5941 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5942 5943 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5944 AllArgs, CallType); 5945 if (Invalid) 5946 return true; 5947 unsigned TotalNumArgs = AllArgs.size(); 5948 for (unsigned i = 0; i < TotalNumArgs; ++i) 5949 Call->setArg(i, AllArgs[i]); 5950 5951 Call->computeDependence(); 5952 return false; 5953 } 5954 5955 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5956 const FunctionProtoType *Proto, 5957 unsigned FirstParam, ArrayRef<Expr *> Args, 5958 SmallVectorImpl<Expr *> &AllArgs, 5959 VariadicCallType CallType, bool AllowExplicit, 5960 bool IsListInitialization) { 5961 unsigned NumParams = Proto->getNumParams(); 5962 bool Invalid = false; 5963 size_t ArgIx = 0; 5964 // Continue to check argument types (even if we have too few/many args). 5965 for (unsigned i = FirstParam; i < NumParams; i++) { 5966 QualType ProtoArgType = Proto->getParamType(i); 5967 5968 Expr *Arg; 5969 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5970 if (ArgIx < Args.size()) { 5971 Arg = Args[ArgIx++]; 5972 5973 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5974 diag::err_call_incomplete_argument, Arg)) 5975 return true; 5976 5977 // Strip the unbridged-cast placeholder expression off, if applicable. 5978 bool CFAudited = false; 5979 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5980 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5981 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5982 Arg = stripARCUnbridgedCast(Arg); 5983 else if (getLangOpts().ObjCAutoRefCount && 5984 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5985 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5986 CFAudited = true; 5987 5988 if (Proto->getExtParameterInfo(i).isNoEscape() && 5989 ProtoArgType->isBlockPointerType()) 5990 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5991 BE->getBlockDecl()->setDoesNotEscape(); 5992 5993 InitializedEntity Entity = 5994 Param ? InitializedEntity::InitializeParameter(Context, Param, 5995 ProtoArgType) 5996 : InitializedEntity::InitializeParameter( 5997 Context, ProtoArgType, Proto->isParamConsumed(i)); 5998 5999 // Remember that parameter belongs to a CF audited API. 6000 if (CFAudited) 6001 Entity.setParameterCFAudited(); 6002 6003 ExprResult ArgE = PerformCopyInitialization( 6004 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 6005 if (ArgE.isInvalid()) 6006 return true; 6007 6008 Arg = ArgE.getAs<Expr>(); 6009 } else { 6010 assert(Param && "can't use default arguments without a known callee"); 6011 6012 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 6013 if (ArgExpr.isInvalid()) 6014 return true; 6015 6016 Arg = ArgExpr.getAs<Expr>(); 6017 } 6018 6019 // Check for array bounds violations for each argument to the call. This 6020 // check only triggers warnings when the argument isn't a more complex Expr 6021 // with its own checking, such as a BinaryOperator. 6022 CheckArrayAccess(Arg); 6023 6024 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6025 CheckStaticArrayArgument(CallLoc, Param, Arg); 6026 6027 AllArgs.push_back(Arg); 6028 } 6029 6030 // If this is a variadic call, handle args passed through "...". 6031 if (CallType != VariadicDoesNotApply) { 6032 // Assume that extern "C" functions with variadic arguments that 6033 // return __unknown_anytype aren't *really* variadic. 6034 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6035 FDecl->isExternC()) { 6036 for (Expr *A : Args.slice(ArgIx)) { 6037 QualType paramType; // ignored 6038 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6039 Invalid |= arg.isInvalid(); 6040 AllArgs.push_back(arg.get()); 6041 } 6042 6043 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6044 } else { 6045 for (Expr *A : Args.slice(ArgIx)) { 6046 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6047 Invalid |= Arg.isInvalid(); 6048 AllArgs.push_back(Arg.get()); 6049 } 6050 } 6051 6052 // Check for array bounds violations. 6053 for (Expr *A : Args.slice(ArgIx)) 6054 CheckArrayAccess(A); 6055 } 6056 return Invalid; 6057 } 6058 6059 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6060 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6061 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6062 TL = DTL.getOriginalLoc(); 6063 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6064 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6065 << ATL.getLocalSourceRange(); 6066 } 6067 6068 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6069 /// array parameter, check that it is non-null, and that if it is formed by 6070 /// array-to-pointer decay, the underlying array is sufficiently large. 6071 /// 6072 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6073 /// array type derivation, then for each call to the function, the value of the 6074 /// corresponding actual argument shall provide access to the first element of 6075 /// an array with at least as many elements as specified by the size expression. 6076 void 6077 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6078 ParmVarDecl *Param, 6079 const Expr *ArgExpr) { 6080 // Static array parameters are not supported in C++. 6081 if (!Param || getLangOpts().CPlusPlus) 6082 return; 6083 6084 QualType OrigTy = Param->getOriginalType(); 6085 6086 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6087 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6088 return; 6089 6090 if (ArgExpr->isNullPointerConstant(Context, 6091 Expr::NPC_NeverValueDependent)) { 6092 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6093 DiagnoseCalleeStaticArrayParam(*this, Param); 6094 return; 6095 } 6096 6097 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6098 if (!CAT) 6099 return; 6100 6101 const ConstantArrayType *ArgCAT = 6102 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6103 if (!ArgCAT) 6104 return; 6105 6106 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6107 ArgCAT->getElementType())) { 6108 if (ArgCAT->getSize().ult(CAT->getSize())) { 6109 Diag(CallLoc, diag::warn_static_array_too_small) 6110 << ArgExpr->getSourceRange() 6111 << (unsigned)ArgCAT->getSize().getZExtValue() 6112 << (unsigned)CAT->getSize().getZExtValue() << 0; 6113 DiagnoseCalleeStaticArrayParam(*this, Param); 6114 } 6115 return; 6116 } 6117 6118 Optional<CharUnits> ArgSize = 6119 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6120 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6121 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6122 Diag(CallLoc, diag::warn_static_array_too_small) 6123 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6124 << (unsigned)ParmSize->getQuantity() << 1; 6125 DiagnoseCalleeStaticArrayParam(*this, Param); 6126 } 6127 } 6128 6129 /// Given a function expression of unknown-any type, try to rebuild it 6130 /// to have a function type. 6131 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6132 6133 /// Is the given type a placeholder that we need to lower out 6134 /// immediately during argument processing? 6135 static bool isPlaceholderToRemoveAsArg(QualType type) { 6136 // Placeholders are never sugared. 6137 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6138 if (!placeholder) return false; 6139 6140 switch (placeholder->getKind()) { 6141 // Ignore all the non-placeholder types. 6142 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6143 case BuiltinType::Id: 6144 #include "clang/Basic/OpenCLImageTypes.def" 6145 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6146 case BuiltinType::Id: 6147 #include "clang/Basic/OpenCLExtensionTypes.def" 6148 // In practice we'll never use this, since all SVE types are sugared 6149 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6150 #define SVE_TYPE(Name, Id, SingletonId) \ 6151 case BuiltinType::Id: 6152 #include "clang/Basic/AArch64SVEACLETypes.def" 6153 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6154 case BuiltinType::Id: 6155 #include "clang/Basic/PPCTypes.def" 6156 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6157 #include "clang/Basic/RISCVVTypes.def" 6158 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6159 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6160 #include "clang/AST/BuiltinTypes.def" 6161 return false; 6162 6163 // We cannot lower out overload sets; they might validly be resolved 6164 // by the call machinery. 6165 case BuiltinType::Overload: 6166 return false; 6167 6168 // Unbridged casts in ARC can be handled in some call positions and 6169 // should be left in place. 6170 case BuiltinType::ARCUnbridgedCast: 6171 return false; 6172 6173 // Pseudo-objects should be converted as soon as possible. 6174 case BuiltinType::PseudoObject: 6175 return true; 6176 6177 // The debugger mode could theoretically but currently does not try 6178 // to resolve unknown-typed arguments based on known parameter types. 6179 case BuiltinType::UnknownAny: 6180 return true; 6181 6182 // These are always invalid as call arguments and should be reported. 6183 case BuiltinType::BoundMember: 6184 case BuiltinType::BuiltinFn: 6185 case BuiltinType::IncompleteMatrixIdx: 6186 case BuiltinType::OMPArraySection: 6187 case BuiltinType::OMPArrayShaping: 6188 case BuiltinType::OMPIterator: 6189 return true; 6190 6191 } 6192 llvm_unreachable("bad builtin type kind"); 6193 } 6194 6195 /// Check an argument list for placeholders that we won't try to 6196 /// handle later. 6197 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6198 // Apply this processing to all the arguments at once instead of 6199 // dying at the first failure. 6200 bool hasInvalid = false; 6201 for (size_t i = 0, e = args.size(); i != e; i++) { 6202 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6203 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6204 if (result.isInvalid()) hasInvalid = true; 6205 else args[i] = result.get(); 6206 } 6207 } 6208 return hasInvalid; 6209 } 6210 6211 /// If a builtin function has a pointer argument with no explicit address 6212 /// space, then it should be able to accept a pointer to any address 6213 /// space as input. In order to do this, we need to replace the 6214 /// standard builtin declaration with one that uses the same address space 6215 /// as the call. 6216 /// 6217 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6218 /// it does not contain any pointer arguments without 6219 /// an address space qualifer. Otherwise the rewritten 6220 /// FunctionDecl is returned. 6221 /// TODO: Handle pointer return types. 6222 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6223 FunctionDecl *FDecl, 6224 MultiExprArg ArgExprs) { 6225 6226 QualType DeclType = FDecl->getType(); 6227 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6228 6229 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6230 ArgExprs.size() < FT->getNumParams()) 6231 return nullptr; 6232 6233 bool NeedsNewDecl = false; 6234 unsigned i = 0; 6235 SmallVector<QualType, 8> OverloadParams; 6236 6237 for (QualType ParamType : FT->param_types()) { 6238 6239 // Convert array arguments to pointer to simplify type lookup. 6240 ExprResult ArgRes = 6241 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6242 if (ArgRes.isInvalid()) 6243 return nullptr; 6244 Expr *Arg = ArgRes.get(); 6245 QualType ArgType = Arg->getType(); 6246 if (!ParamType->isPointerType() || 6247 ParamType.hasAddressSpace() || 6248 !ArgType->isPointerType() || 6249 !ArgType->getPointeeType().hasAddressSpace()) { 6250 OverloadParams.push_back(ParamType); 6251 continue; 6252 } 6253 6254 QualType PointeeType = ParamType->getPointeeType(); 6255 if (PointeeType.hasAddressSpace()) 6256 continue; 6257 6258 NeedsNewDecl = true; 6259 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6260 6261 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6262 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6263 } 6264 6265 if (!NeedsNewDecl) 6266 return nullptr; 6267 6268 FunctionProtoType::ExtProtoInfo EPI; 6269 EPI.Variadic = FT->isVariadic(); 6270 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6271 OverloadParams, EPI); 6272 DeclContext *Parent = FDecl->getParent(); 6273 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6274 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6275 FDecl->getIdentifier(), OverloadTy, 6276 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6277 false, 6278 /*hasPrototype=*/true); 6279 SmallVector<ParmVarDecl*, 16> Params; 6280 FT = cast<FunctionProtoType>(OverloadTy); 6281 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6282 QualType ParamType = FT->getParamType(i); 6283 ParmVarDecl *Parm = 6284 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6285 SourceLocation(), nullptr, ParamType, 6286 /*TInfo=*/nullptr, SC_None, nullptr); 6287 Parm->setScopeInfo(0, i); 6288 Params.push_back(Parm); 6289 } 6290 OverloadDecl->setParams(Params); 6291 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6292 return OverloadDecl; 6293 } 6294 6295 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6296 FunctionDecl *Callee, 6297 MultiExprArg ArgExprs) { 6298 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6299 // similar attributes) really don't like it when functions are called with an 6300 // invalid number of args. 6301 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6302 /*PartialOverloading=*/false) && 6303 !Callee->isVariadic()) 6304 return; 6305 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6306 return; 6307 6308 if (const EnableIfAttr *Attr = 6309 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6310 S.Diag(Fn->getBeginLoc(), 6311 isa<CXXMethodDecl>(Callee) 6312 ? diag::err_ovl_no_viable_member_function_in_call 6313 : diag::err_ovl_no_viable_function_in_call) 6314 << Callee << Callee->getSourceRange(); 6315 S.Diag(Callee->getLocation(), 6316 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6317 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6318 return; 6319 } 6320 } 6321 6322 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6323 const UnresolvedMemberExpr *const UME, Sema &S) { 6324 6325 const auto GetFunctionLevelDCIfCXXClass = 6326 [](Sema &S) -> const CXXRecordDecl * { 6327 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6328 if (!DC || !DC->getParent()) 6329 return nullptr; 6330 6331 // If the call to some member function was made from within a member 6332 // function body 'M' return return 'M's parent. 6333 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6334 return MD->getParent()->getCanonicalDecl(); 6335 // else the call was made from within a default member initializer of a 6336 // class, so return the class. 6337 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6338 return RD->getCanonicalDecl(); 6339 return nullptr; 6340 }; 6341 // If our DeclContext is neither a member function nor a class (in the 6342 // case of a lambda in a default member initializer), we can't have an 6343 // enclosing 'this'. 6344 6345 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6346 if (!CurParentClass) 6347 return false; 6348 6349 // The naming class for implicit member functions call is the class in which 6350 // name lookup starts. 6351 const CXXRecordDecl *const NamingClass = 6352 UME->getNamingClass()->getCanonicalDecl(); 6353 assert(NamingClass && "Must have naming class even for implicit access"); 6354 6355 // If the unresolved member functions were found in a 'naming class' that is 6356 // related (either the same or derived from) to the class that contains the 6357 // member function that itself contained the implicit member access. 6358 6359 return CurParentClass == NamingClass || 6360 CurParentClass->isDerivedFrom(NamingClass); 6361 } 6362 6363 static void 6364 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6365 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6366 6367 if (!UME) 6368 return; 6369 6370 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6371 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6372 // already been captured, or if this is an implicit member function call (if 6373 // it isn't, an attempt to capture 'this' should already have been made). 6374 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6375 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6376 return; 6377 6378 // Check if the naming class in which the unresolved members were found is 6379 // related (same as or is a base of) to the enclosing class. 6380 6381 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6382 return; 6383 6384 6385 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6386 // If the enclosing function is not dependent, then this lambda is 6387 // capture ready, so if we can capture this, do so. 6388 if (!EnclosingFunctionCtx->isDependentContext()) { 6389 // If the current lambda and all enclosing lambdas can capture 'this' - 6390 // then go ahead and capture 'this' (since our unresolved overload set 6391 // contains at least one non-static member function). 6392 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6393 S.CheckCXXThisCapture(CallLoc); 6394 } else if (S.CurContext->isDependentContext()) { 6395 // ... since this is an implicit member reference, that might potentially 6396 // involve a 'this' capture, mark 'this' for potential capture in 6397 // enclosing lambdas. 6398 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6399 CurLSI->addPotentialThisCapture(CallLoc); 6400 } 6401 } 6402 6403 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6404 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6405 Expr *ExecConfig) { 6406 ExprResult Call = 6407 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6408 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6409 if (Call.isInvalid()) 6410 return Call; 6411 6412 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6413 // language modes. 6414 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6415 if (ULE->hasExplicitTemplateArgs() && 6416 ULE->decls_begin() == ULE->decls_end()) { 6417 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6418 ? diag::warn_cxx17_compat_adl_only_template_id 6419 : diag::ext_adl_only_template_id) 6420 << ULE->getName(); 6421 } 6422 } 6423 6424 if (LangOpts.OpenMP) 6425 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6426 ExecConfig); 6427 6428 return Call; 6429 } 6430 6431 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6432 /// This provides the location of the left/right parens and a list of comma 6433 /// locations. 6434 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6435 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6436 Expr *ExecConfig, bool IsExecConfig, 6437 bool AllowRecovery) { 6438 // Since this might be a postfix expression, get rid of ParenListExprs. 6439 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6440 if (Result.isInvalid()) return ExprError(); 6441 Fn = Result.get(); 6442 6443 if (checkArgsForPlaceholders(*this, ArgExprs)) 6444 return ExprError(); 6445 6446 if (getLangOpts().CPlusPlus) { 6447 // If this is a pseudo-destructor expression, build the call immediately. 6448 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6449 if (!ArgExprs.empty()) { 6450 // Pseudo-destructor calls should not have any arguments. 6451 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6452 << FixItHint::CreateRemoval( 6453 SourceRange(ArgExprs.front()->getBeginLoc(), 6454 ArgExprs.back()->getEndLoc())); 6455 } 6456 6457 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6458 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6459 } 6460 if (Fn->getType() == Context.PseudoObjectTy) { 6461 ExprResult result = CheckPlaceholderExpr(Fn); 6462 if (result.isInvalid()) return ExprError(); 6463 Fn = result.get(); 6464 } 6465 6466 // Determine whether this is a dependent call inside a C++ template, 6467 // in which case we won't do any semantic analysis now. 6468 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6469 if (ExecConfig) { 6470 return CUDAKernelCallExpr::Create(Context, Fn, 6471 cast<CallExpr>(ExecConfig), ArgExprs, 6472 Context.DependentTy, VK_PRValue, 6473 RParenLoc, CurFPFeatureOverrides()); 6474 } else { 6475 6476 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6477 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6478 Fn->getBeginLoc()); 6479 6480 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6481 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6482 } 6483 } 6484 6485 // Determine whether this is a call to an object (C++ [over.call.object]). 6486 if (Fn->getType()->isRecordType()) 6487 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6488 RParenLoc); 6489 6490 if (Fn->getType() == Context.UnknownAnyTy) { 6491 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6492 if (result.isInvalid()) return ExprError(); 6493 Fn = result.get(); 6494 } 6495 6496 if (Fn->getType() == Context.BoundMemberTy) { 6497 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6498 RParenLoc, ExecConfig, IsExecConfig, 6499 AllowRecovery); 6500 } 6501 } 6502 6503 // Check for overloaded calls. This can happen even in C due to extensions. 6504 if (Fn->getType() == Context.OverloadTy) { 6505 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6506 6507 // We aren't supposed to apply this logic if there's an '&' involved. 6508 if (!find.HasFormOfMemberPointer) { 6509 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6510 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6511 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6512 OverloadExpr *ovl = find.Expression; 6513 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6514 return BuildOverloadedCallExpr( 6515 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6516 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6517 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6518 RParenLoc, ExecConfig, IsExecConfig, 6519 AllowRecovery); 6520 } 6521 } 6522 6523 // If we're directly calling a function, get the appropriate declaration. 6524 if (Fn->getType() == Context.UnknownAnyTy) { 6525 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6526 if (result.isInvalid()) return ExprError(); 6527 Fn = result.get(); 6528 } 6529 6530 Expr *NakedFn = Fn->IgnoreParens(); 6531 6532 bool CallingNDeclIndirectly = false; 6533 NamedDecl *NDecl = nullptr; 6534 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6535 if (UnOp->getOpcode() == UO_AddrOf) { 6536 CallingNDeclIndirectly = true; 6537 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6538 } 6539 } 6540 6541 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6542 NDecl = DRE->getDecl(); 6543 6544 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6545 if (FDecl && FDecl->getBuiltinID()) { 6546 // Rewrite the function decl for this builtin by replacing parameters 6547 // with no explicit address space with the address space of the arguments 6548 // in ArgExprs. 6549 if ((FDecl = 6550 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6551 NDecl = FDecl; 6552 Fn = DeclRefExpr::Create( 6553 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6554 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6555 nullptr, DRE->isNonOdrUse()); 6556 } 6557 } 6558 } else if (isa<MemberExpr>(NakedFn)) 6559 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6560 6561 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6562 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6563 FD, /*Complain=*/true, Fn->getBeginLoc())) 6564 return ExprError(); 6565 6566 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6567 6568 // If this expression is a call to a builtin function in HIP device 6569 // compilation, allow a pointer-type argument to default address space to be 6570 // passed as a pointer-type parameter to a non-default address space. 6571 // If Arg is declared in the default address space and Param is declared 6572 // in a non-default address space, perform an implicit address space cast to 6573 // the parameter type. 6574 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6575 FD->getBuiltinID()) { 6576 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6577 ParmVarDecl *Param = FD->getParamDecl(Idx); 6578 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6579 !ArgExprs[Idx]->getType()->isPointerType()) 6580 continue; 6581 6582 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6583 auto ArgTy = ArgExprs[Idx]->getType(); 6584 auto ArgPtTy = ArgTy->getPointeeType(); 6585 auto ArgAS = ArgPtTy.getAddressSpace(); 6586 6587 // Add address space cast if target address spaces are different 6588 bool NeedImplicitASC = 6589 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 6590 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 6591 // or from specific AS which has target AS matching that of Param. 6592 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 6593 if (!NeedImplicitASC) 6594 continue; 6595 6596 // First, ensure that the Arg is an RValue. 6597 if (ArgExprs[Idx]->isGLValue()) { 6598 ArgExprs[Idx] = ImplicitCastExpr::Create( 6599 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6600 nullptr, VK_PRValue, FPOptionsOverride()); 6601 } 6602 6603 // Construct a new arg type with address space of Param 6604 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6605 ArgPtQuals.setAddressSpace(ParamAS); 6606 auto NewArgPtTy = 6607 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6608 auto NewArgTy = 6609 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6610 ArgTy.getQualifiers()); 6611 6612 // Finally perform an implicit address space cast 6613 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6614 CK_AddressSpaceConversion) 6615 .get(); 6616 } 6617 } 6618 } 6619 6620 if (Context.isDependenceAllowed() && 6621 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6622 assert(!getLangOpts().CPlusPlus); 6623 assert((Fn->containsErrors() || 6624 llvm::any_of(ArgExprs, 6625 [](clang::Expr *E) { return E->containsErrors(); })) && 6626 "should only occur in error-recovery path."); 6627 QualType ReturnType = 6628 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6629 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6630 : Context.DependentTy; 6631 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6632 Expr::getValueKindForType(ReturnType), RParenLoc, 6633 CurFPFeatureOverrides()); 6634 } 6635 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6636 ExecConfig, IsExecConfig); 6637 } 6638 6639 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6640 // with the specified CallArgs 6641 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6642 MultiExprArg CallArgs) { 6643 StringRef Name = Context.BuiltinInfo.getName(Id); 6644 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6645 Sema::LookupOrdinaryName); 6646 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6647 6648 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6649 assert(BuiltInDecl && "failed to find builtin declaration"); 6650 6651 ExprResult DeclRef = 6652 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6653 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6654 6655 ExprResult Call = 6656 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6657 6658 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6659 return Call.get(); 6660 } 6661 6662 /// Parse a __builtin_astype expression. 6663 /// 6664 /// __builtin_astype( value, dst type ) 6665 /// 6666 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6667 SourceLocation BuiltinLoc, 6668 SourceLocation RParenLoc) { 6669 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6670 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6671 } 6672 6673 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6674 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6675 SourceLocation BuiltinLoc, 6676 SourceLocation RParenLoc) { 6677 ExprValueKind VK = VK_PRValue; 6678 ExprObjectKind OK = OK_Ordinary; 6679 QualType SrcTy = E->getType(); 6680 if (!SrcTy->isDependentType() && 6681 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6682 return ExprError( 6683 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6684 << DestTy << SrcTy << E->getSourceRange()); 6685 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6686 } 6687 6688 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6689 /// provided arguments. 6690 /// 6691 /// __builtin_convertvector( value, dst type ) 6692 /// 6693 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6694 SourceLocation BuiltinLoc, 6695 SourceLocation RParenLoc) { 6696 TypeSourceInfo *TInfo; 6697 GetTypeFromParser(ParsedDestTy, &TInfo); 6698 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6699 } 6700 6701 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6702 /// i.e. an expression not of \p OverloadTy. The expression should 6703 /// unary-convert to an expression of function-pointer or 6704 /// block-pointer type. 6705 /// 6706 /// \param NDecl the declaration being called, if available 6707 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6708 SourceLocation LParenLoc, 6709 ArrayRef<Expr *> Args, 6710 SourceLocation RParenLoc, Expr *Config, 6711 bool IsExecConfig, ADLCallKind UsesADL) { 6712 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6713 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6714 6715 // Functions with 'interrupt' attribute cannot be called directly. 6716 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6717 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6718 return ExprError(); 6719 } 6720 6721 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6722 // so there's some risk when calling out to non-interrupt handler functions 6723 // that the callee might not preserve them. This is easy to diagnose here, 6724 // but can be very challenging to debug. 6725 // Likewise, X86 interrupt handlers may only call routines with attribute 6726 // no_caller_saved_registers since there is no efficient way to 6727 // save and restore the non-GPR state. 6728 if (auto *Caller = getCurFunctionDecl()) { 6729 if (Caller->hasAttr<ARMInterruptAttr>()) { 6730 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6731 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6732 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6733 if (FDecl) 6734 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6735 } 6736 } 6737 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6738 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6739 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6740 if (FDecl) 6741 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6742 } 6743 } 6744 6745 // Promote the function operand. 6746 // We special-case function promotion here because we only allow promoting 6747 // builtin functions to function pointers in the callee of a call. 6748 ExprResult Result; 6749 QualType ResultTy; 6750 if (BuiltinID && 6751 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6752 // Extract the return type from the (builtin) function pointer type. 6753 // FIXME Several builtins still have setType in 6754 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6755 // Builtins.def to ensure they are correct before removing setType calls. 6756 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6757 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6758 ResultTy = FDecl->getCallResultType(); 6759 } else { 6760 Result = CallExprUnaryConversions(Fn); 6761 ResultTy = Context.BoolTy; 6762 } 6763 if (Result.isInvalid()) 6764 return ExprError(); 6765 Fn = Result.get(); 6766 6767 // Check for a valid function type, but only if it is not a builtin which 6768 // requires custom type checking. These will be handled by 6769 // CheckBuiltinFunctionCall below just after creation of the call expression. 6770 const FunctionType *FuncT = nullptr; 6771 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6772 retry: 6773 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6774 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6775 // have type pointer to function". 6776 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6777 if (!FuncT) 6778 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6779 << Fn->getType() << Fn->getSourceRange()); 6780 } else if (const BlockPointerType *BPT = 6781 Fn->getType()->getAs<BlockPointerType>()) { 6782 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6783 } else { 6784 // Handle calls to expressions of unknown-any type. 6785 if (Fn->getType() == Context.UnknownAnyTy) { 6786 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6787 if (rewrite.isInvalid()) 6788 return ExprError(); 6789 Fn = rewrite.get(); 6790 goto retry; 6791 } 6792 6793 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6794 << Fn->getType() << Fn->getSourceRange()); 6795 } 6796 } 6797 6798 // Get the number of parameters in the function prototype, if any. 6799 // We will allocate space for max(Args.size(), NumParams) arguments 6800 // in the call expression. 6801 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6802 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6803 6804 CallExpr *TheCall; 6805 if (Config) { 6806 assert(UsesADL == ADLCallKind::NotADL && 6807 "CUDAKernelCallExpr should not use ADL"); 6808 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6809 Args, ResultTy, VK_PRValue, RParenLoc, 6810 CurFPFeatureOverrides(), NumParams); 6811 } else { 6812 TheCall = 6813 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6814 CurFPFeatureOverrides(), NumParams, UsesADL); 6815 } 6816 6817 if (!Context.isDependenceAllowed()) { 6818 // Forget about the nulled arguments since typo correction 6819 // do not handle them well. 6820 TheCall->shrinkNumArgs(Args.size()); 6821 // C cannot always handle TypoExpr nodes in builtin calls and direct 6822 // function calls as their argument checking don't necessarily handle 6823 // dependent types properly, so make sure any TypoExprs have been 6824 // dealt with. 6825 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6826 if (!Result.isUsable()) return ExprError(); 6827 CallExpr *TheOldCall = TheCall; 6828 TheCall = dyn_cast<CallExpr>(Result.get()); 6829 bool CorrectedTypos = TheCall != TheOldCall; 6830 if (!TheCall) return Result; 6831 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6832 6833 // A new call expression node was created if some typos were corrected. 6834 // However it may not have been constructed with enough storage. In this 6835 // case, rebuild the node with enough storage. The waste of space is 6836 // immaterial since this only happens when some typos were corrected. 6837 if (CorrectedTypos && Args.size() < NumParams) { 6838 if (Config) 6839 TheCall = CUDAKernelCallExpr::Create( 6840 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6841 RParenLoc, CurFPFeatureOverrides(), NumParams); 6842 else 6843 TheCall = 6844 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6845 CurFPFeatureOverrides(), NumParams, UsesADL); 6846 } 6847 // We can now handle the nulled arguments for the default arguments. 6848 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6849 } 6850 6851 // Bail out early if calling a builtin with custom type checking. 6852 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6853 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6854 6855 if (getLangOpts().CUDA) { 6856 if (Config) { 6857 // CUDA: Kernel calls must be to global functions 6858 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6859 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6860 << FDecl << Fn->getSourceRange()); 6861 6862 // CUDA: Kernel function must have 'void' return type 6863 if (!FuncT->getReturnType()->isVoidType() && 6864 !FuncT->getReturnType()->getAs<AutoType>() && 6865 !FuncT->getReturnType()->isInstantiationDependentType()) 6866 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6867 << Fn->getType() << Fn->getSourceRange()); 6868 } else { 6869 // CUDA: Calls to global functions must be configured 6870 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6871 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6872 << FDecl << Fn->getSourceRange()); 6873 } 6874 } 6875 6876 // Check for a valid return type 6877 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6878 FDecl)) 6879 return ExprError(); 6880 6881 // We know the result type of the call, set it. 6882 TheCall->setType(FuncT->getCallResultType(Context)); 6883 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6884 6885 if (Proto) { 6886 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6887 IsExecConfig)) 6888 return ExprError(); 6889 } else { 6890 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6891 6892 if (FDecl) { 6893 // Check if we have too few/too many template arguments, based 6894 // on our knowledge of the function definition. 6895 const FunctionDecl *Def = nullptr; 6896 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6897 Proto = Def->getType()->getAs<FunctionProtoType>(); 6898 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6899 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6900 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6901 } 6902 6903 // If the function we're calling isn't a function prototype, but we have 6904 // a function prototype from a prior declaratiom, use that prototype. 6905 if (!FDecl->hasPrototype()) 6906 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6907 } 6908 6909 // Promote the arguments (C99 6.5.2.2p6). 6910 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6911 Expr *Arg = Args[i]; 6912 6913 if (Proto && i < Proto->getNumParams()) { 6914 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6915 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6916 ExprResult ArgE = 6917 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6918 if (ArgE.isInvalid()) 6919 return true; 6920 6921 Arg = ArgE.getAs<Expr>(); 6922 6923 } else { 6924 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6925 6926 if (ArgE.isInvalid()) 6927 return true; 6928 6929 Arg = ArgE.getAs<Expr>(); 6930 } 6931 6932 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6933 diag::err_call_incomplete_argument, Arg)) 6934 return ExprError(); 6935 6936 TheCall->setArg(i, Arg); 6937 } 6938 TheCall->computeDependence(); 6939 } 6940 6941 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6942 if (!Method->isStatic()) 6943 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6944 << Fn->getSourceRange()); 6945 6946 // Check for sentinels 6947 if (NDecl) 6948 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6949 6950 // Warn for unions passing across security boundary (CMSE). 6951 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6952 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6953 if (const auto *RT = 6954 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6955 if (RT->getDecl()->isOrContainsUnion()) 6956 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6957 << 0 << i; 6958 } 6959 } 6960 } 6961 6962 // Do special checking on direct calls to functions. 6963 if (FDecl) { 6964 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6965 return ExprError(); 6966 6967 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6968 6969 if (BuiltinID) 6970 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6971 } else if (NDecl) { 6972 if (CheckPointerCall(NDecl, TheCall, Proto)) 6973 return ExprError(); 6974 } else { 6975 if (CheckOtherCall(TheCall, Proto)) 6976 return ExprError(); 6977 } 6978 6979 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6980 } 6981 6982 ExprResult 6983 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6984 SourceLocation RParenLoc, Expr *InitExpr) { 6985 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6986 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6987 6988 TypeSourceInfo *TInfo; 6989 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6990 if (!TInfo) 6991 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6992 6993 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6994 } 6995 6996 ExprResult 6997 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6998 SourceLocation RParenLoc, Expr *LiteralExpr) { 6999 QualType literalType = TInfo->getType(); 7000 7001 if (literalType->isArrayType()) { 7002 if (RequireCompleteSizedType( 7003 LParenLoc, Context.getBaseElementType(literalType), 7004 diag::err_array_incomplete_or_sizeless_type, 7005 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7006 return ExprError(); 7007 if (literalType->isVariableArrayType()) { 7008 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 7009 diag::err_variable_object_no_init)) { 7010 return ExprError(); 7011 } 7012 } 7013 } else if (!literalType->isDependentType() && 7014 RequireCompleteType(LParenLoc, literalType, 7015 diag::err_typecheck_decl_incomplete_type, 7016 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7017 return ExprError(); 7018 7019 InitializedEntity Entity 7020 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 7021 InitializationKind Kind 7022 = InitializationKind::CreateCStyleCast(LParenLoc, 7023 SourceRange(LParenLoc, RParenLoc), 7024 /*InitList=*/true); 7025 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 7026 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 7027 &literalType); 7028 if (Result.isInvalid()) 7029 return ExprError(); 7030 LiteralExpr = Result.get(); 7031 7032 bool isFileScope = !CurContext->isFunctionOrMethod(); 7033 7034 // In C, compound literals are l-values for some reason. 7035 // For GCC compatibility, in C++, file-scope array compound literals with 7036 // constant initializers are also l-values, and compound literals are 7037 // otherwise prvalues. 7038 // 7039 // (GCC also treats C++ list-initialized file-scope array prvalues with 7040 // constant initializers as l-values, but that's non-conforming, so we don't 7041 // follow it there.) 7042 // 7043 // FIXME: It would be better to handle the lvalue cases as materializing and 7044 // lifetime-extending a temporary object, but our materialized temporaries 7045 // representation only supports lifetime extension from a variable, not "out 7046 // of thin air". 7047 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7048 // is bound to the result of applying array-to-pointer decay to the compound 7049 // literal. 7050 // FIXME: GCC supports compound literals of reference type, which should 7051 // obviously have a value kind derived from the kind of reference involved. 7052 ExprValueKind VK = 7053 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7054 ? VK_PRValue 7055 : VK_LValue; 7056 7057 if (isFileScope) 7058 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7059 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7060 Expr *Init = ILE->getInit(i); 7061 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7062 } 7063 7064 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7065 VK, LiteralExpr, isFileScope); 7066 if (isFileScope) { 7067 if (!LiteralExpr->isTypeDependent() && 7068 !LiteralExpr->isValueDependent() && 7069 !literalType->isDependentType()) // C99 6.5.2.5p3 7070 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7071 return ExprError(); 7072 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7073 literalType.getAddressSpace() != LangAS::Default) { 7074 // Embedded-C extensions to C99 6.5.2.5: 7075 // "If the compound literal occurs inside the body of a function, the 7076 // type name shall not be qualified by an address-space qualifier." 7077 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7078 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7079 return ExprError(); 7080 } 7081 7082 if (!isFileScope && !getLangOpts().CPlusPlus) { 7083 // Compound literals that have automatic storage duration are destroyed at 7084 // the end of the scope in C; in C++, they're just temporaries. 7085 7086 // Emit diagnostics if it is or contains a C union type that is non-trivial 7087 // to destruct. 7088 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7089 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7090 NTCUC_CompoundLiteral, NTCUK_Destruct); 7091 7092 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7093 if (literalType.isDestructedType()) { 7094 Cleanup.setExprNeedsCleanups(true); 7095 ExprCleanupObjects.push_back(E); 7096 getCurFunction()->setHasBranchProtectedScope(); 7097 } 7098 } 7099 7100 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7101 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7102 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7103 E->getInitializer()->getExprLoc()); 7104 7105 return MaybeBindToTemporary(E); 7106 } 7107 7108 ExprResult 7109 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7110 SourceLocation RBraceLoc) { 7111 // Only produce each kind of designated initialization diagnostic once. 7112 SourceLocation FirstDesignator; 7113 bool DiagnosedArrayDesignator = false; 7114 bool DiagnosedNestedDesignator = false; 7115 bool DiagnosedMixedDesignator = false; 7116 7117 // Check that any designated initializers are syntactically valid in the 7118 // current language mode. 7119 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7120 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7121 if (FirstDesignator.isInvalid()) 7122 FirstDesignator = DIE->getBeginLoc(); 7123 7124 if (!getLangOpts().CPlusPlus) 7125 break; 7126 7127 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7128 DiagnosedNestedDesignator = true; 7129 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7130 << DIE->getDesignatorsSourceRange(); 7131 } 7132 7133 for (auto &Desig : DIE->designators()) { 7134 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7135 DiagnosedArrayDesignator = true; 7136 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7137 << Desig.getSourceRange(); 7138 } 7139 } 7140 7141 if (!DiagnosedMixedDesignator && 7142 !isa<DesignatedInitExpr>(InitArgList[0])) { 7143 DiagnosedMixedDesignator = true; 7144 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7145 << DIE->getSourceRange(); 7146 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7147 << InitArgList[0]->getSourceRange(); 7148 } 7149 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7150 isa<DesignatedInitExpr>(InitArgList[0])) { 7151 DiagnosedMixedDesignator = true; 7152 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7153 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7154 << DIE->getSourceRange(); 7155 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7156 << InitArgList[I]->getSourceRange(); 7157 } 7158 } 7159 7160 if (FirstDesignator.isValid()) { 7161 // Only diagnose designated initiaization as a C++20 extension if we didn't 7162 // already diagnose use of (non-C++20) C99 designator syntax. 7163 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7164 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7165 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7166 ? diag::warn_cxx17_compat_designated_init 7167 : diag::ext_cxx_designated_init); 7168 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7169 Diag(FirstDesignator, diag::ext_designated_init); 7170 } 7171 } 7172 7173 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7174 } 7175 7176 ExprResult 7177 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7178 SourceLocation RBraceLoc) { 7179 // Semantic analysis for initializers is done by ActOnDeclarator() and 7180 // CheckInitializer() - it requires knowledge of the object being initialized. 7181 7182 // Immediately handle non-overload placeholders. Overloads can be 7183 // resolved contextually, but everything else here can't. 7184 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7185 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7186 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7187 7188 // Ignore failures; dropping the entire initializer list because 7189 // of one failure would be terrible for indexing/etc. 7190 if (result.isInvalid()) continue; 7191 7192 InitArgList[I] = result.get(); 7193 } 7194 } 7195 7196 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7197 RBraceLoc); 7198 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7199 return E; 7200 } 7201 7202 /// Do an explicit extend of the given block pointer if we're in ARC. 7203 void Sema::maybeExtendBlockObject(ExprResult &E) { 7204 assert(E.get()->getType()->isBlockPointerType()); 7205 assert(E.get()->isPRValue()); 7206 7207 // Only do this in an r-value context. 7208 if (!getLangOpts().ObjCAutoRefCount) return; 7209 7210 E = ImplicitCastExpr::Create( 7211 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7212 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7213 Cleanup.setExprNeedsCleanups(true); 7214 } 7215 7216 /// Prepare a conversion of the given expression to an ObjC object 7217 /// pointer type. 7218 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7219 QualType type = E.get()->getType(); 7220 if (type->isObjCObjectPointerType()) { 7221 return CK_BitCast; 7222 } else if (type->isBlockPointerType()) { 7223 maybeExtendBlockObject(E); 7224 return CK_BlockPointerToObjCPointerCast; 7225 } else { 7226 assert(type->isPointerType()); 7227 return CK_CPointerToObjCPointerCast; 7228 } 7229 } 7230 7231 /// Prepares for a scalar cast, performing all the necessary stages 7232 /// except the final cast and returning the kind required. 7233 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7234 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7235 // Also, callers should have filtered out the invalid cases with 7236 // pointers. Everything else should be possible. 7237 7238 QualType SrcTy = Src.get()->getType(); 7239 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7240 return CK_NoOp; 7241 7242 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7243 case Type::STK_MemberPointer: 7244 llvm_unreachable("member pointer type in C"); 7245 7246 case Type::STK_CPointer: 7247 case Type::STK_BlockPointer: 7248 case Type::STK_ObjCObjectPointer: 7249 switch (DestTy->getScalarTypeKind()) { 7250 case Type::STK_CPointer: { 7251 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7252 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7253 if (SrcAS != DestAS) 7254 return CK_AddressSpaceConversion; 7255 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7256 return CK_NoOp; 7257 return CK_BitCast; 7258 } 7259 case Type::STK_BlockPointer: 7260 return (SrcKind == Type::STK_BlockPointer 7261 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7262 case Type::STK_ObjCObjectPointer: 7263 if (SrcKind == Type::STK_ObjCObjectPointer) 7264 return CK_BitCast; 7265 if (SrcKind == Type::STK_CPointer) 7266 return CK_CPointerToObjCPointerCast; 7267 maybeExtendBlockObject(Src); 7268 return CK_BlockPointerToObjCPointerCast; 7269 case Type::STK_Bool: 7270 return CK_PointerToBoolean; 7271 case Type::STK_Integral: 7272 return CK_PointerToIntegral; 7273 case Type::STK_Floating: 7274 case Type::STK_FloatingComplex: 7275 case Type::STK_IntegralComplex: 7276 case Type::STK_MemberPointer: 7277 case Type::STK_FixedPoint: 7278 llvm_unreachable("illegal cast from pointer"); 7279 } 7280 llvm_unreachable("Should have returned before this"); 7281 7282 case Type::STK_FixedPoint: 7283 switch (DestTy->getScalarTypeKind()) { 7284 case Type::STK_FixedPoint: 7285 return CK_FixedPointCast; 7286 case Type::STK_Bool: 7287 return CK_FixedPointToBoolean; 7288 case Type::STK_Integral: 7289 return CK_FixedPointToIntegral; 7290 case Type::STK_Floating: 7291 return CK_FixedPointToFloating; 7292 case Type::STK_IntegralComplex: 7293 case Type::STK_FloatingComplex: 7294 Diag(Src.get()->getExprLoc(), 7295 diag::err_unimplemented_conversion_with_fixed_point_type) 7296 << DestTy; 7297 return CK_IntegralCast; 7298 case Type::STK_CPointer: 7299 case Type::STK_ObjCObjectPointer: 7300 case Type::STK_BlockPointer: 7301 case Type::STK_MemberPointer: 7302 llvm_unreachable("illegal cast to pointer type"); 7303 } 7304 llvm_unreachable("Should have returned before this"); 7305 7306 case Type::STK_Bool: // casting from bool is like casting from an integer 7307 case Type::STK_Integral: 7308 switch (DestTy->getScalarTypeKind()) { 7309 case Type::STK_CPointer: 7310 case Type::STK_ObjCObjectPointer: 7311 case Type::STK_BlockPointer: 7312 if (Src.get()->isNullPointerConstant(Context, 7313 Expr::NPC_ValueDependentIsNull)) 7314 return CK_NullToPointer; 7315 return CK_IntegralToPointer; 7316 case Type::STK_Bool: 7317 return CK_IntegralToBoolean; 7318 case Type::STK_Integral: 7319 return CK_IntegralCast; 7320 case Type::STK_Floating: 7321 return CK_IntegralToFloating; 7322 case Type::STK_IntegralComplex: 7323 Src = ImpCastExprToType(Src.get(), 7324 DestTy->castAs<ComplexType>()->getElementType(), 7325 CK_IntegralCast); 7326 return CK_IntegralRealToComplex; 7327 case Type::STK_FloatingComplex: 7328 Src = ImpCastExprToType(Src.get(), 7329 DestTy->castAs<ComplexType>()->getElementType(), 7330 CK_IntegralToFloating); 7331 return CK_FloatingRealToComplex; 7332 case Type::STK_MemberPointer: 7333 llvm_unreachable("member pointer type in C"); 7334 case Type::STK_FixedPoint: 7335 return CK_IntegralToFixedPoint; 7336 } 7337 llvm_unreachable("Should have returned before this"); 7338 7339 case Type::STK_Floating: 7340 switch (DestTy->getScalarTypeKind()) { 7341 case Type::STK_Floating: 7342 return CK_FloatingCast; 7343 case Type::STK_Bool: 7344 return CK_FloatingToBoolean; 7345 case Type::STK_Integral: 7346 return CK_FloatingToIntegral; 7347 case Type::STK_FloatingComplex: 7348 Src = ImpCastExprToType(Src.get(), 7349 DestTy->castAs<ComplexType>()->getElementType(), 7350 CK_FloatingCast); 7351 return CK_FloatingRealToComplex; 7352 case Type::STK_IntegralComplex: 7353 Src = ImpCastExprToType(Src.get(), 7354 DestTy->castAs<ComplexType>()->getElementType(), 7355 CK_FloatingToIntegral); 7356 return CK_IntegralRealToComplex; 7357 case Type::STK_CPointer: 7358 case Type::STK_ObjCObjectPointer: 7359 case Type::STK_BlockPointer: 7360 llvm_unreachable("valid float->pointer cast?"); 7361 case Type::STK_MemberPointer: 7362 llvm_unreachable("member pointer type in C"); 7363 case Type::STK_FixedPoint: 7364 return CK_FloatingToFixedPoint; 7365 } 7366 llvm_unreachable("Should have returned before this"); 7367 7368 case Type::STK_FloatingComplex: 7369 switch (DestTy->getScalarTypeKind()) { 7370 case Type::STK_FloatingComplex: 7371 return CK_FloatingComplexCast; 7372 case Type::STK_IntegralComplex: 7373 return CK_FloatingComplexToIntegralComplex; 7374 case Type::STK_Floating: { 7375 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7376 if (Context.hasSameType(ET, DestTy)) 7377 return CK_FloatingComplexToReal; 7378 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7379 return CK_FloatingCast; 7380 } 7381 case Type::STK_Bool: 7382 return CK_FloatingComplexToBoolean; 7383 case Type::STK_Integral: 7384 Src = ImpCastExprToType(Src.get(), 7385 SrcTy->castAs<ComplexType>()->getElementType(), 7386 CK_FloatingComplexToReal); 7387 return CK_FloatingToIntegral; 7388 case Type::STK_CPointer: 7389 case Type::STK_ObjCObjectPointer: 7390 case Type::STK_BlockPointer: 7391 llvm_unreachable("valid complex float->pointer cast?"); 7392 case Type::STK_MemberPointer: 7393 llvm_unreachable("member pointer type in C"); 7394 case Type::STK_FixedPoint: 7395 Diag(Src.get()->getExprLoc(), 7396 diag::err_unimplemented_conversion_with_fixed_point_type) 7397 << SrcTy; 7398 return CK_IntegralCast; 7399 } 7400 llvm_unreachable("Should have returned before this"); 7401 7402 case Type::STK_IntegralComplex: 7403 switch (DestTy->getScalarTypeKind()) { 7404 case Type::STK_FloatingComplex: 7405 return CK_IntegralComplexToFloatingComplex; 7406 case Type::STK_IntegralComplex: 7407 return CK_IntegralComplexCast; 7408 case Type::STK_Integral: { 7409 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7410 if (Context.hasSameType(ET, DestTy)) 7411 return CK_IntegralComplexToReal; 7412 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7413 return CK_IntegralCast; 7414 } 7415 case Type::STK_Bool: 7416 return CK_IntegralComplexToBoolean; 7417 case Type::STK_Floating: 7418 Src = ImpCastExprToType(Src.get(), 7419 SrcTy->castAs<ComplexType>()->getElementType(), 7420 CK_IntegralComplexToReal); 7421 return CK_IntegralToFloating; 7422 case Type::STK_CPointer: 7423 case Type::STK_ObjCObjectPointer: 7424 case Type::STK_BlockPointer: 7425 llvm_unreachable("valid complex int->pointer cast?"); 7426 case Type::STK_MemberPointer: 7427 llvm_unreachable("member pointer type in C"); 7428 case Type::STK_FixedPoint: 7429 Diag(Src.get()->getExprLoc(), 7430 diag::err_unimplemented_conversion_with_fixed_point_type) 7431 << SrcTy; 7432 return CK_IntegralCast; 7433 } 7434 llvm_unreachable("Should have returned before this"); 7435 } 7436 7437 llvm_unreachable("Unhandled scalar cast"); 7438 } 7439 7440 static bool breakDownVectorType(QualType type, uint64_t &len, 7441 QualType &eltType) { 7442 // Vectors are simple. 7443 if (const VectorType *vecType = type->getAs<VectorType>()) { 7444 len = vecType->getNumElements(); 7445 eltType = vecType->getElementType(); 7446 assert(eltType->isScalarType()); 7447 return true; 7448 } 7449 7450 // We allow lax conversion to and from non-vector types, but only if 7451 // they're real types (i.e. non-complex, non-pointer scalar types). 7452 if (!type->isRealType()) return false; 7453 7454 len = 1; 7455 eltType = type; 7456 return true; 7457 } 7458 7459 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7460 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7461 /// allowed? 7462 /// 7463 /// This will also return false if the two given types do not make sense from 7464 /// the perspective of SVE bitcasts. 7465 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7466 assert(srcTy->isVectorType() || destTy->isVectorType()); 7467 7468 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7469 if (!FirstType->isSizelessBuiltinType()) 7470 return false; 7471 7472 const auto *VecTy = SecondType->getAs<VectorType>(); 7473 return VecTy && 7474 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7475 }; 7476 7477 return ValidScalableConversion(srcTy, destTy) || 7478 ValidScalableConversion(destTy, srcTy); 7479 } 7480 7481 /// Are the two types matrix types and do they have the same dimensions i.e. 7482 /// do they have the same number of rows and the same number of columns? 7483 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7484 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7485 return false; 7486 7487 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7488 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7489 7490 return matSrcType->getNumRows() == matDestType->getNumRows() && 7491 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7492 } 7493 7494 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7495 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7496 7497 uint64_t SrcLen, DestLen; 7498 QualType SrcEltTy, DestEltTy; 7499 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7500 return false; 7501 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7502 return false; 7503 7504 // ASTContext::getTypeSize will return the size rounded up to a 7505 // power of 2, so instead of using that, we need to use the raw 7506 // element size multiplied by the element count. 7507 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7508 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7509 7510 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7511 } 7512 7513 /// Are the two types lax-compatible vector types? That is, given 7514 /// that one of them is a vector, do they have equal storage sizes, 7515 /// where the storage size is the number of elements times the element 7516 /// size? 7517 /// 7518 /// This will also return false if either of the types is neither a 7519 /// vector nor a real type. 7520 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7521 assert(destTy->isVectorType() || srcTy->isVectorType()); 7522 7523 // Disallow lax conversions between scalars and ExtVectors (these 7524 // conversions are allowed for other vector types because common headers 7525 // depend on them). Most scalar OP ExtVector cases are handled by the 7526 // splat path anyway, which does what we want (convert, not bitcast). 7527 // What this rules out for ExtVectors is crazy things like char4*float. 7528 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7529 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7530 7531 return areVectorTypesSameSize(srcTy, destTy); 7532 } 7533 7534 /// Is this a legal conversion between two types, one of which is 7535 /// known to be a vector type? 7536 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7537 assert(destTy->isVectorType() || srcTy->isVectorType()); 7538 7539 switch (Context.getLangOpts().getLaxVectorConversions()) { 7540 case LangOptions::LaxVectorConversionKind::None: 7541 return false; 7542 7543 case LangOptions::LaxVectorConversionKind::Integer: 7544 if (!srcTy->isIntegralOrEnumerationType()) { 7545 auto *Vec = srcTy->getAs<VectorType>(); 7546 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7547 return false; 7548 } 7549 if (!destTy->isIntegralOrEnumerationType()) { 7550 auto *Vec = destTy->getAs<VectorType>(); 7551 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7552 return false; 7553 } 7554 // OK, integer (vector) -> integer (vector) bitcast. 7555 break; 7556 7557 case LangOptions::LaxVectorConversionKind::All: 7558 break; 7559 } 7560 7561 return areLaxCompatibleVectorTypes(srcTy, destTy); 7562 } 7563 7564 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7565 CastKind &Kind) { 7566 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7567 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7568 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7569 << DestTy << SrcTy << R; 7570 } 7571 } else if (SrcTy->isMatrixType()) { 7572 return Diag(R.getBegin(), 7573 diag::err_invalid_conversion_between_matrix_and_type) 7574 << SrcTy << DestTy << R; 7575 } else if (DestTy->isMatrixType()) { 7576 return Diag(R.getBegin(), 7577 diag::err_invalid_conversion_between_matrix_and_type) 7578 << DestTy << SrcTy << R; 7579 } 7580 7581 Kind = CK_MatrixCast; 7582 return false; 7583 } 7584 7585 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7586 CastKind &Kind) { 7587 assert(VectorTy->isVectorType() && "Not a vector type!"); 7588 7589 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7590 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7591 return Diag(R.getBegin(), 7592 Ty->isVectorType() ? 7593 diag::err_invalid_conversion_between_vectors : 7594 diag::err_invalid_conversion_between_vector_and_integer) 7595 << VectorTy << Ty << R; 7596 } else 7597 return Diag(R.getBegin(), 7598 diag::err_invalid_conversion_between_vector_and_scalar) 7599 << VectorTy << Ty << R; 7600 7601 Kind = CK_BitCast; 7602 return false; 7603 } 7604 7605 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7606 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7607 7608 if (DestElemTy == SplattedExpr->getType()) 7609 return SplattedExpr; 7610 7611 assert(DestElemTy->isFloatingType() || 7612 DestElemTy->isIntegralOrEnumerationType()); 7613 7614 CastKind CK; 7615 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7616 // OpenCL requires that we convert `true` boolean expressions to -1, but 7617 // only when splatting vectors. 7618 if (DestElemTy->isFloatingType()) { 7619 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7620 // in two steps: boolean to signed integral, then to floating. 7621 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7622 CK_BooleanToSignedIntegral); 7623 SplattedExpr = CastExprRes.get(); 7624 CK = CK_IntegralToFloating; 7625 } else { 7626 CK = CK_BooleanToSignedIntegral; 7627 } 7628 } else { 7629 ExprResult CastExprRes = SplattedExpr; 7630 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7631 if (CastExprRes.isInvalid()) 7632 return ExprError(); 7633 SplattedExpr = CastExprRes.get(); 7634 } 7635 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7636 } 7637 7638 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7639 Expr *CastExpr, CastKind &Kind) { 7640 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7641 7642 QualType SrcTy = CastExpr->getType(); 7643 7644 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7645 // an ExtVectorType. 7646 // In OpenCL, casts between vectors of different types are not allowed. 7647 // (See OpenCL 6.2). 7648 if (SrcTy->isVectorType()) { 7649 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7650 (getLangOpts().OpenCL && 7651 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7652 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7653 << DestTy << SrcTy << R; 7654 return ExprError(); 7655 } 7656 Kind = CK_BitCast; 7657 return CastExpr; 7658 } 7659 7660 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7661 // conversion will take place first from scalar to elt type, and then 7662 // splat from elt type to vector. 7663 if (SrcTy->isPointerType()) 7664 return Diag(R.getBegin(), 7665 diag::err_invalid_conversion_between_vector_and_scalar) 7666 << DestTy << SrcTy << R; 7667 7668 Kind = CK_VectorSplat; 7669 return prepareVectorSplat(DestTy, CastExpr); 7670 } 7671 7672 ExprResult 7673 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7674 Declarator &D, ParsedType &Ty, 7675 SourceLocation RParenLoc, Expr *CastExpr) { 7676 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7677 "ActOnCastExpr(): missing type or expr"); 7678 7679 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7680 if (D.isInvalidType()) 7681 return ExprError(); 7682 7683 if (getLangOpts().CPlusPlus) { 7684 // Check that there are no default arguments (C++ only). 7685 CheckExtraCXXDefaultArguments(D); 7686 } else { 7687 // Make sure any TypoExprs have been dealt with. 7688 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7689 if (!Res.isUsable()) 7690 return ExprError(); 7691 CastExpr = Res.get(); 7692 } 7693 7694 checkUnusedDeclAttributes(D); 7695 7696 QualType castType = castTInfo->getType(); 7697 Ty = CreateParsedType(castType, castTInfo); 7698 7699 bool isVectorLiteral = false; 7700 7701 // Check for an altivec or OpenCL literal, 7702 // i.e. all the elements are integer constants. 7703 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7704 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7705 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7706 && castType->isVectorType() && (PE || PLE)) { 7707 if (PLE && PLE->getNumExprs() == 0) { 7708 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7709 return ExprError(); 7710 } 7711 if (PE || PLE->getNumExprs() == 1) { 7712 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7713 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7714 isVectorLiteral = true; 7715 } 7716 else 7717 isVectorLiteral = true; 7718 } 7719 7720 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7721 // then handle it as such. 7722 if (isVectorLiteral) 7723 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7724 7725 // If the Expr being casted is a ParenListExpr, handle it specially. 7726 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7727 // sequence of BinOp comma operators. 7728 if (isa<ParenListExpr>(CastExpr)) { 7729 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7730 if (Result.isInvalid()) return ExprError(); 7731 CastExpr = Result.get(); 7732 } 7733 7734 if (getLangOpts().CPlusPlus && !castType->isVoidType()) 7735 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7736 7737 CheckTollFreeBridgeCast(castType, CastExpr); 7738 7739 CheckObjCBridgeRelatedCast(castType, CastExpr); 7740 7741 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7742 7743 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7744 } 7745 7746 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7747 SourceLocation RParenLoc, Expr *E, 7748 TypeSourceInfo *TInfo) { 7749 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7750 "Expected paren or paren list expression"); 7751 7752 Expr **exprs; 7753 unsigned numExprs; 7754 Expr *subExpr; 7755 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7756 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7757 LiteralLParenLoc = PE->getLParenLoc(); 7758 LiteralRParenLoc = PE->getRParenLoc(); 7759 exprs = PE->getExprs(); 7760 numExprs = PE->getNumExprs(); 7761 } else { // isa<ParenExpr> by assertion at function entrance 7762 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7763 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7764 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7765 exprs = &subExpr; 7766 numExprs = 1; 7767 } 7768 7769 QualType Ty = TInfo->getType(); 7770 assert(Ty->isVectorType() && "Expected vector type"); 7771 7772 SmallVector<Expr *, 8> initExprs; 7773 const VectorType *VTy = Ty->castAs<VectorType>(); 7774 unsigned numElems = VTy->getNumElements(); 7775 7776 // '(...)' form of vector initialization in AltiVec: the number of 7777 // initializers must be one or must match the size of the vector. 7778 // If a single value is specified in the initializer then it will be 7779 // replicated to all the components of the vector 7780 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7781 VTy->getElementType())) 7782 return ExprError(); 7783 if (ShouldSplatAltivecScalarInCast(VTy)) { 7784 // The number of initializers must be one or must match the size of the 7785 // vector. If a single value is specified in the initializer then it will 7786 // be replicated to all the components of the vector 7787 if (numExprs == 1) { 7788 QualType ElemTy = VTy->getElementType(); 7789 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7790 if (Literal.isInvalid()) 7791 return ExprError(); 7792 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7793 PrepareScalarCast(Literal, ElemTy)); 7794 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7795 } 7796 else if (numExprs < numElems) { 7797 Diag(E->getExprLoc(), 7798 diag::err_incorrect_number_of_vector_initializers); 7799 return ExprError(); 7800 } 7801 else 7802 initExprs.append(exprs, exprs + numExprs); 7803 } 7804 else { 7805 // For OpenCL, when the number of initializers is a single value, 7806 // it will be replicated to all components of the vector. 7807 if (getLangOpts().OpenCL && 7808 VTy->getVectorKind() == VectorType::GenericVector && 7809 numExprs == 1) { 7810 QualType ElemTy = VTy->getElementType(); 7811 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7812 if (Literal.isInvalid()) 7813 return ExprError(); 7814 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7815 PrepareScalarCast(Literal, ElemTy)); 7816 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7817 } 7818 7819 initExprs.append(exprs, exprs + numExprs); 7820 } 7821 // FIXME: This means that pretty-printing the final AST will produce curly 7822 // braces instead of the original commas. 7823 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7824 initExprs, LiteralRParenLoc); 7825 initE->setType(Ty); 7826 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7827 } 7828 7829 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7830 /// the ParenListExpr into a sequence of comma binary operators. 7831 ExprResult 7832 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7833 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7834 if (!E) 7835 return OrigExpr; 7836 7837 ExprResult Result(E->getExpr(0)); 7838 7839 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7840 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7841 E->getExpr(i)); 7842 7843 if (Result.isInvalid()) return ExprError(); 7844 7845 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7846 } 7847 7848 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7849 SourceLocation R, 7850 MultiExprArg Val) { 7851 return ParenListExpr::Create(Context, L, Val, R); 7852 } 7853 7854 /// Emit a specialized diagnostic when one expression is a null pointer 7855 /// constant and the other is not a pointer. Returns true if a diagnostic is 7856 /// emitted. 7857 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7858 SourceLocation QuestionLoc) { 7859 Expr *NullExpr = LHSExpr; 7860 Expr *NonPointerExpr = RHSExpr; 7861 Expr::NullPointerConstantKind NullKind = 7862 NullExpr->isNullPointerConstant(Context, 7863 Expr::NPC_ValueDependentIsNotNull); 7864 7865 if (NullKind == Expr::NPCK_NotNull) { 7866 NullExpr = RHSExpr; 7867 NonPointerExpr = LHSExpr; 7868 NullKind = 7869 NullExpr->isNullPointerConstant(Context, 7870 Expr::NPC_ValueDependentIsNotNull); 7871 } 7872 7873 if (NullKind == Expr::NPCK_NotNull) 7874 return false; 7875 7876 if (NullKind == Expr::NPCK_ZeroExpression) 7877 return false; 7878 7879 if (NullKind == Expr::NPCK_ZeroLiteral) { 7880 // In this case, check to make sure that we got here from a "NULL" 7881 // string in the source code. 7882 NullExpr = NullExpr->IgnoreParenImpCasts(); 7883 SourceLocation loc = NullExpr->getExprLoc(); 7884 if (!findMacroSpelling(loc, "NULL")) 7885 return false; 7886 } 7887 7888 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7889 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7890 << NonPointerExpr->getType() << DiagType 7891 << NonPointerExpr->getSourceRange(); 7892 return true; 7893 } 7894 7895 /// Return false if the condition expression is valid, true otherwise. 7896 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7897 QualType CondTy = Cond->getType(); 7898 7899 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7900 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7901 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7902 << CondTy << Cond->getSourceRange(); 7903 return true; 7904 } 7905 7906 // C99 6.5.15p2 7907 if (CondTy->isScalarType()) return false; 7908 7909 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7910 << CondTy << Cond->getSourceRange(); 7911 return true; 7912 } 7913 7914 /// Handle when one or both operands are void type. 7915 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7916 ExprResult &RHS) { 7917 Expr *LHSExpr = LHS.get(); 7918 Expr *RHSExpr = RHS.get(); 7919 7920 if (!LHSExpr->getType()->isVoidType()) 7921 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7922 << RHSExpr->getSourceRange(); 7923 if (!RHSExpr->getType()->isVoidType()) 7924 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7925 << LHSExpr->getSourceRange(); 7926 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7927 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7928 return S.Context.VoidTy; 7929 } 7930 7931 /// Return false if the NullExpr can be promoted to PointerTy, 7932 /// true otherwise. 7933 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7934 QualType PointerTy) { 7935 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7936 !NullExpr.get()->isNullPointerConstant(S.Context, 7937 Expr::NPC_ValueDependentIsNull)) 7938 return true; 7939 7940 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7941 return false; 7942 } 7943 7944 /// Checks compatibility between two pointers and return the resulting 7945 /// type. 7946 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7947 ExprResult &RHS, 7948 SourceLocation Loc) { 7949 QualType LHSTy = LHS.get()->getType(); 7950 QualType RHSTy = RHS.get()->getType(); 7951 7952 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7953 // Two identical pointers types are always compatible. 7954 return LHSTy; 7955 } 7956 7957 QualType lhptee, rhptee; 7958 7959 // Get the pointee types. 7960 bool IsBlockPointer = false; 7961 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7962 lhptee = LHSBTy->getPointeeType(); 7963 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7964 IsBlockPointer = true; 7965 } else { 7966 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7967 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7968 } 7969 7970 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7971 // differently qualified versions of compatible types, the result type is 7972 // a pointer to an appropriately qualified version of the composite 7973 // type. 7974 7975 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7976 // clause doesn't make sense for our extensions. E.g. address space 2 should 7977 // be incompatible with address space 3: they may live on different devices or 7978 // anything. 7979 Qualifiers lhQual = lhptee.getQualifiers(); 7980 Qualifiers rhQual = rhptee.getQualifiers(); 7981 7982 LangAS ResultAddrSpace = LangAS::Default; 7983 LangAS LAddrSpace = lhQual.getAddressSpace(); 7984 LangAS RAddrSpace = rhQual.getAddressSpace(); 7985 7986 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7987 // spaces is disallowed. 7988 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7989 ResultAddrSpace = LAddrSpace; 7990 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7991 ResultAddrSpace = RAddrSpace; 7992 else { 7993 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7994 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7995 << RHS.get()->getSourceRange(); 7996 return QualType(); 7997 } 7998 7999 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 8000 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 8001 lhQual.removeCVRQualifiers(); 8002 rhQual.removeCVRQualifiers(); 8003 8004 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 8005 // (C99 6.7.3) for address spaces. We assume that the check should behave in 8006 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 8007 // qual types are compatible iff 8008 // * corresponded types are compatible 8009 // * CVR qualifiers are equal 8010 // * address spaces are equal 8011 // Thus for conditional operator we merge CVR and address space unqualified 8012 // pointees and if there is a composite type we return a pointer to it with 8013 // merged qualifiers. 8014 LHSCastKind = 8015 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8016 RHSCastKind = 8017 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8018 lhQual.removeAddressSpace(); 8019 rhQual.removeAddressSpace(); 8020 8021 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 8022 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 8023 8024 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 8025 8026 if (CompositeTy.isNull()) { 8027 // In this situation, we assume void* type. No especially good 8028 // reason, but this is what gcc does, and we do have to pick 8029 // to get a consistent AST. 8030 QualType incompatTy; 8031 incompatTy = S.Context.getPointerType( 8032 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 8033 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 8034 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 8035 8036 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 8037 // for casts between types with incompatible address space qualifiers. 8038 // For the following code the compiler produces casts between global and 8039 // local address spaces of the corresponded innermost pointees: 8040 // local int *global *a; 8041 // global int *global *b; 8042 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8043 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8044 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8045 << RHS.get()->getSourceRange(); 8046 8047 return incompatTy; 8048 } 8049 8050 // The pointer types are compatible. 8051 // In case of OpenCL ResultTy should have the address space qualifier 8052 // which is a superset of address spaces of both the 2nd and the 3rd 8053 // operands of the conditional operator. 8054 QualType ResultTy = [&, ResultAddrSpace]() { 8055 if (S.getLangOpts().OpenCL) { 8056 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8057 CompositeQuals.setAddressSpace(ResultAddrSpace); 8058 return S.Context 8059 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8060 .withCVRQualifiers(MergedCVRQual); 8061 } 8062 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8063 }(); 8064 if (IsBlockPointer) 8065 ResultTy = S.Context.getBlockPointerType(ResultTy); 8066 else 8067 ResultTy = S.Context.getPointerType(ResultTy); 8068 8069 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8070 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8071 return ResultTy; 8072 } 8073 8074 /// Return the resulting type when the operands are both block pointers. 8075 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8076 ExprResult &LHS, 8077 ExprResult &RHS, 8078 SourceLocation Loc) { 8079 QualType LHSTy = LHS.get()->getType(); 8080 QualType RHSTy = RHS.get()->getType(); 8081 8082 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8083 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8084 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8085 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8086 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8087 return destType; 8088 } 8089 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8090 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8091 << RHS.get()->getSourceRange(); 8092 return QualType(); 8093 } 8094 8095 // We have 2 block pointer types. 8096 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8097 } 8098 8099 /// Return the resulting type when the operands are both pointers. 8100 static QualType 8101 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8102 ExprResult &RHS, 8103 SourceLocation Loc) { 8104 // get the pointer types 8105 QualType LHSTy = LHS.get()->getType(); 8106 QualType RHSTy = RHS.get()->getType(); 8107 8108 // get the "pointed to" types 8109 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8110 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8111 8112 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8113 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8114 // Figure out necessary qualifiers (C99 6.5.15p6) 8115 QualType destPointee 8116 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8117 QualType destType = S.Context.getPointerType(destPointee); 8118 // Add qualifiers if necessary. 8119 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8120 // Promote to void*. 8121 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8122 return destType; 8123 } 8124 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8125 QualType destPointee 8126 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8127 QualType destType = S.Context.getPointerType(destPointee); 8128 // Add qualifiers if necessary. 8129 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8130 // Promote to void*. 8131 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8132 return destType; 8133 } 8134 8135 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8136 } 8137 8138 /// Return false if the first expression is not an integer and the second 8139 /// expression is not a pointer, true otherwise. 8140 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8141 Expr* PointerExpr, SourceLocation Loc, 8142 bool IsIntFirstExpr) { 8143 if (!PointerExpr->getType()->isPointerType() || 8144 !Int.get()->getType()->isIntegerType()) 8145 return false; 8146 8147 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8148 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8149 8150 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8151 << Expr1->getType() << Expr2->getType() 8152 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8153 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8154 CK_IntegralToPointer); 8155 return true; 8156 } 8157 8158 /// Simple conversion between integer and floating point types. 8159 /// 8160 /// Used when handling the OpenCL conditional operator where the 8161 /// condition is a vector while the other operands are scalar. 8162 /// 8163 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8164 /// types are either integer or floating type. Between the two 8165 /// operands, the type with the higher rank is defined as the "result 8166 /// type". The other operand needs to be promoted to the same type. No 8167 /// other type promotion is allowed. We cannot use 8168 /// UsualArithmeticConversions() for this purpose, since it always 8169 /// promotes promotable types. 8170 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8171 ExprResult &RHS, 8172 SourceLocation QuestionLoc) { 8173 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8174 if (LHS.isInvalid()) 8175 return QualType(); 8176 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8177 if (RHS.isInvalid()) 8178 return QualType(); 8179 8180 // For conversion purposes, we ignore any qualifiers. 8181 // For example, "const float" and "float" are equivalent. 8182 QualType LHSType = 8183 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8184 QualType RHSType = 8185 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8186 8187 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8188 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8189 << LHSType << LHS.get()->getSourceRange(); 8190 return QualType(); 8191 } 8192 8193 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8194 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8195 << RHSType << RHS.get()->getSourceRange(); 8196 return QualType(); 8197 } 8198 8199 // If both types are identical, no conversion is needed. 8200 if (LHSType == RHSType) 8201 return LHSType; 8202 8203 // Now handle "real" floating types (i.e. float, double, long double). 8204 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8205 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8206 /*IsCompAssign = */ false); 8207 8208 // Finally, we have two differing integer types. 8209 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8210 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8211 } 8212 8213 /// Convert scalar operands to a vector that matches the 8214 /// condition in length. 8215 /// 8216 /// Used when handling the OpenCL conditional operator where the 8217 /// condition is a vector while the other operands are scalar. 8218 /// 8219 /// We first compute the "result type" for the scalar operands 8220 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8221 /// into a vector of that type where the length matches the condition 8222 /// vector type. s6.11.6 requires that the element types of the result 8223 /// and the condition must have the same number of bits. 8224 static QualType 8225 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8226 QualType CondTy, SourceLocation QuestionLoc) { 8227 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8228 if (ResTy.isNull()) return QualType(); 8229 8230 const VectorType *CV = CondTy->getAs<VectorType>(); 8231 assert(CV); 8232 8233 // Determine the vector result type 8234 unsigned NumElements = CV->getNumElements(); 8235 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8236 8237 // Ensure that all types have the same number of bits 8238 if (S.Context.getTypeSize(CV->getElementType()) 8239 != S.Context.getTypeSize(ResTy)) { 8240 // Since VectorTy is created internally, it does not pretty print 8241 // with an OpenCL name. Instead, we just print a description. 8242 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8243 SmallString<64> Str; 8244 llvm::raw_svector_ostream OS(Str); 8245 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8246 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8247 << CondTy << OS.str(); 8248 return QualType(); 8249 } 8250 8251 // Convert operands to the vector result type 8252 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8253 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8254 8255 return VectorTy; 8256 } 8257 8258 /// Return false if this is a valid OpenCL condition vector 8259 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8260 SourceLocation QuestionLoc) { 8261 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8262 // integral type. 8263 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8264 assert(CondTy); 8265 QualType EleTy = CondTy->getElementType(); 8266 if (EleTy->isIntegerType()) return false; 8267 8268 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8269 << Cond->getType() << Cond->getSourceRange(); 8270 return true; 8271 } 8272 8273 /// Return false if the vector condition type and the vector 8274 /// result type are compatible. 8275 /// 8276 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8277 /// number of elements, and their element types have the same number 8278 /// of bits. 8279 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8280 SourceLocation QuestionLoc) { 8281 const VectorType *CV = CondTy->getAs<VectorType>(); 8282 const VectorType *RV = VecResTy->getAs<VectorType>(); 8283 assert(CV && RV); 8284 8285 if (CV->getNumElements() != RV->getNumElements()) { 8286 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8287 << CondTy << VecResTy; 8288 return true; 8289 } 8290 8291 QualType CVE = CV->getElementType(); 8292 QualType RVE = RV->getElementType(); 8293 8294 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8295 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8296 << CondTy << VecResTy; 8297 return true; 8298 } 8299 8300 return false; 8301 } 8302 8303 /// Return the resulting type for the conditional operator in 8304 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8305 /// s6.3.i) when the condition is a vector type. 8306 static QualType 8307 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8308 ExprResult &LHS, ExprResult &RHS, 8309 SourceLocation QuestionLoc) { 8310 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8311 if (Cond.isInvalid()) 8312 return QualType(); 8313 QualType CondTy = Cond.get()->getType(); 8314 8315 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8316 return QualType(); 8317 8318 // If either operand is a vector then find the vector type of the 8319 // result as specified in OpenCL v1.1 s6.3.i. 8320 if (LHS.get()->getType()->isVectorType() || 8321 RHS.get()->getType()->isVectorType()) { 8322 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8323 /*isCompAssign*/false, 8324 /*AllowBothBool*/true, 8325 /*AllowBoolConversions*/false); 8326 if (VecResTy.isNull()) return QualType(); 8327 // The result type must match the condition type as specified in 8328 // OpenCL v1.1 s6.11.6. 8329 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8330 return QualType(); 8331 return VecResTy; 8332 } 8333 8334 // Both operands are scalar. 8335 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8336 } 8337 8338 /// Return true if the Expr is block type 8339 static bool checkBlockType(Sema &S, const Expr *E) { 8340 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8341 QualType Ty = CE->getCallee()->getType(); 8342 if (Ty->isBlockPointerType()) { 8343 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8344 return true; 8345 } 8346 } 8347 return false; 8348 } 8349 8350 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8351 /// In that case, LHS = cond. 8352 /// C99 6.5.15 8353 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8354 ExprResult &RHS, ExprValueKind &VK, 8355 ExprObjectKind &OK, 8356 SourceLocation QuestionLoc) { 8357 8358 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8359 if (!LHSResult.isUsable()) return QualType(); 8360 LHS = LHSResult; 8361 8362 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8363 if (!RHSResult.isUsable()) return QualType(); 8364 RHS = RHSResult; 8365 8366 // C++ is sufficiently different to merit its own checker. 8367 if (getLangOpts().CPlusPlus) 8368 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8369 8370 VK = VK_PRValue; 8371 OK = OK_Ordinary; 8372 8373 if (Context.isDependenceAllowed() && 8374 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8375 RHS.get()->isTypeDependent())) { 8376 assert(!getLangOpts().CPlusPlus); 8377 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8378 RHS.get()->containsErrors()) && 8379 "should only occur in error-recovery path."); 8380 return Context.DependentTy; 8381 } 8382 8383 // The OpenCL operator with a vector condition is sufficiently 8384 // different to merit its own checker. 8385 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8386 Cond.get()->getType()->isExtVectorType()) 8387 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8388 8389 // First, check the condition. 8390 Cond = UsualUnaryConversions(Cond.get()); 8391 if (Cond.isInvalid()) 8392 return QualType(); 8393 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8394 return QualType(); 8395 8396 // Now check the two expressions. 8397 if (LHS.get()->getType()->isVectorType() || 8398 RHS.get()->getType()->isVectorType()) 8399 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8400 /*AllowBothBool*/true, 8401 /*AllowBoolConversions*/false); 8402 8403 QualType ResTy = 8404 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8405 if (LHS.isInvalid() || RHS.isInvalid()) 8406 return QualType(); 8407 8408 QualType LHSTy = LHS.get()->getType(); 8409 QualType RHSTy = RHS.get()->getType(); 8410 8411 // Diagnose attempts to convert between __ibm128, __float128 and long double 8412 // where such conversions currently can't be handled. 8413 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8414 Diag(QuestionLoc, 8415 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8416 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8417 return QualType(); 8418 } 8419 8420 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8421 // selection operator (?:). 8422 if (getLangOpts().OpenCL && 8423 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8424 return QualType(); 8425 } 8426 8427 // If both operands have arithmetic type, do the usual arithmetic conversions 8428 // to find a common type: C99 6.5.15p3,5. 8429 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8430 // Disallow invalid arithmetic conversions, such as those between bit- 8431 // precise integers types of different sizes, or between a bit-precise 8432 // integer and another type. 8433 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { 8434 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8435 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8436 << RHS.get()->getSourceRange(); 8437 return QualType(); 8438 } 8439 8440 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8441 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8442 8443 return ResTy; 8444 } 8445 8446 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8447 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8448 return LHSTy; 8449 } 8450 8451 // If both operands are the same structure or union type, the result is that 8452 // type. 8453 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8454 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8455 if (LHSRT->getDecl() == RHSRT->getDecl()) 8456 // "If both the operands have structure or union type, the result has 8457 // that type." This implies that CV qualifiers are dropped. 8458 return LHSTy.getUnqualifiedType(); 8459 // FIXME: Type of conditional expression must be complete in C mode. 8460 } 8461 8462 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8463 // The following || allows only one side to be void (a GCC-ism). 8464 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8465 return checkConditionalVoidType(*this, LHS, RHS); 8466 } 8467 8468 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8469 // the type of the other operand." 8470 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8471 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8472 8473 // All objective-c pointer type analysis is done here. 8474 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8475 QuestionLoc); 8476 if (LHS.isInvalid() || RHS.isInvalid()) 8477 return QualType(); 8478 if (!compositeType.isNull()) 8479 return compositeType; 8480 8481 8482 // Handle block pointer types. 8483 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8484 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8485 QuestionLoc); 8486 8487 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8488 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8489 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8490 QuestionLoc); 8491 8492 // GCC compatibility: soften pointer/integer mismatch. Note that 8493 // null pointers have been filtered out by this point. 8494 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8495 /*IsIntFirstExpr=*/true)) 8496 return RHSTy; 8497 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8498 /*IsIntFirstExpr=*/false)) 8499 return LHSTy; 8500 8501 // Allow ?: operations in which both operands have the same 8502 // built-in sizeless type. 8503 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8504 return LHSTy; 8505 8506 // Emit a better diagnostic if one of the expressions is a null pointer 8507 // constant and the other is not a pointer type. In this case, the user most 8508 // likely forgot to take the address of the other expression. 8509 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8510 return QualType(); 8511 8512 // Otherwise, the operands are not compatible. 8513 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8514 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8515 << RHS.get()->getSourceRange(); 8516 return QualType(); 8517 } 8518 8519 /// FindCompositeObjCPointerType - Helper method to find composite type of 8520 /// two objective-c pointer types of the two input expressions. 8521 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8522 SourceLocation QuestionLoc) { 8523 QualType LHSTy = LHS.get()->getType(); 8524 QualType RHSTy = RHS.get()->getType(); 8525 8526 // Handle things like Class and struct objc_class*. Here we case the result 8527 // to the pseudo-builtin, because that will be implicitly cast back to the 8528 // redefinition type if an attempt is made to access its fields. 8529 if (LHSTy->isObjCClassType() && 8530 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8531 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8532 return LHSTy; 8533 } 8534 if (RHSTy->isObjCClassType() && 8535 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8536 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8537 return RHSTy; 8538 } 8539 // And the same for struct objc_object* / id 8540 if (LHSTy->isObjCIdType() && 8541 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8542 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8543 return LHSTy; 8544 } 8545 if (RHSTy->isObjCIdType() && 8546 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8547 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8548 return RHSTy; 8549 } 8550 // And the same for struct objc_selector* / SEL 8551 if (Context.isObjCSelType(LHSTy) && 8552 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8553 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8554 return LHSTy; 8555 } 8556 if (Context.isObjCSelType(RHSTy) && 8557 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8558 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8559 return RHSTy; 8560 } 8561 // Check constraints for Objective-C object pointers types. 8562 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8563 8564 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8565 // Two identical object pointer types are always compatible. 8566 return LHSTy; 8567 } 8568 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8569 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8570 QualType compositeType = LHSTy; 8571 8572 // If both operands are interfaces and either operand can be 8573 // assigned to the other, use that type as the composite 8574 // type. This allows 8575 // xxx ? (A*) a : (B*) b 8576 // where B is a subclass of A. 8577 // 8578 // Additionally, as for assignment, if either type is 'id' 8579 // allow silent coercion. Finally, if the types are 8580 // incompatible then make sure to use 'id' as the composite 8581 // type so the result is acceptable for sending messages to. 8582 8583 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8584 // It could return the composite type. 8585 if (!(compositeType = 8586 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8587 // Nothing more to do. 8588 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8589 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8590 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8591 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8592 } else if ((LHSOPT->isObjCQualifiedIdType() || 8593 RHSOPT->isObjCQualifiedIdType()) && 8594 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8595 true)) { 8596 // Need to handle "id<xx>" explicitly. 8597 // GCC allows qualified id and any Objective-C type to devolve to 8598 // id. Currently localizing to here until clear this should be 8599 // part of ObjCQualifiedIdTypesAreCompatible. 8600 compositeType = Context.getObjCIdType(); 8601 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8602 compositeType = Context.getObjCIdType(); 8603 } else { 8604 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8605 << LHSTy << RHSTy 8606 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8607 QualType incompatTy = Context.getObjCIdType(); 8608 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8609 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8610 return incompatTy; 8611 } 8612 // The object pointer types are compatible. 8613 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8614 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8615 return compositeType; 8616 } 8617 // Check Objective-C object pointer types and 'void *' 8618 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8619 if (getLangOpts().ObjCAutoRefCount) { 8620 // ARC forbids the implicit conversion of object pointers to 'void *', 8621 // so these types are not compatible. 8622 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8623 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8624 LHS = RHS = true; 8625 return QualType(); 8626 } 8627 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8628 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8629 QualType destPointee 8630 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8631 QualType destType = Context.getPointerType(destPointee); 8632 // Add qualifiers if necessary. 8633 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8634 // Promote to void*. 8635 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8636 return destType; 8637 } 8638 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8639 if (getLangOpts().ObjCAutoRefCount) { 8640 // ARC forbids the implicit conversion of object pointers to 'void *', 8641 // so these types are not compatible. 8642 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8643 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8644 LHS = RHS = true; 8645 return QualType(); 8646 } 8647 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8648 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8649 QualType destPointee 8650 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8651 QualType destType = Context.getPointerType(destPointee); 8652 // Add qualifiers if necessary. 8653 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8654 // Promote to void*. 8655 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8656 return destType; 8657 } 8658 return QualType(); 8659 } 8660 8661 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8662 /// ParenRange in parentheses. 8663 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8664 const PartialDiagnostic &Note, 8665 SourceRange ParenRange) { 8666 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8667 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8668 EndLoc.isValid()) { 8669 Self.Diag(Loc, Note) 8670 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8671 << FixItHint::CreateInsertion(EndLoc, ")"); 8672 } else { 8673 // We can't display the parentheses, so just show the bare note. 8674 Self.Diag(Loc, Note) << ParenRange; 8675 } 8676 } 8677 8678 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8679 return BinaryOperator::isAdditiveOp(Opc) || 8680 BinaryOperator::isMultiplicativeOp(Opc) || 8681 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8682 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8683 // not any of the logical operators. Bitwise-xor is commonly used as a 8684 // logical-xor because there is no logical-xor operator. The logical 8685 // operators, including uses of xor, have a high false positive rate for 8686 // precedence warnings. 8687 } 8688 8689 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8690 /// expression, either using a built-in or overloaded operator, 8691 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8692 /// expression. 8693 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8694 Expr **RHSExprs) { 8695 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8696 E = E->IgnoreImpCasts(); 8697 E = E->IgnoreConversionOperatorSingleStep(); 8698 E = E->IgnoreImpCasts(); 8699 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8700 E = MTE->getSubExpr(); 8701 E = E->IgnoreImpCasts(); 8702 } 8703 8704 // Built-in binary operator. 8705 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8706 if (IsArithmeticOp(OP->getOpcode())) { 8707 *Opcode = OP->getOpcode(); 8708 *RHSExprs = OP->getRHS(); 8709 return true; 8710 } 8711 } 8712 8713 // Overloaded operator. 8714 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8715 if (Call->getNumArgs() != 2) 8716 return false; 8717 8718 // Make sure this is really a binary operator that is safe to pass into 8719 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8720 OverloadedOperatorKind OO = Call->getOperator(); 8721 if (OO < OO_Plus || OO > OO_Arrow || 8722 OO == OO_PlusPlus || OO == OO_MinusMinus) 8723 return false; 8724 8725 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8726 if (IsArithmeticOp(OpKind)) { 8727 *Opcode = OpKind; 8728 *RHSExprs = Call->getArg(1); 8729 return true; 8730 } 8731 } 8732 8733 return false; 8734 } 8735 8736 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8737 /// or is a logical expression such as (x==y) which has int type, but is 8738 /// commonly interpreted as boolean. 8739 static bool ExprLooksBoolean(Expr *E) { 8740 E = E->IgnoreParenImpCasts(); 8741 8742 if (E->getType()->isBooleanType()) 8743 return true; 8744 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8745 return OP->isComparisonOp() || OP->isLogicalOp(); 8746 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8747 return OP->getOpcode() == UO_LNot; 8748 if (E->getType()->isPointerType()) 8749 return true; 8750 // FIXME: What about overloaded operator calls returning "unspecified boolean 8751 // type"s (commonly pointer-to-members)? 8752 8753 return false; 8754 } 8755 8756 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8757 /// and binary operator are mixed in a way that suggests the programmer assumed 8758 /// the conditional operator has higher precedence, for example: 8759 /// "int x = a + someBinaryCondition ? 1 : 2". 8760 static void DiagnoseConditionalPrecedence(Sema &Self, 8761 SourceLocation OpLoc, 8762 Expr *Condition, 8763 Expr *LHSExpr, 8764 Expr *RHSExpr) { 8765 BinaryOperatorKind CondOpcode; 8766 Expr *CondRHS; 8767 8768 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8769 return; 8770 if (!ExprLooksBoolean(CondRHS)) 8771 return; 8772 8773 // The condition is an arithmetic binary expression, with a right- 8774 // hand side that looks boolean, so warn. 8775 8776 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8777 ? diag::warn_precedence_bitwise_conditional 8778 : diag::warn_precedence_conditional; 8779 8780 Self.Diag(OpLoc, DiagID) 8781 << Condition->getSourceRange() 8782 << BinaryOperator::getOpcodeStr(CondOpcode); 8783 8784 SuggestParentheses( 8785 Self, OpLoc, 8786 Self.PDiag(diag::note_precedence_silence) 8787 << BinaryOperator::getOpcodeStr(CondOpcode), 8788 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8789 8790 SuggestParentheses(Self, OpLoc, 8791 Self.PDiag(diag::note_precedence_conditional_first), 8792 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8793 } 8794 8795 /// Compute the nullability of a conditional expression. 8796 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8797 QualType LHSTy, QualType RHSTy, 8798 ASTContext &Ctx) { 8799 if (!ResTy->isAnyPointerType()) 8800 return ResTy; 8801 8802 auto GetNullability = [&Ctx](QualType Ty) { 8803 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8804 if (Kind) { 8805 // For our purposes, treat _Nullable_result as _Nullable. 8806 if (*Kind == NullabilityKind::NullableResult) 8807 return NullabilityKind::Nullable; 8808 return *Kind; 8809 } 8810 return NullabilityKind::Unspecified; 8811 }; 8812 8813 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8814 NullabilityKind MergedKind; 8815 8816 // Compute nullability of a binary conditional expression. 8817 if (IsBin) { 8818 if (LHSKind == NullabilityKind::NonNull) 8819 MergedKind = NullabilityKind::NonNull; 8820 else 8821 MergedKind = RHSKind; 8822 // Compute nullability of a normal conditional expression. 8823 } else { 8824 if (LHSKind == NullabilityKind::Nullable || 8825 RHSKind == NullabilityKind::Nullable) 8826 MergedKind = NullabilityKind::Nullable; 8827 else if (LHSKind == NullabilityKind::NonNull) 8828 MergedKind = RHSKind; 8829 else if (RHSKind == NullabilityKind::NonNull) 8830 MergedKind = LHSKind; 8831 else 8832 MergedKind = NullabilityKind::Unspecified; 8833 } 8834 8835 // Return if ResTy already has the correct nullability. 8836 if (GetNullability(ResTy) == MergedKind) 8837 return ResTy; 8838 8839 // Strip all nullability from ResTy. 8840 while (ResTy->getNullability(Ctx)) 8841 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8842 8843 // Create a new AttributedType with the new nullability kind. 8844 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8845 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8846 } 8847 8848 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8849 /// in the case of a the GNU conditional expr extension. 8850 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8851 SourceLocation ColonLoc, 8852 Expr *CondExpr, Expr *LHSExpr, 8853 Expr *RHSExpr) { 8854 if (!Context.isDependenceAllowed()) { 8855 // C cannot handle TypoExpr nodes in the condition because it 8856 // doesn't handle dependent types properly, so make sure any TypoExprs have 8857 // been dealt with before checking the operands. 8858 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8859 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8860 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8861 8862 if (!CondResult.isUsable()) 8863 return ExprError(); 8864 8865 if (LHSExpr) { 8866 if (!LHSResult.isUsable()) 8867 return ExprError(); 8868 } 8869 8870 if (!RHSResult.isUsable()) 8871 return ExprError(); 8872 8873 CondExpr = CondResult.get(); 8874 LHSExpr = LHSResult.get(); 8875 RHSExpr = RHSResult.get(); 8876 } 8877 8878 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8879 // was the condition. 8880 OpaqueValueExpr *opaqueValue = nullptr; 8881 Expr *commonExpr = nullptr; 8882 if (!LHSExpr) { 8883 commonExpr = CondExpr; 8884 // Lower out placeholder types first. This is important so that we don't 8885 // try to capture a placeholder. This happens in few cases in C++; such 8886 // as Objective-C++'s dictionary subscripting syntax. 8887 if (commonExpr->hasPlaceholderType()) { 8888 ExprResult result = CheckPlaceholderExpr(commonExpr); 8889 if (!result.isUsable()) return ExprError(); 8890 commonExpr = result.get(); 8891 } 8892 // We usually want to apply unary conversions *before* saving, except 8893 // in the special case of a C++ l-value conditional. 8894 if (!(getLangOpts().CPlusPlus 8895 && !commonExpr->isTypeDependent() 8896 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8897 && commonExpr->isGLValue() 8898 && commonExpr->isOrdinaryOrBitFieldObject() 8899 && RHSExpr->isOrdinaryOrBitFieldObject() 8900 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8901 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8902 if (commonRes.isInvalid()) 8903 return ExprError(); 8904 commonExpr = commonRes.get(); 8905 } 8906 8907 // If the common expression is a class or array prvalue, materialize it 8908 // so that we can safely refer to it multiple times. 8909 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8910 commonExpr->getType()->isArrayType())) { 8911 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8912 if (MatExpr.isInvalid()) 8913 return ExprError(); 8914 commonExpr = MatExpr.get(); 8915 } 8916 8917 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8918 commonExpr->getType(), 8919 commonExpr->getValueKind(), 8920 commonExpr->getObjectKind(), 8921 commonExpr); 8922 LHSExpr = CondExpr = opaqueValue; 8923 } 8924 8925 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8926 ExprValueKind VK = VK_PRValue; 8927 ExprObjectKind OK = OK_Ordinary; 8928 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8929 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8930 VK, OK, QuestionLoc); 8931 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8932 RHS.isInvalid()) 8933 return ExprError(); 8934 8935 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8936 RHS.get()); 8937 8938 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8939 8940 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8941 Context); 8942 8943 if (!commonExpr) 8944 return new (Context) 8945 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8946 RHS.get(), result, VK, OK); 8947 8948 return new (Context) BinaryConditionalOperator( 8949 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8950 ColonLoc, result, VK, OK); 8951 } 8952 8953 // Check if we have a conversion between incompatible cmse function pointer 8954 // types, that is, a conversion between a function pointer with the 8955 // cmse_nonsecure_call attribute and one without. 8956 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8957 QualType ToType) { 8958 if (const auto *ToFn = 8959 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8960 if (const auto *FromFn = 8961 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8962 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8963 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8964 8965 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8966 } 8967 } 8968 return false; 8969 } 8970 8971 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8972 // being closely modeled after the C99 spec:-). The odd characteristic of this 8973 // routine is it effectively iqnores the qualifiers on the top level pointee. 8974 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8975 // FIXME: add a couple examples in this comment. 8976 static Sema::AssignConvertType 8977 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8978 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8979 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8980 8981 // get the "pointed to" type (ignoring qualifiers at the top level) 8982 const Type *lhptee, *rhptee; 8983 Qualifiers lhq, rhq; 8984 std::tie(lhptee, lhq) = 8985 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8986 std::tie(rhptee, rhq) = 8987 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8988 8989 Sema::AssignConvertType ConvTy = Sema::Compatible; 8990 8991 // C99 6.5.16.1p1: This following citation is common to constraints 8992 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8993 // qualifiers of the type *pointed to* by the right; 8994 8995 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8996 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8997 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8998 // Ignore lifetime for further calculation. 8999 lhq.removeObjCLifetime(); 9000 rhq.removeObjCLifetime(); 9001 } 9002 9003 if (!lhq.compatiblyIncludes(rhq)) { 9004 // Treat address-space mismatches as fatal. 9005 if (!lhq.isAddressSpaceSupersetOf(rhq)) 9006 return Sema::IncompatiblePointerDiscardsQualifiers; 9007 9008 // It's okay to add or remove GC or lifetime qualifiers when converting to 9009 // and from void*. 9010 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 9011 .compatiblyIncludes( 9012 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 9013 && (lhptee->isVoidType() || rhptee->isVoidType())) 9014 ; // keep old 9015 9016 // Treat lifetime mismatches as fatal. 9017 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 9018 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 9019 9020 // For GCC/MS compatibility, other qualifier mismatches are treated 9021 // as still compatible in C. 9022 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9023 } 9024 9025 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 9026 // incomplete type and the other is a pointer to a qualified or unqualified 9027 // version of void... 9028 if (lhptee->isVoidType()) { 9029 if (rhptee->isIncompleteOrObjectType()) 9030 return ConvTy; 9031 9032 // As an extension, we allow cast to/from void* to function pointer. 9033 assert(rhptee->isFunctionType()); 9034 return Sema::FunctionVoidPointer; 9035 } 9036 9037 if (rhptee->isVoidType()) { 9038 if (lhptee->isIncompleteOrObjectType()) 9039 return ConvTy; 9040 9041 // As an extension, we allow cast to/from void* to function pointer. 9042 assert(lhptee->isFunctionType()); 9043 return Sema::FunctionVoidPointer; 9044 } 9045 9046 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9047 // unqualified versions of compatible types, ... 9048 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9049 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9050 // Check if the pointee types are compatible ignoring the sign. 9051 // We explicitly check for char so that we catch "char" vs 9052 // "unsigned char" on systems where "char" is unsigned. 9053 if (lhptee->isCharType()) 9054 ltrans = S.Context.UnsignedCharTy; 9055 else if (lhptee->hasSignedIntegerRepresentation()) 9056 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9057 9058 if (rhptee->isCharType()) 9059 rtrans = S.Context.UnsignedCharTy; 9060 else if (rhptee->hasSignedIntegerRepresentation()) 9061 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9062 9063 if (ltrans == rtrans) { 9064 // Types are compatible ignoring the sign. Qualifier incompatibility 9065 // takes priority over sign incompatibility because the sign 9066 // warning can be disabled. 9067 if (ConvTy != Sema::Compatible) 9068 return ConvTy; 9069 9070 return Sema::IncompatiblePointerSign; 9071 } 9072 9073 // If we are a multi-level pointer, it's possible that our issue is simply 9074 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9075 // the eventual target type is the same and the pointers have the same 9076 // level of indirection, this must be the issue. 9077 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9078 do { 9079 std::tie(lhptee, lhq) = 9080 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9081 std::tie(rhptee, rhq) = 9082 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9083 9084 // Inconsistent address spaces at this point is invalid, even if the 9085 // address spaces would be compatible. 9086 // FIXME: This doesn't catch address space mismatches for pointers of 9087 // different nesting levels, like: 9088 // __local int *** a; 9089 // int ** b = a; 9090 // It's not clear how to actually determine when such pointers are 9091 // invalidly incompatible. 9092 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9093 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9094 9095 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9096 9097 if (lhptee == rhptee) 9098 return Sema::IncompatibleNestedPointerQualifiers; 9099 } 9100 9101 // General pointer incompatibility takes priority over qualifiers. 9102 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9103 return Sema::IncompatibleFunctionPointer; 9104 return Sema::IncompatiblePointer; 9105 } 9106 if (!S.getLangOpts().CPlusPlus && 9107 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9108 return Sema::IncompatibleFunctionPointer; 9109 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9110 return Sema::IncompatibleFunctionPointer; 9111 return ConvTy; 9112 } 9113 9114 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9115 /// block pointer types are compatible or whether a block and normal pointer 9116 /// are compatible. It is more restrict than comparing two function pointer 9117 // types. 9118 static Sema::AssignConvertType 9119 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9120 QualType RHSType) { 9121 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9122 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9123 9124 QualType lhptee, rhptee; 9125 9126 // get the "pointed to" type (ignoring qualifiers at the top level) 9127 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9128 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9129 9130 // In C++, the types have to match exactly. 9131 if (S.getLangOpts().CPlusPlus) 9132 return Sema::IncompatibleBlockPointer; 9133 9134 Sema::AssignConvertType ConvTy = Sema::Compatible; 9135 9136 // For blocks we enforce that qualifiers are identical. 9137 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9138 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9139 if (S.getLangOpts().OpenCL) { 9140 LQuals.removeAddressSpace(); 9141 RQuals.removeAddressSpace(); 9142 } 9143 if (LQuals != RQuals) 9144 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9145 9146 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9147 // assignment. 9148 // The current behavior is similar to C++ lambdas. A block might be 9149 // assigned to a variable iff its return type and parameters are compatible 9150 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9151 // an assignment. Presumably it should behave in way that a function pointer 9152 // assignment does in C, so for each parameter and return type: 9153 // * CVR and address space of LHS should be a superset of CVR and address 9154 // space of RHS. 9155 // * unqualified types should be compatible. 9156 if (S.getLangOpts().OpenCL) { 9157 if (!S.Context.typesAreBlockPointerCompatible( 9158 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9159 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9160 return Sema::IncompatibleBlockPointer; 9161 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9162 return Sema::IncompatibleBlockPointer; 9163 9164 return ConvTy; 9165 } 9166 9167 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9168 /// for assignment compatibility. 9169 static Sema::AssignConvertType 9170 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9171 QualType RHSType) { 9172 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9173 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9174 9175 if (LHSType->isObjCBuiltinType()) { 9176 // Class is not compatible with ObjC object pointers. 9177 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9178 !RHSType->isObjCQualifiedClassType()) 9179 return Sema::IncompatiblePointer; 9180 return Sema::Compatible; 9181 } 9182 if (RHSType->isObjCBuiltinType()) { 9183 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9184 !LHSType->isObjCQualifiedClassType()) 9185 return Sema::IncompatiblePointer; 9186 return Sema::Compatible; 9187 } 9188 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9189 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9190 9191 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9192 // make an exception for id<P> 9193 !LHSType->isObjCQualifiedIdType()) 9194 return Sema::CompatiblePointerDiscardsQualifiers; 9195 9196 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9197 return Sema::Compatible; 9198 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9199 return Sema::IncompatibleObjCQualifiedId; 9200 return Sema::IncompatiblePointer; 9201 } 9202 9203 Sema::AssignConvertType 9204 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9205 QualType LHSType, QualType RHSType) { 9206 // Fake up an opaque expression. We don't actually care about what 9207 // cast operations are required, so if CheckAssignmentConstraints 9208 // adds casts to this they'll be wasted, but fortunately that doesn't 9209 // usually happen on valid code. 9210 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9211 ExprResult RHSPtr = &RHSExpr; 9212 CastKind K; 9213 9214 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9215 } 9216 9217 /// This helper function returns true if QT is a vector type that has element 9218 /// type ElementType. 9219 static bool isVector(QualType QT, QualType ElementType) { 9220 if (const VectorType *VT = QT->getAs<VectorType>()) 9221 return VT->getElementType().getCanonicalType() == ElementType; 9222 return false; 9223 } 9224 9225 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9226 /// has code to accommodate several GCC extensions when type checking 9227 /// pointers. Here are some objectionable examples that GCC considers warnings: 9228 /// 9229 /// int a, *pint; 9230 /// short *pshort; 9231 /// struct foo *pfoo; 9232 /// 9233 /// pint = pshort; // warning: assignment from incompatible pointer type 9234 /// a = pint; // warning: assignment makes integer from pointer without a cast 9235 /// pint = a; // warning: assignment makes pointer from integer without a cast 9236 /// pint = pfoo; // warning: assignment from incompatible pointer type 9237 /// 9238 /// As a result, the code for dealing with pointers is more complex than the 9239 /// C99 spec dictates. 9240 /// 9241 /// Sets 'Kind' for any result kind except Incompatible. 9242 Sema::AssignConvertType 9243 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9244 CastKind &Kind, bool ConvertRHS) { 9245 QualType RHSType = RHS.get()->getType(); 9246 QualType OrigLHSType = LHSType; 9247 9248 // Get canonical types. We're not formatting these types, just comparing 9249 // them. 9250 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9251 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9252 9253 // Common case: no conversion required. 9254 if (LHSType == RHSType) { 9255 Kind = CK_NoOp; 9256 return Compatible; 9257 } 9258 9259 // If we have an atomic type, try a non-atomic assignment, then just add an 9260 // atomic qualification step. 9261 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9262 Sema::AssignConvertType result = 9263 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9264 if (result != Compatible) 9265 return result; 9266 if (Kind != CK_NoOp && ConvertRHS) 9267 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9268 Kind = CK_NonAtomicToAtomic; 9269 return Compatible; 9270 } 9271 9272 // If the left-hand side is a reference type, then we are in a 9273 // (rare!) case where we've allowed the use of references in C, 9274 // e.g., as a parameter type in a built-in function. In this case, 9275 // just make sure that the type referenced is compatible with the 9276 // right-hand side type. The caller is responsible for adjusting 9277 // LHSType so that the resulting expression does not have reference 9278 // type. 9279 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9280 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9281 Kind = CK_LValueBitCast; 9282 return Compatible; 9283 } 9284 return Incompatible; 9285 } 9286 9287 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9288 // to the same ExtVector type. 9289 if (LHSType->isExtVectorType()) { 9290 if (RHSType->isExtVectorType()) 9291 return Incompatible; 9292 if (RHSType->isArithmeticType()) { 9293 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9294 if (ConvertRHS) 9295 RHS = prepareVectorSplat(LHSType, RHS.get()); 9296 Kind = CK_VectorSplat; 9297 return Compatible; 9298 } 9299 } 9300 9301 // Conversions to or from vector type. 9302 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9303 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9304 // Allow assignments of an AltiVec vector type to an equivalent GCC 9305 // vector type and vice versa 9306 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9307 Kind = CK_BitCast; 9308 return Compatible; 9309 } 9310 9311 // If we are allowing lax vector conversions, and LHS and RHS are both 9312 // vectors, the total size only needs to be the same. This is a bitcast; 9313 // no bits are changed but the result type is different. 9314 if (isLaxVectorConversion(RHSType, LHSType)) { 9315 Kind = CK_BitCast; 9316 return IncompatibleVectors; 9317 } 9318 } 9319 9320 // When the RHS comes from another lax conversion (e.g. binops between 9321 // scalars and vectors) the result is canonicalized as a vector. When the 9322 // LHS is also a vector, the lax is allowed by the condition above. Handle 9323 // the case where LHS is a scalar. 9324 if (LHSType->isScalarType()) { 9325 const VectorType *VecType = RHSType->getAs<VectorType>(); 9326 if (VecType && VecType->getNumElements() == 1 && 9327 isLaxVectorConversion(RHSType, LHSType)) { 9328 ExprResult *VecExpr = &RHS; 9329 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9330 Kind = CK_BitCast; 9331 return Compatible; 9332 } 9333 } 9334 9335 // Allow assignments between fixed-length and sizeless SVE vectors. 9336 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9337 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9338 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9339 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9340 Kind = CK_BitCast; 9341 return Compatible; 9342 } 9343 9344 return Incompatible; 9345 } 9346 9347 // Diagnose attempts to convert between __ibm128, __float128 and long double 9348 // where such conversions currently can't be handled. 9349 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9350 return Incompatible; 9351 9352 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9353 // discards the imaginary part. 9354 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9355 !LHSType->getAs<ComplexType>()) 9356 return Incompatible; 9357 9358 // Arithmetic conversions. 9359 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9360 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9361 if (ConvertRHS) 9362 Kind = PrepareScalarCast(RHS, LHSType); 9363 return Compatible; 9364 } 9365 9366 // Conversions to normal pointers. 9367 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9368 // U* -> T* 9369 if (isa<PointerType>(RHSType)) { 9370 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9371 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9372 if (AddrSpaceL != AddrSpaceR) 9373 Kind = CK_AddressSpaceConversion; 9374 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9375 Kind = CK_NoOp; 9376 else 9377 Kind = CK_BitCast; 9378 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9379 } 9380 9381 // int -> T* 9382 if (RHSType->isIntegerType()) { 9383 Kind = CK_IntegralToPointer; // FIXME: null? 9384 return IntToPointer; 9385 } 9386 9387 // C pointers are not compatible with ObjC object pointers, 9388 // with two exceptions: 9389 if (isa<ObjCObjectPointerType>(RHSType)) { 9390 // - conversions to void* 9391 if (LHSPointer->getPointeeType()->isVoidType()) { 9392 Kind = CK_BitCast; 9393 return Compatible; 9394 } 9395 9396 // - conversions from 'Class' to the redefinition type 9397 if (RHSType->isObjCClassType() && 9398 Context.hasSameType(LHSType, 9399 Context.getObjCClassRedefinitionType())) { 9400 Kind = CK_BitCast; 9401 return Compatible; 9402 } 9403 9404 Kind = CK_BitCast; 9405 return IncompatiblePointer; 9406 } 9407 9408 // U^ -> void* 9409 if (RHSType->getAs<BlockPointerType>()) { 9410 if (LHSPointer->getPointeeType()->isVoidType()) { 9411 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9412 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9413 ->getPointeeType() 9414 .getAddressSpace(); 9415 Kind = 9416 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9417 return Compatible; 9418 } 9419 } 9420 9421 return Incompatible; 9422 } 9423 9424 // Conversions to block pointers. 9425 if (isa<BlockPointerType>(LHSType)) { 9426 // U^ -> T^ 9427 if (RHSType->isBlockPointerType()) { 9428 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9429 ->getPointeeType() 9430 .getAddressSpace(); 9431 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9432 ->getPointeeType() 9433 .getAddressSpace(); 9434 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9435 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9436 } 9437 9438 // int or null -> T^ 9439 if (RHSType->isIntegerType()) { 9440 Kind = CK_IntegralToPointer; // FIXME: null 9441 return IntToBlockPointer; 9442 } 9443 9444 // id -> T^ 9445 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9446 Kind = CK_AnyPointerToBlockPointerCast; 9447 return Compatible; 9448 } 9449 9450 // void* -> T^ 9451 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9452 if (RHSPT->getPointeeType()->isVoidType()) { 9453 Kind = CK_AnyPointerToBlockPointerCast; 9454 return Compatible; 9455 } 9456 9457 return Incompatible; 9458 } 9459 9460 // Conversions to Objective-C pointers. 9461 if (isa<ObjCObjectPointerType>(LHSType)) { 9462 // A* -> B* 9463 if (RHSType->isObjCObjectPointerType()) { 9464 Kind = CK_BitCast; 9465 Sema::AssignConvertType result = 9466 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9467 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9468 result == Compatible && 9469 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9470 result = IncompatibleObjCWeakRef; 9471 return result; 9472 } 9473 9474 // int or null -> A* 9475 if (RHSType->isIntegerType()) { 9476 Kind = CK_IntegralToPointer; // FIXME: null 9477 return IntToPointer; 9478 } 9479 9480 // In general, C pointers are not compatible with ObjC object pointers, 9481 // with two exceptions: 9482 if (isa<PointerType>(RHSType)) { 9483 Kind = CK_CPointerToObjCPointerCast; 9484 9485 // - conversions from 'void*' 9486 if (RHSType->isVoidPointerType()) { 9487 return Compatible; 9488 } 9489 9490 // - conversions to 'Class' from its redefinition type 9491 if (LHSType->isObjCClassType() && 9492 Context.hasSameType(RHSType, 9493 Context.getObjCClassRedefinitionType())) { 9494 return Compatible; 9495 } 9496 9497 return IncompatiblePointer; 9498 } 9499 9500 // Only under strict condition T^ is compatible with an Objective-C pointer. 9501 if (RHSType->isBlockPointerType() && 9502 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9503 if (ConvertRHS) 9504 maybeExtendBlockObject(RHS); 9505 Kind = CK_BlockPointerToObjCPointerCast; 9506 return Compatible; 9507 } 9508 9509 return Incompatible; 9510 } 9511 9512 // Conversions from pointers that are not covered by the above. 9513 if (isa<PointerType>(RHSType)) { 9514 // T* -> _Bool 9515 if (LHSType == Context.BoolTy) { 9516 Kind = CK_PointerToBoolean; 9517 return Compatible; 9518 } 9519 9520 // T* -> int 9521 if (LHSType->isIntegerType()) { 9522 Kind = CK_PointerToIntegral; 9523 return PointerToInt; 9524 } 9525 9526 return Incompatible; 9527 } 9528 9529 // Conversions from Objective-C pointers that are not covered by the above. 9530 if (isa<ObjCObjectPointerType>(RHSType)) { 9531 // T* -> _Bool 9532 if (LHSType == Context.BoolTy) { 9533 Kind = CK_PointerToBoolean; 9534 return Compatible; 9535 } 9536 9537 // T* -> int 9538 if (LHSType->isIntegerType()) { 9539 Kind = CK_PointerToIntegral; 9540 return PointerToInt; 9541 } 9542 9543 return Incompatible; 9544 } 9545 9546 // struct A -> struct B 9547 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9548 if (Context.typesAreCompatible(LHSType, RHSType)) { 9549 Kind = CK_NoOp; 9550 return Compatible; 9551 } 9552 } 9553 9554 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9555 Kind = CK_IntToOCLSampler; 9556 return Compatible; 9557 } 9558 9559 return Incompatible; 9560 } 9561 9562 /// Constructs a transparent union from an expression that is 9563 /// used to initialize the transparent union. 9564 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9565 ExprResult &EResult, QualType UnionType, 9566 FieldDecl *Field) { 9567 // Build an initializer list that designates the appropriate member 9568 // of the transparent union. 9569 Expr *E = EResult.get(); 9570 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9571 E, SourceLocation()); 9572 Initializer->setType(UnionType); 9573 Initializer->setInitializedFieldInUnion(Field); 9574 9575 // Build a compound literal constructing a value of the transparent 9576 // union type from this initializer list. 9577 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9578 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9579 VK_PRValue, Initializer, false); 9580 } 9581 9582 Sema::AssignConvertType 9583 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9584 ExprResult &RHS) { 9585 QualType RHSType = RHS.get()->getType(); 9586 9587 // If the ArgType is a Union type, we want to handle a potential 9588 // transparent_union GCC extension. 9589 const RecordType *UT = ArgType->getAsUnionType(); 9590 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9591 return Incompatible; 9592 9593 // The field to initialize within the transparent union. 9594 RecordDecl *UD = UT->getDecl(); 9595 FieldDecl *InitField = nullptr; 9596 // It's compatible if the expression matches any of the fields. 9597 for (auto *it : UD->fields()) { 9598 if (it->getType()->isPointerType()) { 9599 // If the transparent union contains a pointer type, we allow: 9600 // 1) void pointer 9601 // 2) null pointer constant 9602 if (RHSType->isPointerType()) 9603 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9604 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9605 InitField = it; 9606 break; 9607 } 9608 9609 if (RHS.get()->isNullPointerConstant(Context, 9610 Expr::NPC_ValueDependentIsNull)) { 9611 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9612 CK_NullToPointer); 9613 InitField = it; 9614 break; 9615 } 9616 } 9617 9618 CastKind Kind; 9619 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9620 == Compatible) { 9621 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9622 InitField = it; 9623 break; 9624 } 9625 } 9626 9627 if (!InitField) 9628 return Incompatible; 9629 9630 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9631 return Compatible; 9632 } 9633 9634 Sema::AssignConvertType 9635 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9636 bool Diagnose, 9637 bool DiagnoseCFAudited, 9638 bool ConvertRHS) { 9639 // We need to be able to tell the caller whether we diagnosed a problem, if 9640 // they ask us to issue diagnostics. 9641 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9642 9643 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9644 // we can't avoid *all* modifications at the moment, so we need some somewhere 9645 // to put the updated value. 9646 ExprResult LocalRHS = CallerRHS; 9647 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9648 9649 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9650 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9651 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9652 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9653 Diag(RHS.get()->getExprLoc(), 9654 diag::warn_noderef_to_dereferenceable_pointer) 9655 << RHS.get()->getSourceRange(); 9656 } 9657 } 9658 } 9659 9660 if (getLangOpts().CPlusPlus) { 9661 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9662 // C++ 5.17p3: If the left operand is not of class type, the 9663 // expression is implicitly converted (C++ 4) to the 9664 // cv-unqualified type of the left operand. 9665 QualType RHSType = RHS.get()->getType(); 9666 if (Diagnose) { 9667 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9668 AA_Assigning); 9669 } else { 9670 ImplicitConversionSequence ICS = 9671 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9672 /*SuppressUserConversions=*/false, 9673 AllowedExplicit::None, 9674 /*InOverloadResolution=*/false, 9675 /*CStyle=*/false, 9676 /*AllowObjCWritebackConversion=*/false); 9677 if (ICS.isFailure()) 9678 return Incompatible; 9679 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9680 ICS, AA_Assigning); 9681 } 9682 if (RHS.isInvalid()) 9683 return Incompatible; 9684 Sema::AssignConvertType result = Compatible; 9685 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9686 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9687 result = IncompatibleObjCWeakRef; 9688 return result; 9689 } 9690 9691 // FIXME: Currently, we fall through and treat C++ classes like C 9692 // structures. 9693 // FIXME: We also fall through for atomics; not sure what should 9694 // happen there, though. 9695 } else if (RHS.get()->getType() == Context.OverloadTy) { 9696 // As a set of extensions to C, we support overloading on functions. These 9697 // functions need to be resolved here. 9698 DeclAccessPair DAP; 9699 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9700 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9701 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9702 else 9703 return Incompatible; 9704 } 9705 9706 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9707 // a null pointer constant. 9708 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9709 LHSType->isBlockPointerType()) && 9710 RHS.get()->isNullPointerConstant(Context, 9711 Expr::NPC_ValueDependentIsNull)) { 9712 if (Diagnose || ConvertRHS) { 9713 CastKind Kind; 9714 CXXCastPath Path; 9715 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9716 /*IgnoreBaseAccess=*/false, Diagnose); 9717 if (ConvertRHS) 9718 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9719 } 9720 return Compatible; 9721 } 9722 9723 // OpenCL queue_t type assignment. 9724 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9725 Context, Expr::NPC_ValueDependentIsNull)) { 9726 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9727 return Compatible; 9728 } 9729 9730 // This check seems unnatural, however it is necessary to ensure the proper 9731 // conversion of functions/arrays. If the conversion were done for all 9732 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9733 // expressions that suppress this implicit conversion (&, sizeof). 9734 // 9735 // Suppress this for references: C++ 8.5.3p5. 9736 if (!LHSType->isReferenceType()) { 9737 // FIXME: We potentially allocate here even if ConvertRHS is false. 9738 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9739 if (RHS.isInvalid()) 9740 return Incompatible; 9741 } 9742 CastKind Kind; 9743 Sema::AssignConvertType result = 9744 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9745 9746 // C99 6.5.16.1p2: The value of the right operand is converted to the 9747 // type of the assignment expression. 9748 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9749 // so that we can use references in built-in functions even in C. 9750 // The getNonReferenceType() call makes sure that the resulting expression 9751 // does not have reference type. 9752 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9753 QualType Ty = LHSType.getNonLValueExprType(Context); 9754 Expr *E = RHS.get(); 9755 9756 // Check for various Objective-C errors. If we are not reporting 9757 // diagnostics and just checking for errors, e.g., during overload 9758 // resolution, return Incompatible to indicate the failure. 9759 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9760 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9761 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9762 if (!Diagnose) 9763 return Incompatible; 9764 } 9765 if (getLangOpts().ObjC && 9766 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9767 E->getType(), E, Diagnose) || 9768 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9769 if (!Diagnose) 9770 return Incompatible; 9771 // Replace the expression with a corrected version and continue so we 9772 // can find further errors. 9773 RHS = E; 9774 return Compatible; 9775 } 9776 9777 if (ConvertRHS) 9778 RHS = ImpCastExprToType(E, Ty, Kind); 9779 } 9780 9781 return result; 9782 } 9783 9784 namespace { 9785 /// The original operand to an operator, prior to the application of the usual 9786 /// arithmetic conversions and converting the arguments of a builtin operator 9787 /// candidate. 9788 struct OriginalOperand { 9789 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9790 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9791 Op = MTE->getSubExpr(); 9792 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9793 Op = BTE->getSubExpr(); 9794 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9795 Orig = ICE->getSubExprAsWritten(); 9796 Conversion = ICE->getConversionFunction(); 9797 } 9798 } 9799 9800 QualType getType() const { return Orig->getType(); } 9801 9802 Expr *Orig; 9803 NamedDecl *Conversion; 9804 }; 9805 } 9806 9807 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9808 ExprResult &RHS) { 9809 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9810 9811 Diag(Loc, diag::err_typecheck_invalid_operands) 9812 << OrigLHS.getType() << OrigRHS.getType() 9813 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9814 9815 // If a user-defined conversion was applied to either of the operands prior 9816 // to applying the built-in operator rules, tell the user about it. 9817 if (OrigLHS.Conversion) { 9818 Diag(OrigLHS.Conversion->getLocation(), 9819 diag::note_typecheck_invalid_operands_converted) 9820 << 0 << LHS.get()->getType(); 9821 } 9822 if (OrigRHS.Conversion) { 9823 Diag(OrigRHS.Conversion->getLocation(), 9824 diag::note_typecheck_invalid_operands_converted) 9825 << 1 << RHS.get()->getType(); 9826 } 9827 9828 return QualType(); 9829 } 9830 9831 // Diagnose cases where a scalar was implicitly converted to a vector and 9832 // diagnose the underlying types. Otherwise, diagnose the error 9833 // as invalid vector logical operands for non-C++ cases. 9834 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9835 ExprResult &RHS) { 9836 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9837 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9838 9839 bool LHSNatVec = LHSType->isVectorType(); 9840 bool RHSNatVec = RHSType->isVectorType(); 9841 9842 if (!(LHSNatVec && RHSNatVec)) { 9843 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9844 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9845 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9846 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9847 << Vector->getSourceRange(); 9848 return QualType(); 9849 } 9850 9851 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9852 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9853 << RHS.get()->getSourceRange(); 9854 9855 return QualType(); 9856 } 9857 9858 /// Try to convert a value of non-vector type to a vector type by converting 9859 /// the type to the element type of the vector and then performing a splat. 9860 /// If the language is OpenCL, we only use conversions that promote scalar 9861 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9862 /// for float->int. 9863 /// 9864 /// OpenCL V2.0 6.2.6.p2: 9865 /// An error shall occur if any scalar operand type has greater rank 9866 /// than the type of the vector element. 9867 /// 9868 /// \param scalar - if non-null, actually perform the conversions 9869 /// \return true if the operation fails (but without diagnosing the failure) 9870 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9871 QualType scalarTy, 9872 QualType vectorEltTy, 9873 QualType vectorTy, 9874 unsigned &DiagID) { 9875 // The conversion to apply to the scalar before splatting it, 9876 // if necessary. 9877 CastKind scalarCast = CK_NoOp; 9878 9879 if (vectorEltTy->isIntegralType(S.Context)) { 9880 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9881 (scalarTy->isIntegerType() && 9882 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9883 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9884 return true; 9885 } 9886 if (!scalarTy->isIntegralType(S.Context)) 9887 return true; 9888 scalarCast = CK_IntegralCast; 9889 } else if (vectorEltTy->isRealFloatingType()) { 9890 if (scalarTy->isRealFloatingType()) { 9891 if (S.getLangOpts().OpenCL && 9892 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9893 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9894 return true; 9895 } 9896 scalarCast = CK_FloatingCast; 9897 } 9898 else if (scalarTy->isIntegralType(S.Context)) 9899 scalarCast = CK_IntegralToFloating; 9900 else 9901 return true; 9902 } else { 9903 return true; 9904 } 9905 9906 // Adjust scalar if desired. 9907 if (scalar) { 9908 if (scalarCast != CK_NoOp) 9909 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9910 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9911 } 9912 return false; 9913 } 9914 9915 /// Convert vector E to a vector with the same number of elements but different 9916 /// element type. 9917 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9918 const auto *VecTy = E->getType()->getAs<VectorType>(); 9919 assert(VecTy && "Expression E must be a vector"); 9920 QualType NewVecTy = S.Context.getVectorType(ElementType, 9921 VecTy->getNumElements(), 9922 VecTy->getVectorKind()); 9923 9924 // Look through the implicit cast. Return the subexpression if its type is 9925 // NewVecTy. 9926 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9927 if (ICE->getSubExpr()->getType() == NewVecTy) 9928 return ICE->getSubExpr(); 9929 9930 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9931 return S.ImpCastExprToType(E, NewVecTy, Cast); 9932 } 9933 9934 /// Test if a (constant) integer Int can be casted to another integer type 9935 /// IntTy without losing precision. 9936 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9937 QualType OtherIntTy) { 9938 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9939 9940 // Reject cases where the value of the Int is unknown as that would 9941 // possibly cause truncation, but accept cases where the scalar can be 9942 // demoted without loss of precision. 9943 Expr::EvalResult EVResult; 9944 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9945 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9946 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9947 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9948 9949 if (CstInt) { 9950 // If the scalar is constant and is of a higher order and has more active 9951 // bits that the vector element type, reject it. 9952 llvm::APSInt Result = EVResult.Val.getInt(); 9953 unsigned NumBits = IntSigned 9954 ? (Result.isNegative() ? Result.getMinSignedBits() 9955 : Result.getActiveBits()) 9956 : Result.getActiveBits(); 9957 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9958 return true; 9959 9960 // If the signedness of the scalar type and the vector element type 9961 // differs and the number of bits is greater than that of the vector 9962 // element reject it. 9963 return (IntSigned != OtherIntSigned && 9964 NumBits > S.Context.getIntWidth(OtherIntTy)); 9965 } 9966 9967 // Reject cases where the value of the scalar is not constant and it's 9968 // order is greater than that of the vector element type. 9969 return (Order < 0); 9970 } 9971 9972 /// Test if a (constant) integer Int can be casted to floating point type 9973 /// FloatTy without losing precision. 9974 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9975 QualType FloatTy) { 9976 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9977 9978 // Determine if the integer constant can be expressed as a floating point 9979 // number of the appropriate type. 9980 Expr::EvalResult EVResult; 9981 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9982 9983 uint64_t Bits = 0; 9984 if (CstInt) { 9985 // Reject constants that would be truncated if they were converted to 9986 // the floating point type. Test by simple to/from conversion. 9987 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9988 // could be avoided if there was a convertFromAPInt method 9989 // which could signal back if implicit truncation occurred. 9990 llvm::APSInt Result = EVResult.Val.getInt(); 9991 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9992 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9993 llvm::APFloat::rmTowardZero); 9994 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9995 !IntTy->hasSignedIntegerRepresentation()); 9996 bool Ignored = false; 9997 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9998 &Ignored); 9999 if (Result != ConvertBack) 10000 return true; 10001 } else { 10002 // Reject types that cannot be fully encoded into the mantissa of 10003 // the float. 10004 Bits = S.Context.getTypeSize(IntTy); 10005 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 10006 S.Context.getFloatTypeSemantics(FloatTy)); 10007 if (Bits > FloatPrec) 10008 return true; 10009 } 10010 10011 return false; 10012 } 10013 10014 /// Attempt to convert and splat Scalar into a vector whose types matches 10015 /// Vector following GCC conversion rules. The rule is that implicit 10016 /// conversion can occur when Scalar can be casted to match Vector's element 10017 /// type without causing truncation of Scalar. 10018 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 10019 ExprResult *Vector) { 10020 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 10021 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 10022 const VectorType *VT = VectorTy->getAs<VectorType>(); 10023 10024 assert(!isa<ExtVectorType>(VT) && 10025 "ExtVectorTypes should not be handled here!"); 10026 10027 QualType VectorEltTy = VT->getElementType(); 10028 10029 // Reject cases where the vector element type or the scalar element type are 10030 // not integral or floating point types. 10031 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 10032 return true; 10033 10034 // The conversion to apply to the scalar before splatting it, 10035 // if necessary. 10036 CastKind ScalarCast = CK_NoOp; 10037 10038 // Accept cases where the vector elements are integers and the scalar is 10039 // an integer. 10040 // FIXME: Notionally if the scalar was a floating point value with a precise 10041 // integral representation, we could cast it to an appropriate integer 10042 // type and then perform the rest of the checks here. GCC will perform 10043 // this conversion in some cases as determined by the input language. 10044 // We should accept it on a language independent basis. 10045 if (VectorEltTy->isIntegralType(S.Context) && 10046 ScalarTy->isIntegralType(S.Context) && 10047 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10048 10049 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10050 return true; 10051 10052 ScalarCast = CK_IntegralCast; 10053 } else if (VectorEltTy->isIntegralType(S.Context) && 10054 ScalarTy->isRealFloatingType()) { 10055 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10056 ScalarCast = CK_FloatingToIntegral; 10057 else 10058 return true; 10059 } else if (VectorEltTy->isRealFloatingType()) { 10060 if (ScalarTy->isRealFloatingType()) { 10061 10062 // Reject cases where the scalar type is not a constant and has a higher 10063 // Order than the vector element type. 10064 llvm::APFloat Result(0.0); 10065 10066 // Determine whether this is a constant scalar. In the event that the 10067 // value is dependent (and thus cannot be evaluated by the constant 10068 // evaluator), skip the evaluation. This will then diagnose once the 10069 // expression is instantiated. 10070 bool CstScalar = Scalar->get()->isValueDependent() || 10071 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10072 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10073 if (!CstScalar && Order < 0) 10074 return true; 10075 10076 // If the scalar cannot be safely casted to the vector element type, 10077 // reject it. 10078 if (CstScalar) { 10079 bool Truncated = false; 10080 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10081 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10082 if (Truncated) 10083 return true; 10084 } 10085 10086 ScalarCast = CK_FloatingCast; 10087 } else if (ScalarTy->isIntegralType(S.Context)) { 10088 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10089 return true; 10090 10091 ScalarCast = CK_IntegralToFloating; 10092 } else 10093 return true; 10094 } else if (ScalarTy->isEnumeralType()) 10095 return true; 10096 10097 // Adjust scalar if desired. 10098 if (Scalar) { 10099 if (ScalarCast != CK_NoOp) 10100 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10101 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10102 } 10103 return false; 10104 } 10105 10106 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10107 SourceLocation Loc, bool IsCompAssign, 10108 bool AllowBothBool, 10109 bool AllowBoolConversions) { 10110 if (!IsCompAssign) { 10111 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10112 if (LHS.isInvalid()) 10113 return QualType(); 10114 } 10115 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10116 if (RHS.isInvalid()) 10117 return QualType(); 10118 10119 // For conversion purposes, we ignore any qualifiers. 10120 // For example, "const float" and "float" are equivalent. 10121 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10122 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10123 10124 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10125 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10126 assert(LHSVecType || RHSVecType); 10127 10128 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10129 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10130 return InvalidOperands(Loc, LHS, RHS); 10131 10132 // AltiVec-style "vector bool op vector bool" combinations are allowed 10133 // for some operators but not others. 10134 if (!AllowBothBool && 10135 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10136 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10137 return InvalidOperands(Loc, LHS, RHS); 10138 10139 // If the vector types are identical, return. 10140 if (Context.hasSameType(LHSType, RHSType)) 10141 return LHSType; 10142 10143 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10144 if (LHSVecType && RHSVecType && 10145 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10146 if (isa<ExtVectorType>(LHSVecType)) { 10147 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10148 return LHSType; 10149 } 10150 10151 if (!IsCompAssign) 10152 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10153 return RHSType; 10154 } 10155 10156 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10157 // can be mixed, with the result being the non-bool type. The non-bool 10158 // operand must have integer element type. 10159 if (AllowBoolConversions && LHSVecType && RHSVecType && 10160 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10161 (Context.getTypeSize(LHSVecType->getElementType()) == 10162 Context.getTypeSize(RHSVecType->getElementType()))) { 10163 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10164 LHSVecType->getElementType()->isIntegerType() && 10165 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10166 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10167 return LHSType; 10168 } 10169 if (!IsCompAssign && 10170 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10171 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10172 RHSVecType->getElementType()->isIntegerType()) { 10173 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10174 return RHSType; 10175 } 10176 } 10177 10178 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10179 // since the ambiguity can affect the ABI. 10180 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10181 const VectorType *VecType = SecondType->getAs<VectorType>(); 10182 return FirstType->isSizelessBuiltinType() && VecType && 10183 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10184 VecType->getVectorKind() == 10185 VectorType::SveFixedLengthPredicateVector); 10186 }; 10187 10188 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10189 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10190 return QualType(); 10191 } 10192 10193 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10194 // since the ambiguity can affect the ABI. 10195 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10196 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10197 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10198 10199 if (FirstVecType && SecondVecType) 10200 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10201 (SecondVecType->getVectorKind() == 10202 VectorType::SveFixedLengthDataVector || 10203 SecondVecType->getVectorKind() == 10204 VectorType::SveFixedLengthPredicateVector); 10205 10206 return FirstType->isSizelessBuiltinType() && SecondVecType && 10207 SecondVecType->getVectorKind() == VectorType::GenericVector; 10208 }; 10209 10210 if (IsSveGnuConversion(LHSType, RHSType) || 10211 IsSveGnuConversion(RHSType, LHSType)) { 10212 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10213 return QualType(); 10214 } 10215 10216 // If there's a vector type and a scalar, try to convert the scalar to 10217 // the vector element type and splat. 10218 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10219 if (!RHSVecType) { 10220 if (isa<ExtVectorType>(LHSVecType)) { 10221 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10222 LHSVecType->getElementType(), LHSType, 10223 DiagID)) 10224 return LHSType; 10225 } else { 10226 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10227 return LHSType; 10228 } 10229 } 10230 if (!LHSVecType) { 10231 if (isa<ExtVectorType>(RHSVecType)) { 10232 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10233 LHSType, RHSVecType->getElementType(), 10234 RHSType, DiagID)) 10235 return RHSType; 10236 } else { 10237 if (LHS.get()->isLValue() || 10238 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10239 return RHSType; 10240 } 10241 } 10242 10243 // FIXME: The code below also handles conversion between vectors and 10244 // non-scalars, we should break this down into fine grained specific checks 10245 // and emit proper diagnostics. 10246 QualType VecType = LHSVecType ? LHSType : RHSType; 10247 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10248 QualType OtherType = LHSVecType ? RHSType : LHSType; 10249 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10250 if (isLaxVectorConversion(OtherType, VecType)) { 10251 // If we're allowing lax vector conversions, only the total (data) size 10252 // needs to be the same. For non compound assignment, if one of the types is 10253 // scalar, the result is always the vector type. 10254 if (!IsCompAssign) { 10255 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10256 return VecType; 10257 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10258 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10259 // type. Note that this is already done by non-compound assignments in 10260 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10261 // <1 x T> -> T. The result is also a vector type. 10262 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10263 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10264 ExprResult *RHSExpr = &RHS; 10265 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10266 return VecType; 10267 } 10268 } 10269 10270 // Okay, the expression is invalid. 10271 10272 // If there's a non-vector, non-real operand, diagnose that. 10273 if ((!RHSVecType && !RHSType->isRealType()) || 10274 (!LHSVecType && !LHSType->isRealType())) { 10275 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10276 << LHSType << RHSType 10277 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10278 return QualType(); 10279 } 10280 10281 // OpenCL V1.1 6.2.6.p1: 10282 // If the operands are of more than one vector type, then an error shall 10283 // occur. Implicit conversions between vector types are not permitted, per 10284 // section 6.2.1. 10285 if (getLangOpts().OpenCL && 10286 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10287 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10288 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10289 << RHSType; 10290 return QualType(); 10291 } 10292 10293 10294 // If there is a vector type that is not a ExtVector and a scalar, we reach 10295 // this point if scalar could not be converted to the vector's element type 10296 // without truncation. 10297 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10298 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10299 QualType Scalar = LHSVecType ? RHSType : LHSType; 10300 QualType Vector = LHSVecType ? LHSType : RHSType; 10301 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10302 Diag(Loc, 10303 diag::err_typecheck_vector_not_convertable_implict_truncation) 10304 << ScalarOrVector << Scalar << Vector; 10305 10306 return QualType(); 10307 } 10308 10309 // Otherwise, use the generic diagnostic. 10310 Diag(Loc, DiagID) 10311 << LHSType << RHSType 10312 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10313 return QualType(); 10314 } 10315 10316 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10317 // expression. These are mainly cases where the null pointer is used as an 10318 // integer instead of a pointer. 10319 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10320 SourceLocation Loc, bool IsCompare) { 10321 // The canonical way to check for a GNU null is with isNullPointerConstant, 10322 // but we use a bit of a hack here for speed; this is a relatively 10323 // hot path, and isNullPointerConstant is slow. 10324 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10325 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10326 10327 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10328 10329 // Avoid analyzing cases where the result will either be invalid (and 10330 // diagnosed as such) or entirely valid and not something to warn about. 10331 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10332 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10333 return; 10334 10335 // Comparison operations would not make sense with a null pointer no matter 10336 // what the other expression is. 10337 if (!IsCompare) { 10338 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10339 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10340 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10341 return; 10342 } 10343 10344 // The rest of the operations only make sense with a null pointer 10345 // if the other expression is a pointer. 10346 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10347 NonNullType->canDecayToPointerType()) 10348 return; 10349 10350 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10351 << LHSNull /* LHS is NULL */ << NonNullType 10352 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10353 } 10354 10355 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10356 SourceLocation Loc) { 10357 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10358 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10359 if (!LUE || !RUE) 10360 return; 10361 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10362 RUE->getKind() != UETT_SizeOf) 10363 return; 10364 10365 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10366 QualType LHSTy = LHSArg->getType(); 10367 QualType RHSTy; 10368 10369 if (RUE->isArgumentType()) 10370 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10371 else 10372 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10373 10374 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10375 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10376 return; 10377 10378 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10379 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10380 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10381 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10382 << LHSArgDecl; 10383 } 10384 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10385 QualType ArrayElemTy = ArrayTy->getElementType(); 10386 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10387 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10388 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10389 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10390 return; 10391 S.Diag(Loc, diag::warn_division_sizeof_array) 10392 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10393 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10394 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10395 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10396 << LHSArgDecl; 10397 } 10398 10399 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10400 } 10401 } 10402 10403 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10404 ExprResult &RHS, 10405 SourceLocation Loc, bool IsDiv) { 10406 // Check for division/remainder by zero. 10407 Expr::EvalResult RHSValue; 10408 if (!RHS.get()->isValueDependent() && 10409 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10410 RHSValue.Val.getInt() == 0) 10411 S.DiagRuntimeBehavior(Loc, RHS.get(), 10412 S.PDiag(diag::warn_remainder_division_by_zero) 10413 << IsDiv << RHS.get()->getSourceRange()); 10414 } 10415 10416 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10417 SourceLocation Loc, 10418 bool IsCompAssign, bool IsDiv) { 10419 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10420 10421 QualType LHSTy = LHS.get()->getType(); 10422 QualType RHSTy = RHS.get()->getType(); 10423 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10424 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10425 /*AllowBothBool*/getLangOpts().AltiVec, 10426 /*AllowBoolConversions*/false); 10427 if (!IsDiv && 10428 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10429 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10430 // For division, only matrix-by-scalar is supported. Other combinations with 10431 // matrix types are invalid. 10432 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10433 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10434 10435 QualType compType = UsualArithmeticConversions( 10436 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10437 if (LHS.isInvalid() || RHS.isInvalid()) 10438 return QualType(); 10439 10440 10441 if (compType.isNull() || !compType->isArithmeticType()) 10442 return InvalidOperands(Loc, LHS, RHS); 10443 if (IsDiv) { 10444 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10445 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10446 } 10447 return compType; 10448 } 10449 10450 QualType Sema::CheckRemainderOperands( 10451 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10452 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10453 10454 if (LHS.get()->getType()->isVectorType() || 10455 RHS.get()->getType()->isVectorType()) { 10456 if (LHS.get()->getType()->hasIntegerRepresentation() && 10457 RHS.get()->getType()->hasIntegerRepresentation()) 10458 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10459 /*AllowBothBool*/getLangOpts().AltiVec, 10460 /*AllowBoolConversions*/false); 10461 return InvalidOperands(Loc, LHS, RHS); 10462 } 10463 10464 QualType compType = UsualArithmeticConversions( 10465 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10466 if (LHS.isInvalid() || RHS.isInvalid()) 10467 return QualType(); 10468 10469 if (compType.isNull() || !compType->isIntegerType()) 10470 return InvalidOperands(Loc, LHS, RHS); 10471 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10472 return compType; 10473 } 10474 10475 /// Diagnose invalid arithmetic on two void pointers. 10476 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10477 Expr *LHSExpr, Expr *RHSExpr) { 10478 S.Diag(Loc, S.getLangOpts().CPlusPlus 10479 ? diag::err_typecheck_pointer_arith_void_type 10480 : diag::ext_gnu_void_ptr) 10481 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10482 << RHSExpr->getSourceRange(); 10483 } 10484 10485 /// Diagnose invalid arithmetic on a void pointer. 10486 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10487 Expr *Pointer) { 10488 S.Diag(Loc, S.getLangOpts().CPlusPlus 10489 ? diag::err_typecheck_pointer_arith_void_type 10490 : diag::ext_gnu_void_ptr) 10491 << 0 /* one pointer */ << Pointer->getSourceRange(); 10492 } 10493 10494 /// Diagnose invalid arithmetic on a null pointer. 10495 /// 10496 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10497 /// idiom, which we recognize as a GNU extension. 10498 /// 10499 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10500 Expr *Pointer, bool IsGNUIdiom) { 10501 if (IsGNUIdiom) 10502 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10503 << Pointer->getSourceRange(); 10504 else 10505 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10506 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10507 } 10508 10509 /// Diagnose invalid subraction on a null pointer. 10510 /// 10511 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10512 Expr *Pointer, bool BothNull) { 10513 // Null - null is valid in C++ [expr.add]p7 10514 if (BothNull && S.getLangOpts().CPlusPlus) 10515 return; 10516 10517 // Is this s a macro from a system header? 10518 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10519 return; 10520 10521 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10522 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10523 } 10524 10525 /// Diagnose invalid arithmetic on two function pointers. 10526 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10527 Expr *LHS, Expr *RHS) { 10528 assert(LHS->getType()->isAnyPointerType()); 10529 assert(RHS->getType()->isAnyPointerType()); 10530 S.Diag(Loc, S.getLangOpts().CPlusPlus 10531 ? diag::err_typecheck_pointer_arith_function_type 10532 : diag::ext_gnu_ptr_func_arith) 10533 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10534 // We only show the second type if it differs from the first. 10535 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10536 RHS->getType()) 10537 << RHS->getType()->getPointeeType() 10538 << LHS->getSourceRange() << RHS->getSourceRange(); 10539 } 10540 10541 /// Diagnose invalid arithmetic on a function pointer. 10542 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10543 Expr *Pointer) { 10544 assert(Pointer->getType()->isAnyPointerType()); 10545 S.Diag(Loc, S.getLangOpts().CPlusPlus 10546 ? diag::err_typecheck_pointer_arith_function_type 10547 : diag::ext_gnu_ptr_func_arith) 10548 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10549 << 0 /* one pointer, so only one type */ 10550 << Pointer->getSourceRange(); 10551 } 10552 10553 /// Emit error if Operand is incomplete pointer type 10554 /// 10555 /// \returns True if pointer has incomplete type 10556 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10557 Expr *Operand) { 10558 QualType ResType = Operand->getType(); 10559 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10560 ResType = ResAtomicType->getValueType(); 10561 10562 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10563 QualType PointeeTy = ResType->getPointeeType(); 10564 return S.RequireCompleteSizedType( 10565 Loc, PointeeTy, 10566 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10567 Operand->getSourceRange()); 10568 } 10569 10570 /// Check the validity of an arithmetic pointer operand. 10571 /// 10572 /// If the operand has pointer type, this code will check for pointer types 10573 /// which are invalid in arithmetic operations. These will be diagnosed 10574 /// appropriately, including whether or not the use is supported as an 10575 /// extension. 10576 /// 10577 /// \returns True when the operand is valid to use (even if as an extension). 10578 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10579 Expr *Operand) { 10580 QualType ResType = Operand->getType(); 10581 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10582 ResType = ResAtomicType->getValueType(); 10583 10584 if (!ResType->isAnyPointerType()) return true; 10585 10586 QualType PointeeTy = ResType->getPointeeType(); 10587 if (PointeeTy->isVoidType()) { 10588 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10589 return !S.getLangOpts().CPlusPlus; 10590 } 10591 if (PointeeTy->isFunctionType()) { 10592 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10593 return !S.getLangOpts().CPlusPlus; 10594 } 10595 10596 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10597 10598 return true; 10599 } 10600 10601 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10602 /// operands. 10603 /// 10604 /// This routine will diagnose any invalid arithmetic on pointer operands much 10605 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10606 /// for emitting a single diagnostic even for operations where both LHS and RHS 10607 /// are (potentially problematic) pointers. 10608 /// 10609 /// \returns True when the operand is valid to use (even if as an extension). 10610 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10611 Expr *LHSExpr, Expr *RHSExpr) { 10612 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10613 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10614 if (!isLHSPointer && !isRHSPointer) return true; 10615 10616 QualType LHSPointeeTy, RHSPointeeTy; 10617 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10618 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10619 10620 // if both are pointers check if operation is valid wrt address spaces 10621 if (isLHSPointer && isRHSPointer) { 10622 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10623 S.Diag(Loc, 10624 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10625 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10626 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10627 return false; 10628 } 10629 } 10630 10631 // Check for arithmetic on pointers to incomplete types. 10632 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10633 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10634 if (isLHSVoidPtr || isRHSVoidPtr) { 10635 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10636 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10637 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10638 10639 return !S.getLangOpts().CPlusPlus; 10640 } 10641 10642 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10643 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10644 if (isLHSFuncPtr || isRHSFuncPtr) { 10645 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10646 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10647 RHSExpr); 10648 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10649 10650 return !S.getLangOpts().CPlusPlus; 10651 } 10652 10653 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10654 return false; 10655 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10656 return false; 10657 10658 return true; 10659 } 10660 10661 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10662 /// literal. 10663 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10664 Expr *LHSExpr, Expr *RHSExpr) { 10665 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10666 Expr* IndexExpr = RHSExpr; 10667 if (!StrExpr) { 10668 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10669 IndexExpr = LHSExpr; 10670 } 10671 10672 bool IsStringPlusInt = StrExpr && 10673 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10674 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10675 return; 10676 10677 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10678 Self.Diag(OpLoc, diag::warn_string_plus_int) 10679 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10680 10681 // Only print a fixit for "str" + int, not for int + "str". 10682 if (IndexExpr == RHSExpr) { 10683 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10684 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10685 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10686 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10687 << FixItHint::CreateInsertion(EndLoc, "]"); 10688 } else 10689 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10690 } 10691 10692 /// Emit a warning when adding a char literal to a string. 10693 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10694 Expr *LHSExpr, Expr *RHSExpr) { 10695 const Expr *StringRefExpr = LHSExpr; 10696 const CharacterLiteral *CharExpr = 10697 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10698 10699 if (!CharExpr) { 10700 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10701 StringRefExpr = RHSExpr; 10702 } 10703 10704 if (!CharExpr || !StringRefExpr) 10705 return; 10706 10707 const QualType StringType = StringRefExpr->getType(); 10708 10709 // Return if not a PointerType. 10710 if (!StringType->isAnyPointerType()) 10711 return; 10712 10713 // Return if not a CharacterType. 10714 if (!StringType->getPointeeType()->isAnyCharacterType()) 10715 return; 10716 10717 ASTContext &Ctx = Self.getASTContext(); 10718 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10719 10720 const QualType CharType = CharExpr->getType(); 10721 if (!CharType->isAnyCharacterType() && 10722 CharType->isIntegerType() && 10723 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10724 Self.Diag(OpLoc, diag::warn_string_plus_char) 10725 << DiagRange << Ctx.CharTy; 10726 } else { 10727 Self.Diag(OpLoc, diag::warn_string_plus_char) 10728 << DiagRange << CharExpr->getType(); 10729 } 10730 10731 // Only print a fixit for str + char, not for char + str. 10732 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10733 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10734 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10735 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10736 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10737 << FixItHint::CreateInsertion(EndLoc, "]"); 10738 } else { 10739 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10740 } 10741 } 10742 10743 /// Emit error when two pointers are incompatible. 10744 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10745 Expr *LHSExpr, Expr *RHSExpr) { 10746 assert(LHSExpr->getType()->isAnyPointerType()); 10747 assert(RHSExpr->getType()->isAnyPointerType()); 10748 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10749 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10750 << RHSExpr->getSourceRange(); 10751 } 10752 10753 // C99 6.5.6 10754 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10755 SourceLocation Loc, BinaryOperatorKind Opc, 10756 QualType* CompLHSTy) { 10757 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10758 10759 if (LHS.get()->getType()->isVectorType() || 10760 RHS.get()->getType()->isVectorType()) { 10761 QualType compType = CheckVectorOperands( 10762 LHS, RHS, Loc, CompLHSTy, 10763 /*AllowBothBool*/getLangOpts().AltiVec, 10764 /*AllowBoolConversions*/getLangOpts().ZVector); 10765 if (CompLHSTy) *CompLHSTy = compType; 10766 return compType; 10767 } 10768 10769 if (LHS.get()->getType()->isConstantMatrixType() || 10770 RHS.get()->getType()->isConstantMatrixType()) { 10771 QualType compType = 10772 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10773 if (CompLHSTy) 10774 *CompLHSTy = compType; 10775 return compType; 10776 } 10777 10778 QualType compType = UsualArithmeticConversions( 10779 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10780 if (LHS.isInvalid() || RHS.isInvalid()) 10781 return QualType(); 10782 10783 // Diagnose "string literal" '+' int and string '+' "char literal". 10784 if (Opc == BO_Add) { 10785 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10786 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10787 } 10788 10789 // handle the common case first (both operands are arithmetic). 10790 if (!compType.isNull() && compType->isArithmeticType()) { 10791 if (CompLHSTy) *CompLHSTy = compType; 10792 return compType; 10793 } 10794 10795 // Type-checking. Ultimately the pointer's going to be in PExp; 10796 // note that we bias towards the LHS being the pointer. 10797 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10798 10799 bool isObjCPointer; 10800 if (PExp->getType()->isPointerType()) { 10801 isObjCPointer = false; 10802 } else if (PExp->getType()->isObjCObjectPointerType()) { 10803 isObjCPointer = true; 10804 } else { 10805 std::swap(PExp, IExp); 10806 if (PExp->getType()->isPointerType()) { 10807 isObjCPointer = false; 10808 } else if (PExp->getType()->isObjCObjectPointerType()) { 10809 isObjCPointer = true; 10810 } else { 10811 return InvalidOperands(Loc, LHS, RHS); 10812 } 10813 } 10814 assert(PExp->getType()->isAnyPointerType()); 10815 10816 if (!IExp->getType()->isIntegerType()) 10817 return InvalidOperands(Loc, LHS, RHS); 10818 10819 // Adding to a null pointer results in undefined behavior. 10820 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10821 Context, Expr::NPC_ValueDependentIsNotNull)) { 10822 // In C++ adding zero to a null pointer is defined. 10823 Expr::EvalResult KnownVal; 10824 if (!getLangOpts().CPlusPlus || 10825 (!IExp->isValueDependent() && 10826 (!IExp->EvaluateAsInt(KnownVal, Context) || 10827 KnownVal.Val.getInt() != 0))) { 10828 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10829 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10830 Context, BO_Add, PExp, IExp); 10831 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10832 } 10833 } 10834 10835 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10836 return QualType(); 10837 10838 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10839 return QualType(); 10840 10841 // Check array bounds for pointer arithemtic 10842 CheckArrayAccess(PExp, IExp); 10843 10844 if (CompLHSTy) { 10845 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10846 if (LHSTy.isNull()) { 10847 LHSTy = LHS.get()->getType(); 10848 if (LHSTy->isPromotableIntegerType()) 10849 LHSTy = Context.getPromotedIntegerType(LHSTy); 10850 } 10851 *CompLHSTy = LHSTy; 10852 } 10853 10854 return PExp->getType(); 10855 } 10856 10857 // C99 6.5.6 10858 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10859 SourceLocation Loc, 10860 QualType* CompLHSTy) { 10861 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10862 10863 if (LHS.get()->getType()->isVectorType() || 10864 RHS.get()->getType()->isVectorType()) { 10865 QualType compType = CheckVectorOperands( 10866 LHS, RHS, Loc, CompLHSTy, 10867 /*AllowBothBool*/getLangOpts().AltiVec, 10868 /*AllowBoolConversions*/getLangOpts().ZVector); 10869 if (CompLHSTy) *CompLHSTy = compType; 10870 return compType; 10871 } 10872 10873 if (LHS.get()->getType()->isConstantMatrixType() || 10874 RHS.get()->getType()->isConstantMatrixType()) { 10875 QualType compType = 10876 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10877 if (CompLHSTy) 10878 *CompLHSTy = compType; 10879 return compType; 10880 } 10881 10882 QualType compType = UsualArithmeticConversions( 10883 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10884 if (LHS.isInvalid() || RHS.isInvalid()) 10885 return QualType(); 10886 10887 // Enforce type constraints: C99 6.5.6p3. 10888 10889 // Handle the common case first (both operands are arithmetic). 10890 if (!compType.isNull() && compType->isArithmeticType()) { 10891 if (CompLHSTy) *CompLHSTy = compType; 10892 return compType; 10893 } 10894 10895 // Either ptr - int or ptr - ptr. 10896 if (LHS.get()->getType()->isAnyPointerType()) { 10897 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10898 10899 // Diagnose bad cases where we step over interface counts. 10900 if (LHS.get()->getType()->isObjCObjectPointerType() && 10901 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10902 return QualType(); 10903 10904 // The result type of a pointer-int computation is the pointer type. 10905 if (RHS.get()->getType()->isIntegerType()) { 10906 // Subtracting from a null pointer should produce a warning. 10907 // The last argument to the diagnose call says this doesn't match the 10908 // GNU int-to-pointer idiom. 10909 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10910 Expr::NPC_ValueDependentIsNotNull)) { 10911 // In C++ adding zero to a null pointer is defined. 10912 Expr::EvalResult KnownVal; 10913 if (!getLangOpts().CPlusPlus || 10914 (!RHS.get()->isValueDependent() && 10915 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10916 KnownVal.Val.getInt() != 0))) { 10917 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10918 } 10919 } 10920 10921 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10922 return QualType(); 10923 10924 // Check array bounds for pointer arithemtic 10925 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10926 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10927 10928 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10929 return LHS.get()->getType(); 10930 } 10931 10932 // Handle pointer-pointer subtractions. 10933 if (const PointerType *RHSPTy 10934 = RHS.get()->getType()->getAs<PointerType>()) { 10935 QualType rpointee = RHSPTy->getPointeeType(); 10936 10937 if (getLangOpts().CPlusPlus) { 10938 // Pointee types must be the same: C++ [expr.add] 10939 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10940 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10941 } 10942 } else { 10943 // Pointee types must be compatible C99 6.5.6p3 10944 if (!Context.typesAreCompatible( 10945 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10946 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10947 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10948 return QualType(); 10949 } 10950 } 10951 10952 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10953 LHS.get(), RHS.get())) 10954 return QualType(); 10955 10956 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10957 Context, Expr::NPC_ValueDependentIsNotNull); 10958 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10959 Context, Expr::NPC_ValueDependentIsNotNull); 10960 10961 // Subtracting nullptr or from nullptr is suspect 10962 if (LHSIsNullPtr) 10963 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10964 if (RHSIsNullPtr) 10965 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10966 10967 // The pointee type may have zero size. As an extension, a structure or 10968 // union may have zero size or an array may have zero length. In this 10969 // case subtraction does not make sense. 10970 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10971 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10972 if (ElementSize.isZero()) { 10973 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10974 << rpointee.getUnqualifiedType() 10975 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10976 } 10977 } 10978 10979 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10980 return Context.getPointerDiffType(); 10981 } 10982 } 10983 10984 return InvalidOperands(Loc, LHS, RHS); 10985 } 10986 10987 static bool isScopedEnumerationType(QualType T) { 10988 if (const EnumType *ET = T->getAs<EnumType>()) 10989 return ET->getDecl()->isScoped(); 10990 return false; 10991 } 10992 10993 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10994 SourceLocation Loc, BinaryOperatorKind Opc, 10995 QualType LHSType) { 10996 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10997 // so skip remaining warnings as we don't want to modify values within Sema. 10998 if (S.getLangOpts().OpenCL) 10999 return; 11000 11001 // Check right/shifter operand 11002 Expr::EvalResult RHSResult; 11003 if (RHS.get()->isValueDependent() || 11004 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 11005 return; 11006 llvm::APSInt Right = RHSResult.Val.getInt(); 11007 11008 if (Right.isNegative()) { 11009 S.DiagRuntimeBehavior(Loc, RHS.get(), 11010 S.PDiag(diag::warn_shift_negative) 11011 << RHS.get()->getSourceRange()); 11012 return; 11013 } 11014 11015 QualType LHSExprType = LHS.get()->getType(); 11016 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 11017 if (LHSExprType->isBitIntType()) 11018 LeftSize = S.Context.getIntWidth(LHSExprType); 11019 else if (LHSExprType->isFixedPointType()) { 11020 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 11021 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 11022 } 11023 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 11024 if (Right.uge(LeftBits)) { 11025 S.DiagRuntimeBehavior(Loc, RHS.get(), 11026 S.PDiag(diag::warn_shift_gt_typewidth) 11027 << RHS.get()->getSourceRange()); 11028 return; 11029 } 11030 11031 // FIXME: We probably need to handle fixed point types specially here. 11032 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 11033 return; 11034 11035 // When left shifting an ICE which is signed, we can check for overflow which 11036 // according to C++ standards prior to C++2a has undefined behavior 11037 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 11038 // more than the maximum value representable in the result type, so never 11039 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11040 // expression is still probably a bug.) 11041 Expr::EvalResult LHSResult; 11042 if (LHS.get()->isValueDependent() || 11043 LHSType->hasUnsignedIntegerRepresentation() || 11044 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11045 return; 11046 llvm::APSInt Left = LHSResult.Val.getInt(); 11047 11048 // If LHS does not have a signed type and non-negative value 11049 // then, the behavior is undefined before C++2a. Warn about it. 11050 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11051 !S.getLangOpts().CPlusPlus20) { 11052 S.DiagRuntimeBehavior(Loc, LHS.get(), 11053 S.PDiag(diag::warn_shift_lhs_negative) 11054 << LHS.get()->getSourceRange()); 11055 return; 11056 } 11057 11058 llvm::APInt ResultBits = 11059 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11060 if (LeftBits.uge(ResultBits)) 11061 return; 11062 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11063 Result = Result.shl(Right); 11064 11065 // Print the bit representation of the signed integer as an unsigned 11066 // hexadecimal number. 11067 SmallString<40> HexResult; 11068 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11069 11070 // If we are only missing a sign bit, this is less likely to result in actual 11071 // bugs -- if the result is cast back to an unsigned type, it will have the 11072 // expected value. Thus we place this behind a different warning that can be 11073 // turned off separately if needed. 11074 if (LeftBits == ResultBits - 1) { 11075 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11076 << HexResult << LHSType 11077 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11078 return; 11079 } 11080 11081 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11082 << HexResult.str() << Result.getMinSignedBits() << LHSType 11083 << Left.getBitWidth() << LHS.get()->getSourceRange() 11084 << RHS.get()->getSourceRange(); 11085 } 11086 11087 /// Return the resulting type when a vector is shifted 11088 /// by a scalar or vector shift amount. 11089 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11090 SourceLocation Loc, bool IsCompAssign) { 11091 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11092 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11093 !LHS.get()->getType()->isVectorType()) { 11094 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11095 << RHS.get()->getType() << LHS.get()->getType() 11096 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11097 return QualType(); 11098 } 11099 11100 if (!IsCompAssign) { 11101 LHS = S.UsualUnaryConversions(LHS.get()); 11102 if (LHS.isInvalid()) return QualType(); 11103 } 11104 11105 RHS = S.UsualUnaryConversions(RHS.get()); 11106 if (RHS.isInvalid()) return QualType(); 11107 11108 QualType LHSType = LHS.get()->getType(); 11109 // Note that LHS might be a scalar because the routine calls not only in 11110 // OpenCL case. 11111 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11112 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11113 11114 // Note that RHS might not be a vector. 11115 QualType RHSType = RHS.get()->getType(); 11116 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11117 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11118 11119 // The operands need to be integers. 11120 if (!LHSEleType->isIntegerType()) { 11121 S.Diag(Loc, diag::err_typecheck_expect_int) 11122 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11123 return QualType(); 11124 } 11125 11126 if (!RHSEleType->isIntegerType()) { 11127 S.Diag(Loc, diag::err_typecheck_expect_int) 11128 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11129 return QualType(); 11130 } 11131 11132 if (!LHSVecTy) { 11133 assert(RHSVecTy); 11134 if (IsCompAssign) 11135 return RHSType; 11136 if (LHSEleType != RHSEleType) { 11137 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11138 LHSEleType = RHSEleType; 11139 } 11140 QualType VecTy = 11141 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11142 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11143 LHSType = VecTy; 11144 } else if (RHSVecTy) { 11145 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11146 // are applied component-wise. So if RHS is a vector, then ensure 11147 // that the number of elements is the same as LHS... 11148 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11149 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11150 << LHS.get()->getType() << RHS.get()->getType() 11151 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11152 return QualType(); 11153 } 11154 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11155 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11156 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11157 if (LHSBT != RHSBT && 11158 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11159 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11160 << LHS.get()->getType() << RHS.get()->getType() 11161 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11162 } 11163 } 11164 } else { 11165 // ...else expand RHS to match the number of elements in LHS. 11166 QualType VecTy = 11167 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11168 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11169 } 11170 11171 return LHSType; 11172 } 11173 11174 // C99 6.5.7 11175 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11176 SourceLocation Loc, BinaryOperatorKind Opc, 11177 bool IsCompAssign) { 11178 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11179 11180 // Vector shifts promote their scalar inputs to vector type. 11181 if (LHS.get()->getType()->isVectorType() || 11182 RHS.get()->getType()->isVectorType()) { 11183 if (LangOpts.ZVector) { 11184 // The shift operators for the z vector extensions work basically 11185 // like general shifts, except that neither the LHS nor the RHS is 11186 // allowed to be a "vector bool". 11187 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11188 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11189 return InvalidOperands(Loc, LHS, RHS); 11190 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11191 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11192 return InvalidOperands(Loc, LHS, RHS); 11193 } 11194 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11195 } 11196 11197 // Shifts don't perform usual arithmetic conversions, they just do integer 11198 // promotions on each operand. C99 6.5.7p3 11199 11200 // For the LHS, do usual unary conversions, but then reset them away 11201 // if this is a compound assignment. 11202 ExprResult OldLHS = LHS; 11203 LHS = UsualUnaryConversions(LHS.get()); 11204 if (LHS.isInvalid()) 11205 return QualType(); 11206 QualType LHSType = LHS.get()->getType(); 11207 if (IsCompAssign) LHS = OldLHS; 11208 11209 // The RHS is simpler. 11210 RHS = UsualUnaryConversions(RHS.get()); 11211 if (RHS.isInvalid()) 11212 return QualType(); 11213 QualType RHSType = RHS.get()->getType(); 11214 11215 // C99 6.5.7p2: Each of the operands shall have integer type. 11216 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11217 if ((!LHSType->isFixedPointOrIntegerType() && 11218 !LHSType->hasIntegerRepresentation()) || 11219 !RHSType->hasIntegerRepresentation()) 11220 return InvalidOperands(Loc, LHS, RHS); 11221 11222 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11223 // hasIntegerRepresentation() above instead of this. 11224 if (isScopedEnumerationType(LHSType) || 11225 isScopedEnumerationType(RHSType)) { 11226 return InvalidOperands(Loc, LHS, RHS); 11227 } 11228 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11229 11230 // "The type of the result is that of the promoted left operand." 11231 return LHSType; 11232 } 11233 11234 /// Diagnose bad pointer comparisons. 11235 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11236 ExprResult &LHS, ExprResult &RHS, 11237 bool IsError) { 11238 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11239 : diag::ext_typecheck_comparison_of_distinct_pointers) 11240 << LHS.get()->getType() << RHS.get()->getType() 11241 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11242 } 11243 11244 /// Returns false if the pointers are converted to a composite type, 11245 /// true otherwise. 11246 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11247 ExprResult &LHS, ExprResult &RHS) { 11248 // C++ [expr.rel]p2: 11249 // [...] Pointer conversions (4.10) and qualification 11250 // conversions (4.4) are performed on pointer operands (or on 11251 // a pointer operand and a null pointer constant) to bring 11252 // them to their composite pointer type. [...] 11253 // 11254 // C++ [expr.eq]p1 uses the same notion for (in)equality 11255 // comparisons of pointers. 11256 11257 QualType LHSType = LHS.get()->getType(); 11258 QualType RHSType = RHS.get()->getType(); 11259 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11260 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11261 11262 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11263 if (T.isNull()) { 11264 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11265 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11266 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11267 else 11268 S.InvalidOperands(Loc, LHS, RHS); 11269 return true; 11270 } 11271 11272 return false; 11273 } 11274 11275 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11276 ExprResult &LHS, 11277 ExprResult &RHS, 11278 bool IsError) { 11279 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11280 : diag::ext_typecheck_comparison_of_fptr_to_void) 11281 << LHS.get()->getType() << RHS.get()->getType() 11282 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11283 } 11284 11285 static bool isObjCObjectLiteral(ExprResult &E) { 11286 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11287 case Stmt::ObjCArrayLiteralClass: 11288 case Stmt::ObjCDictionaryLiteralClass: 11289 case Stmt::ObjCStringLiteralClass: 11290 case Stmt::ObjCBoxedExprClass: 11291 return true; 11292 default: 11293 // Note that ObjCBoolLiteral is NOT an object literal! 11294 return false; 11295 } 11296 } 11297 11298 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11299 const ObjCObjectPointerType *Type = 11300 LHS->getType()->getAs<ObjCObjectPointerType>(); 11301 11302 // If this is not actually an Objective-C object, bail out. 11303 if (!Type) 11304 return false; 11305 11306 // Get the LHS object's interface type. 11307 QualType InterfaceType = Type->getPointeeType(); 11308 11309 // If the RHS isn't an Objective-C object, bail out. 11310 if (!RHS->getType()->isObjCObjectPointerType()) 11311 return false; 11312 11313 // Try to find the -isEqual: method. 11314 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11315 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11316 InterfaceType, 11317 /*IsInstance=*/true); 11318 if (!Method) { 11319 if (Type->isObjCIdType()) { 11320 // For 'id', just check the global pool. 11321 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11322 /*receiverId=*/true); 11323 } else { 11324 // Check protocols. 11325 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11326 /*IsInstance=*/true); 11327 } 11328 } 11329 11330 if (!Method) 11331 return false; 11332 11333 QualType T = Method->parameters()[0]->getType(); 11334 if (!T->isObjCObjectPointerType()) 11335 return false; 11336 11337 QualType R = Method->getReturnType(); 11338 if (!R->isScalarType()) 11339 return false; 11340 11341 return true; 11342 } 11343 11344 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11345 FromE = FromE->IgnoreParenImpCasts(); 11346 switch (FromE->getStmtClass()) { 11347 default: 11348 break; 11349 case Stmt::ObjCStringLiteralClass: 11350 // "string literal" 11351 return LK_String; 11352 case Stmt::ObjCArrayLiteralClass: 11353 // "array literal" 11354 return LK_Array; 11355 case Stmt::ObjCDictionaryLiteralClass: 11356 // "dictionary literal" 11357 return LK_Dictionary; 11358 case Stmt::BlockExprClass: 11359 return LK_Block; 11360 case Stmt::ObjCBoxedExprClass: { 11361 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11362 switch (Inner->getStmtClass()) { 11363 case Stmt::IntegerLiteralClass: 11364 case Stmt::FloatingLiteralClass: 11365 case Stmt::CharacterLiteralClass: 11366 case Stmt::ObjCBoolLiteralExprClass: 11367 case Stmt::CXXBoolLiteralExprClass: 11368 // "numeric literal" 11369 return LK_Numeric; 11370 case Stmt::ImplicitCastExprClass: { 11371 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11372 // Boolean literals can be represented by implicit casts. 11373 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11374 return LK_Numeric; 11375 break; 11376 } 11377 default: 11378 break; 11379 } 11380 return LK_Boxed; 11381 } 11382 } 11383 return LK_None; 11384 } 11385 11386 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11387 ExprResult &LHS, ExprResult &RHS, 11388 BinaryOperator::Opcode Opc){ 11389 Expr *Literal; 11390 Expr *Other; 11391 if (isObjCObjectLiteral(LHS)) { 11392 Literal = LHS.get(); 11393 Other = RHS.get(); 11394 } else { 11395 Literal = RHS.get(); 11396 Other = LHS.get(); 11397 } 11398 11399 // Don't warn on comparisons against nil. 11400 Other = Other->IgnoreParenCasts(); 11401 if (Other->isNullPointerConstant(S.getASTContext(), 11402 Expr::NPC_ValueDependentIsNotNull)) 11403 return; 11404 11405 // This should be kept in sync with warn_objc_literal_comparison. 11406 // LK_String should always be after the other literals, since it has its own 11407 // warning flag. 11408 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11409 assert(LiteralKind != Sema::LK_Block); 11410 if (LiteralKind == Sema::LK_None) { 11411 llvm_unreachable("Unknown Objective-C object literal kind"); 11412 } 11413 11414 if (LiteralKind == Sema::LK_String) 11415 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11416 << Literal->getSourceRange(); 11417 else 11418 S.Diag(Loc, diag::warn_objc_literal_comparison) 11419 << LiteralKind << Literal->getSourceRange(); 11420 11421 if (BinaryOperator::isEqualityOp(Opc) && 11422 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11423 SourceLocation Start = LHS.get()->getBeginLoc(); 11424 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11425 CharSourceRange OpRange = 11426 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11427 11428 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11429 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11430 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11431 << FixItHint::CreateInsertion(End, "]"); 11432 } 11433 } 11434 11435 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11436 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11437 ExprResult &RHS, SourceLocation Loc, 11438 BinaryOperatorKind Opc) { 11439 // Check that left hand side is !something. 11440 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11441 if (!UO || UO->getOpcode() != UO_LNot) return; 11442 11443 // Only check if the right hand side is non-bool arithmetic type. 11444 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11445 11446 // Make sure that the something in !something is not bool. 11447 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11448 if (SubExpr->isKnownToHaveBooleanValue()) return; 11449 11450 // Emit warning. 11451 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11452 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11453 << Loc << IsBitwiseOp; 11454 11455 // First note suggest !(x < y) 11456 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11457 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11458 FirstClose = S.getLocForEndOfToken(FirstClose); 11459 if (FirstClose.isInvalid()) 11460 FirstOpen = SourceLocation(); 11461 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11462 << IsBitwiseOp 11463 << FixItHint::CreateInsertion(FirstOpen, "(") 11464 << FixItHint::CreateInsertion(FirstClose, ")"); 11465 11466 // Second note suggests (!x) < y 11467 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11468 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11469 SecondClose = S.getLocForEndOfToken(SecondClose); 11470 if (SecondClose.isInvalid()) 11471 SecondOpen = SourceLocation(); 11472 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11473 << FixItHint::CreateInsertion(SecondOpen, "(") 11474 << FixItHint::CreateInsertion(SecondClose, ")"); 11475 } 11476 11477 // Returns true if E refers to a non-weak array. 11478 static bool checkForArray(const Expr *E) { 11479 const ValueDecl *D = nullptr; 11480 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11481 D = DR->getDecl(); 11482 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11483 if (Mem->isImplicitAccess()) 11484 D = Mem->getMemberDecl(); 11485 } 11486 if (!D) 11487 return false; 11488 return D->getType()->isArrayType() && !D->isWeak(); 11489 } 11490 11491 /// Diagnose some forms of syntactically-obvious tautological comparison. 11492 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11493 Expr *LHS, Expr *RHS, 11494 BinaryOperatorKind Opc) { 11495 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11496 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11497 11498 QualType LHSType = LHS->getType(); 11499 QualType RHSType = RHS->getType(); 11500 if (LHSType->hasFloatingRepresentation() || 11501 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11502 S.inTemplateInstantiation()) 11503 return; 11504 11505 // Comparisons between two array types are ill-formed for operator<=>, so 11506 // we shouldn't emit any additional warnings about it. 11507 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11508 return; 11509 11510 // For non-floating point types, check for self-comparisons of the form 11511 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11512 // often indicate logic errors in the program. 11513 // 11514 // NOTE: Don't warn about comparison expressions resulting from macro 11515 // expansion. Also don't warn about comparisons which are only self 11516 // comparisons within a template instantiation. The warnings should catch 11517 // obvious cases in the definition of the template anyways. The idea is to 11518 // warn when the typed comparison operator will always evaluate to the same 11519 // result. 11520 11521 // Used for indexing into %select in warn_comparison_always 11522 enum { 11523 AlwaysConstant, 11524 AlwaysTrue, 11525 AlwaysFalse, 11526 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11527 }; 11528 11529 // C++2a [depr.array.comp]: 11530 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11531 // operands of array type are deprecated. 11532 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11533 RHSStripped->getType()->isArrayType()) { 11534 S.Diag(Loc, diag::warn_depr_array_comparison) 11535 << LHS->getSourceRange() << RHS->getSourceRange() 11536 << LHSStripped->getType() << RHSStripped->getType(); 11537 // Carry on to produce the tautological comparison warning, if this 11538 // expression is potentially-evaluated, we can resolve the array to a 11539 // non-weak declaration, and so on. 11540 } 11541 11542 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11543 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11544 unsigned Result; 11545 switch (Opc) { 11546 case BO_EQ: 11547 case BO_LE: 11548 case BO_GE: 11549 Result = AlwaysTrue; 11550 break; 11551 case BO_NE: 11552 case BO_LT: 11553 case BO_GT: 11554 Result = AlwaysFalse; 11555 break; 11556 case BO_Cmp: 11557 Result = AlwaysEqual; 11558 break; 11559 default: 11560 Result = AlwaysConstant; 11561 break; 11562 } 11563 S.DiagRuntimeBehavior(Loc, nullptr, 11564 S.PDiag(diag::warn_comparison_always) 11565 << 0 /*self-comparison*/ 11566 << Result); 11567 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11568 // What is it always going to evaluate to? 11569 unsigned Result; 11570 switch (Opc) { 11571 case BO_EQ: // e.g. array1 == array2 11572 Result = AlwaysFalse; 11573 break; 11574 case BO_NE: // e.g. array1 != array2 11575 Result = AlwaysTrue; 11576 break; 11577 default: // e.g. array1 <= array2 11578 // The best we can say is 'a constant' 11579 Result = AlwaysConstant; 11580 break; 11581 } 11582 S.DiagRuntimeBehavior(Loc, nullptr, 11583 S.PDiag(diag::warn_comparison_always) 11584 << 1 /*array comparison*/ 11585 << Result); 11586 } 11587 } 11588 11589 if (isa<CastExpr>(LHSStripped)) 11590 LHSStripped = LHSStripped->IgnoreParenCasts(); 11591 if (isa<CastExpr>(RHSStripped)) 11592 RHSStripped = RHSStripped->IgnoreParenCasts(); 11593 11594 // Warn about comparisons against a string constant (unless the other 11595 // operand is null); the user probably wants string comparison function. 11596 Expr *LiteralString = nullptr; 11597 Expr *LiteralStringStripped = nullptr; 11598 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11599 !RHSStripped->isNullPointerConstant(S.Context, 11600 Expr::NPC_ValueDependentIsNull)) { 11601 LiteralString = LHS; 11602 LiteralStringStripped = LHSStripped; 11603 } else if ((isa<StringLiteral>(RHSStripped) || 11604 isa<ObjCEncodeExpr>(RHSStripped)) && 11605 !LHSStripped->isNullPointerConstant(S.Context, 11606 Expr::NPC_ValueDependentIsNull)) { 11607 LiteralString = RHS; 11608 LiteralStringStripped = RHSStripped; 11609 } 11610 11611 if (LiteralString) { 11612 S.DiagRuntimeBehavior(Loc, nullptr, 11613 S.PDiag(diag::warn_stringcompare) 11614 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11615 << LiteralString->getSourceRange()); 11616 } 11617 } 11618 11619 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11620 switch (CK) { 11621 default: { 11622 #ifndef NDEBUG 11623 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11624 << "\n"; 11625 #endif 11626 llvm_unreachable("unhandled cast kind"); 11627 } 11628 case CK_UserDefinedConversion: 11629 return ICK_Identity; 11630 case CK_LValueToRValue: 11631 return ICK_Lvalue_To_Rvalue; 11632 case CK_ArrayToPointerDecay: 11633 return ICK_Array_To_Pointer; 11634 case CK_FunctionToPointerDecay: 11635 return ICK_Function_To_Pointer; 11636 case CK_IntegralCast: 11637 return ICK_Integral_Conversion; 11638 case CK_FloatingCast: 11639 return ICK_Floating_Conversion; 11640 case CK_IntegralToFloating: 11641 case CK_FloatingToIntegral: 11642 return ICK_Floating_Integral; 11643 case CK_IntegralComplexCast: 11644 case CK_FloatingComplexCast: 11645 case CK_FloatingComplexToIntegralComplex: 11646 case CK_IntegralComplexToFloatingComplex: 11647 return ICK_Complex_Conversion; 11648 case CK_FloatingComplexToReal: 11649 case CK_FloatingRealToComplex: 11650 case CK_IntegralComplexToReal: 11651 case CK_IntegralRealToComplex: 11652 return ICK_Complex_Real; 11653 } 11654 } 11655 11656 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11657 QualType FromType, 11658 SourceLocation Loc) { 11659 // Check for a narrowing implicit conversion. 11660 StandardConversionSequence SCS; 11661 SCS.setAsIdentityConversion(); 11662 SCS.setToType(0, FromType); 11663 SCS.setToType(1, ToType); 11664 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11665 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11666 11667 APValue PreNarrowingValue; 11668 QualType PreNarrowingType; 11669 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11670 PreNarrowingType, 11671 /*IgnoreFloatToIntegralConversion*/ true)) { 11672 case NK_Dependent_Narrowing: 11673 // Implicit conversion to a narrower type, but the expression is 11674 // value-dependent so we can't tell whether it's actually narrowing. 11675 case NK_Not_Narrowing: 11676 return false; 11677 11678 case NK_Constant_Narrowing: 11679 // Implicit conversion to a narrower type, and the value is not a constant 11680 // expression. 11681 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11682 << /*Constant*/ 1 11683 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11684 return true; 11685 11686 case NK_Variable_Narrowing: 11687 // Implicit conversion to a narrower type, and the value is not a constant 11688 // expression. 11689 case NK_Type_Narrowing: 11690 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11691 << /*Constant*/ 0 << FromType << ToType; 11692 // TODO: It's not a constant expression, but what if the user intended it 11693 // to be? Can we produce notes to help them figure out why it isn't? 11694 return true; 11695 } 11696 llvm_unreachable("unhandled case in switch"); 11697 } 11698 11699 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11700 ExprResult &LHS, 11701 ExprResult &RHS, 11702 SourceLocation Loc) { 11703 QualType LHSType = LHS.get()->getType(); 11704 QualType RHSType = RHS.get()->getType(); 11705 // Dig out the original argument type and expression before implicit casts 11706 // were applied. These are the types/expressions we need to check the 11707 // [expr.spaceship] requirements against. 11708 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11709 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11710 QualType LHSStrippedType = LHSStripped.get()->getType(); 11711 QualType RHSStrippedType = RHSStripped.get()->getType(); 11712 11713 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11714 // other is not, the program is ill-formed. 11715 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11716 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11717 return QualType(); 11718 } 11719 11720 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11721 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11722 RHSStrippedType->isEnumeralType(); 11723 if (NumEnumArgs == 1) { 11724 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11725 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11726 if (OtherTy->hasFloatingRepresentation()) { 11727 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11728 return QualType(); 11729 } 11730 } 11731 if (NumEnumArgs == 2) { 11732 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11733 // type E, the operator yields the result of converting the operands 11734 // to the underlying type of E and applying <=> to the converted operands. 11735 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11736 S.InvalidOperands(Loc, LHS, RHS); 11737 return QualType(); 11738 } 11739 QualType IntType = 11740 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11741 assert(IntType->isArithmeticType()); 11742 11743 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11744 // promote the boolean type, and all other promotable integer types, to 11745 // avoid this. 11746 if (IntType->isPromotableIntegerType()) 11747 IntType = S.Context.getPromotedIntegerType(IntType); 11748 11749 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11750 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11751 LHSType = RHSType = IntType; 11752 } 11753 11754 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11755 // usual arithmetic conversions are applied to the operands. 11756 QualType Type = 11757 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11758 if (LHS.isInvalid() || RHS.isInvalid()) 11759 return QualType(); 11760 if (Type.isNull()) 11761 return S.InvalidOperands(Loc, LHS, RHS); 11762 11763 Optional<ComparisonCategoryType> CCT = 11764 getComparisonCategoryForBuiltinCmp(Type); 11765 if (!CCT) 11766 return S.InvalidOperands(Loc, LHS, RHS); 11767 11768 bool HasNarrowing = checkThreeWayNarrowingConversion( 11769 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11770 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11771 RHS.get()->getBeginLoc()); 11772 if (HasNarrowing) 11773 return QualType(); 11774 11775 assert(!Type.isNull() && "composite type for <=> has not been set"); 11776 11777 return S.CheckComparisonCategoryType( 11778 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11779 } 11780 11781 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11782 ExprResult &RHS, 11783 SourceLocation Loc, 11784 BinaryOperatorKind Opc) { 11785 if (Opc == BO_Cmp) 11786 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11787 11788 // C99 6.5.8p3 / C99 6.5.9p4 11789 QualType Type = 11790 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11791 if (LHS.isInvalid() || RHS.isInvalid()) 11792 return QualType(); 11793 if (Type.isNull()) 11794 return S.InvalidOperands(Loc, LHS, RHS); 11795 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11796 11797 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11798 return S.InvalidOperands(Loc, LHS, RHS); 11799 11800 // Check for comparisons of floating point operands using != and ==. 11801 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11802 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11803 11804 // The result of comparisons is 'bool' in C++, 'int' in C. 11805 return S.Context.getLogicalOperationType(); 11806 } 11807 11808 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11809 if (!NullE.get()->getType()->isAnyPointerType()) 11810 return; 11811 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11812 if (!E.get()->getType()->isAnyPointerType() && 11813 E.get()->isNullPointerConstant(Context, 11814 Expr::NPC_ValueDependentIsNotNull) == 11815 Expr::NPCK_ZeroExpression) { 11816 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11817 if (CL->getValue() == 0) 11818 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11819 << NullValue 11820 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11821 NullValue ? "NULL" : "(void *)0"); 11822 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11823 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11824 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11825 if (T == Context.CharTy) 11826 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11827 << NullValue 11828 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11829 NullValue ? "NULL" : "(void *)0"); 11830 } 11831 } 11832 } 11833 11834 // C99 6.5.8, C++ [expr.rel] 11835 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11836 SourceLocation Loc, 11837 BinaryOperatorKind Opc) { 11838 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11839 bool IsThreeWay = Opc == BO_Cmp; 11840 bool IsOrdered = IsRelational || IsThreeWay; 11841 auto IsAnyPointerType = [](ExprResult E) { 11842 QualType Ty = E.get()->getType(); 11843 return Ty->isPointerType() || Ty->isMemberPointerType(); 11844 }; 11845 11846 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11847 // type, array-to-pointer, ..., conversions are performed on both operands to 11848 // bring them to their composite type. 11849 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11850 // any type-related checks. 11851 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11852 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11853 if (LHS.isInvalid()) 11854 return QualType(); 11855 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11856 if (RHS.isInvalid()) 11857 return QualType(); 11858 } else { 11859 LHS = DefaultLvalueConversion(LHS.get()); 11860 if (LHS.isInvalid()) 11861 return QualType(); 11862 RHS = DefaultLvalueConversion(RHS.get()); 11863 if (RHS.isInvalid()) 11864 return QualType(); 11865 } 11866 11867 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11868 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11869 CheckPtrComparisonWithNullChar(LHS, RHS); 11870 CheckPtrComparisonWithNullChar(RHS, LHS); 11871 } 11872 11873 // Handle vector comparisons separately. 11874 if (LHS.get()->getType()->isVectorType() || 11875 RHS.get()->getType()->isVectorType()) 11876 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11877 11878 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11879 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11880 11881 QualType LHSType = LHS.get()->getType(); 11882 QualType RHSType = RHS.get()->getType(); 11883 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11884 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11885 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11886 11887 const Expr::NullPointerConstantKind LHSNullKind = 11888 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11889 const Expr::NullPointerConstantKind RHSNullKind = 11890 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11891 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11892 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11893 11894 auto computeResultTy = [&]() { 11895 if (Opc != BO_Cmp) 11896 return Context.getLogicalOperationType(); 11897 assert(getLangOpts().CPlusPlus); 11898 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11899 11900 QualType CompositeTy = LHS.get()->getType(); 11901 assert(!CompositeTy->isReferenceType()); 11902 11903 Optional<ComparisonCategoryType> CCT = 11904 getComparisonCategoryForBuiltinCmp(CompositeTy); 11905 if (!CCT) 11906 return InvalidOperands(Loc, LHS, RHS); 11907 11908 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11909 // P0946R0: Comparisons between a null pointer constant and an object 11910 // pointer result in std::strong_equality, which is ill-formed under 11911 // P1959R0. 11912 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11913 << (LHSIsNull ? LHS.get()->getSourceRange() 11914 : RHS.get()->getSourceRange()); 11915 return QualType(); 11916 } 11917 11918 return CheckComparisonCategoryType( 11919 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11920 }; 11921 11922 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11923 bool IsEquality = Opc == BO_EQ; 11924 if (RHSIsNull) 11925 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11926 RHS.get()->getSourceRange()); 11927 else 11928 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11929 LHS.get()->getSourceRange()); 11930 } 11931 11932 if (IsOrdered && LHSType->isFunctionPointerType() && 11933 RHSType->isFunctionPointerType()) { 11934 // Valid unless a relational comparison of function pointers 11935 bool IsError = Opc == BO_Cmp; 11936 auto DiagID = 11937 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11938 : getLangOpts().CPlusPlus 11939 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11940 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11941 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11942 << RHS.get()->getSourceRange(); 11943 if (IsError) 11944 return QualType(); 11945 } 11946 11947 if ((LHSType->isIntegerType() && !LHSIsNull) || 11948 (RHSType->isIntegerType() && !RHSIsNull)) { 11949 // Skip normal pointer conversion checks in this case; we have better 11950 // diagnostics for this below. 11951 } else if (getLangOpts().CPlusPlus) { 11952 // Equality comparison of a function pointer to a void pointer is invalid, 11953 // but we allow it as an extension. 11954 // FIXME: If we really want to allow this, should it be part of composite 11955 // pointer type computation so it works in conditionals too? 11956 if (!IsOrdered && 11957 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11958 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11959 // This is a gcc extension compatibility comparison. 11960 // In a SFINAE context, we treat this as a hard error to maintain 11961 // conformance with the C++ standard. 11962 diagnoseFunctionPointerToVoidComparison( 11963 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11964 11965 if (isSFINAEContext()) 11966 return QualType(); 11967 11968 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11969 return computeResultTy(); 11970 } 11971 11972 // C++ [expr.eq]p2: 11973 // If at least one operand is a pointer [...] bring them to their 11974 // composite pointer type. 11975 // C++ [expr.spaceship]p6 11976 // If at least one of the operands is of pointer type, [...] bring them 11977 // to their composite pointer type. 11978 // C++ [expr.rel]p2: 11979 // If both operands are pointers, [...] bring them to their composite 11980 // pointer type. 11981 // For <=>, the only valid non-pointer types are arrays and functions, and 11982 // we already decayed those, so this is really the same as the relational 11983 // comparison rule. 11984 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11985 (IsOrdered ? 2 : 1) && 11986 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11987 RHSType->isObjCObjectPointerType()))) { 11988 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11989 return QualType(); 11990 return computeResultTy(); 11991 } 11992 } else if (LHSType->isPointerType() && 11993 RHSType->isPointerType()) { // C99 6.5.8p2 11994 // All of the following pointer-related warnings are GCC extensions, except 11995 // when handling null pointer constants. 11996 QualType LCanPointeeTy = 11997 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11998 QualType RCanPointeeTy = 11999 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12000 12001 // C99 6.5.9p2 and C99 6.5.8p2 12002 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 12003 RCanPointeeTy.getUnqualifiedType())) { 12004 if (IsRelational) { 12005 // Pointers both need to point to complete or incomplete types 12006 if ((LCanPointeeTy->isIncompleteType() != 12007 RCanPointeeTy->isIncompleteType()) && 12008 !getLangOpts().C11) { 12009 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 12010 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 12011 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 12012 << RCanPointeeTy->isIncompleteType(); 12013 } 12014 } 12015 } else if (!IsRelational && 12016 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 12017 // Valid unless comparison between non-null pointer and function pointer 12018 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 12019 && !LHSIsNull && !RHSIsNull) 12020 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 12021 /*isError*/false); 12022 } else { 12023 // Invalid 12024 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 12025 } 12026 if (LCanPointeeTy != RCanPointeeTy) { 12027 // Treat NULL constant as a special case in OpenCL. 12028 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 12029 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 12030 Diag(Loc, 12031 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 12032 << LHSType << RHSType << 0 /* comparison */ 12033 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12034 } 12035 } 12036 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 12037 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12038 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12039 : CK_BitCast; 12040 if (LHSIsNull && !RHSIsNull) 12041 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12042 else 12043 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12044 } 12045 return computeResultTy(); 12046 } 12047 12048 if (getLangOpts().CPlusPlus) { 12049 // C++ [expr.eq]p4: 12050 // Two operands of type std::nullptr_t or one operand of type 12051 // std::nullptr_t and the other a null pointer constant compare equal. 12052 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12053 if (LHSType->isNullPtrType()) { 12054 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12055 return computeResultTy(); 12056 } 12057 if (RHSType->isNullPtrType()) { 12058 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12059 return computeResultTy(); 12060 } 12061 } 12062 12063 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12064 // These aren't covered by the composite pointer type rules. 12065 if (!IsOrdered && RHSType->isNullPtrType() && 12066 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12067 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12068 return computeResultTy(); 12069 } 12070 if (!IsOrdered && LHSType->isNullPtrType() && 12071 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12072 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12073 return computeResultTy(); 12074 } 12075 12076 if (IsRelational && 12077 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12078 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12079 // HACK: Relational comparison of nullptr_t against a pointer type is 12080 // invalid per DR583, but we allow it within std::less<> and friends, 12081 // since otherwise common uses of it break. 12082 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12083 // friends to have std::nullptr_t overload candidates. 12084 DeclContext *DC = CurContext; 12085 if (isa<FunctionDecl>(DC)) 12086 DC = DC->getParent(); 12087 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12088 if (CTSD->isInStdNamespace() && 12089 llvm::StringSwitch<bool>(CTSD->getName()) 12090 .Cases("less", "less_equal", "greater", "greater_equal", true) 12091 .Default(false)) { 12092 if (RHSType->isNullPtrType()) 12093 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12094 else 12095 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12096 return computeResultTy(); 12097 } 12098 } 12099 } 12100 12101 // C++ [expr.eq]p2: 12102 // If at least one operand is a pointer to member, [...] bring them to 12103 // their composite pointer type. 12104 if (!IsOrdered && 12105 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12106 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12107 return QualType(); 12108 else 12109 return computeResultTy(); 12110 } 12111 } 12112 12113 // Handle block pointer types. 12114 if (!IsOrdered && LHSType->isBlockPointerType() && 12115 RHSType->isBlockPointerType()) { 12116 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12117 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12118 12119 if (!LHSIsNull && !RHSIsNull && 12120 !Context.typesAreCompatible(lpointee, rpointee)) { 12121 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12122 << LHSType << RHSType << LHS.get()->getSourceRange() 12123 << RHS.get()->getSourceRange(); 12124 } 12125 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12126 return computeResultTy(); 12127 } 12128 12129 // Allow block pointers to be compared with null pointer constants. 12130 if (!IsOrdered 12131 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12132 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12133 if (!LHSIsNull && !RHSIsNull) { 12134 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12135 ->getPointeeType()->isVoidType()) 12136 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12137 ->getPointeeType()->isVoidType()))) 12138 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12139 << LHSType << RHSType << LHS.get()->getSourceRange() 12140 << RHS.get()->getSourceRange(); 12141 } 12142 if (LHSIsNull && !RHSIsNull) 12143 LHS = ImpCastExprToType(LHS.get(), RHSType, 12144 RHSType->isPointerType() ? CK_BitCast 12145 : CK_AnyPointerToBlockPointerCast); 12146 else 12147 RHS = ImpCastExprToType(RHS.get(), LHSType, 12148 LHSType->isPointerType() ? CK_BitCast 12149 : CK_AnyPointerToBlockPointerCast); 12150 return computeResultTy(); 12151 } 12152 12153 if (LHSType->isObjCObjectPointerType() || 12154 RHSType->isObjCObjectPointerType()) { 12155 const PointerType *LPT = LHSType->getAs<PointerType>(); 12156 const PointerType *RPT = RHSType->getAs<PointerType>(); 12157 if (LPT || RPT) { 12158 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12159 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12160 12161 if (!LPtrToVoid && !RPtrToVoid && 12162 !Context.typesAreCompatible(LHSType, RHSType)) { 12163 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12164 /*isError*/false); 12165 } 12166 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12167 // the RHS, but we have test coverage for this behavior. 12168 // FIXME: Consider using convertPointersToCompositeType in C++. 12169 if (LHSIsNull && !RHSIsNull) { 12170 Expr *E = LHS.get(); 12171 if (getLangOpts().ObjCAutoRefCount) 12172 CheckObjCConversion(SourceRange(), RHSType, E, 12173 CCK_ImplicitConversion); 12174 LHS = ImpCastExprToType(E, RHSType, 12175 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12176 } 12177 else { 12178 Expr *E = RHS.get(); 12179 if (getLangOpts().ObjCAutoRefCount) 12180 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12181 /*Diagnose=*/true, 12182 /*DiagnoseCFAudited=*/false, Opc); 12183 RHS = ImpCastExprToType(E, LHSType, 12184 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12185 } 12186 return computeResultTy(); 12187 } 12188 if (LHSType->isObjCObjectPointerType() && 12189 RHSType->isObjCObjectPointerType()) { 12190 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12191 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12192 /*isError*/false); 12193 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12194 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12195 12196 if (LHSIsNull && !RHSIsNull) 12197 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12198 else 12199 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12200 return computeResultTy(); 12201 } 12202 12203 if (!IsOrdered && LHSType->isBlockPointerType() && 12204 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12205 LHS = ImpCastExprToType(LHS.get(), RHSType, 12206 CK_BlockPointerToObjCPointerCast); 12207 return computeResultTy(); 12208 } else if (!IsOrdered && 12209 LHSType->isBlockCompatibleObjCPointerType(Context) && 12210 RHSType->isBlockPointerType()) { 12211 RHS = ImpCastExprToType(RHS.get(), LHSType, 12212 CK_BlockPointerToObjCPointerCast); 12213 return computeResultTy(); 12214 } 12215 } 12216 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12217 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12218 unsigned DiagID = 0; 12219 bool isError = false; 12220 if (LangOpts.DebuggerSupport) { 12221 // Under a debugger, allow the comparison of pointers to integers, 12222 // since users tend to want to compare addresses. 12223 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12224 (RHSIsNull && RHSType->isIntegerType())) { 12225 if (IsOrdered) { 12226 isError = getLangOpts().CPlusPlus; 12227 DiagID = 12228 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12229 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12230 } 12231 } else if (getLangOpts().CPlusPlus) { 12232 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12233 isError = true; 12234 } else if (IsOrdered) 12235 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12236 else 12237 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12238 12239 if (DiagID) { 12240 Diag(Loc, DiagID) 12241 << LHSType << RHSType << LHS.get()->getSourceRange() 12242 << RHS.get()->getSourceRange(); 12243 if (isError) 12244 return QualType(); 12245 } 12246 12247 if (LHSType->isIntegerType()) 12248 LHS = ImpCastExprToType(LHS.get(), RHSType, 12249 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12250 else 12251 RHS = ImpCastExprToType(RHS.get(), LHSType, 12252 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12253 return computeResultTy(); 12254 } 12255 12256 // Handle block pointers. 12257 if (!IsOrdered && RHSIsNull 12258 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12259 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12260 return computeResultTy(); 12261 } 12262 if (!IsOrdered && LHSIsNull 12263 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12264 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12265 return computeResultTy(); 12266 } 12267 12268 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 12269 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12270 return computeResultTy(); 12271 } 12272 12273 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12274 return computeResultTy(); 12275 } 12276 12277 if (LHSIsNull && RHSType->isQueueT()) { 12278 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12279 return computeResultTy(); 12280 } 12281 12282 if (LHSType->isQueueT() && RHSIsNull) { 12283 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12284 return computeResultTy(); 12285 } 12286 } 12287 12288 return InvalidOperands(Loc, LHS, RHS); 12289 } 12290 12291 // Return a signed ext_vector_type that is of identical size and number of 12292 // elements. For floating point vectors, return an integer type of identical 12293 // size and number of elements. In the non ext_vector_type case, search from 12294 // the largest type to the smallest type to avoid cases where long long == long, 12295 // where long gets picked over long long. 12296 QualType Sema::GetSignedVectorType(QualType V) { 12297 const VectorType *VTy = V->castAs<VectorType>(); 12298 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12299 12300 if (isa<ExtVectorType>(VTy)) { 12301 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12302 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12303 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12304 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12305 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12306 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12307 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12308 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); 12309 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12310 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12311 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12312 "Unhandled vector element size in vector compare"); 12313 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12314 } 12315 12316 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 12317 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), 12318 VectorType::GenericVector); 12319 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12320 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12321 VectorType::GenericVector); 12322 if (TypeSize == Context.getTypeSize(Context.LongTy)) 12323 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12324 VectorType::GenericVector); 12325 if (TypeSize == Context.getTypeSize(Context.IntTy)) 12326 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12327 VectorType::GenericVector); 12328 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12329 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12330 VectorType::GenericVector); 12331 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12332 "Unhandled vector element size in vector compare"); 12333 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12334 VectorType::GenericVector); 12335 } 12336 12337 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12338 /// operates on extended vector types. Instead of producing an IntTy result, 12339 /// like a scalar comparison, a vector comparison produces a vector of integer 12340 /// types. 12341 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12342 SourceLocation Loc, 12343 BinaryOperatorKind Opc) { 12344 if (Opc == BO_Cmp) { 12345 Diag(Loc, diag::err_three_way_vector_comparison); 12346 return QualType(); 12347 } 12348 12349 // Check to make sure we're operating on vectors of the same type and width, 12350 // Allowing one side to be a scalar of element type. 12351 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12352 /*AllowBothBool*/true, 12353 /*AllowBoolConversions*/getLangOpts().ZVector); 12354 if (vType.isNull()) 12355 return vType; 12356 12357 QualType LHSType = LHS.get()->getType(); 12358 12359 // Determine the return type of a vector compare. By default clang will return 12360 // a scalar for all vector compares except vector bool and vector pixel. 12361 // With the gcc compiler we will always return a vector type and with the xl 12362 // compiler we will always return a scalar type. This switch allows choosing 12363 // which behavior is prefered. 12364 if (getLangOpts().AltiVec) { 12365 switch (getLangOpts().getAltivecSrcCompat()) { 12366 case LangOptions::AltivecSrcCompatKind::Mixed: 12367 // If AltiVec, the comparison results in a numeric type, i.e. 12368 // bool for C++, int for C 12369 if (vType->castAs<VectorType>()->getVectorKind() == 12370 VectorType::AltiVecVector) 12371 return Context.getLogicalOperationType(); 12372 else 12373 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12374 break; 12375 case LangOptions::AltivecSrcCompatKind::GCC: 12376 // For GCC we always return the vector type. 12377 break; 12378 case LangOptions::AltivecSrcCompatKind::XL: 12379 return Context.getLogicalOperationType(); 12380 break; 12381 } 12382 } 12383 12384 // For non-floating point types, check for self-comparisons of the form 12385 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12386 // often indicate logic errors in the program. 12387 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12388 12389 // Check for comparisons of floating point operands using != and ==. 12390 if (BinaryOperator::isEqualityOp(Opc) && 12391 LHSType->hasFloatingRepresentation()) { 12392 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12393 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12394 } 12395 12396 // Return a signed type for the vector. 12397 return GetSignedVectorType(vType); 12398 } 12399 12400 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12401 const ExprResult &XorRHS, 12402 const SourceLocation Loc) { 12403 // Do not diagnose macros. 12404 if (Loc.isMacroID()) 12405 return; 12406 12407 // Do not diagnose if both LHS and RHS are macros. 12408 if (XorLHS.get()->getExprLoc().isMacroID() && 12409 XorRHS.get()->getExprLoc().isMacroID()) 12410 return; 12411 12412 bool Negative = false; 12413 bool ExplicitPlus = false; 12414 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12415 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12416 12417 if (!LHSInt) 12418 return; 12419 if (!RHSInt) { 12420 // Check negative literals. 12421 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12422 UnaryOperatorKind Opc = UO->getOpcode(); 12423 if (Opc != UO_Minus && Opc != UO_Plus) 12424 return; 12425 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12426 if (!RHSInt) 12427 return; 12428 Negative = (Opc == UO_Minus); 12429 ExplicitPlus = !Negative; 12430 } else { 12431 return; 12432 } 12433 } 12434 12435 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12436 llvm::APInt RightSideValue = RHSInt->getValue(); 12437 if (LeftSideValue != 2 && LeftSideValue != 10) 12438 return; 12439 12440 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12441 return; 12442 12443 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12444 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12445 llvm::StringRef ExprStr = 12446 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12447 12448 CharSourceRange XorRange = 12449 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12450 llvm::StringRef XorStr = 12451 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12452 // Do not diagnose if xor keyword/macro is used. 12453 if (XorStr == "xor") 12454 return; 12455 12456 std::string LHSStr = std::string(Lexer::getSourceText( 12457 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12458 S.getSourceManager(), S.getLangOpts())); 12459 std::string RHSStr = std::string(Lexer::getSourceText( 12460 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12461 S.getSourceManager(), S.getLangOpts())); 12462 12463 if (Negative) { 12464 RightSideValue = -RightSideValue; 12465 RHSStr = "-" + RHSStr; 12466 } else if (ExplicitPlus) { 12467 RHSStr = "+" + RHSStr; 12468 } 12469 12470 StringRef LHSStrRef = LHSStr; 12471 StringRef RHSStrRef = RHSStr; 12472 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12473 // literals. 12474 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12475 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12476 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12477 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12478 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12479 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12480 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 12481 return; 12482 12483 bool SuggestXor = 12484 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12485 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12486 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12487 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12488 std::string SuggestedExpr = "1 << " + RHSStr; 12489 bool Overflow = false; 12490 llvm::APInt One = (LeftSideValue - 1); 12491 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12492 if (Overflow) { 12493 if (RightSideIntValue < 64) 12494 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12495 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12496 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12497 else if (RightSideIntValue == 64) 12498 S.Diag(Loc, diag::warn_xor_used_as_pow) 12499 << ExprStr << toString(XorValue, 10, true); 12500 else 12501 return; 12502 } else { 12503 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12504 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12505 << toString(PowValue, 10, true) 12506 << FixItHint::CreateReplacement( 12507 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12508 } 12509 12510 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12511 << ("0x2 ^ " + RHSStr) << SuggestXor; 12512 } else if (LeftSideValue == 10) { 12513 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12514 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12515 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12516 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12517 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12518 << ("0xA ^ " + RHSStr) << SuggestXor; 12519 } 12520 } 12521 12522 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12523 SourceLocation Loc) { 12524 // Ensure that either both operands are of the same vector type, or 12525 // one operand is of a vector type and the other is of its element type. 12526 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12527 /*AllowBothBool*/true, 12528 /*AllowBoolConversions*/false); 12529 if (vType.isNull()) 12530 return InvalidOperands(Loc, LHS, RHS); 12531 if (getLangOpts().OpenCL && 12532 getLangOpts().getOpenCLCompatibleVersion() < 120 && 12533 vType->hasFloatingRepresentation()) 12534 return InvalidOperands(Loc, LHS, RHS); 12535 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12536 // usage of the logical operators && and || with vectors in C. This 12537 // check could be notionally dropped. 12538 if (!getLangOpts().CPlusPlus && 12539 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12540 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12541 12542 return GetSignedVectorType(LHS.get()->getType()); 12543 } 12544 12545 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12546 SourceLocation Loc, 12547 bool IsCompAssign) { 12548 if (!IsCompAssign) { 12549 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12550 if (LHS.isInvalid()) 12551 return QualType(); 12552 } 12553 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12554 if (RHS.isInvalid()) 12555 return QualType(); 12556 12557 // For conversion purposes, we ignore any qualifiers. 12558 // For example, "const float" and "float" are equivalent. 12559 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12560 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12561 12562 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12563 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12564 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12565 12566 if (Context.hasSameType(LHSType, RHSType)) 12567 return LHSType; 12568 12569 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12570 // case we have to return InvalidOperands. 12571 ExprResult OriginalLHS = LHS; 12572 ExprResult OriginalRHS = RHS; 12573 if (LHSMatType && !RHSMatType) { 12574 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12575 if (!RHS.isInvalid()) 12576 return LHSType; 12577 12578 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12579 } 12580 12581 if (!LHSMatType && RHSMatType) { 12582 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12583 if (!LHS.isInvalid()) 12584 return RHSType; 12585 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12586 } 12587 12588 return InvalidOperands(Loc, LHS, RHS); 12589 } 12590 12591 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12592 SourceLocation Loc, 12593 bool IsCompAssign) { 12594 if (!IsCompAssign) { 12595 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12596 if (LHS.isInvalid()) 12597 return QualType(); 12598 } 12599 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12600 if (RHS.isInvalid()) 12601 return QualType(); 12602 12603 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12604 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12605 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12606 12607 if (LHSMatType && RHSMatType) { 12608 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12609 return InvalidOperands(Loc, LHS, RHS); 12610 12611 if (!Context.hasSameType(LHSMatType->getElementType(), 12612 RHSMatType->getElementType())) 12613 return InvalidOperands(Loc, LHS, RHS); 12614 12615 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12616 LHSMatType->getNumRows(), 12617 RHSMatType->getNumColumns()); 12618 } 12619 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12620 } 12621 12622 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12623 SourceLocation Loc, 12624 BinaryOperatorKind Opc) { 12625 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12626 12627 bool IsCompAssign = 12628 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12629 12630 if (LHS.get()->getType()->isVectorType() || 12631 RHS.get()->getType()->isVectorType()) { 12632 if (LHS.get()->getType()->hasIntegerRepresentation() && 12633 RHS.get()->getType()->hasIntegerRepresentation()) 12634 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12635 /*AllowBothBool*/true, 12636 /*AllowBoolConversions*/getLangOpts().ZVector); 12637 return InvalidOperands(Loc, LHS, RHS); 12638 } 12639 12640 if (Opc == BO_And) 12641 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12642 12643 if (LHS.get()->getType()->hasFloatingRepresentation() || 12644 RHS.get()->getType()->hasFloatingRepresentation()) 12645 return InvalidOperands(Loc, LHS, RHS); 12646 12647 ExprResult LHSResult = LHS, RHSResult = RHS; 12648 QualType compType = UsualArithmeticConversions( 12649 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12650 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12651 return QualType(); 12652 LHS = LHSResult.get(); 12653 RHS = RHSResult.get(); 12654 12655 if (Opc == BO_Xor) 12656 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12657 12658 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12659 return compType; 12660 return InvalidOperands(Loc, LHS, RHS); 12661 } 12662 12663 // C99 6.5.[13,14] 12664 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12665 SourceLocation Loc, 12666 BinaryOperatorKind Opc) { 12667 // Check vector operands differently. 12668 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12669 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12670 12671 bool EnumConstantInBoolContext = false; 12672 for (const ExprResult &HS : {LHS, RHS}) { 12673 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12674 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12675 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12676 EnumConstantInBoolContext = true; 12677 } 12678 } 12679 12680 if (EnumConstantInBoolContext) 12681 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12682 12683 // Diagnose cases where the user write a logical and/or but probably meant a 12684 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12685 // is a constant. 12686 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12687 !LHS.get()->getType()->isBooleanType() && 12688 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12689 // Don't warn in macros or template instantiations. 12690 !Loc.isMacroID() && !inTemplateInstantiation()) { 12691 // If the RHS can be constant folded, and if it constant folds to something 12692 // that isn't 0 or 1 (which indicate a potential logical operation that 12693 // happened to fold to true/false) then warn. 12694 // Parens on the RHS are ignored. 12695 Expr::EvalResult EVResult; 12696 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12697 llvm::APSInt Result = EVResult.Val.getInt(); 12698 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12699 !RHS.get()->getExprLoc().isMacroID()) || 12700 (Result != 0 && Result != 1)) { 12701 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12702 << RHS.get()->getSourceRange() 12703 << (Opc == BO_LAnd ? "&&" : "||"); 12704 // Suggest replacing the logical operator with the bitwise version 12705 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12706 << (Opc == BO_LAnd ? "&" : "|") 12707 << FixItHint::CreateReplacement(SourceRange( 12708 Loc, getLocForEndOfToken(Loc)), 12709 Opc == BO_LAnd ? "&" : "|"); 12710 if (Opc == BO_LAnd) 12711 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12712 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12713 << FixItHint::CreateRemoval( 12714 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12715 RHS.get()->getEndLoc())); 12716 } 12717 } 12718 } 12719 12720 if (!Context.getLangOpts().CPlusPlus) { 12721 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12722 // not operate on the built-in scalar and vector float types. 12723 if (Context.getLangOpts().OpenCL && 12724 Context.getLangOpts().OpenCLVersion < 120) { 12725 if (LHS.get()->getType()->isFloatingType() || 12726 RHS.get()->getType()->isFloatingType()) 12727 return InvalidOperands(Loc, LHS, RHS); 12728 } 12729 12730 LHS = UsualUnaryConversions(LHS.get()); 12731 if (LHS.isInvalid()) 12732 return QualType(); 12733 12734 RHS = UsualUnaryConversions(RHS.get()); 12735 if (RHS.isInvalid()) 12736 return QualType(); 12737 12738 if (!LHS.get()->getType()->isScalarType() || 12739 !RHS.get()->getType()->isScalarType()) 12740 return InvalidOperands(Loc, LHS, RHS); 12741 12742 return Context.IntTy; 12743 } 12744 12745 // The following is safe because we only use this method for 12746 // non-overloadable operands. 12747 12748 // C++ [expr.log.and]p1 12749 // C++ [expr.log.or]p1 12750 // The operands are both contextually converted to type bool. 12751 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12752 if (LHSRes.isInvalid()) 12753 return InvalidOperands(Loc, LHS, RHS); 12754 LHS = LHSRes; 12755 12756 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12757 if (RHSRes.isInvalid()) 12758 return InvalidOperands(Loc, LHS, RHS); 12759 RHS = RHSRes; 12760 12761 // C++ [expr.log.and]p2 12762 // C++ [expr.log.or]p2 12763 // The result is a bool. 12764 return Context.BoolTy; 12765 } 12766 12767 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12768 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12769 if (!ME) return false; 12770 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12771 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12772 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12773 if (!Base) return false; 12774 return Base->getMethodDecl() != nullptr; 12775 } 12776 12777 /// Is the given expression (which must be 'const') a reference to a 12778 /// variable which was originally non-const, but which has become 12779 /// 'const' due to being captured within a block? 12780 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12781 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12782 assert(E->isLValue() && E->getType().isConstQualified()); 12783 E = E->IgnoreParens(); 12784 12785 // Must be a reference to a declaration from an enclosing scope. 12786 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12787 if (!DRE) return NCCK_None; 12788 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12789 12790 // The declaration must be a variable which is not declared 'const'. 12791 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12792 if (!var) return NCCK_None; 12793 if (var->getType().isConstQualified()) return NCCK_None; 12794 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12795 12796 // Decide whether the first capture was for a block or a lambda. 12797 DeclContext *DC = S.CurContext, *Prev = nullptr; 12798 // Decide whether the first capture was for a block or a lambda. 12799 while (DC) { 12800 // For init-capture, it is possible that the variable belongs to the 12801 // template pattern of the current context. 12802 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12803 if (var->isInitCapture() && 12804 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12805 break; 12806 if (DC == var->getDeclContext()) 12807 break; 12808 Prev = DC; 12809 DC = DC->getParent(); 12810 } 12811 // Unless we have an init-capture, we've gone one step too far. 12812 if (!var->isInitCapture()) 12813 DC = Prev; 12814 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12815 } 12816 12817 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12818 Ty = Ty.getNonReferenceType(); 12819 if (IsDereference && Ty->isPointerType()) 12820 Ty = Ty->getPointeeType(); 12821 return !Ty.isConstQualified(); 12822 } 12823 12824 // Update err_typecheck_assign_const and note_typecheck_assign_const 12825 // when this enum is changed. 12826 enum { 12827 ConstFunction, 12828 ConstVariable, 12829 ConstMember, 12830 ConstMethod, 12831 NestedConstMember, 12832 ConstUnknown, // Keep as last element 12833 }; 12834 12835 /// Emit the "read-only variable not assignable" error and print notes to give 12836 /// more information about why the variable is not assignable, such as pointing 12837 /// to the declaration of a const variable, showing that a method is const, or 12838 /// that the function is returning a const reference. 12839 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12840 SourceLocation Loc) { 12841 SourceRange ExprRange = E->getSourceRange(); 12842 12843 // Only emit one error on the first const found. All other consts will emit 12844 // a note to the error. 12845 bool DiagnosticEmitted = false; 12846 12847 // Track if the current expression is the result of a dereference, and if the 12848 // next checked expression is the result of a dereference. 12849 bool IsDereference = false; 12850 bool NextIsDereference = false; 12851 12852 // Loop to process MemberExpr chains. 12853 while (true) { 12854 IsDereference = NextIsDereference; 12855 12856 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12857 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12858 NextIsDereference = ME->isArrow(); 12859 const ValueDecl *VD = ME->getMemberDecl(); 12860 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12861 // Mutable fields can be modified even if the class is const. 12862 if (Field->isMutable()) { 12863 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12864 break; 12865 } 12866 12867 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12868 if (!DiagnosticEmitted) { 12869 S.Diag(Loc, diag::err_typecheck_assign_const) 12870 << ExprRange << ConstMember << false /*static*/ << Field 12871 << Field->getType(); 12872 DiagnosticEmitted = true; 12873 } 12874 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12875 << ConstMember << false /*static*/ << Field << Field->getType() 12876 << Field->getSourceRange(); 12877 } 12878 E = ME->getBase(); 12879 continue; 12880 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12881 if (VDecl->getType().isConstQualified()) { 12882 if (!DiagnosticEmitted) { 12883 S.Diag(Loc, diag::err_typecheck_assign_const) 12884 << ExprRange << ConstMember << true /*static*/ << VDecl 12885 << VDecl->getType(); 12886 DiagnosticEmitted = true; 12887 } 12888 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12889 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12890 << VDecl->getSourceRange(); 12891 } 12892 // Static fields do not inherit constness from parents. 12893 break; 12894 } 12895 break; // End MemberExpr 12896 } else if (const ArraySubscriptExpr *ASE = 12897 dyn_cast<ArraySubscriptExpr>(E)) { 12898 E = ASE->getBase()->IgnoreParenImpCasts(); 12899 continue; 12900 } else if (const ExtVectorElementExpr *EVE = 12901 dyn_cast<ExtVectorElementExpr>(E)) { 12902 E = EVE->getBase()->IgnoreParenImpCasts(); 12903 continue; 12904 } 12905 break; 12906 } 12907 12908 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12909 // Function calls 12910 const FunctionDecl *FD = CE->getDirectCallee(); 12911 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12912 if (!DiagnosticEmitted) { 12913 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12914 << ConstFunction << FD; 12915 DiagnosticEmitted = true; 12916 } 12917 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12918 diag::note_typecheck_assign_const) 12919 << ConstFunction << FD << FD->getReturnType() 12920 << FD->getReturnTypeSourceRange(); 12921 } 12922 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12923 // Point to variable declaration. 12924 if (const ValueDecl *VD = DRE->getDecl()) { 12925 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12926 if (!DiagnosticEmitted) { 12927 S.Diag(Loc, diag::err_typecheck_assign_const) 12928 << ExprRange << ConstVariable << VD << VD->getType(); 12929 DiagnosticEmitted = true; 12930 } 12931 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12932 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12933 } 12934 } 12935 } else if (isa<CXXThisExpr>(E)) { 12936 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12937 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12938 if (MD->isConst()) { 12939 if (!DiagnosticEmitted) { 12940 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12941 << ConstMethod << MD; 12942 DiagnosticEmitted = true; 12943 } 12944 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12945 << ConstMethod << MD << MD->getSourceRange(); 12946 } 12947 } 12948 } 12949 } 12950 12951 if (DiagnosticEmitted) 12952 return; 12953 12954 // Can't determine a more specific message, so display the generic error. 12955 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12956 } 12957 12958 enum OriginalExprKind { 12959 OEK_Variable, 12960 OEK_Member, 12961 OEK_LValue 12962 }; 12963 12964 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12965 const RecordType *Ty, 12966 SourceLocation Loc, SourceRange Range, 12967 OriginalExprKind OEK, 12968 bool &DiagnosticEmitted) { 12969 std::vector<const RecordType *> RecordTypeList; 12970 RecordTypeList.push_back(Ty); 12971 unsigned NextToCheckIndex = 0; 12972 // We walk the record hierarchy breadth-first to ensure that we print 12973 // diagnostics in field nesting order. 12974 while (RecordTypeList.size() > NextToCheckIndex) { 12975 bool IsNested = NextToCheckIndex > 0; 12976 for (const FieldDecl *Field : 12977 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12978 // First, check every field for constness. 12979 QualType FieldTy = Field->getType(); 12980 if (FieldTy.isConstQualified()) { 12981 if (!DiagnosticEmitted) { 12982 S.Diag(Loc, diag::err_typecheck_assign_const) 12983 << Range << NestedConstMember << OEK << VD 12984 << IsNested << Field; 12985 DiagnosticEmitted = true; 12986 } 12987 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12988 << NestedConstMember << IsNested << Field 12989 << FieldTy << Field->getSourceRange(); 12990 } 12991 12992 // Then we append it to the list to check next in order. 12993 FieldTy = FieldTy.getCanonicalType(); 12994 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12995 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 12996 RecordTypeList.push_back(FieldRecTy); 12997 } 12998 } 12999 ++NextToCheckIndex; 13000 } 13001 } 13002 13003 /// Emit an error for the case where a record we are trying to assign to has a 13004 /// const-qualified field somewhere in its hierarchy. 13005 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 13006 SourceLocation Loc) { 13007 QualType Ty = E->getType(); 13008 assert(Ty->isRecordType() && "lvalue was not record?"); 13009 SourceRange Range = E->getSourceRange(); 13010 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 13011 bool DiagEmitted = false; 13012 13013 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 13014 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 13015 Range, OEK_Member, DiagEmitted); 13016 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13017 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 13018 Range, OEK_Variable, DiagEmitted); 13019 else 13020 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 13021 Range, OEK_LValue, DiagEmitted); 13022 if (!DiagEmitted) 13023 DiagnoseConstAssignment(S, E, Loc); 13024 } 13025 13026 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 13027 /// emit an error and return true. If so, return false. 13028 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 13029 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 13030 13031 S.CheckShadowingDeclModification(E, Loc); 13032 13033 SourceLocation OrigLoc = Loc; 13034 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 13035 &Loc); 13036 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 13037 IsLV = Expr::MLV_InvalidMessageExpression; 13038 if (IsLV == Expr::MLV_Valid) 13039 return false; 13040 13041 unsigned DiagID = 0; 13042 bool NeedType = false; 13043 switch (IsLV) { // C99 6.5.16p2 13044 case Expr::MLV_ConstQualified: 13045 // Use a specialized diagnostic when we're assigning to an object 13046 // from an enclosing function or block. 13047 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13048 if (NCCK == NCCK_Block) 13049 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13050 else 13051 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13052 break; 13053 } 13054 13055 // In ARC, use some specialized diagnostics for occasions where we 13056 // infer 'const'. These are always pseudo-strong variables. 13057 if (S.getLangOpts().ObjCAutoRefCount) { 13058 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13059 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13060 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13061 13062 // Use the normal diagnostic if it's pseudo-__strong but the 13063 // user actually wrote 'const'. 13064 if (var->isARCPseudoStrong() && 13065 (!var->getTypeSourceInfo() || 13066 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13067 // There are three pseudo-strong cases: 13068 // - self 13069 ObjCMethodDecl *method = S.getCurMethodDecl(); 13070 if (method && var == method->getSelfDecl()) { 13071 DiagID = method->isClassMethod() 13072 ? diag::err_typecheck_arc_assign_self_class_method 13073 : diag::err_typecheck_arc_assign_self; 13074 13075 // - Objective-C externally_retained attribute. 13076 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13077 isa<ParmVarDecl>(var)) { 13078 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13079 13080 // - fast enumeration variables 13081 } else { 13082 DiagID = diag::err_typecheck_arr_assign_enumeration; 13083 } 13084 13085 SourceRange Assign; 13086 if (Loc != OrigLoc) 13087 Assign = SourceRange(OrigLoc, OrigLoc); 13088 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13089 // We need to preserve the AST regardless, so migration tool 13090 // can do its job. 13091 return false; 13092 } 13093 } 13094 } 13095 13096 // If none of the special cases above are triggered, then this is a 13097 // simple const assignment. 13098 if (DiagID == 0) { 13099 DiagnoseConstAssignment(S, E, Loc); 13100 return true; 13101 } 13102 13103 break; 13104 case Expr::MLV_ConstAddrSpace: 13105 DiagnoseConstAssignment(S, E, Loc); 13106 return true; 13107 case Expr::MLV_ConstQualifiedField: 13108 DiagnoseRecursiveConstFields(S, E, Loc); 13109 return true; 13110 case Expr::MLV_ArrayType: 13111 case Expr::MLV_ArrayTemporary: 13112 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13113 NeedType = true; 13114 break; 13115 case Expr::MLV_NotObjectType: 13116 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13117 NeedType = true; 13118 break; 13119 case Expr::MLV_LValueCast: 13120 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13121 break; 13122 case Expr::MLV_Valid: 13123 llvm_unreachable("did not take early return for MLV_Valid"); 13124 case Expr::MLV_InvalidExpression: 13125 case Expr::MLV_MemberFunction: 13126 case Expr::MLV_ClassTemporary: 13127 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13128 break; 13129 case Expr::MLV_IncompleteType: 13130 case Expr::MLV_IncompleteVoidType: 13131 return S.RequireCompleteType(Loc, E->getType(), 13132 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13133 case Expr::MLV_DuplicateVectorComponents: 13134 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13135 break; 13136 case Expr::MLV_NoSetterProperty: 13137 llvm_unreachable("readonly properties should be processed differently"); 13138 case Expr::MLV_InvalidMessageExpression: 13139 DiagID = diag::err_readonly_message_assignment; 13140 break; 13141 case Expr::MLV_SubObjCPropertySetting: 13142 DiagID = diag::err_no_subobject_property_setting; 13143 break; 13144 } 13145 13146 SourceRange Assign; 13147 if (Loc != OrigLoc) 13148 Assign = SourceRange(OrigLoc, OrigLoc); 13149 if (NeedType) 13150 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13151 else 13152 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13153 return true; 13154 } 13155 13156 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13157 SourceLocation Loc, 13158 Sema &Sema) { 13159 if (Sema.inTemplateInstantiation()) 13160 return; 13161 if (Sema.isUnevaluatedContext()) 13162 return; 13163 if (Loc.isInvalid() || Loc.isMacroID()) 13164 return; 13165 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13166 return; 13167 13168 // C / C++ fields 13169 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13170 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13171 if (ML && MR) { 13172 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13173 return; 13174 const ValueDecl *LHSDecl = 13175 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13176 const ValueDecl *RHSDecl = 13177 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13178 if (LHSDecl != RHSDecl) 13179 return; 13180 if (LHSDecl->getType().isVolatileQualified()) 13181 return; 13182 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13183 if (RefTy->getPointeeType().isVolatileQualified()) 13184 return; 13185 13186 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13187 } 13188 13189 // Objective-C instance variables 13190 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13191 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13192 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13193 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13194 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13195 if (RL && RR && RL->getDecl() == RR->getDecl()) 13196 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13197 } 13198 } 13199 13200 // C99 6.5.16.1 13201 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13202 SourceLocation Loc, 13203 QualType CompoundType) { 13204 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13205 13206 // Verify that LHS is a modifiable lvalue, and emit error if not. 13207 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13208 return QualType(); 13209 13210 QualType LHSType = LHSExpr->getType(); 13211 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13212 CompoundType; 13213 // OpenCL v1.2 s6.1.1.1 p2: 13214 // The half data type can only be used to declare a pointer to a buffer that 13215 // contains half values 13216 if (getLangOpts().OpenCL && 13217 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13218 LHSType->isHalfType()) { 13219 Diag(Loc, diag::err_opencl_half_load_store) << 1 13220 << LHSType.getUnqualifiedType(); 13221 return QualType(); 13222 } 13223 13224 AssignConvertType ConvTy; 13225 if (CompoundType.isNull()) { 13226 Expr *RHSCheck = RHS.get(); 13227 13228 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13229 13230 QualType LHSTy(LHSType); 13231 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13232 if (RHS.isInvalid()) 13233 return QualType(); 13234 // Special case of NSObject attributes on c-style pointer types. 13235 if (ConvTy == IncompatiblePointer && 13236 ((Context.isObjCNSObjectType(LHSType) && 13237 RHSType->isObjCObjectPointerType()) || 13238 (Context.isObjCNSObjectType(RHSType) && 13239 LHSType->isObjCObjectPointerType()))) 13240 ConvTy = Compatible; 13241 13242 if (ConvTy == Compatible && 13243 LHSType->isObjCObjectType()) 13244 Diag(Loc, diag::err_objc_object_assignment) 13245 << LHSType; 13246 13247 // If the RHS is a unary plus or minus, check to see if they = and + are 13248 // right next to each other. If so, the user may have typo'd "x =+ 4" 13249 // instead of "x += 4". 13250 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13251 RHSCheck = ICE->getSubExpr(); 13252 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13253 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13254 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13255 // Only if the two operators are exactly adjacent. 13256 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13257 // And there is a space or other character before the subexpr of the 13258 // unary +/-. We don't want to warn on "x=-1". 13259 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13260 UO->getSubExpr()->getBeginLoc().isFileID()) { 13261 Diag(Loc, diag::warn_not_compound_assign) 13262 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13263 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13264 } 13265 } 13266 13267 if (ConvTy == Compatible) { 13268 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13269 // Warn about retain cycles where a block captures the LHS, but 13270 // not if the LHS is a simple variable into which the block is 13271 // being stored...unless that variable can be captured by reference! 13272 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13273 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13274 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13275 checkRetainCycles(LHSExpr, RHS.get()); 13276 } 13277 13278 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13279 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13280 // It is safe to assign a weak reference into a strong variable. 13281 // Although this code can still have problems: 13282 // id x = self.weakProp; 13283 // id y = self.weakProp; 13284 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13285 // paths through the function. This should be revisited if 13286 // -Wrepeated-use-of-weak is made flow-sensitive. 13287 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13288 // variable, which will be valid for the current autorelease scope. 13289 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13290 RHS.get()->getBeginLoc())) 13291 getCurFunction()->markSafeWeakUse(RHS.get()); 13292 13293 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13294 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13295 } 13296 } 13297 } else { 13298 // Compound assignment "x += y" 13299 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13300 } 13301 13302 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13303 RHS.get(), AA_Assigning)) 13304 return QualType(); 13305 13306 CheckForNullPointerDereference(*this, LHSExpr); 13307 13308 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13309 if (CompoundType.isNull()) { 13310 // C++2a [expr.ass]p5: 13311 // A simple-assignment whose left operand is of a volatile-qualified 13312 // type is deprecated unless the assignment is either a discarded-value 13313 // expression or an unevaluated operand 13314 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13315 } else { 13316 // C++2a [expr.ass]p6: 13317 // [Compound-assignment] expressions are deprecated if E1 has 13318 // volatile-qualified type 13319 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13320 } 13321 } 13322 13323 // C99 6.5.16p3: The type of an assignment expression is the type of the 13324 // left operand unless the left operand has qualified type, in which case 13325 // it is the unqualified version of the type of the left operand. 13326 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13327 // is converted to the type of the assignment expression (above). 13328 // C++ 5.17p1: the type of the assignment expression is that of its left 13329 // operand. 13330 return (getLangOpts().CPlusPlus 13331 ? LHSType : LHSType.getUnqualifiedType()); 13332 } 13333 13334 // Only ignore explicit casts to void. 13335 static bool IgnoreCommaOperand(const Expr *E) { 13336 E = E->IgnoreParens(); 13337 13338 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13339 if (CE->getCastKind() == CK_ToVoid) { 13340 return true; 13341 } 13342 13343 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13344 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13345 CE->getSubExpr()->getType()->isDependentType()) { 13346 return true; 13347 } 13348 } 13349 13350 return false; 13351 } 13352 13353 // Look for instances where it is likely the comma operator is confused with 13354 // another operator. There is an explicit list of acceptable expressions for 13355 // the left hand side of the comma operator, otherwise emit a warning. 13356 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13357 // No warnings in macros 13358 if (Loc.isMacroID()) 13359 return; 13360 13361 // Don't warn in template instantiations. 13362 if (inTemplateInstantiation()) 13363 return; 13364 13365 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13366 // instead, skip more than needed, then call back into here with the 13367 // CommaVisitor in SemaStmt.cpp. 13368 // The listed locations are the initialization and increment portions 13369 // of a for loop. The additional checks are on the condition of 13370 // if statements, do/while loops, and for loops. 13371 // Differences in scope flags for C89 mode requires the extra logic. 13372 const unsigned ForIncrementFlags = 13373 getLangOpts().C99 || getLangOpts().CPlusPlus 13374 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13375 : Scope::ContinueScope | Scope::BreakScope; 13376 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13377 const unsigned ScopeFlags = getCurScope()->getFlags(); 13378 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13379 (ScopeFlags & ForInitFlags) == ForInitFlags) 13380 return; 13381 13382 // If there are multiple comma operators used together, get the RHS of the 13383 // of the comma operator as the LHS. 13384 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13385 if (BO->getOpcode() != BO_Comma) 13386 break; 13387 LHS = BO->getRHS(); 13388 } 13389 13390 // Only allow some expressions on LHS to not warn. 13391 if (IgnoreCommaOperand(LHS)) 13392 return; 13393 13394 Diag(Loc, diag::warn_comma_operator); 13395 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13396 << LHS->getSourceRange() 13397 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13398 LangOpts.CPlusPlus ? "static_cast<void>(" 13399 : "(void)(") 13400 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13401 ")"); 13402 } 13403 13404 // C99 6.5.17 13405 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13406 SourceLocation Loc) { 13407 LHS = S.CheckPlaceholderExpr(LHS.get()); 13408 RHS = S.CheckPlaceholderExpr(RHS.get()); 13409 if (LHS.isInvalid() || RHS.isInvalid()) 13410 return QualType(); 13411 13412 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13413 // operands, but not unary promotions. 13414 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13415 13416 // So we treat the LHS as a ignored value, and in C++ we allow the 13417 // containing site to determine what should be done with the RHS. 13418 LHS = S.IgnoredValueConversions(LHS.get()); 13419 if (LHS.isInvalid()) 13420 return QualType(); 13421 13422 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 13423 13424 if (!S.getLangOpts().CPlusPlus) { 13425 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13426 if (RHS.isInvalid()) 13427 return QualType(); 13428 if (!RHS.get()->getType()->isVoidType()) 13429 S.RequireCompleteType(Loc, RHS.get()->getType(), 13430 diag::err_incomplete_type); 13431 } 13432 13433 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13434 S.DiagnoseCommaOperator(LHS.get(), Loc); 13435 13436 return RHS.get()->getType(); 13437 } 13438 13439 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13440 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13441 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13442 ExprValueKind &VK, 13443 ExprObjectKind &OK, 13444 SourceLocation OpLoc, 13445 bool IsInc, bool IsPrefix) { 13446 if (Op->isTypeDependent()) 13447 return S.Context.DependentTy; 13448 13449 QualType ResType = Op->getType(); 13450 // Atomic types can be used for increment / decrement where the non-atomic 13451 // versions can, so ignore the _Atomic() specifier for the purpose of 13452 // checking. 13453 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13454 ResType = ResAtomicType->getValueType(); 13455 13456 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13457 13458 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13459 // Decrement of bool is not allowed. 13460 if (!IsInc) { 13461 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13462 return QualType(); 13463 } 13464 // Increment of bool sets it to true, but is deprecated. 13465 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13466 : diag::warn_increment_bool) 13467 << Op->getSourceRange(); 13468 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13469 // Error on enum increments and decrements in C++ mode 13470 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13471 return QualType(); 13472 } else if (ResType->isRealType()) { 13473 // OK! 13474 } else if (ResType->isPointerType()) { 13475 // C99 6.5.2.4p2, 6.5.6p2 13476 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13477 return QualType(); 13478 } else if (ResType->isObjCObjectPointerType()) { 13479 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13480 // Otherwise, we just need a complete type. 13481 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13482 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13483 return QualType(); 13484 } else if (ResType->isAnyComplexType()) { 13485 // C99 does not support ++/-- on complex types, we allow as an extension. 13486 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13487 << ResType << Op->getSourceRange(); 13488 } else if (ResType->isPlaceholderType()) { 13489 ExprResult PR = S.CheckPlaceholderExpr(Op); 13490 if (PR.isInvalid()) return QualType(); 13491 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13492 IsInc, IsPrefix); 13493 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13494 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13495 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13496 (ResType->castAs<VectorType>()->getVectorKind() != 13497 VectorType::AltiVecBool)) { 13498 // The z vector extensions allow ++ and -- for non-bool vectors. 13499 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13500 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13501 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13502 } else { 13503 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13504 << ResType << int(IsInc) << Op->getSourceRange(); 13505 return QualType(); 13506 } 13507 // At this point, we know we have a real, complex or pointer type. 13508 // Now make sure the operand is a modifiable lvalue. 13509 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13510 return QualType(); 13511 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13512 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13513 // An operand with volatile-qualified type is deprecated 13514 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13515 << IsInc << ResType; 13516 } 13517 // In C++, a prefix increment is the same type as the operand. Otherwise 13518 // (in C or with postfix), the increment is the unqualified type of the 13519 // operand. 13520 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13521 VK = VK_LValue; 13522 OK = Op->getObjectKind(); 13523 return ResType; 13524 } else { 13525 VK = VK_PRValue; 13526 return ResType.getUnqualifiedType(); 13527 } 13528 } 13529 13530 13531 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13532 /// This routine allows us to typecheck complex/recursive expressions 13533 /// where the declaration is needed for type checking. We only need to 13534 /// handle cases when the expression references a function designator 13535 /// or is an lvalue. Here are some examples: 13536 /// - &(x) => x 13537 /// - &*****f => f for f a function designator. 13538 /// - &s.xx => s 13539 /// - &s.zz[1].yy -> s, if zz is an array 13540 /// - *(x + 1) -> x, if x is an array 13541 /// - &"123"[2] -> 0 13542 /// - & __real__ x -> x 13543 /// 13544 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13545 /// members. 13546 static ValueDecl *getPrimaryDecl(Expr *E) { 13547 switch (E->getStmtClass()) { 13548 case Stmt::DeclRefExprClass: 13549 return cast<DeclRefExpr>(E)->getDecl(); 13550 case Stmt::MemberExprClass: 13551 // If this is an arrow operator, the address is an offset from 13552 // the base's value, so the object the base refers to is 13553 // irrelevant. 13554 if (cast<MemberExpr>(E)->isArrow()) 13555 return nullptr; 13556 // Otherwise, the expression refers to a part of the base 13557 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13558 case Stmt::ArraySubscriptExprClass: { 13559 // FIXME: This code shouldn't be necessary! We should catch the implicit 13560 // promotion of register arrays earlier. 13561 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13562 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13563 if (ICE->getSubExpr()->getType()->isArrayType()) 13564 return getPrimaryDecl(ICE->getSubExpr()); 13565 } 13566 return nullptr; 13567 } 13568 case Stmt::UnaryOperatorClass: { 13569 UnaryOperator *UO = cast<UnaryOperator>(E); 13570 13571 switch(UO->getOpcode()) { 13572 case UO_Real: 13573 case UO_Imag: 13574 case UO_Extension: 13575 return getPrimaryDecl(UO->getSubExpr()); 13576 default: 13577 return nullptr; 13578 } 13579 } 13580 case Stmt::ParenExprClass: 13581 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13582 case Stmt::ImplicitCastExprClass: 13583 // If the result of an implicit cast is an l-value, we care about 13584 // the sub-expression; otherwise, the result here doesn't matter. 13585 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13586 case Stmt::CXXUuidofExprClass: 13587 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13588 default: 13589 return nullptr; 13590 } 13591 } 13592 13593 namespace { 13594 enum { 13595 AO_Bit_Field = 0, 13596 AO_Vector_Element = 1, 13597 AO_Property_Expansion = 2, 13598 AO_Register_Variable = 3, 13599 AO_Matrix_Element = 4, 13600 AO_No_Error = 5 13601 }; 13602 } 13603 /// Diagnose invalid operand for address of operations. 13604 /// 13605 /// \param Type The type of operand which cannot have its address taken. 13606 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13607 Expr *E, unsigned Type) { 13608 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13609 } 13610 13611 /// CheckAddressOfOperand - The operand of & must be either a function 13612 /// designator or an lvalue designating an object. If it is an lvalue, the 13613 /// object cannot be declared with storage class register or be a bit field. 13614 /// Note: The usual conversions are *not* applied to the operand of the & 13615 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13616 /// In C++, the operand might be an overloaded function name, in which case 13617 /// we allow the '&' but retain the overloaded-function type. 13618 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13619 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13620 if (PTy->getKind() == BuiltinType::Overload) { 13621 Expr *E = OrigOp.get()->IgnoreParens(); 13622 if (!isa<OverloadExpr>(E)) { 13623 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13624 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13625 << OrigOp.get()->getSourceRange(); 13626 return QualType(); 13627 } 13628 13629 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13630 if (isa<UnresolvedMemberExpr>(Ovl)) 13631 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13632 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13633 << OrigOp.get()->getSourceRange(); 13634 return QualType(); 13635 } 13636 13637 return Context.OverloadTy; 13638 } 13639 13640 if (PTy->getKind() == BuiltinType::UnknownAny) 13641 return Context.UnknownAnyTy; 13642 13643 if (PTy->getKind() == BuiltinType::BoundMember) { 13644 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13645 << OrigOp.get()->getSourceRange(); 13646 return QualType(); 13647 } 13648 13649 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13650 if (OrigOp.isInvalid()) return QualType(); 13651 } 13652 13653 if (OrigOp.get()->isTypeDependent()) 13654 return Context.DependentTy; 13655 13656 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13657 13658 // Make sure to ignore parentheses in subsequent checks 13659 Expr *op = OrigOp.get()->IgnoreParens(); 13660 13661 // In OpenCL captures for blocks called as lambda functions 13662 // are located in the private address space. Blocks used in 13663 // enqueue_kernel can be located in a different address space 13664 // depending on a vendor implementation. Thus preventing 13665 // taking an address of the capture to avoid invalid AS casts. 13666 if (LangOpts.OpenCL) { 13667 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13668 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13669 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13670 return QualType(); 13671 } 13672 } 13673 13674 if (getLangOpts().C99) { 13675 // Implement C99-only parts of addressof rules. 13676 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13677 if (uOp->getOpcode() == UO_Deref) 13678 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13679 // (assuming the deref expression is valid). 13680 return uOp->getSubExpr()->getType(); 13681 } 13682 // Technically, there should be a check for array subscript 13683 // expressions here, but the result of one is always an lvalue anyway. 13684 } 13685 ValueDecl *dcl = getPrimaryDecl(op); 13686 13687 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13688 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13689 op->getBeginLoc())) 13690 return QualType(); 13691 13692 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13693 unsigned AddressOfError = AO_No_Error; 13694 13695 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13696 bool sfinae = (bool)isSFINAEContext(); 13697 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13698 : diag::ext_typecheck_addrof_temporary) 13699 << op->getType() << op->getSourceRange(); 13700 if (sfinae) 13701 return QualType(); 13702 // Materialize the temporary as an lvalue so that we can take its address. 13703 OrigOp = op = 13704 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13705 } else if (isa<ObjCSelectorExpr>(op)) { 13706 return Context.getPointerType(op->getType()); 13707 } else if (lval == Expr::LV_MemberFunction) { 13708 // If it's an instance method, make a member pointer. 13709 // The expression must have exactly the form &A::foo. 13710 13711 // If the underlying expression isn't a decl ref, give up. 13712 if (!isa<DeclRefExpr>(op)) { 13713 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13714 << OrigOp.get()->getSourceRange(); 13715 return QualType(); 13716 } 13717 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13718 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13719 13720 // The id-expression was parenthesized. 13721 if (OrigOp.get() != DRE) { 13722 Diag(OpLoc, diag::err_parens_pointer_member_function) 13723 << OrigOp.get()->getSourceRange(); 13724 13725 // The method was named without a qualifier. 13726 } else if (!DRE->getQualifier()) { 13727 if (MD->getParent()->getName().empty()) 13728 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13729 << op->getSourceRange(); 13730 else { 13731 SmallString<32> Str; 13732 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13733 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13734 << op->getSourceRange() 13735 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13736 } 13737 } 13738 13739 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13740 if (isa<CXXDestructorDecl>(MD)) 13741 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13742 13743 QualType MPTy = Context.getMemberPointerType( 13744 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13745 // Under the MS ABI, lock down the inheritance model now. 13746 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13747 (void)isCompleteType(OpLoc, MPTy); 13748 return MPTy; 13749 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13750 // C99 6.5.3.2p1 13751 // The operand must be either an l-value or a function designator 13752 if (!op->getType()->isFunctionType()) { 13753 // Use a special diagnostic for loads from property references. 13754 if (isa<PseudoObjectExpr>(op)) { 13755 AddressOfError = AO_Property_Expansion; 13756 } else { 13757 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13758 << op->getType() << op->getSourceRange(); 13759 return QualType(); 13760 } 13761 } 13762 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13763 // The operand cannot be a bit-field 13764 AddressOfError = AO_Bit_Field; 13765 } else if (op->getObjectKind() == OK_VectorComponent) { 13766 // The operand cannot be an element of a vector 13767 AddressOfError = AO_Vector_Element; 13768 } else if (op->getObjectKind() == OK_MatrixComponent) { 13769 // The operand cannot be an element of a matrix. 13770 AddressOfError = AO_Matrix_Element; 13771 } else if (dcl) { // C99 6.5.3.2p1 13772 // We have an lvalue with a decl. Make sure the decl is not declared 13773 // with the register storage-class specifier. 13774 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13775 // in C++ it is not error to take address of a register 13776 // variable (c++03 7.1.1P3) 13777 if (vd->getStorageClass() == SC_Register && 13778 !getLangOpts().CPlusPlus) { 13779 AddressOfError = AO_Register_Variable; 13780 } 13781 } else if (isa<MSPropertyDecl>(dcl)) { 13782 AddressOfError = AO_Property_Expansion; 13783 } else if (isa<FunctionTemplateDecl>(dcl)) { 13784 return Context.OverloadTy; 13785 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13786 // Okay: we can take the address of a field. 13787 // Could be a pointer to member, though, if there is an explicit 13788 // scope qualifier for the class. 13789 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13790 DeclContext *Ctx = dcl->getDeclContext(); 13791 if (Ctx && Ctx->isRecord()) { 13792 if (dcl->getType()->isReferenceType()) { 13793 Diag(OpLoc, 13794 diag::err_cannot_form_pointer_to_member_of_reference_type) 13795 << dcl->getDeclName() << dcl->getType(); 13796 return QualType(); 13797 } 13798 13799 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13800 Ctx = Ctx->getParent(); 13801 13802 QualType MPTy = Context.getMemberPointerType( 13803 op->getType(), 13804 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13805 // Under the MS ABI, lock down the inheritance model now. 13806 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13807 (void)isCompleteType(OpLoc, MPTy); 13808 return MPTy; 13809 } 13810 } 13811 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13812 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13813 llvm_unreachable("Unknown/unexpected decl type"); 13814 } 13815 13816 if (AddressOfError != AO_No_Error) { 13817 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13818 return QualType(); 13819 } 13820 13821 if (lval == Expr::LV_IncompleteVoidType) { 13822 // Taking the address of a void variable is technically illegal, but we 13823 // allow it in cases which are otherwise valid. 13824 // Example: "extern void x; void* y = &x;". 13825 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13826 } 13827 13828 // If the operand has type "type", the result has type "pointer to type". 13829 if (op->getType()->isObjCObjectType()) 13830 return Context.getObjCObjectPointerType(op->getType()); 13831 13832 CheckAddressOfPackedMember(op); 13833 13834 return Context.getPointerType(op->getType()); 13835 } 13836 13837 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13838 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13839 if (!DRE) 13840 return; 13841 const Decl *D = DRE->getDecl(); 13842 if (!D) 13843 return; 13844 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13845 if (!Param) 13846 return; 13847 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13848 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13849 return; 13850 if (FunctionScopeInfo *FD = S.getCurFunction()) 13851 if (!FD->ModifiedNonNullParams.count(Param)) 13852 FD->ModifiedNonNullParams.insert(Param); 13853 } 13854 13855 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13856 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13857 SourceLocation OpLoc) { 13858 if (Op->isTypeDependent()) 13859 return S.Context.DependentTy; 13860 13861 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13862 if (ConvResult.isInvalid()) 13863 return QualType(); 13864 Op = ConvResult.get(); 13865 QualType OpTy = Op->getType(); 13866 QualType Result; 13867 13868 if (isa<CXXReinterpretCastExpr>(Op)) { 13869 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13870 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13871 Op->getSourceRange()); 13872 } 13873 13874 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13875 { 13876 Result = PT->getPointeeType(); 13877 } 13878 else if (const ObjCObjectPointerType *OPT = 13879 OpTy->getAs<ObjCObjectPointerType>()) 13880 Result = OPT->getPointeeType(); 13881 else { 13882 ExprResult PR = S.CheckPlaceholderExpr(Op); 13883 if (PR.isInvalid()) return QualType(); 13884 if (PR.get() != Op) 13885 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13886 } 13887 13888 if (Result.isNull()) { 13889 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13890 << OpTy << Op->getSourceRange(); 13891 return QualType(); 13892 } 13893 13894 // Note that per both C89 and C99, indirection is always legal, even if Result 13895 // is an incomplete type or void. It would be possible to warn about 13896 // dereferencing a void pointer, but it's completely well-defined, and such a 13897 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13898 // for pointers to 'void' but is fine for any other pointer type: 13899 // 13900 // C++ [expr.unary.op]p1: 13901 // [...] the expression to which [the unary * operator] is applied shall 13902 // be a pointer to an object type, or a pointer to a function type 13903 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13904 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13905 << OpTy << Op->getSourceRange(); 13906 13907 // Dereferences are usually l-values... 13908 VK = VK_LValue; 13909 13910 // ...except that certain expressions are never l-values in C. 13911 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13912 VK = VK_PRValue; 13913 13914 return Result; 13915 } 13916 13917 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13918 BinaryOperatorKind Opc; 13919 switch (Kind) { 13920 default: llvm_unreachable("Unknown binop!"); 13921 case tok::periodstar: Opc = BO_PtrMemD; break; 13922 case tok::arrowstar: Opc = BO_PtrMemI; break; 13923 case tok::star: Opc = BO_Mul; break; 13924 case tok::slash: Opc = BO_Div; break; 13925 case tok::percent: Opc = BO_Rem; break; 13926 case tok::plus: Opc = BO_Add; break; 13927 case tok::minus: Opc = BO_Sub; break; 13928 case tok::lessless: Opc = BO_Shl; break; 13929 case tok::greatergreater: Opc = BO_Shr; break; 13930 case tok::lessequal: Opc = BO_LE; break; 13931 case tok::less: Opc = BO_LT; break; 13932 case tok::greaterequal: Opc = BO_GE; break; 13933 case tok::greater: Opc = BO_GT; break; 13934 case tok::exclaimequal: Opc = BO_NE; break; 13935 case tok::equalequal: Opc = BO_EQ; break; 13936 case tok::spaceship: Opc = BO_Cmp; break; 13937 case tok::amp: Opc = BO_And; break; 13938 case tok::caret: Opc = BO_Xor; break; 13939 case tok::pipe: Opc = BO_Or; break; 13940 case tok::ampamp: Opc = BO_LAnd; break; 13941 case tok::pipepipe: Opc = BO_LOr; break; 13942 case tok::equal: Opc = BO_Assign; break; 13943 case tok::starequal: Opc = BO_MulAssign; break; 13944 case tok::slashequal: Opc = BO_DivAssign; break; 13945 case tok::percentequal: Opc = BO_RemAssign; break; 13946 case tok::plusequal: Opc = BO_AddAssign; break; 13947 case tok::minusequal: Opc = BO_SubAssign; break; 13948 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13949 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13950 case tok::ampequal: Opc = BO_AndAssign; break; 13951 case tok::caretequal: Opc = BO_XorAssign; break; 13952 case tok::pipeequal: Opc = BO_OrAssign; break; 13953 case tok::comma: Opc = BO_Comma; break; 13954 } 13955 return Opc; 13956 } 13957 13958 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13959 tok::TokenKind Kind) { 13960 UnaryOperatorKind Opc; 13961 switch (Kind) { 13962 default: llvm_unreachable("Unknown unary op!"); 13963 case tok::plusplus: Opc = UO_PreInc; break; 13964 case tok::minusminus: Opc = UO_PreDec; break; 13965 case tok::amp: Opc = UO_AddrOf; break; 13966 case tok::star: Opc = UO_Deref; break; 13967 case tok::plus: Opc = UO_Plus; break; 13968 case tok::minus: Opc = UO_Minus; break; 13969 case tok::tilde: Opc = UO_Not; break; 13970 case tok::exclaim: Opc = UO_LNot; break; 13971 case tok::kw___real: Opc = UO_Real; break; 13972 case tok::kw___imag: Opc = UO_Imag; break; 13973 case tok::kw___extension__: Opc = UO_Extension; break; 13974 } 13975 return Opc; 13976 } 13977 13978 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13979 /// This warning suppressed in the event of macro expansions. 13980 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13981 SourceLocation OpLoc, bool IsBuiltin) { 13982 if (S.inTemplateInstantiation()) 13983 return; 13984 if (S.isUnevaluatedContext()) 13985 return; 13986 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13987 return; 13988 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13989 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13990 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13991 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13992 if (!LHSDeclRef || !RHSDeclRef || 13993 LHSDeclRef->getLocation().isMacroID() || 13994 RHSDeclRef->getLocation().isMacroID()) 13995 return; 13996 const ValueDecl *LHSDecl = 13997 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13998 const ValueDecl *RHSDecl = 13999 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 14000 if (LHSDecl != RHSDecl) 14001 return; 14002 if (LHSDecl->getType().isVolatileQualified()) 14003 return; 14004 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 14005 if (RefTy->getPointeeType().isVolatileQualified()) 14006 return; 14007 14008 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 14009 : diag::warn_self_assignment_overloaded) 14010 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 14011 << RHSExpr->getSourceRange(); 14012 } 14013 14014 /// Check if a bitwise-& is performed on an Objective-C pointer. This 14015 /// is usually indicative of introspection within the Objective-C pointer. 14016 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 14017 SourceLocation OpLoc) { 14018 if (!S.getLangOpts().ObjC) 14019 return; 14020 14021 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 14022 const Expr *LHS = L.get(); 14023 const Expr *RHS = R.get(); 14024 14025 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14026 ObjCPointerExpr = LHS; 14027 OtherExpr = RHS; 14028 } 14029 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14030 ObjCPointerExpr = RHS; 14031 OtherExpr = LHS; 14032 } 14033 14034 // This warning is deliberately made very specific to reduce false 14035 // positives with logic that uses '&' for hashing. This logic mainly 14036 // looks for code trying to introspect into tagged pointers, which 14037 // code should generally never do. 14038 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 14039 unsigned Diag = diag::warn_objc_pointer_masking; 14040 // Determine if we are introspecting the result of performSelectorXXX. 14041 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 14042 // Special case messages to -performSelector and friends, which 14043 // can return non-pointer values boxed in a pointer value. 14044 // Some clients may wish to silence warnings in this subcase. 14045 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14046 Selector S = ME->getSelector(); 14047 StringRef SelArg0 = S.getNameForSlot(0); 14048 if (SelArg0.startswith("performSelector")) 14049 Diag = diag::warn_objc_pointer_masking_performSelector; 14050 } 14051 14052 S.Diag(OpLoc, Diag) 14053 << ObjCPointerExpr->getSourceRange(); 14054 } 14055 } 14056 14057 static NamedDecl *getDeclFromExpr(Expr *E) { 14058 if (!E) 14059 return nullptr; 14060 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14061 return DRE->getDecl(); 14062 if (auto *ME = dyn_cast<MemberExpr>(E)) 14063 return ME->getMemberDecl(); 14064 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14065 return IRE->getDecl(); 14066 return nullptr; 14067 } 14068 14069 // This helper function promotes a binary operator's operands (which are of a 14070 // half vector type) to a vector of floats and then truncates the result to 14071 // a vector of either half or short. 14072 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14073 BinaryOperatorKind Opc, QualType ResultTy, 14074 ExprValueKind VK, ExprObjectKind OK, 14075 bool IsCompAssign, SourceLocation OpLoc, 14076 FPOptionsOverride FPFeatures) { 14077 auto &Context = S.getASTContext(); 14078 assert((isVector(ResultTy, Context.HalfTy) || 14079 isVector(ResultTy, Context.ShortTy)) && 14080 "Result must be a vector of half or short"); 14081 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14082 isVector(RHS.get()->getType(), Context.HalfTy) && 14083 "both operands expected to be a half vector"); 14084 14085 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14086 QualType BinOpResTy = RHS.get()->getType(); 14087 14088 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14089 // change BinOpResTy to a vector of ints. 14090 if (isVector(ResultTy, Context.ShortTy)) 14091 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14092 14093 if (IsCompAssign) 14094 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14095 ResultTy, VK, OK, OpLoc, FPFeatures, 14096 BinOpResTy, BinOpResTy); 14097 14098 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14099 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14100 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14101 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14102 } 14103 14104 static std::pair<ExprResult, ExprResult> 14105 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14106 Expr *RHSExpr) { 14107 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14108 if (!S.Context.isDependenceAllowed()) { 14109 // C cannot handle TypoExpr nodes on either side of a binop because it 14110 // doesn't handle dependent types properly, so make sure any TypoExprs have 14111 // been dealt with before checking the operands. 14112 LHS = S.CorrectDelayedTyposInExpr(LHS); 14113 RHS = S.CorrectDelayedTyposInExpr( 14114 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14115 [Opc, LHS](Expr *E) { 14116 if (Opc != BO_Assign) 14117 return ExprResult(E); 14118 // Avoid correcting the RHS to the same Expr as the LHS. 14119 Decl *D = getDeclFromExpr(E); 14120 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14121 }); 14122 } 14123 return std::make_pair(LHS, RHS); 14124 } 14125 14126 /// Returns true if conversion between vectors of halfs and vectors of floats 14127 /// is needed. 14128 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14129 Expr *E0, Expr *E1 = nullptr) { 14130 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14131 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14132 return false; 14133 14134 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14135 QualType Ty = E->IgnoreImplicit()->getType(); 14136 14137 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14138 // to vectors of floats. Although the element type of the vectors is __fp16, 14139 // the vectors shouldn't be treated as storage-only types. See the 14140 // discussion here: https://reviews.llvm.org/rG825235c140e7 14141 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14142 if (VT->getVectorKind() == VectorType::NeonVector) 14143 return false; 14144 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14145 } 14146 return false; 14147 }; 14148 14149 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14150 } 14151 14152 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14153 /// operator @p Opc at location @c TokLoc. This routine only supports 14154 /// built-in operations; ActOnBinOp handles overloaded operators. 14155 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14156 BinaryOperatorKind Opc, 14157 Expr *LHSExpr, Expr *RHSExpr) { 14158 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14159 // The syntax only allows initializer lists on the RHS of assignment, 14160 // so we don't need to worry about accepting invalid code for 14161 // non-assignment operators. 14162 // C++11 5.17p9: 14163 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14164 // of x = {} is x = T(). 14165 InitializationKind Kind = InitializationKind::CreateDirectList( 14166 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14167 InitializedEntity Entity = 14168 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14169 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14170 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14171 if (Init.isInvalid()) 14172 return Init; 14173 RHSExpr = Init.get(); 14174 } 14175 14176 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14177 QualType ResultTy; // Result type of the binary operator. 14178 // The following two variables are used for compound assignment operators 14179 QualType CompLHSTy; // Type of LHS after promotions for computation 14180 QualType CompResultTy; // Type of computation result 14181 ExprValueKind VK = VK_PRValue; 14182 ExprObjectKind OK = OK_Ordinary; 14183 bool ConvertHalfVec = false; 14184 14185 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14186 if (!LHS.isUsable() || !RHS.isUsable()) 14187 return ExprError(); 14188 14189 if (getLangOpts().OpenCL) { 14190 QualType LHSTy = LHSExpr->getType(); 14191 QualType RHSTy = RHSExpr->getType(); 14192 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14193 // the ATOMIC_VAR_INIT macro. 14194 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14195 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14196 if (BO_Assign == Opc) 14197 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14198 else 14199 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14200 return ExprError(); 14201 } 14202 14203 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14204 // only with a builtin functions and therefore should be disallowed here. 14205 if (LHSTy->isImageType() || RHSTy->isImageType() || 14206 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14207 LHSTy->isPipeType() || RHSTy->isPipeType() || 14208 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14209 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14210 return ExprError(); 14211 } 14212 } 14213 14214 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14215 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 14216 14217 switch (Opc) { 14218 case BO_Assign: 14219 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14220 if (getLangOpts().CPlusPlus && 14221 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14222 VK = LHS.get()->getValueKind(); 14223 OK = LHS.get()->getObjectKind(); 14224 } 14225 if (!ResultTy.isNull()) { 14226 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14227 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14228 14229 // Avoid copying a block to the heap if the block is assigned to a local 14230 // auto variable that is declared in the same scope as the block. This 14231 // optimization is unsafe if the local variable is declared in an outer 14232 // scope. For example: 14233 // 14234 // BlockTy b; 14235 // { 14236 // b = ^{...}; 14237 // } 14238 // // It is unsafe to invoke the block here if it wasn't copied to the 14239 // // heap. 14240 // b(); 14241 14242 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14243 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14244 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14245 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14246 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14247 14248 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14249 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14250 NTCUC_Assignment, NTCUK_Copy); 14251 } 14252 RecordModifiableNonNullParam(*this, LHS.get()); 14253 break; 14254 case BO_PtrMemD: 14255 case BO_PtrMemI: 14256 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14257 Opc == BO_PtrMemI); 14258 break; 14259 case BO_Mul: 14260 case BO_Div: 14261 ConvertHalfVec = true; 14262 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14263 Opc == BO_Div); 14264 break; 14265 case BO_Rem: 14266 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14267 break; 14268 case BO_Add: 14269 ConvertHalfVec = true; 14270 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14271 break; 14272 case BO_Sub: 14273 ConvertHalfVec = true; 14274 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14275 break; 14276 case BO_Shl: 14277 case BO_Shr: 14278 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14279 break; 14280 case BO_LE: 14281 case BO_LT: 14282 case BO_GE: 14283 case BO_GT: 14284 ConvertHalfVec = true; 14285 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14286 break; 14287 case BO_EQ: 14288 case BO_NE: 14289 ConvertHalfVec = true; 14290 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14291 break; 14292 case BO_Cmp: 14293 ConvertHalfVec = true; 14294 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14295 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14296 break; 14297 case BO_And: 14298 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14299 LLVM_FALLTHROUGH; 14300 case BO_Xor: 14301 case BO_Or: 14302 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14303 break; 14304 case BO_LAnd: 14305 case BO_LOr: 14306 ConvertHalfVec = true; 14307 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14308 break; 14309 case BO_MulAssign: 14310 case BO_DivAssign: 14311 ConvertHalfVec = true; 14312 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14313 Opc == BO_DivAssign); 14314 CompLHSTy = CompResultTy; 14315 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14316 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14317 break; 14318 case BO_RemAssign: 14319 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14320 CompLHSTy = CompResultTy; 14321 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14322 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14323 break; 14324 case BO_AddAssign: 14325 ConvertHalfVec = true; 14326 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14327 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14328 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14329 break; 14330 case BO_SubAssign: 14331 ConvertHalfVec = true; 14332 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14333 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14334 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14335 break; 14336 case BO_ShlAssign: 14337 case BO_ShrAssign: 14338 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14339 CompLHSTy = CompResultTy; 14340 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14341 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14342 break; 14343 case BO_AndAssign: 14344 case BO_OrAssign: // fallthrough 14345 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14346 LLVM_FALLTHROUGH; 14347 case BO_XorAssign: 14348 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14349 CompLHSTy = CompResultTy; 14350 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14351 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14352 break; 14353 case BO_Comma: 14354 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14355 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14356 VK = RHS.get()->getValueKind(); 14357 OK = RHS.get()->getObjectKind(); 14358 } 14359 break; 14360 } 14361 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14362 return ExprError(); 14363 14364 // Some of the binary operations require promoting operands of half vector to 14365 // float vectors and truncating the result back to half vector. For now, we do 14366 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14367 // arm64). 14368 assert( 14369 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14370 isVector(LHS.get()->getType(), Context.HalfTy)) && 14371 "both sides are half vectors or neither sides are"); 14372 ConvertHalfVec = 14373 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14374 14375 // Check for array bounds violations for both sides of the BinaryOperator 14376 CheckArrayAccess(LHS.get()); 14377 CheckArrayAccess(RHS.get()); 14378 14379 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14380 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14381 &Context.Idents.get("object_setClass"), 14382 SourceLocation(), LookupOrdinaryName); 14383 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14384 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14385 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14386 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14387 "object_setClass(") 14388 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14389 ",") 14390 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14391 } 14392 else 14393 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14394 } 14395 else if (const ObjCIvarRefExpr *OIRE = 14396 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14397 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14398 14399 // Opc is not a compound assignment if CompResultTy is null. 14400 if (CompResultTy.isNull()) { 14401 if (ConvertHalfVec) 14402 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14403 OpLoc, CurFPFeatureOverrides()); 14404 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14405 VK, OK, OpLoc, CurFPFeatureOverrides()); 14406 } 14407 14408 // Handle compound assignments. 14409 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14410 OK_ObjCProperty) { 14411 VK = VK_LValue; 14412 OK = LHS.get()->getObjectKind(); 14413 } 14414 14415 // The LHS is not converted to the result type for fixed-point compound 14416 // assignment as the common type is computed on demand. Reset the CompLHSTy 14417 // to the LHS type we would have gotten after unary conversions. 14418 if (CompResultTy->isFixedPointType()) 14419 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14420 14421 if (ConvertHalfVec) 14422 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14423 OpLoc, CurFPFeatureOverrides()); 14424 14425 return CompoundAssignOperator::Create( 14426 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14427 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14428 } 14429 14430 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14431 /// operators are mixed in a way that suggests that the programmer forgot that 14432 /// comparison operators have higher precedence. The most typical example of 14433 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14434 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14435 SourceLocation OpLoc, Expr *LHSExpr, 14436 Expr *RHSExpr) { 14437 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14438 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14439 14440 // Check that one of the sides is a comparison operator and the other isn't. 14441 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14442 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14443 if (isLeftComp == isRightComp) 14444 return; 14445 14446 // Bitwise operations are sometimes used as eager logical ops. 14447 // Don't diagnose this. 14448 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14449 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14450 if (isLeftBitwise || isRightBitwise) 14451 return; 14452 14453 SourceRange DiagRange = isLeftComp 14454 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14455 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14456 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14457 SourceRange ParensRange = 14458 isLeftComp 14459 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14460 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14461 14462 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14463 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14464 SuggestParentheses(Self, OpLoc, 14465 Self.PDiag(diag::note_precedence_silence) << OpStr, 14466 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14467 SuggestParentheses(Self, OpLoc, 14468 Self.PDiag(diag::note_precedence_bitwise_first) 14469 << BinaryOperator::getOpcodeStr(Opc), 14470 ParensRange); 14471 } 14472 14473 /// It accepts a '&&' expr that is inside a '||' one. 14474 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14475 /// in parentheses. 14476 static void 14477 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14478 BinaryOperator *Bop) { 14479 assert(Bop->getOpcode() == BO_LAnd); 14480 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14481 << Bop->getSourceRange() << OpLoc; 14482 SuggestParentheses(Self, Bop->getOperatorLoc(), 14483 Self.PDiag(diag::note_precedence_silence) 14484 << Bop->getOpcodeStr(), 14485 Bop->getSourceRange()); 14486 } 14487 14488 /// Returns true if the given expression can be evaluated as a constant 14489 /// 'true'. 14490 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14491 bool Res; 14492 return !E->isValueDependent() && 14493 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14494 } 14495 14496 /// Returns true if the given expression can be evaluated as a constant 14497 /// 'false'. 14498 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14499 bool Res; 14500 return !E->isValueDependent() && 14501 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14502 } 14503 14504 /// Look for '&&' in the left hand of a '||' expr. 14505 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14506 Expr *LHSExpr, Expr *RHSExpr) { 14507 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14508 if (Bop->getOpcode() == BO_LAnd) { 14509 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14510 if (EvaluatesAsFalse(S, RHSExpr)) 14511 return; 14512 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14513 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14514 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14515 } else if (Bop->getOpcode() == BO_LOr) { 14516 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14517 // If it's "a || b && 1 || c" we didn't warn earlier for 14518 // "a || b && 1", but warn now. 14519 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14520 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14521 } 14522 } 14523 } 14524 } 14525 14526 /// Look for '&&' in the right hand of a '||' expr. 14527 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14528 Expr *LHSExpr, Expr *RHSExpr) { 14529 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14530 if (Bop->getOpcode() == BO_LAnd) { 14531 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14532 if (EvaluatesAsFalse(S, LHSExpr)) 14533 return; 14534 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14535 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14536 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14537 } 14538 } 14539 } 14540 14541 /// Look for bitwise op in the left or right hand of a bitwise op with 14542 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14543 /// the '&' expression in parentheses. 14544 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14545 SourceLocation OpLoc, Expr *SubExpr) { 14546 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14547 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14548 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14549 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14550 << Bop->getSourceRange() << OpLoc; 14551 SuggestParentheses(S, Bop->getOperatorLoc(), 14552 S.PDiag(diag::note_precedence_silence) 14553 << Bop->getOpcodeStr(), 14554 Bop->getSourceRange()); 14555 } 14556 } 14557 } 14558 14559 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14560 Expr *SubExpr, StringRef Shift) { 14561 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14562 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14563 StringRef Op = Bop->getOpcodeStr(); 14564 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14565 << Bop->getSourceRange() << OpLoc << Shift << Op; 14566 SuggestParentheses(S, Bop->getOperatorLoc(), 14567 S.PDiag(diag::note_precedence_silence) << Op, 14568 Bop->getSourceRange()); 14569 } 14570 } 14571 } 14572 14573 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14574 Expr *LHSExpr, Expr *RHSExpr) { 14575 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14576 if (!OCE) 14577 return; 14578 14579 FunctionDecl *FD = OCE->getDirectCallee(); 14580 if (!FD || !FD->isOverloadedOperator()) 14581 return; 14582 14583 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14584 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14585 return; 14586 14587 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14588 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14589 << (Kind == OO_LessLess); 14590 SuggestParentheses(S, OCE->getOperatorLoc(), 14591 S.PDiag(diag::note_precedence_silence) 14592 << (Kind == OO_LessLess ? "<<" : ">>"), 14593 OCE->getSourceRange()); 14594 SuggestParentheses( 14595 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14596 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14597 } 14598 14599 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14600 /// precedence. 14601 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14602 SourceLocation OpLoc, Expr *LHSExpr, 14603 Expr *RHSExpr){ 14604 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14605 if (BinaryOperator::isBitwiseOp(Opc)) 14606 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14607 14608 // Diagnose "arg1 & arg2 | arg3" 14609 if ((Opc == BO_Or || Opc == BO_Xor) && 14610 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14611 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14612 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14613 } 14614 14615 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14616 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14617 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14618 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14619 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14620 } 14621 14622 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14623 || Opc == BO_Shr) { 14624 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14625 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14626 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14627 } 14628 14629 // Warn on overloaded shift operators and comparisons, such as: 14630 // cout << 5 == 4; 14631 if (BinaryOperator::isComparisonOp(Opc)) 14632 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14633 } 14634 14635 // Binary Operators. 'Tok' is the token for the operator. 14636 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14637 tok::TokenKind Kind, 14638 Expr *LHSExpr, Expr *RHSExpr) { 14639 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14640 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14641 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14642 14643 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14644 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14645 14646 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14647 } 14648 14649 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14650 UnresolvedSetImpl &Functions) { 14651 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14652 if (OverOp != OO_None && OverOp != OO_Equal) 14653 LookupOverloadedOperatorName(OverOp, S, Functions); 14654 14655 // In C++20 onwards, we may have a second operator to look up. 14656 if (getLangOpts().CPlusPlus20) { 14657 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14658 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14659 } 14660 } 14661 14662 /// Build an overloaded binary operator expression in the given scope. 14663 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14664 BinaryOperatorKind Opc, 14665 Expr *LHS, Expr *RHS) { 14666 switch (Opc) { 14667 case BO_Assign: 14668 case BO_DivAssign: 14669 case BO_RemAssign: 14670 case BO_SubAssign: 14671 case BO_AndAssign: 14672 case BO_OrAssign: 14673 case BO_XorAssign: 14674 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14675 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14676 break; 14677 default: 14678 break; 14679 } 14680 14681 // Find all of the overloaded operators visible from this point. 14682 UnresolvedSet<16> Functions; 14683 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14684 14685 // Build the (potentially-overloaded, potentially-dependent) 14686 // binary operation. 14687 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14688 } 14689 14690 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14691 BinaryOperatorKind Opc, 14692 Expr *LHSExpr, Expr *RHSExpr) { 14693 ExprResult LHS, RHS; 14694 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14695 if (!LHS.isUsable() || !RHS.isUsable()) 14696 return ExprError(); 14697 LHSExpr = LHS.get(); 14698 RHSExpr = RHS.get(); 14699 14700 // We want to end up calling one of checkPseudoObjectAssignment 14701 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14702 // both expressions are overloadable or either is type-dependent), 14703 // or CreateBuiltinBinOp (in any other case). We also want to get 14704 // any placeholder types out of the way. 14705 14706 // Handle pseudo-objects in the LHS. 14707 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14708 // Assignments with a pseudo-object l-value need special analysis. 14709 if (pty->getKind() == BuiltinType::PseudoObject && 14710 BinaryOperator::isAssignmentOp(Opc)) 14711 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14712 14713 // Don't resolve overloads if the other type is overloadable. 14714 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14715 // We can't actually test that if we still have a placeholder, 14716 // though. Fortunately, none of the exceptions we see in that 14717 // code below are valid when the LHS is an overload set. Note 14718 // that an overload set can be dependently-typed, but it never 14719 // instantiates to having an overloadable type. 14720 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14721 if (resolvedRHS.isInvalid()) return ExprError(); 14722 RHSExpr = resolvedRHS.get(); 14723 14724 if (RHSExpr->isTypeDependent() || 14725 RHSExpr->getType()->isOverloadableType()) 14726 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14727 } 14728 14729 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14730 // template, diagnose the missing 'template' keyword instead of diagnosing 14731 // an invalid use of a bound member function. 14732 // 14733 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14734 // to C++1z [over.over]/1.4, but we already checked for that case above. 14735 if (Opc == BO_LT && inTemplateInstantiation() && 14736 (pty->getKind() == BuiltinType::BoundMember || 14737 pty->getKind() == BuiltinType::Overload)) { 14738 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14739 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14740 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14741 return isa<FunctionTemplateDecl>(ND); 14742 })) { 14743 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14744 : OE->getNameLoc(), 14745 diag::err_template_kw_missing) 14746 << OE->getName().getAsString() << ""; 14747 return ExprError(); 14748 } 14749 } 14750 14751 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14752 if (LHS.isInvalid()) return ExprError(); 14753 LHSExpr = LHS.get(); 14754 } 14755 14756 // Handle pseudo-objects in the RHS. 14757 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14758 // An overload in the RHS can potentially be resolved by the type 14759 // being assigned to. 14760 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14761 if (getLangOpts().CPlusPlus && 14762 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14763 LHSExpr->getType()->isOverloadableType())) 14764 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14765 14766 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14767 } 14768 14769 // Don't resolve overloads if the other type is overloadable. 14770 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14771 LHSExpr->getType()->isOverloadableType()) 14772 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14773 14774 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14775 if (!resolvedRHS.isUsable()) return ExprError(); 14776 RHSExpr = resolvedRHS.get(); 14777 } 14778 14779 if (getLangOpts().CPlusPlus) { 14780 // If either expression is type-dependent, always build an 14781 // overloaded op. 14782 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14783 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14784 14785 // Otherwise, build an overloaded op if either expression has an 14786 // overloadable type. 14787 if (LHSExpr->getType()->isOverloadableType() || 14788 RHSExpr->getType()->isOverloadableType()) 14789 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14790 } 14791 14792 if (getLangOpts().RecoveryAST && 14793 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14794 assert(!getLangOpts().CPlusPlus); 14795 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14796 "Should only occur in error-recovery path."); 14797 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14798 // C [6.15.16] p3: 14799 // An assignment expression has the value of the left operand after the 14800 // assignment, but is not an lvalue. 14801 return CompoundAssignOperator::Create( 14802 Context, LHSExpr, RHSExpr, Opc, 14803 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14804 OpLoc, CurFPFeatureOverrides()); 14805 QualType ResultType; 14806 switch (Opc) { 14807 case BO_Assign: 14808 ResultType = LHSExpr->getType().getUnqualifiedType(); 14809 break; 14810 case BO_LT: 14811 case BO_GT: 14812 case BO_LE: 14813 case BO_GE: 14814 case BO_EQ: 14815 case BO_NE: 14816 case BO_LAnd: 14817 case BO_LOr: 14818 // These operators have a fixed result type regardless of operands. 14819 ResultType = Context.IntTy; 14820 break; 14821 case BO_Comma: 14822 ResultType = RHSExpr->getType(); 14823 break; 14824 default: 14825 ResultType = Context.DependentTy; 14826 break; 14827 } 14828 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14829 VK_PRValue, OK_Ordinary, OpLoc, 14830 CurFPFeatureOverrides()); 14831 } 14832 14833 // Build a built-in binary operation. 14834 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14835 } 14836 14837 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14838 if (T.isNull() || T->isDependentType()) 14839 return false; 14840 14841 if (!T->isPromotableIntegerType()) 14842 return true; 14843 14844 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14845 } 14846 14847 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14848 UnaryOperatorKind Opc, 14849 Expr *InputExpr) { 14850 ExprResult Input = InputExpr; 14851 ExprValueKind VK = VK_PRValue; 14852 ExprObjectKind OK = OK_Ordinary; 14853 QualType resultType; 14854 bool CanOverflow = false; 14855 14856 bool ConvertHalfVec = false; 14857 if (getLangOpts().OpenCL) { 14858 QualType Ty = InputExpr->getType(); 14859 // The only legal unary operation for atomics is '&'. 14860 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14861 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14862 // only with a builtin functions and therefore should be disallowed here. 14863 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14864 || Ty->isBlockPointerType())) { 14865 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14866 << InputExpr->getType() 14867 << Input.get()->getSourceRange()); 14868 } 14869 } 14870 14871 switch (Opc) { 14872 case UO_PreInc: 14873 case UO_PreDec: 14874 case UO_PostInc: 14875 case UO_PostDec: 14876 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14877 OpLoc, 14878 Opc == UO_PreInc || 14879 Opc == UO_PostInc, 14880 Opc == UO_PreInc || 14881 Opc == UO_PreDec); 14882 CanOverflow = isOverflowingIntegerType(Context, resultType); 14883 break; 14884 case UO_AddrOf: 14885 resultType = CheckAddressOfOperand(Input, OpLoc); 14886 CheckAddressOfNoDeref(InputExpr); 14887 RecordModifiableNonNullParam(*this, InputExpr); 14888 break; 14889 case UO_Deref: { 14890 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14891 if (Input.isInvalid()) return ExprError(); 14892 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14893 break; 14894 } 14895 case UO_Plus: 14896 case UO_Minus: 14897 CanOverflow = Opc == UO_Minus && 14898 isOverflowingIntegerType(Context, Input.get()->getType()); 14899 Input = UsualUnaryConversions(Input.get()); 14900 if (Input.isInvalid()) return ExprError(); 14901 // Unary plus and minus require promoting an operand of half vector to a 14902 // float vector and truncating the result back to a half vector. For now, we 14903 // do this only when HalfArgsAndReturns is set (that is, when the target is 14904 // arm or arm64). 14905 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14906 14907 // If the operand is a half vector, promote it to a float vector. 14908 if (ConvertHalfVec) 14909 Input = convertVector(Input.get(), Context.FloatTy, *this); 14910 resultType = Input.get()->getType(); 14911 if (resultType->isDependentType()) 14912 break; 14913 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14914 break; 14915 else if (resultType->isVectorType() && 14916 // The z vector extensions don't allow + or - with bool vectors. 14917 (!Context.getLangOpts().ZVector || 14918 resultType->castAs<VectorType>()->getVectorKind() != 14919 VectorType::AltiVecBool)) 14920 break; 14921 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14922 Opc == UO_Plus && 14923 resultType->isPointerType()) 14924 break; 14925 14926 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14927 << resultType << Input.get()->getSourceRange()); 14928 14929 case UO_Not: // bitwise complement 14930 Input = UsualUnaryConversions(Input.get()); 14931 if (Input.isInvalid()) 14932 return ExprError(); 14933 resultType = Input.get()->getType(); 14934 if (resultType->isDependentType()) 14935 break; 14936 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14937 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14938 // C99 does not support '~' for complex conjugation. 14939 Diag(OpLoc, diag::ext_integer_complement_complex) 14940 << resultType << Input.get()->getSourceRange(); 14941 else if (resultType->hasIntegerRepresentation()) 14942 break; 14943 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14944 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14945 // 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 } else { 14951 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14952 << resultType << Input.get()->getSourceRange()); 14953 } 14954 break; 14955 14956 case UO_LNot: // logical negation 14957 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14958 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14959 if (Input.isInvalid()) return ExprError(); 14960 resultType = Input.get()->getType(); 14961 14962 // Though we still have to promote half FP to float... 14963 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14964 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14965 resultType = Context.FloatTy; 14966 } 14967 14968 if (resultType->isDependentType()) 14969 break; 14970 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14971 // C99 6.5.3.3p1: ok, fallthrough; 14972 if (Context.getLangOpts().CPlusPlus) { 14973 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14974 // operand contextually converted to bool. 14975 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14976 ScalarTypeToBooleanCastKind(resultType)); 14977 } else if (Context.getLangOpts().OpenCL && 14978 Context.getLangOpts().OpenCLVersion < 120) { 14979 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14980 // operate on scalar float types. 14981 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14982 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14983 << resultType << Input.get()->getSourceRange()); 14984 } 14985 } else if (resultType->isExtVectorType()) { 14986 if (Context.getLangOpts().OpenCL && 14987 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 14988 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14989 // operate on vector float types. 14990 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14991 if (!T->isIntegerType()) 14992 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14993 << resultType << Input.get()->getSourceRange()); 14994 } 14995 // Vector logical not returns the signed variant of the operand type. 14996 resultType = GetSignedVectorType(resultType); 14997 break; 14998 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14999 const VectorType *VTy = resultType->castAs<VectorType>(); 15000 if (VTy->getVectorKind() != VectorType::GenericVector) 15001 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15002 << resultType << Input.get()->getSourceRange()); 15003 15004 // Vector logical not returns the signed variant of the operand type. 15005 resultType = GetSignedVectorType(resultType); 15006 break; 15007 } else { 15008 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15009 << resultType << Input.get()->getSourceRange()); 15010 } 15011 15012 // LNot always has type int. C99 6.5.3.3p5. 15013 // In C++, it's bool. C++ 5.3.1p8 15014 resultType = Context.getLogicalOperationType(); 15015 break; 15016 case UO_Real: 15017 case UO_Imag: 15018 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 15019 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 15020 // complex l-values to ordinary l-values and all other values to r-values. 15021 if (Input.isInvalid()) return ExprError(); 15022 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 15023 if (Input.get()->isGLValue() && 15024 Input.get()->getObjectKind() == OK_Ordinary) 15025 VK = Input.get()->getValueKind(); 15026 } else if (!getLangOpts().CPlusPlus) { 15027 // In C, a volatile scalar is read by __imag. In C++, it is not. 15028 Input = DefaultLvalueConversion(Input.get()); 15029 } 15030 break; 15031 case UO_Extension: 15032 resultType = Input.get()->getType(); 15033 VK = Input.get()->getValueKind(); 15034 OK = Input.get()->getObjectKind(); 15035 break; 15036 case UO_Coawait: 15037 // It's unnecessary to represent the pass-through operator co_await in the 15038 // AST; just return the input expression instead. 15039 assert(!Input.get()->getType()->isDependentType() && 15040 "the co_await expression must be non-dependant before " 15041 "building operator co_await"); 15042 return Input; 15043 } 15044 if (resultType.isNull() || Input.isInvalid()) 15045 return ExprError(); 15046 15047 // Check for array bounds violations in the operand of the UnaryOperator, 15048 // except for the '*' and '&' operators that have to be handled specially 15049 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15050 // that are explicitly defined as valid by the standard). 15051 if (Opc != UO_AddrOf && Opc != UO_Deref) 15052 CheckArrayAccess(Input.get()); 15053 15054 auto *UO = 15055 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15056 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15057 15058 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15059 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15060 !isUnevaluatedContext()) 15061 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15062 15063 // Convert the result back to a half vector. 15064 if (ConvertHalfVec) 15065 return convertVector(UO, Context.HalfTy, *this); 15066 return UO; 15067 } 15068 15069 /// Determine whether the given expression is a qualified member 15070 /// access expression, of a form that could be turned into a pointer to member 15071 /// with the address-of operator. 15072 bool Sema::isQualifiedMemberAccess(Expr *E) { 15073 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15074 if (!DRE->getQualifier()) 15075 return false; 15076 15077 ValueDecl *VD = DRE->getDecl(); 15078 if (!VD->isCXXClassMember()) 15079 return false; 15080 15081 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15082 return true; 15083 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15084 return Method->isInstance(); 15085 15086 return false; 15087 } 15088 15089 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15090 if (!ULE->getQualifier()) 15091 return false; 15092 15093 for (NamedDecl *D : ULE->decls()) { 15094 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15095 if (Method->isInstance()) 15096 return true; 15097 } else { 15098 // Overload set does not contain methods. 15099 break; 15100 } 15101 } 15102 15103 return false; 15104 } 15105 15106 return false; 15107 } 15108 15109 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15110 UnaryOperatorKind Opc, Expr *Input) { 15111 // First things first: handle placeholders so that the 15112 // overloaded-operator check considers the right type. 15113 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15114 // Increment and decrement of pseudo-object references. 15115 if (pty->getKind() == BuiltinType::PseudoObject && 15116 UnaryOperator::isIncrementDecrementOp(Opc)) 15117 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15118 15119 // extension is always a builtin operator. 15120 if (Opc == UO_Extension) 15121 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15122 15123 // & gets special logic for several kinds of placeholder. 15124 // The builtin code knows what to do. 15125 if (Opc == UO_AddrOf && 15126 (pty->getKind() == BuiltinType::Overload || 15127 pty->getKind() == BuiltinType::UnknownAny || 15128 pty->getKind() == BuiltinType::BoundMember)) 15129 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15130 15131 // Anything else needs to be handled now. 15132 ExprResult Result = CheckPlaceholderExpr(Input); 15133 if (Result.isInvalid()) return ExprError(); 15134 Input = Result.get(); 15135 } 15136 15137 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15138 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15139 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15140 // Find all of the overloaded operators visible from this point. 15141 UnresolvedSet<16> Functions; 15142 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15143 if (S && OverOp != OO_None) 15144 LookupOverloadedOperatorName(OverOp, S, Functions); 15145 15146 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15147 } 15148 15149 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15150 } 15151 15152 // Unary Operators. 'Tok' is the token for the operator. 15153 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15154 tok::TokenKind Op, Expr *Input) { 15155 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15156 } 15157 15158 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15159 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15160 LabelDecl *TheDecl) { 15161 TheDecl->markUsed(Context); 15162 // Create the AST node. The address of a label always has type 'void*'. 15163 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15164 Context.getPointerType(Context.VoidTy)); 15165 } 15166 15167 void Sema::ActOnStartStmtExpr() { 15168 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15169 } 15170 15171 void Sema::ActOnStmtExprError() { 15172 // Note that function is also called by TreeTransform when leaving a 15173 // StmtExpr scope without rebuilding anything. 15174 15175 DiscardCleanupsInEvaluationContext(); 15176 PopExpressionEvaluationContext(); 15177 } 15178 15179 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15180 SourceLocation RPLoc) { 15181 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15182 } 15183 15184 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15185 SourceLocation RPLoc, unsigned TemplateDepth) { 15186 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15187 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15188 15189 if (hasAnyUnrecoverableErrorsInThisFunction()) 15190 DiscardCleanupsInEvaluationContext(); 15191 assert(!Cleanup.exprNeedsCleanups() && 15192 "cleanups within StmtExpr not correctly bound!"); 15193 PopExpressionEvaluationContext(); 15194 15195 // FIXME: there are a variety of strange constraints to enforce here, for 15196 // example, it is not possible to goto into a stmt expression apparently. 15197 // More semantic analysis is needed. 15198 15199 // If there are sub-stmts in the compound stmt, take the type of the last one 15200 // as the type of the stmtexpr. 15201 QualType Ty = Context.VoidTy; 15202 bool StmtExprMayBindToTemp = false; 15203 if (!Compound->body_empty()) { 15204 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15205 if (const auto *LastStmt = 15206 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15207 if (const Expr *Value = LastStmt->getExprStmt()) { 15208 StmtExprMayBindToTemp = true; 15209 Ty = Value->getType(); 15210 } 15211 } 15212 } 15213 15214 // FIXME: Check that expression type is complete/non-abstract; statement 15215 // expressions are not lvalues. 15216 Expr *ResStmtExpr = 15217 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15218 if (StmtExprMayBindToTemp) 15219 return MaybeBindToTemporary(ResStmtExpr); 15220 return ResStmtExpr; 15221 } 15222 15223 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15224 if (ER.isInvalid()) 15225 return ExprError(); 15226 15227 // Do function/array conversion on the last expression, but not 15228 // lvalue-to-rvalue. However, initialize an unqualified type. 15229 ER = DefaultFunctionArrayConversion(ER.get()); 15230 if (ER.isInvalid()) 15231 return ExprError(); 15232 Expr *E = ER.get(); 15233 15234 if (E->isTypeDependent()) 15235 return E; 15236 15237 // In ARC, if the final expression ends in a consume, splice 15238 // the consume out and bind it later. In the alternate case 15239 // (when dealing with a retainable type), the result 15240 // initialization will create a produce. In both cases the 15241 // result will be +1, and we'll need to balance that out with 15242 // a bind. 15243 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15244 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15245 return Cast->getSubExpr(); 15246 15247 // FIXME: Provide a better location for the initialization. 15248 return PerformCopyInitialization( 15249 InitializedEntity::InitializeStmtExprResult( 15250 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15251 SourceLocation(), E); 15252 } 15253 15254 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15255 TypeSourceInfo *TInfo, 15256 ArrayRef<OffsetOfComponent> Components, 15257 SourceLocation RParenLoc) { 15258 QualType ArgTy = TInfo->getType(); 15259 bool Dependent = ArgTy->isDependentType(); 15260 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15261 15262 // We must have at least one component that refers to the type, and the first 15263 // one is known to be a field designator. Verify that the ArgTy represents 15264 // a struct/union/class. 15265 if (!Dependent && !ArgTy->isRecordType()) 15266 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15267 << ArgTy << TypeRange); 15268 15269 // Type must be complete per C99 7.17p3 because a declaring a variable 15270 // with an incomplete type would be ill-formed. 15271 if (!Dependent 15272 && RequireCompleteType(BuiltinLoc, ArgTy, 15273 diag::err_offsetof_incomplete_type, TypeRange)) 15274 return ExprError(); 15275 15276 bool DidWarnAboutNonPOD = false; 15277 QualType CurrentType = ArgTy; 15278 SmallVector<OffsetOfNode, 4> Comps; 15279 SmallVector<Expr*, 4> Exprs; 15280 for (const OffsetOfComponent &OC : Components) { 15281 if (OC.isBrackets) { 15282 // Offset of an array sub-field. TODO: Should we allow vector elements? 15283 if (!CurrentType->isDependentType()) { 15284 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15285 if(!AT) 15286 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15287 << CurrentType); 15288 CurrentType = AT->getElementType(); 15289 } else 15290 CurrentType = Context.DependentTy; 15291 15292 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15293 if (IdxRval.isInvalid()) 15294 return ExprError(); 15295 Expr *Idx = IdxRval.get(); 15296 15297 // The expression must be an integral expression. 15298 // FIXME: An integral constant expression? 15299 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15300 !Idx->getType()->isIntegerType()) 15301 return ExprError( 15302 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15303 << Idx->getSourceRange()); 15304 15305 // Record this array index. 15306 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15307 Exprs.push_back(Idx); 15308 continue; 15309 } 15310 15311 // Offset of a field. 15312 if (CurrentType->isDependentType()) { 15313 // We have the offset of a field, but we can't look into the dependent 15314 // type. Just record the identifier of the field. 15315 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15316 CurrentType = Context.DependentTy; 15317 continue; 15318 } 15319 15320 // We need to have a complete type to look into. 15321 if (RequireCompleteType(OC.LocStart, CurrentType, 15322 diag::err_offsetof_incomplete_type)) 15323 return ExprError(); 15324 15325 // Look for the designated field. 15326 const RecordType *RC = CurrentType->getAs<RecordType>(); 15327 if (!RC) 15328 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15329 << CurrentType); 15330 RecordDecl *RD = RC->getDecl(); 15331 15332 // C++ [lib.support.types]p5: 15333 // The macro offsetof accepts a restricted set of type arguments in this 15334 // International Standard. type shall be a POD structure or a POD union 15335 // (clause 9). 15336 // C++11 [support.types]p4: 15337 // If type is not a standard-layout class (Clause 9), the results are 15338 // undefined. 15339 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15340 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15341 unsigned DiagID = 15342 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15343 : diag::ext_offsetof_non_pod_type; 15344 15345 if (!IsSafe && !DidWarnAboutNonPOD && 15346 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15347 PDiag(DiagID) 15348 << SourceRange(Components[0].LocStart, OC.LocEnd) 15349 << CurrentType)) 15350 DidWarnAboutNonPOD = true; 15351 } 15352 15353 // Look for the field. 15354 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15355 LookupQualifiedName(R, RD); 15356 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15357 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15358 if (!MemberDecl) { 15359 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15360 MemberDecl = IndirectMemberDecl->getAnonField(); 15361 } 15362 15363 if (!MemberDecl) 15364 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15365 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15366 OC.LocEnd)); 15367 15368 // C99 7.17p3: 15369 // (If the specified member is a bit-field, the behavior is undefined.) 15370 // 15371 // We diagnose this as an error. 15372 if (MemberDecl->isBitField()) { 15373 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15374 << MemberDecl->getDeclName() 15375 << SourceRange(BuiltinLoc, RParenLoc); 15376 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15377 return ExprError(); 15378 } 15379 15380 RecordDecl *Parent = MemberDecl->getParent(); 15381 if (IndirectMemberDecl) 15382 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15383 15384 // If the member was found in a base class, introduce OffsetOfNodes for 15385 // the base class indirections. 15386 CXXBasePaths Paths; 15387 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15388 Paths)) { 15389 if (Paths.getDetectedVirtual()) { 15390 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15391 << MemberDecl->getDeclName() 15392 << SourceRange(BuiltinLoc, RParenLoc); 15393 return ExprError(); 15394 } 15395 15396 CXXBasePath &Path = Paths.front(); 15397 for (const CXXBasePathElement &B : Path) 15398 Comps.push_back(OffsetOfNode(B.Base)); 15399 } 15400 15401 if (IndirectMemberDecl) { 15402 for (auto *FI : IndirectMemberDecl->chain()) { 15403 assert(isa<FieldDecl>(FI)); 15404 Comps.push_back(OffsetOfNode(OC.LocStart, 15405 cast<FieldDecl>(FI), OC.LocEnd)); 15406 } 15407 } else 15408 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15409 15410 CurrentType = MemberDecl->getType().getNonReferenceType(); 15411 } 15412 15413 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15414 Comps, Exprs, RParenLoc); 15415 } 15416 15417 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15418 SourceLocation BuiltinLoc, 15419 SourceLocation TypeLoc, 15420 ParsedType ParsedArgTy, 15421 ArrayRef<OffsetOfComponent> Components, 15422 SourceLocation RParenLoc) { 15423 15424 TypeSourceInfo *ArgTInfo; 15425 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15426 if (ArgTy.isNull()) 15427 return ExprError(); 15428 15429 if (!ArgTInfo) 15430 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15431 15432 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15433 } 15434 15435 15436 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15437 Expr *CondExpr, 15438 Expr *LHSExpr, Expr *RHSExpr, 15439 SourceLocation RPLoc) { 15440 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15441 15442 ExprValueKind VK = VK_PRValue; 15443 ExprObjectKind OK = OK_Ordinary; 15444 QualType resType; 15445 bool CondIsTrue = false; 15446 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15447 resType = Context.DependentTy; 15448 } else { 15449 // The conditional expression is required to be a constant expression. 15450 llvm::APSInt condEval(32); 15451 ExprResult CondICE = VerifyIntegerConstantExpression( 15452 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15453 if (CondICE.isInvalid()) 15454 return ExprError(); 15455 CondExpr = CondICE.get(); 15456 CondIsTrue = condEval.getZExtValue(); 15457 15458 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15459 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15460 15461 resType = ActiveExpr->getType(); 15462 VK = ActiveExpr->getValueKind(); 15463 OK = ActiveExpr->getObjectKind(); 15464 } 15465 15466 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15467 resType, VK, OK, RPLoc, CondIsTrue); 15468 } 15469 15470 //===----------------------------------------------------------------------===// 15471 // Clang Extensions. 15472 //===----------------------------------------------------------------------===// 15473 15474 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15475 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15476 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15477 15478 if (LangOpts.CPlusPlus) { 15479 MangleNumberingContext *MCtx; 15480 Decl *ManglingContextDecl; 15481 std::tie(MCtx, ManglingContextDecl) = 15482 getCurrentMangleNumberContext(Block->getDeclContext()); 15483 if (MCtx) { 15484 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15485 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15486 } 15487 } 15488 15489 PushBlockScope(CurScope, Block); 15490 CurContext->addDecl(Block); 15491 if (CurScope) 15492 PushDeclContext(CurScope, Block); 15493 else 15494 CurContext = Block; 15495 15496 getCurBlock()->HasImplicitReturnType = true; 15497 15498 // Enter a new evaluation context to insulate the block from any 15499 // cleanups from the enclosing full-expression. 15500 PushExpressionEvaluationContext( 15501 ExpressionEvaluationContext::PotentiallyEvaluated); 15502 } 15503 15504 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15505 Scope *CurScope) { 15506 assert(ParamInfo.getIdentifier() == nullptr && 15507 "block-id should have no identifier!"); 15508 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15509 BlockScopeInfo *CurBlock = getCurBlock(); 15510 15511 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15512 QualType T = Sig->getType(); 15513 15514 // FIXME: We should allow unexpanded parameter packs here, but that would, 15515 // in turn, make the block expression contain unexpanded parameter packs. 15516 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15517 // Drop the parameters. 15518 FunctionProtoType::ExtProtoInfo EPI; 15519 EPI.HasTrailingReturn = false; 15520 EPI.TypeQuals.addConst(); 15521 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15522 Sig = Context.getTrivialTypeSourceInfo(T); 15523 } 15524 15525 // GetTypeForDeclarator always produces a function type for a block 15526 // literal signature. Furthermore, it is always a FunctionProtoType 15527 // unless the function was written with a typedef. 15528 assert(T->isFunctionType() && 15529 "GetTypeForDeclarator made a non-function block signature"); 15530 15531 // Look for an explicit signature in that function type. 15532 FunctionProtoTypeLoc ExplicitSignature; 15533 15534 if ((ExplicitSignature = Sig->getTypeLoc() 15535 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15536 15537 // Check whether that explicit signature was synthesized by 15538 // GetTypeForDeclarator. If so, don't save that as part of the 15539 // written signature. 15540 if (ExplicitSignature.getLocalRangeBegin() == 15541 ExplicitSignature.getLocalRangeEnd()) { 15542 // This would be much cheaper if we stored TypeLocs instead of 15543 // TypeSourceInfos. 15544 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15545 unsigned Size = Result.getFullDataSize(); 15546 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15547 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15548 15549 ExplicitSignature = FunctionProtoTypeLoc(); 15550 } 15551 } 15552 15553 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15554 CurBlock->FunctionType = T; 15555 15556 const auto *Fn = T->castAs<FunctionType>(); 15557 QualType RetTy = Fn->getReturnType(); 15558 bool isVariadic = 15559 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15560 15561 CurBlock->TheDecl->setIsVariadic(isVariadic); 15562 15563 // Context.DependentTy is used as a placeholder for a missing block 15564 // return type. TODO: what should we do with declarators like: 15565 // ^ * { ... } 15566 // If the answer is "apply template argument deduction".... 15567 if (RetTy != Context.DependentTy) { 15568 CurBlock->ReturnType = RetTy; 15569 CurBlock->TheDecl->setBlockMissingReturnType(false); 15570 CurBlock->HasImplicitReturnType = false; 15571 } 15572 15573 // Push block parameters from the declarator if we had them. 15574 SmallVector<ParmVarDecl*, 8> Params; 15575 if (ExplicitSignature) { 15576 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15577 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15578 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15579 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15580 // Diagnose this as an extension in C17 and earlier. 15581 if (!getLangOpts().C2x) 15582 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15583 } 15584 Params.push_back(Param); 15585 } 15586 15587 // Fake up parameter variables if we have a typedef, like 15588 // ^ fntype { ... } 15589 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15590 for (const auto &I : Fn->param_types()) { 15591 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15592 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15593 Params.push_back(Param); 15594 } 15595 } 15596 15597 // Set the parameters on the block decl. 15598 if (!Params.empty()) { 15599 CurBlock->TheDecl->setParams(Params); 15600 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15601 /*CheckParameterNames=*/false); 15602 } 15603 15604 // Finally we can process decl attributes. 15605 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15606 15607 // Put the parameter variables in scope. 15608 for (auto AI : CurBlock->TheDecl->parameters()) { 15609 AI->setOwningFunction(CurBlock->TheDecl); 15610 15611 // If this has an identifier, add it to the scope stack. 15612 if (AI->getIdentifier()) { 15613 CheckShadow(CurBlock->TheScope, AI); 15614 15615 PushOnScopeChains(AI, CurBlock->TheScope); 15616 } 15617 } 15618 } 15619 15620 /// ActOnBlockError - If there is an error parsing a block, this callback 15621 /// is invoked to pop the information about the block from the action impl. 15622 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15623 // Leave the expression-evaluation context. 15624 DiscardCleanupsInEvaluationContext(); 15625 PopExpressionEvaluationContext(); 15626 15627 // Pop off CurBlock, handle nested blocks. 15628 PopDeclContext(); 15629 PopFunctionScopeInfo(); 15630 } 15631 15632 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15633 /// literal was successfully completed. ^(int x){...} 15634 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15635 Stmt *Body, Scope *CurScope) { 15636 // If blocks are disabled, emit an error. 15637 if (!LangOpts.Blocks) 15638 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15639 15640 // Leave the expression-evaluation context. 15641 if (hasAnyUnrecoverableErrorsInThisFunction()) 15642 DiscardCleanupsInEvaluationContext(); 15643 assert(!Cleanup.exprNeedsCleanups() && 15644 "cleanups within block not correctly bound!"); 15645 PopExpressionEvaluationContext(); 15646 15647 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15648 BlockDecl *BD = BSI->TheDecl; 15649 15650 if (BSI->HasImplicitReturnType) 15651 deduceClosureReturnType(*BSI); 15652 15653 QualType RetTy = Context.VoidTy; 15654 if (!BSI->ReturnType.isNull()) 15655 RetTy = BSI->ReturnType; 15656 15657 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15658 QualType BlockTy; 15659 15660 // If the user wrote a function type in some form, try to use that. 15661 if (!BSI->FunctionType.isNull()) { 15662 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15663 15664 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15665 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15666 15667 // Turn protoless block types into nullary block types. 15668 if (isa<FunctionNoProtoType>(FTy)) { 15669 FunctionProtoType::ExtProtoInfo EPI; 15670 EPI.ExtInfo = Ext; 15671 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15672 15673 // Otherwise, if we don't need to change anything about the function type, 15674 // preserve its sugar structure. 15675 } else if (FTy->getReturnType() == RetTy && 15676 (!NoReturn || FTy->getNoReturnAttr())) { 15677 BlockTy = BSI->FunctionType; 15678 15679 // Otherwise, make the minimal modifications to the function type. 15680 } else { 15681 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15682 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15683 EPI.TypeQuals = Qualifiers(); 15684 EPI.ExtInfo = Ext; 15685 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15686 } 15687 15688 // If we don't have a function type, just build one from nothing. 15689 } else { 15690 FunctionProtoType::ExtProtoInfo EPI; 15691 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15692 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15693 } 15694 15695 DiagnoseUnusedParameters(BD->parameters()); 15696 BlockTy = Context.getBlockPointerType(BlockTy); 15697 15698 // If needed, diagnose invalid gotos and switches in the block. 15699 if (getCurFunction()->NeedsScopeChecking() && 15700 !PP.isCodeCompletionEnabled()) 15701 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15702 15703 BD->setBody(cast<CompoundStmt>(Body)); 15704 15705 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15706 DiagnoseUnguardedAvailabilityViolations(BD); 15707 15708 // Try to apply the named return value optimization. We have to check again 15709 // if we can do this, though, because blocks keep return statements around 15710 // to deduce an implicit return type. 15711 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15712 !BD->isDependentContext()) 15713 computeNRVO(Body, BSI); 15714 15715 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15716 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15717 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15718 NTCUK_Destruct|NTCUK_Copy); 15719 15720 PopDeclContext(); 15721 15722 // Set the captured variables on the block. 15723 SmallVector<BlockDecl::Capture, 4> Captures; 15724 for (Capture &Cap : BSI->Captures) { 15725 if (Cap.isInvalid() || Cap.isThisCapture()) 15726 continue; 15727 15728 VarDecl *Var = Cap.getVariable(); 15729 Expr *CopyExpr = nullptr; 15730 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15731 if (const RecordType *Record = 15732 Cap.getCaptureType()->getAs<RecordType>()) { 15733 // The capture logic needs the destructor, so make sure we mark it. 15734 // Usually this is unnecessary because most local variables have 15735 // their destructors marked at declaration time, but parameters are 15736 // an exception because it's technically only the call site that 15737 // actually requires the destructor. 15738 if (isa<ParmVarDecl>(Var)) 15739 FinalizeVarWithDestructor(Var, Record); 15740 15741 // Enter a separate potentially-evaluated context while building block 15742 // initializers to isolate their cleanups from those of the block 15743 // itself. 15744 // FIXME: Is this appropriate even when the block itself occurs in an 15745 // unevaluated operand? 15746 EnterExpressionEvaluationContext EvalContext( 15747 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15748 15749 SourceLocation Loc = Cap.getLocation(); 15750 15751 ExprResult Result = BuildDeclarationNameExpr( 15752 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15753 15754 // According to the blocks spec, the capture of a variable from 15755 // the stack requires a const copy constructor. This is not true 15756 // of the copy/move done to move a __block variable to the heap. 15757 if (!Result.isInvalid() && 15758 !Result.get()->getType().isConstQualified()) { 15759 Result = ImpCastExprToType(Result.get(), 15760 Result.get()->getType().withConst(), 15761 CK_NoOp, VK_LValue); 15762 } 15763 15764 if (!Result.isInvalid()) { 15765 Result = PerformCopyInitialization( 15766 InitializedEntity::InitializeBlock(Var->getLocation(), 15767 Cap.getCaptureType()), 15768 Loc, Result.get()); 15769 } 15770 15771 // Build a full-expression copy expression if initialization 15772 // succeeded and used a non-trivial constructor. Recover from 15773 // errors by pretending that the copy isn't necessary. 15774 if (!Result.isInvalid() && 15775 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15776 ->isTrivial()) { 15777 Result = MaybeCreateExprWithCleanups(Result); 15778 CopyExpr = Result.get(); 15779 } 15780 } 15781 } 15782 15783 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15784 CopyExpr); 15785 Captures.push_back(NewCap); 15786 } 15787 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15788 15789 // Pop the block scope now but keep it alive to the end of this function. 15790 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15791 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15792 15793 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15794 15795 // If the block isn't obviously global, i.e. it captures anything at 15796 // all, then we need to do a few things in the surrounding context: 15797 if (Result->getBlockDecl()->hasCaptures()) { 15798 // First, this expression has a new cleanup object. 15799 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15800 Cleanup.setExprNeedsCleanups(true); 15801 15802 // It also gets a branch-protected scope if any of the captured 15803 // variables needs destruction. 15804 for (const auto &CI : Result->getBlockDecl()->captures()) { 15805 const VarDecl *var = CI.getVariable(); 15806 if (var->getType().isDestructedType() != QualType::DK_none) { 15807 setFunctionHasBranchProtectedScope(); 15808 break; 15809 } 15810 } 15811 } 15812 15813 if (getCurFunction()) 15814 getCurFunction()->addBlock(BD); 15815 15816 return Result; 15817 } 15818 15819 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15820 SourceLocation RPLoc) { 15821 TypeSourceInfo *TInfo; 15822 GetTypeFromParser(Ty, &TInfo); 15823 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15824 } 15825 15826 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15827 Expr *E, TypeSourceInfo *TInfo, 15828 SourceLocation RPLoc) { 15829 Expr *OrigExpr = E; 15830 bool IsMS = false; 15831 15832 // CUDA device code does not support varargs. 15833 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15834 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15835 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15836 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15837 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15838 } 15839 } 15840 15841 // NVPTX does not support va_arg expression. 15842 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15843 Context.getTargetInfo().getTriple().isNVPTX()) 15844 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15845 15846 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15847 // as Microsoft ABI on an actual Microsoft platform, where 15848 // __builtin_ms_va_list and __builtin_va_list are the same.) 15849 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15850 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15851 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15852 if (Context.hasSameType(MSVaListType, E->getType())) { 15853 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15854 return ExprError(); 15855 IsMS = true; 15856 } 15857 } 15858 15859 // Get the va_list type 15860 QualType VaListType = Context.getBuiltinVaListType(); 15861 if (!IsMS) { 15862 if (VaListType->isArrayType()) { 15863 // Deal with implicit array decay; for example, on x86-64, 15864 // va_list is an array, but it's supposed to decay to 15865 // a pointer for va_arg. 15866 VaListType = Context.getArrayDecayedType(VaListType); 15867 // Make sure the input expression also decays appropriately. 15868 ExprResult Result = UsualUnaryConversions(E); 15869 if (Result.isInvalid()) 15870 return ExprError(); 15871 E = Result.get(); 15872 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15873 // If va_list is a record type and we are compiling in C++ mode, 15874 // check the argument using reference binding. 15875 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15876 Context, Context.getLValueReferenceType(VaListType), false); 15877 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15878 if (Init.isInvalid()) 15879 return ExprError(); 15880 E = Init.getAs<Expr>(); 15881 } else { 15882 // Otherwise, the va_list argument must be an l-value because 15883 // it is modified by va_arg. 15884 if (!E->isTypeDependent() && 15885 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15886 return ExprError(); 15887 } 15888 } 15889 15890 if (!IsMS && !E->isTypeDependent() && 15891 !Context.hasSameType(VaListType, E->getType())) 15892 return ExprError( 15893 Diag(E->getBeginLoc(), 15894 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15895 << OrigExpr->getType() << E->getSourceRange()); 15896 15897 if (!TInfo->getType()->isDependentType()) { 15898 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15899 diag::err_second_parameter_to_va_arg_incomplete, 15900 TInfo->getTypeLoc())) 15901 return ExprError(); 15902 15903 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15904 TInfo->getType(), 15905 diag::err_second_parameter_to_va_arg_abstract, 15906 TInfo->getTypeLoc())) 15907 return ExprError(); 15908 15909 if (!TInfo->getType().isPODType(Context)) { 15910 Diag(TInfo->getTypeLoc().getBeginLoc(), 15911 TInfo->getType()->isObjCLifetimeType() 15912 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15913 : diag::warn_second_parameter_to_va_arg_not_pod) 15914 << TInfo->getType() 15915 << TInfo->getTypeLoc().getSourceRange(); 15916 } 15917 15918 // Check for va_arg where arguments of the given type will be promoted 15919 // (i.e. this va_arg is guaranteed to have undefined behavior). 15920 QualType PromoteType; 15921 if (TInfo->getType()->isPromotableIntegerType()) { 15922 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15923 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15924 // and C2x 7.16.1.1p2 says, in part: 15925 // If type is not compatible with the type of the actual next argument 15926 // (as promoted according to the default argument promotions), the 15927 // behavior is undefined, except for the following cases: 15928 // - both types are pointers to qualified or unqualified versions of 15929 // compatible types; 15930 // - one type is a signed integer type, the other type is the 15931 // corresponding unsigned integer type, and the value is 15932 // representable in both types; 15933 // - one type is pointer to qualified or unqualified void and the 15934 // other is a pointer to a qualified or unqualified character type. 15935 // Given that type compatibility is the primary requirement (ignoring 15936 // qualifications), you would think we could call typesAreCompatible() 15937 // directly to test this. However, in C++, that checks for *same type*, 15938 // which causes false positives when passing an enumeration type to 15939 // va_arg. Instead, get the underlying type of the enumeration and pass 15940 // that. 15941 QualType UnderlyingType = TInfo->getType(); 15942 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15943 UnderlyingType = ET->getDecl()->getIntegerType(); 15944 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15945 /*CompareUnqualified*/ true)) 15946 PromoteType = QualType(); 15947 15948 // If the types are still not compatible, we need to test whether the 15949 // promoted type and the underlying type are the same except for 15950 // signedness. Ask the AST for the correctly corresponding type and see 15951 // if that's compatible. 15952 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && 15953 PromoteType->isUnsignedIntegerType() != 15954 UnderlyingType->isUnsignedIntegerType()) { 15955 UnderlyingType = 15956 UnderlyingType->isUnsignedIntegerType() 15957 ? Context.getCorrespondingSignedType(UnderlyingType) 15958 : Context.getCorrespondingUnsignedType(UnderlyingType); 15959 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15960 /*CompareUnqualified*/ true)) 15961 PromoteType = QualType(); 15962 } 15963 } 15964 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15965 PromoteType = Context.DoubleTy; 15966 if (!PromoteType.isNull()) 15967 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15968 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15969 << TInfo->getType() 15970 << PromoteType 15971 << TInfo->getTypeLoc().getSourceRange()); 15972 } 15973 15974 QualType T = TInfo->getType().getNonLValueExprType(Context); 15975 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15976 } 15977 15978 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15979 // The type of __null will be int or long, depending on the size of 15980 // pointers on the target. 15981 QualType Ty; 15982 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15983 if (pw == Context.getTargetInfo().getIntWidth()) 15984 Ty = Context.IntTy; 15985 else if (pw == Context.getTargetInfo().getLongWidth()) 15986 Ty = Context.LongTy; 15987 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15988 Ty = Context.LongLongTy; 15989 else { 15990 llvm_unreachable("I don't know size of pointer!"); 15991 } 15992 15993 return new (Context) GNUNullExpr(Ty, TokenLoc); 15994 } 15995 15996 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15997 SourceLocation BuiltinLoc, 15998 SourceLocation RPLoc) { 15999 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 16000 } 16001 16002 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 16003 SourceLocation BuiltinLoc, 16004 SourceLocation RPLoc, 16005 DeclContext *ParentContext) { 16006 return new (Context) 16007 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 16008 } 16009 16010 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 16011 bool Diagnose) { 16012 if (!getLangOpts().ObjC) 16013 return false; 16014 16015 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 16016 if (!PT) 16017 return false; 16018 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 16019 16020 // Ignore any parens, implicit casts (should only be 16021 // array-to-pointer decays), and not-so-opaque values. The last is 16022 // important for making this trigger for property assignments. 16023 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 16024 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 16025 if (OV->getSourceExpr()) 16026 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 16027 16028 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 16029 if (!PT->isObjCIdType() && 16030 !(ID && ID->getIdentifier()->isStr("NSString"))) 16031 return false; 16032 if (!SL->isAscii()) 16033 return false; 16034 16035 if (Diagnose) { 16036 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 16037 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 16038 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 16039 } 16040 return true; 16041 } 16042 16043 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16044 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16045 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16046 !SrcExpr->isNullPointerConstant( 16047 getASTContext(), Expr::NPC_NeverValueDependent)) { 16048 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16049 return false; 16050 if (Diagnose) { 16051 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16052 << /*number*/1 16053 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16054 Expr *NumLit = 16055 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16056 if (NumLit) 16057 Exp = NumLit; 16058 } 16059 return true; 16060 } 16061 16062 return false; 16063 } 16064 16065 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16066 const Expr *SrcExpr) { 16067 if (!DstType->isFunctionPointerType() || 16068 !SrcExpr->getType()->isFunctionType()) 16069 return false; 16070 16071 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16072 if (!DRE) 16073 return false; 16074 16075 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16076 if (!FD) 16077 return false; 16078 16079 return !S.checkAddressOfFunctionIsAvailable(FD, 16080 /*Complain=*/true, 16081 SrcExpr->getBeginLoc()); 16082 } 16083 16084 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16085 SourceLocation Loc, 16086 QualType DstType, QualType SrcType, 16087 Expr *SrcExpr, AssignmentAction Action, 16088 bool *Complained) { 16089 if (Complained) 16090 *Complained = false; 16091 16092 // Decode the result (notice that AST's are still created for extensions). 16093 bool CheckInferredResultType = false; 16094 bool isInvalid = false; 16095 unsigned DiagKind = 0; 16096 ConversionFixItGenerator ConvHints; 16097 bool MayHaveConvFixit = false; 16098 bool MayHaveFunctionDiff = false; 16099 const ObjCInterfaceDecl *IFace = nullptr; 16100 const ObjCProtocolDecl *PDecl = nullptr; 16101 16102 switch (ConvTy) { 16103 case Compatible: 16104 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16105 return false; 16106 16107 case PointerToInt: 16108 if (getLangOpts().CPlusPlus) { 16109 DiagKind = diag::err_typecheck_convert_pointer_int; 16110 isInvalid = true; 16111 } else { 16112 DiagKind = diag::ext_typecheck_convert_pointer_int; 16113 } 16114 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16115 MayHaveConvFixit = true; 16116 break; 16117 case IntToPointer: 16118 if (getLangOpts().CPlusPlus) { 16119 DiagKind = diag::err_typecheck_convert_int_pointer; 16120 isInvalid = true; 16121 } else { 16122 DiagKind = diag::ext_typecheck_convert_int_pointer; 16123 } 16124 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16125 MayHaveConvFixit = true; 16126 break; 16127 case IncompatibleFunctionPointer: 16128 if (getLangOpts().CPlusPlus) { 16129 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16130 isInvalid = true; 16131 } else { 16132 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16133 } 16134 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16135 MayHaveConvFixit = true; 16136 break; 16137 case IncompatiblePointer: 16138 if (Action == AA_Passing_CFAudited) { 16139 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16140 } else if (getLangOpts().CPlusPlus) { 16141 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16142 isInvalid = true; 16143 } else { 16144 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16145 } 16146 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16147 SrcType->isObjCObjectPointerType(); 16148 if (!CheckInferredResultType) { 16149 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16150 } else if (CheckInferredResultType) { 16151 SrcType = SrcType.getUnqualifiedType(); 16152 DstType = DstType.getUnqualifiedType(); 16153 } 16154 MayHaveConvFixit = true; 16155 break; 16156 case IncompatiblePointerSign: 16157 if (getLangOpts().CPlusPlus) { 16158 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16159 isInvalid = true; 16160 } else { 16161 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16162 } 16163 break; 16164 case FunctionVoidPointer: 16165 if (getLangOpts().CPlusPlus) { 16166 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16167 isInvalid = true; 16168 } else { 16169 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16170 } 16171 break; 16172 case IncompatiblePointerDiscardsQualifiers: { 16173 // Perform array-to-pointer decay if necessary. 16174 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16175 16176 isInvalid = true; 16177 16178 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16179 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16180 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16181 DiagKind = diag::err_typecheck_incompatible_address_space; 16182 break; 16183 16184 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16185 DiagKind = diag::err_typecheck_incompatible_ownership; 16186 break; 16187 } 16188 16189 llvm_unreachable("unknown error case for discarding qualifiers!"); 16190 // fallthrough 16191 } 16192 case CompatiblePointerDiscardsQualifiers: 16193 // If the qualifiers lost were because we were applying the 16194 // (deprecated) C++ conversion from a string literal to a char* 16195 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16196 // Ideally, this check would be performed in 16197 // checkPointerTypesForAssignment. However, that would require a 16198 // bit of refactoring (so that the second argument is an 16199 // expression, rather than a type), which should be done as part 16200 // of a larger effort to fix checkPointerTypesForAssignment for 16201 // C++ semantics. 16202 if (getLangOpts().CPlusPlus && 16203 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16204 return false; 16205 if (getLangOpts().CPlusPlus) { 16206 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16207 isInvalid = true; 16208 } else { 16209 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16210 } 16211 16212 break; 16213 case IncompatibleNestedPointerQualifiers: 16214 if (getLangOpts().CPlusPlus) { 16215 isInvalid = true; 16216 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16217 } else { 16218 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16219 } 16220 break; 16221 case IncompatibleNestedPointerAddressSpaceMismatch: 16222 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16223 isInvalid = true; 16224 break; 16225 case IntToBlockPointer: 16226 DiagKind = diag::err_int_to_block_pointer; 16227 isInvalid = true; 16228 break; 16229 case IncompatibleBlockPointer: 16230 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16231 isInvalid = true; 16232 break; 16233 case IncompatibleObjCQualifiedId: { 16234 if (SrcType->isObjCQualifiedIdType()) { 16235 const ObjCObjectPointerType *srcOPT = 16236 SrcType->castAs<ObjCObjectPointerType>(); 16237 for (auto *srcProto : srcOPT->quals()) { 16238 PDecl = srcProto; 16239 break; 16240 } 16241 if (const ObjCInterfaceType *IFaceT = 16242 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16243 IFace = IFaceT->getDecl(); 16244 } 16245 else if (DstType->isObjCQualifiedIdType()) { 16246 const ObjCObjectPointerType *dstOPT = 16247 DstType->castAs<ObjCObjectPointerType>(); 16248 for (auto *dstProto : dstOPT->quals()) { 16249 PDecl = dstProto; 16250 break; 16251 } 16252 if (const ObjCInterfaceType *IFaceT = 16253 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16254 IFace = IFaceT->getDecl(); 16255 } 16256 if (getLangOpts().CPlusPlus) { 16257 DiagKind = diag::err_incompatible_qualified_id; 16258 isInvalid = true; 16259 } else { 16260 DiagKind = diag::warn_incompatible_qualified_id; 16261 } 16262 break; 16263 } 16264 case IncompatibleVectors: 16265 if (getLangOpts().CPlusPlus) { 16266 DiagKind = diag::err_incompatible_vectors; 16267 isInvalid = true; 16268 } else { 16269 DiagKind = diag::warn_incompatible_vectors; 16270 } 16271 break; 16272 case IncompatibleObjCWeakRef: 16273 DiagKind = diag::err_arc_weak_unavailable_assign; 16274 isInvalid = true; 16275 break; 16276 case Incompatible: 16277 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16278 if (Complained) 16279 *Complained = true; 16280 return true; 16281 } 16282 16283 DiagKind = diag::err_typecheck_convert_incompatible; 16284 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16285 MayHaveConvFixit = true; 16286 isInvalid = true; 16287 MayHaveFunctionDiff = true; 16288 break; 16289 } 16290 16291 QualType FirstType, SecondType; 16292 switch (Action) { 16293 case AA_Assigning: 16294 case AA_Initializing: 16295 // The destination type comes first. 16296 FirstType = DstType; 16297 SecondType = SrcType; 16298 break; 16299 16300 case AA_Returning: 16301 case AA_Passing: 16302 case AA_Passing_CFAudited: 16303 case AA_Converting: 16304 case AA_Sending: 16305 case AA_Casting: 16306 // The source type comes first. 16307 FirstType = SrcType; 16308 SecondType = DstType; 16309 break; 16310 } 16311 16312 PartialDiagnostic FDiag = PDiag(DiagKind); 16313 if (Action == AA_Passing_CFAudited) 16314 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16315 else 16316 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16317 16318 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16319 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16320 auto isPlainChar = [](const clang::Type *Type) { 16321 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16322 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16323 }; 16324 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16325 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16326 } 16327 16328 // If we can fix the conversion, suggest the FixIts. 16329 if (!ConvHints.isNull()) { 16330 for (FixItHint &H : ConvHints.Hints) 16331 FDiag << H; 16332 } 16333 16334 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16335 16336 if (MayHaveFunctionDiff) 16337 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16338 16339 Diag(Loc, FDiag); 16340 if ((DiagKind == diag::warn_incompatible_qualified_id || 16341 DiagKind == diag::err_incompatible_qualified_id) && 16342 PDecl && IFace && !IFace->hasDefinition()) 16343 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16344 << IFace << PDecl; 16345 16346 if (SecondType == Context.OverloadTy) 16347 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16348 FirstType, /*TakingAddress=*/true); 16349 16350 if (CheckInferredResultType) 16351 EmitRelatedResultTypeNote(SrcExpr); 16352 16353 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16354 EmitRelatedResultTypeNoteForReturn(DstType); 16355 16356 if (Complained) 16357 *Complained = true; 16358 return isInvalid; 16359 } 16360 16361 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16362 llvm::APSInt *Result, 16363 AllowFoldKind CanFold) { 16364 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16365 public: 16366 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16367 QualType T) override { 16368 return S.Diag(Loc, diag::err_ice_not_integral) 16369 << T << S.LangOpts.CPlusPlus; 16370 } 16371 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16372 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16373 } 16374 } Diagnoser; 16375 16376 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16377 } 16378 16379 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16380 llvm::APSInt *Result, 16381 unsigned DiagID, 16382 AllowFoldKind CanFold) { 16383 class IDDiagnoser : public VerifyICEDiagnoser { 16384 unsigned DiagID; 16385 16386 public: 16387 IDDiagnoser(unsigned DiagID) 16388 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16389 16390 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16391 return S.Diag(Loc, DiagID); 16392 } 16393 } Diagnoser(DiagID); 16394 16395 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16396 } 16397 16398 Sema::SemaDiagnosticBuilder 16399 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16400 QualType T) { 16401 return diagnoseNotICE(S, Loc); 16402 } 16403 16404 Sema::SemaDiagnosticBuilder 16405 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16406 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16407 } 16408 16409 ExprResult 16410 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16411 VerifyICEDiagnoser &Diagnoser, 16412 AllowFoldKind CanFold) { 16413 SourceLocation DiagLoc = E->getBeginLoc(); 16414 16415 if (getLangOpts().CPlusPlus11) { 16416 // C++11 [expr.const]p5: 16417 // If an expression of literal class type is used in a context where an 16418 // integral constant expression is required, then that class type shall 16419 // have a single non-explicit conversion function to an integral or 16420 // unscoped enumeration type 16421 ExprResult Converted; 16422 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16423 VerifyICEDiagnoser &BaseDiagnoser; 16424 public: 16425 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16426 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16427 BaseDiagnoser.Suppress, true), 16428 BaseDiagnoser(BaseDiagnoser) {} 16429 16430 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16431 QualType T) override { 16432 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16433 } 16434 16435 SemaDiagnosticBuilder diagnoseIncomplete( 16436 Sema &S, SourceLocation Loc, QualType T) override { 16437 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16438 } 16439 16440 SemaDiagnosticBuilder diagnoseExplicitConv( 16441 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16442 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16443 } 16444 16445 SemaDiagnosticBuilder noteExplicitConv( 16446 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16447 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16448 << ConvTy->isEnumeralType() << ConvTy; 16449 } 16450 16451 SemaDiagnosticBuilder diagnoseAmbiguous( 16452 Sema &S, SourceLocation Loc, QualType T) override { 16453 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16454 } 16455 16456 SemaDiagnosticBuilder noteAmbiguous( 16457 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16458 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16459 << ConvTy->isEnumeralType() << ConvTy; 16460 } 16461 16462 SemaDiagnosticBuilder diagnoseConversion( 16463 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16464 llvm_unreachable("conversion functions are permitted"); 16465 } 16466 } ConvertDiagnoser(Diagnoser); 16467 16468 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16469 ConvertDiagnoser); 16470 if (Converted.isInvalid()) 16471 return Converted; 16472 E = Converted.get(); 16473 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16474 return ExprError(); 16475 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16476 // An ICE must be of integral or unscoped enumeration type. 16477 if (!Diagnoser.Suppress) 16478 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16479 << E->getSourceRange(); 16480 return ExprError(); 16481 } 16482 16483 ExprResult RValueExpr = DefaultLvalueConversion(E); 16484 if (RValueExpr.isInvalid()) 16485 return ExprError(); 16486 16487 E = RValueExpr.get(); 16488 16489 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16490 // in the non-ICE case. 16491 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16492 if (Result) 16493 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16494 if (!isa<ConstantExpr>(E)) 16495 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16496 : ConstantExpr::Create(Context, E); 16497 return E; 16498 } 16499 16500 Expr::EvalResult EvalResult; 16501 SmallVector<PartialDiagnosticAt, 8> Notes; 16502 EvalResult.Diag = &Notes; 16503 16504 // Try to evaluate the expression, and produce diagnostics explaining why it's 16505 // not a constant expression as a side-effect. 16506 bool Folded = 16507 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16508 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16509 16510 if (!isa<ConstantExpr>(E)) 16511 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16512 16513 // In C++11, we can rely on diagnostics being produced for any expression 16514 // which is not a constant expression. If no diagnostics were produced, then 16515 // this is a constant expression. 16516 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16517 if (Result) 16518 *Result = EvalResult.Val.getInt(); 16519 return E; 16520 } 16521 16522 // If our only note is the usual "invalid subexpression" note, just point 16523 // the caret at its location rather than producing an essentially 16524 // redundant note. 16525 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16526 diag::note_invalid_subexpr_in_const_expr) { 16527 DiagLoc = Notes[0].first; 16528 Notes.clear(); 16529 } 16530 16531 if (!Folded || !CanFold) { 16532 if (!Diagnoser.Suppress) { 16533 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16534 for (const PartialDiagnosticAt &Note : Notes) 16535 Diag(Note.first, Note.second); 16536 } 16537 16538 return ExprError(); 16539 } 16540 16541 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16542 for (const PartialDiagnosticAt &Note : Notes) 16543 Diag(Note.first, Note.second); 16544 16545 if (Result) 16546 *Result = EvalResult.Val.getInt(); 16547 return E; 16548 } 16549 16550 namespace { 16551 // Handle the case where we conclude a expression which we speculatively 16552 // considered to be unevaluated is actually evaluated. 16553 class TransformToPE : public TreeTransform<TransformToPE> { 16554 typedef TreeTransform<TransformToPE> BaseTransform; 16555 16556 public: 16557 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16558 16559 // Make sure we redo semantic analysis 16560 bool AlwaysRebuild() { return true; } 16561 bool ReplacingOriginal() { return true; } 16562 16563 // We need to special-case DeclRefExprs referring to FieldDecls which 16564 // are not part of a member pointer formation; normal TreeTransforming 16565 // doesn't catch this case because of the way we represent them in the AST. 16566 // FIXME: This is a bit ugly; is it really the best way to handle this 16567 // case? 16568 // 16569 // Error on DeclRefExprs referring to FieldDecls. 16570 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16571 if (isa<FieldDecl>(E->getDecl()) && 16572 !SemaRef.isUnevaluatedContext()) 16573 return SemaRef.Diag(E->getLocation(), 16574 diag::err_invalid_non_static_member_use) 16575 << E->getDecl() << E->getSourceRange(); 16576 16577 return BaseTransform::TransformDeclRefExpr(E); 16578 } 16579 16580 // Exception: filter out member pointer formation 16581 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16582 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16583 return E; 16584 16585 return BaseTransform::TransformUnaryOperator(E); 16586 } 16587 16588 // The body of a lambda-expression is in a separate expression evaluation 16589 // context so never needs to be transformed. 16590 // FIXME: Ideally we wouldn't transform the closure type either, and would 16591 // just recreate the capture expressions and lambda expression. 16592 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16593 return SkipLambdaBody(E, Body); 16594 } 16595 }; 16596 } 16597 16598 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16599 assert(isUnevaluatedContext() && 16600 "Should only transform unevaluated expressions"); 16601 ExprEvalContexts.back().Context = 16602 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16603 if (isUnevaluatedContext()) 16604 return E; 16605 return TransformToPE(*this).TransformExpr(E); 16606 } 16607 16608 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { 16609 assert(isUnevaluatedContext() && 16610 "Should only transform unevaluated expressions"); 16611 ExprEvalContexts.back().Context = 16612 ExprEvalContexts[ExprEvalContexts.size() - 2].Context; 16613 if (isUnevaluatedContext()) 16614 return TInfo; 16615 return TransformToPE(*this).TransformType(TInfo); 16616 } 16617 16618 void 16619 Sema::PushExpressionEvaluationContext( 16620 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16621 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16622 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16623 LambdaContextDecl, ExprContext); 16624 16625 // Discarded statements and immediate contexts nested in other 16626 // discarded statements or immediate context are themselves 16627 // a discarded statement or an immediate context, respectively. 16628 ExprEvalContexts.back().InDiscardedStatement = 16629 ExprEvalContexts[ExprEvalContexts.size() - 2] 16630 .isDiscardedStatementContext(); 16631 ExprEvalContexts.back().InImmediateFunctionContext = 16632 ExprEvalContexts[ExprEvalContexts.size() - 2] 16633 .isImmediateFunctionContext(); 16634 16635 Cleanup.reset(); 16636 if (!MaybeODRUseExprs.empty()) 16637 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16638 } 16639 16640 void 16641 Sema::PushExpressionEvaluationContext( 16642 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16643 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16644 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16645 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16646 } 16647 16648 namespace { 16649 16650 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16651 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16652 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16653 if (E->getOpcode() == UO_Deref) 16654 return CheckPossibleDeref(S, E->getSubExpr()); 16655 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16656 return CheckPossibleDeref(S, E->getBase()); 16657 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16658 return CheckPossibleDeref(S, E->getBase()); 16659 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16660 QualType Inner; 16661 QualType Ty = E->getType(); 16662 if (const auto *Ptr = Ty->getAs<PointerType>()) 16663 Inner = Ptr->getPointeeType(); 16664 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16665 Inner = Arr->getElementType(); 16666 else 16667 return nullptr; 16668 16669 if (Inner->hasAttr(attr::NoDeref)) 16670 return E; 16671 } 16672 return nullptr; 16673 } 16674 16675 } // namespace 16676 16677 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16678 for (const Expr *E : Rec.PossibleDerefs) { 16679 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16680 if (DeclRef) { 16681 const ValueDecl *Decl = DeclRef->getDecl(); 16682 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16683 << Decl->getName() << E->getSourceRange(); 16684 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16685 } else { 16686 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16687 << E->getSourceRange(); 16688 } 16689 } 16690 Rec.PossibleDerefs.clear(); 16691 } 16692 16693 /// Check whether E, which is either a discarded-value expression or an 16694 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16695 /// and if so, remove it from the list of volatile-qualified assignments that 16696 /// we are going to warn are deprecated. 16697 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16698 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16699 return; 16700 16701 // Note: ignoring parens here is not justified by the standard rules, but 16702 // ignoring parentheses seems like a more reasonable approach, and this only 16703 // drives a deprecation warning so doesn't affect conformance. 16704 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16705 if (BO->getOpcode() == BO_Assign) { 16706 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16707 llvm::erase_value(LHSs, BO->getLHS()); 16708 } 16709 } 16710 } 16711 16712 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16713 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16714 !Decl->isConsteval() || isConstantEvaluated() || 16715 RebuildingImmediateInvocation || isImmediateFunctionContext()) 16716 return E; 16717 16718 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16719 /// It's OK if this fails; we'll also remove this in 16720 /// HandleImmediateInvocations, but catching it here allows us to avoid 16721 /// walking the AST looking for it in simple cases. 16722 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16723 if (auto *DeclRef = 16724 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16725 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16726 16727 E = MaybeCreateExprWithCleanups(E); 16728 16729 ConstantExpr *Res = ConstantExpr::Create( 16730 getASTContext(), E.get(), 16731 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16732 getASTContext()), 16733 /*IsImmediateInvocation*/ true); 16734 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16735 return Res; 16736 } 16737 16738 static void EvaluateAndDiagnoseImmediateInvocation( 16739 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16740 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16741 Expr::EvalResult Eval; 16742 Eval.Diag = &Notes; 16743 ConstantExpr *CE = Candidate.getPointer(); 16744 bool Result = CE->EvaluateAsConstantExpr( 16745 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16746 if (!Result || !Notes.empty()) { 16747 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16748 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16749 InnerExpr = FunctionalCast->getSubExpr(); 16750 FunctionDecl *FD = nullptr; 16751 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16752 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16753 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16754 FD = Call->getConstructor(); 16755 else 16756 llvm_unreachable("unhandled decl kind"); 16757 assert(FD->isConsteval()); 16758 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16759 for (auto &Note : Notes) 16760 SemaRef.Diag(Note.first, Note.second); 16761 return; 16762 } 16763 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16764 } 16765 16766 static void RemoveNestedImmediateInvocation( 16767 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16768 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16769 struct ComplexRemove : TreeTransform<ComplexRemove> { 16770 using Base = TreeTransform<ComplexRemove>; 16771 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16772 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16773 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16774 CurrentII; 16775 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16776 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16777 SmallVector<Sema::ImmediateInvocationCandidate, 16778 4>::reverse_iterator Current) 16779 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16780 void RemoveImmediateInvocation(ConstantExpr* E) { 16781 auto It = std::find_if(CurrentII, IISet.rend(), 16782 [E](Sema::ImmediateInvocationCandidate Elem) { 16783 return Elem.getPointer() == E; 16784 }); 16785 assert(It != IISet.rend() && 16786 "ConstantExpr marked IsImmediateInvocation should " 16787 "be present"); 16788 It->setInt(1); // Mark as deleted 16789 } 16790 ExprResult TransformConstantExpr(ConstantExpr *E) { 16791 if (!E->isImmediateInvocation()) 16792 return Base::TransformConstantExpr(E); 16793 RemoveImmediateInvocation(E); 16794 return Base::TransformExpr(E->getSubExpr()); 16795 } 16796 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16797 /// we need to remove its DeclRefExpr from the DRSet. 16798 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16799 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16800 return Base::TransformCXXOperatorCallExpr(E); 16801 } 16802 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16803 /// here. 16804 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16805 if (!Init) 16806 return Init; 16807 /// ConstantExpr are the first layer of implicit node to be removed so if 16808 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16809 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16810 if (CE->isImmediateInvocation()) 16811 RemoveImmediateInvocation(CE); 16812 return Base::TransformInitializer(Init, NotCopyInit); 16813 } 16814 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16815 DRSet.erase(E); 16816 return E; 16817 } 16818 bool AlwaysRebuild() { return false; } 16819 bool ReplacingOriginal() { return true; } 16820 bool AllowSkippingCXXConstructExpr() { 16821 bool Res = AllowSkippingFirstCXXConstructExpr; 16822 AllowSkippingFirstCXXConstructExpr = true; 16823 return Res; 16824 } 16825 bool AllowSkippingFirstCXXConstructExpr = true; 16826 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16827 Rec.ImmediateInvocationCandidates, It); 16828 16829 /// CXXConstructExpr with a single argument are getting skipped by 16830 /// TreeTransform in some situtation because they could be implicit. This 16831 /// can only occur for the top-level CXXConstructExpr because it is used 16832 /// nowhere in the expression being transformed therefore will not be rebuilt. 16833 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16834 /// skipping the first CXXConstructExpr. 16835 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16836 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16837 16838 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16839 assert(Res.isUsable()); 16840 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16841 It->getPointer()->setSubExpr(Res.get()); 16842 } 16843 16844 static void 16845 HandleImmediateInvocations(Sema &SemaRef, 16846 Sema::ExpressionEvaluationContextRecord &Rec) { 16847 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16848 Rec.ReferenceToConsteval.size() == 0) || 16849 SemaRef.RebuildingImmediateInvocation) 16850 return; 16851 16852 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16853 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16854 /// need to remove ReferenceToConsteval in the immediate invocation. 16855 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16856 16857 /// Prevent sema calls during the tree transform from adding pointers that 16858 /// are already in the sets. 16859 llvm::SaveAndRestore<bool> DisableIITracking( 16860 SemaRef.RebuildingImmediateInvocation, true); 16861 16862 /// Prevent diagnostic during tree transfrom as they are duplicates 16863 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16864 16865 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16866 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16867 if (!It->getInt()) 16868 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16869 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16870 Rec.ReferenceToConsteval.size()) { 16871 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16872 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16873 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16874 bool VisitDeclRefExpr(DeclRefExpr *E) { 16875 DRSet.erase(E); 16876 return DRSet.size(); 16877 } 16878 } Visitor(Rec.ReferenceToConsteval); 16879 Visitor.TraverseStmt( 16880 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16881 } 16882 for (auto CE : Rec.ImmediateInvocationCandidates) 16883 if (!CE.getInt()) 16884 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16885 for (auto DR : Rec.ReferenceToConsteval) { 16886 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16887 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16888 << FD; 16889 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16890 } 16891 } 16892 16893 void Sema::PopExpressionEvaluationContext() { 16894 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16895 unsigned NumTypos = Rec.NumTypos; 16896 16897 if (!Rec.Lambdas.empty()) { 16898 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16899 if (!getLangOpts().CPlusPlus20 && 16900 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16901 Rec.isUnevaluated() || 16902 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16903 unsigned D; 16904 if (Rec.isUnevaluated()) { 16905 // C++11 [expr.prim.lambda]p2: 16906 // A lambda-expression shall not appear in an unevaluated operand 16907 // (Clause 5). 16908 D = diag::err_lambda_unevaluated_operand; 16909 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16910 // C++1y [expr.const]p2: 16911 // A conditional-expression e is a core constant expression unless the 16912 // evaluation of e, following the rules of the abstract machine, would 16913 // evaluate [...] a lambda-expression. 16914 D = diag::err_lambda_in_constant_expression; 16915 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16916 // C++17 [expr.prim.lamda]p2: 16917 // A lambda-expression shall not appear [...] in a template-argument. 16918 D = diag::err_lambda_in_invalid_context; 16919 } else 16920 llvm_unreachable("Couldn't infer lambda error message."); 16921 16922 for (const auto *L : Rec.Lambdas) 16923 Diag(L->getBeginLoc(), D); 16924 } 16925 } 16926 16927 WarnOnPendingNoDerefs(Rec); 16928 HandleImmediateInvocations(*this, Rec); 16929 16930 // Warn on any volatile-qualified simple-assignments that are not discarded- 16931 // value expressions nor unevaluated operands (those cases get removed from 16932 // this list by CheckUnusedVolatileAssignment). 16933 for (auto *BO : Rec.VolatileAssignmentLHSs) 16934 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16935 << BO->getType(); 16936 16937 // When are coming out of an unevaluated context, clear out any 16938 // temporaries that we may have created as part of the evaluation of 16939 // the expression in that context: they aren't relevant because they 16940 // will never be constructed. 16941 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16942 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16943 ExprCleanupObjects.end()); 16944 Cleanup = Rec.ParentCleanup; 16945 CleanupVarDeclMarking(); 16946 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16947 // Otherwise, merge the contexts together. 16948 } else { 16949 Cleanup.mergeFrom(Rec.ParentCleanup); 16950 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16951 Rec.SavedMaybeODRUseExprs.end()); 16952 } 16953 16954 // Pop the current expression evaluation context off the stack. 16955 ExprEvalContexts.pop_back(); 16956 16957 // The global expression evaluation context record is never popped. 16958 ExprEvalContexts.back().NumTypos += NumTypos; 16959 } 16960 16961 void Sema::DiscardCleanupsInEvaluationContext() { 16962 ExprCleanupObjects.erase( 16963 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16964 ExprCleanupObjects.end()); 16965 Cleanup.reset(); 16966 MaybeODRUseExprs.clear(); 16967 } 16968 16969 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16970 ExprResult Result = CheckPlaceholderExpr(E); 16971 if (Result.isInvalid()) 16972 return ExprError(); 16973 E = Result.get(); 16974 if (!E->getType()->isVariablyModifiedType()) 16975 return E; 16976 return TransformToPotentiallyEvaluated(E); 16977 } 16978 16979 /// Are we in a context that is potentially constant evaluated per C++20 16980 /// [expr.const]p12? 16981 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16982 /// C++2a [expr.const]p12: 16983 // An expression or conversion is potentially constant evaluated if it is 16984 switch (SemaRef.ExprEvalContexts.back().Context) { 16985 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16986 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 16987 16988 // -- a manifestly constant-evaluated expression, 16989 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16990 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16991 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16992 // -- a potentially-evaluated expression, 16993 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16994 // -- an immediate subexpression of a braced-init-list, 16995 16996 // -- [FIXME] an expression of the form & cast-expression that occurs 16997 // within a templated entity 16998 // -- a subexpression of one of the above that is not a subexpression of 16999 // a nested unevaluated operand. 17000 return true; 17001 17002 case Sema::ExpressionEvaluationContext::Unevaluated: 17003 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17004 // Expressions in this context are never evaluated. 17005 return false; 17006 } 17007 llvm_unreachable("Invalid context"); 17008 } 17009 17010 /// Return true if this function has a calling convention that requires mangling 17011 /// in the size of the parameter pack. 17012 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 17013 // These manglings don't do anything on non-Windows or non-x86 platforms, so 17014 // we don't need parameter type sizes. 17015 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 17016 if (!TT.isOSWindows() || !TT.isX86()) 17017 return false; 17018 17019 // If this is C++ and this isn't an extern "C" function, parameters do not 17020 // need to be complete. In this case, C++ mangling will apply, which doesn't 17021 // use the size of the parameters. 17022 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 17023 return false; 17024 17025 // Stdcall, fastcall, and vectorcall need this special treatment. 17026 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17027 switch (CC) { 17028 case CC_X86StdCall: 17029 case CC_X86FastCall: 17030 case CC_X86VectorCall: 17031 return true; 17032 default: 17033 break; 17034 } 17035 return false; 17036 } 17037 17038 /// Require that all of the parameter types of function be complete. Normally, 17039 /// parameter types are only required to be complete when a function is called 17040 /// or defined, but to mangle functions with certain calling conventions, the 17041 /// mangler needs to know the size of the parameter list. In this situation, 17042 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 17043 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 17044 /// result in a linker error. Clang doesn't implement this behavior, and instead 17045 /// attempts to error at compile time. 17046 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 17047 SourceLocation Loc) { 17048 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 17049 FunctionDecl *FD; 17050 ParmVarDecl *Param; 17051 17052 public: 17053 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 17054 : FD(FD), Param(Param) {} 17055 17056 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17057 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17058 StringRef CCName; 17059 switch (CC) { 17060 case CC_X86StdCall: 17061 CCName = "stdcall"; 17062 break; 17063 case CC_X86FastCall: 17064 CCName = "fastcall"; 17065 break; 17066 case CC_X86VectorCall: 17067 CCName = "vectorcall"; 17068 break; 17069 default: 17070 llvm_unreachable("CC does not need mangling"); 17071 } 17072 17073 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17074 << Param->getDeclName() << FD->getDeclName() << CCName; 17075 } 17076 }; 17077 17078 for (ParmVarDecl *Param : FD->parameters()) { 17079 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17080 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17081 } 17082 } 17083 17084 namespace { 17085 enum class OdrUseContext { 17086 /// Declarations in this context are not odr-used. 17087 None, 17088 /// Declarations in this context are formally odr-used, but this is a 17089 /// dependent context. 17090 Dependent, 17091 /// Declarations in this context are odr-used but not actually used (yet). 17092 FormallyOdrUsed, 17093 /// Declarations in this context are used. 17094 Used 17095 }; 17096 } 17097 17098 /// Are we within a context in which references to resolved functions or to 17099 /// variables result in odr-use? 17100 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17101 OdrUseContext Result; 17102 17103 switch (SemaRef.ExprEvalContexts.back().Context) { 17104 case Sema::ExpressionEvaluationContext::Unevaluated: 17105 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17106 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17107 return OdrUseContext::None; 17108 17109 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17110 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 17111 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17112 Result = OdrUseContext::Used; 17113 break; 17114 17115 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17116 Result = OdrUseContext::FormallyOdrUsed; 17117 break; 17118 17119 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17120 // A default argument formally results in odr-use, but doesn't actually 17121 // result in a use in any real sense until it itself is used. 17122 Result = OdrUseContext::FormallyOdrUsed; 17123 break; 17124 } 17125 17126 if (SemaRef.CurContext->isDependentContext()) 17127 return OdrUseContext::Dependent; 17128 17129 return Result; 17130 } 17131 17132 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17133 if (!Func->isConstexpr()) 17134 return false; 17135 17136 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17137 return true; 17138 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17139 return CCD && CCD->getInheritedConstructor(); 17140 } 17141 17142 /// Mark a function referenced, and check whether it is odr-used 17143 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17144 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17145 bool MightBeOdrUse) { 17146 assert(Func && "No function?"); 17147 17148 Func->setReferenced(); 17149 17150 // Recursive functions aren't really used until they're used from some other 17151 // context. 17152 bool IsRecursiveCall = CurContext == Func; 17153 17154 // C++11 [basic.def.odr]p3: 17155 // A function whose name appears as a potentially-evaluated expression is 17156 // odr-used if it is the unique lookup result or the selected member of a 17157 // set of overloaded functions [...]. 17158 // 17159 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17160 // can just check that here. 17161 OdrUseContext OdrUse = 17162 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17163 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17164 OdrUse = OdrUseContext::FormallyOdrUsed; 17165 17166 // Trivial default constructors and destructors are never actually used. 17167 // FIXME: What about other special members? 17168 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17169 OdrUse == OdrUseContext::Used) { 17170 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17171 if (Constructor->isDefaultConstructor()) 17172 OdrUse = OdrUseContext::FormallyOdrUsed; 17173 if (isa<CXXDestructorDecl>(Func)) 17174 OdrUse = OdrUseContext::FormallyOdrUsed; 17175 } 17176 17177 // C++20 [expr.const]p12: 17178 // A function [...] is needed for constant evaluation if it is [...] a 17179 // constexpr function that is named by an expression that is potentially 17180 // constant evaluated 17181 bool NeededForConstantEvaluation = 17182 isPotentiallyConstantEvaluatedContext(*this) && 17183 isImplicitlyDefinableConstexprFunction(Func); 17184 17185 // Determine whether we require a function definition to exist, per 17186 // C++11 [temp.inst]p3: 17187 // Unless a function template specialization has been explicitly 17188 // instantiated or explicitly specialized, the function template 17189 // specialization is implicitly instantiated when the specialization is 17190 // referenced in a context that requires a function definition to exist. 17191 // C++20 [temp.inst]p7: 17192 // The existence of a definition of a [...] function is considered to 17193 // affect the semantics of the program if the [...] function is needed for 17194 // constant evaluation by an expression 17195 // C++20 [basic.def.odr]p10: 17196 // Every program shall contain exactly one definition of every non-inline 17197 // function or variable that is odr-used in that program outside of a 17198 // discarded statement 17199 // C++20 [special]p1: 17200 // The implementation will implicitly define [defaulted special members] 17201 // if they are odr-used or needed for constant evaluation. 17202 // 17203 // Note that we skip the implicit instantiation of templates that are only 17204 // used in unused default arguments or by recursive calls to themselves. 17205 // This is formally non-conforming, but seems reasonable in practice. 17206 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17207 NeededForConstantEvaluation); 17208 17209 // C++14 [temp.expl.spec]p6: 17210 // If a template [...] is explicitly specialized then that specialization 17211 // shall be declared before the first use of that specialization that would 17212 // cause an implicit instantiation to take place, in every translation unit 17213 // in which such a use occurs 17214 if (NeedDefinition && 17215 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17216 Func->getMemberSpecializationInfo())) 17217 checkSpecializationVisibility(Loc, Func); 17218 17219 if (getLangOpts().CUDA) 17220 CheckCUDACall(Loc, Func); 17221 17222 if (getLangOpts().SYCLIsDevice) 17223 checkSYCLDeviceFunction(Loc, Func); 17224 17225 // If we need a definition, try to create one. 17226 if (NeedDefinition && !Func->getBody()) { 17227 runWithSufficientStackSpace(Loc, [&] { 17228 if (CXXConstructorDecl *Constructor = 17229 dyn_cast<CXXConstructorDecl>(Func)) { 17230 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17231 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17232 if (Constructor->isDefaultConstructor()) { 17233 if (Constructor->isTrivial() && 17234 !Constructor->hasAttr<DLLExportAttr>()) 17235 return; 17236 DefineImplicitDefaultConstructor(Loc, Constructor); 17237 } else if (Constructor->isCopyConstructor()) { 17238 DefineImplicitCopyConstructor(Loc, Constructor); 17239 } else if (Constructor->isMoveConstructor()) { 17240 DefineImplicitMoveConstructor(Loc, Constructor); 17241 } 17242 } else if (Constructor->getInheritedConstructor()) { 17243 DefineInheritingConstructor(Loc, Constructor); 17244 } 17245 } else if (CXXDestructorDecl *Destructor = 17246 dyn_cast<CXXDestructorDecl>(Func)) { 17247 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17248 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17249 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17250 return; 17251 DefineImplicitDestructor(Loc, Destructor); 17252 } 17253 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17254 MarkVTableUsed(Loc, Destructor->getParent()); 17255 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17256 if (MethodDecl->isOverloadedOperator() && 17257 MethodDecl->getOverloadedOperator() == OO_Equal) { 17258 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17259 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17260 if (MethodDecl->isCopyAssignmentOperator()) 17261 DefineImplicitCopyAssignment(Loc, MethodDecl); 17262 else if (MethodDecl->isMoveAssignmentOperator()) 17263 DefineImplicitMoveAssignment(Loc, MethodDecl); 17264 } 17265 } else if (isa<CXXConversionDecl>(MethodDecl) && 17266 MethodDecl->getParent()->isLambda()) { 17267 CXXConversionDecl *Conversion = 17268 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17269 if (Conversion->isLambdaToBlockPointerConversion()) 17270 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17271 else 17272 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17273 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17274 MarkVTableUsed(Loc, MethodDecl->getParent()); 17275 } 17276 17277 if (Func->isDefaulted() && !Func->isDeleted()) { 17278 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17279 if (DCK != DefaultedComparisonKind::None) 17280 DefineDefaultedComparison(Loc, Func, DCK); 17281 } 17282 17283 // Implicit instantiation of function templates and member functions of 17284 // class templates. 17285 if (Func->isImplicitlyInstantiable()) { 17286 TemplateSpecializationKind TSK = 17287 Func->getTemplateSpecializationKindForInstantiation(); 17288 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17289 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17290 if (FirstInstantiation) { 17291 PointOfInstantiation = Loc; 17292 if (auto *MSI = Func->getMemberSpecializationInfo()) 17293 MSI->setPointOfInstantiation(Loc); 17294 // FIXME: Notify listener. 17295 else 17296 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17297 } else if (TSK != TSK_ImplicitInstantiation) { 17298 // Use the point of use as the point of instantiation, instead of the 17299 // point of explicit instantiation (which we track as the actual point 17300 // of instantiation). This gives better backtraces in diagnostics. 17301 PointOfInstantiation = Loc; 17302 } 17303 17304 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17305 Func->isConstexpr()) { 17306 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17307 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17308 CodeSynthesisContexts.size()) 17309 PendingLocalImplicitInstantiations.push_back( 17310 std::make_pair(Func, PointOfInstantiation)); 17311 else if (Func->isConstexpr()) 17312 // Do not defer instantiations of constexpr functions, to avoid the 17313 // expression evaluator needing to call back into Sema if it sees a 17314 // call to such a function. 17315 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17316 else { 17317 Func->setInstantiationIsPending(true); 17318 PendingInstantiations.push_back( 17319 std::make_pair(Func, PointOfInstantiation)); 17320 // Notify the consumer that a function was implicitly instantiated. 17321 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17322 } 17323 } 17324 } else { 17325 // Walk redefinitions, as some of them may be instantiable. 17326 for (auto i : Func->redecls()) { 17327 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17328 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17329 } 17330 } 17331 }); 17332 } 17333 17334 // C++14 [except.spec]p17: 17335 // An exception-specification is considered to be needed when: 17336 // - the function is odr-used or, if it appears in an unevaluated operand, 17337 // would be odr-used if the expression were potentially-evaluated; 17338 // 17339 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17340 // function is a pure virtual function we're calling, and in that case the 17341 // function was selected by overload resolution and we need to resolve its 17342 // exception specification for a different reason. 17343 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17344 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17345 ResolveExceptionSpec(Loc, FPT); 17346 17347 // If this is the first "real" use, act on that. 17348 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17349 // Keep track of used but undefined functions. 17350 if (!Func->isDefined()) { 17351 if (mightHaveNonExternalLinkage(Func)) 17352 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17353 else if (Func->getMostRecentDecl()->isInlined() && 17354 !LangOpts.GNUInline && 17355 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17356 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17357 else if (isExternalWithNoLinkageType(Func)) 17358 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17359 } 17360 17361 // Some x86 Windows calling conventions mangle the size of the parameter 17362 // pack into the name. Computing the size of the parameters requires the 17363 // parameter types to be complete. Check that now. 17364 if (funcHasParameterSizeMangling(*this, Func)) 17365 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17366 17367 // In the MS C++ ABI, the compiler emits destructor variants where they are 17368 // used. If the destructor is used here but defined elsewhere, mark the 17369 // virtual base destructors referenced. If those virtual base destructors 17370 // are inline, this will ensure they are defined when emitting the complete 17371 // destructor variant. This checking may be redundant if the destructor is 17372 // provided later in this TU. 17373 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17374 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17375 CXXRecordDecl *Parent = Dtor->getParent(); 17376 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17377 CheckCompleteDestructorVariant(Loc, Dtor); 17378 } 17379 } 17380 17381 Func->markUsed(Context); 17382 } 17383 } 17384 17385 /// Directly mark a variable odr-used. Given a choice, prefer to use 17386 /// MarkVariableReferenced since it does additional checks and then 17387 /// calls MarkVarDeclODRUsed. 17388 /// If the variable must be captured: 17389 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17390 /// - else capture it in the DeclContext that maps to the 17391 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17392 static void 17393 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17394 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17395 // Keep track of used but undefined variables. 17396 // FIXME: We shouldn't suppress this warning for static data members. 17397 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17398 (!Var->isExternallyVisible() || Var->isInline() || 17399 SemaRef.isExternalWithNoLinkageType(Var)) && 17400 !(Var->isStaticDataMember() && Var->hasInit())) { 17401 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17402 if (old.isInvalid()) 17403 old = Loc; 17404 } 17405 QualType CaptureType, DeclRefType; 17406 if (SemaRef.LangOpts.OpenMP) 17407 SemaRef.tryCaptureOpenMPLambdas(Var); 17408 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17409 /*EllipsisLoc*/ SourceLocation(), 17410 /*BuildAndDiagnose*/ true, 17411 CaptureType, DeclRefType, 17412 FunctionScopeIndexToStopAt); 17413 17414 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17415 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17416 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17417 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17418 if (VarTarget == Sema::CVT_Host && 17419 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17420 UserTarget == Sema::CFT_Global)) { 17421 // Diagnose ODR-use of host global variables in device functions. 17422 // Reference of device global variables in host functions is allowed 17423 // through shadow variables therefore it is not diagnosed. 17424 if (SemaRef.LangOpts.CUDAIsDevice) { 17425 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17426 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17427 SemaRef.targetDiag(Var->getLocation(), 17428 Var->getType().isConstQualified() 17429 ? diag::note_cuda_const_var_unpromoted 17430 : diag::note_cuda_host_var); 17431 } 17432 } else if (VarTarget == Sema::CVT_Device && 17433 (UserTarget == Sema::CFT_Host || 17434 UserTarget == Sema::CFT_HostDevice) && 17435 !Var->hasExternalStorage()) { 17436 // Record a CUDA/HIP device side variable if it is ODR-used 17437 // by host code. This is done conservatively, when the variable is 17438 // referenced in any of the following contexts: 17439 // - a non-function context 17440 // - a host function 17441 // - a host device function 17442 // This makes the ODR-use of the device side variable by host code to 17443 // be visible in the device compilation for the compiler to be able to 17444 // emit template variables instantiated by host code only and to 17445 // externalize the static device side variable ODR-used by host code. 17446 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17447 } 17448 } 17449 17450 Var->markUsed(SemaRef.Context); 17451 } 17452 17453 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17454 SourceLocation Loc, 17455 unsigned CapturingScopeIndex) { 17456 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17457 } 17458 17459 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17460 ValueDecl *var) { 17461 DeclContext *VarDC = var->getDeclContext(); 17462 17463 // If the parameter still belongs to the translation unit, then 17464 // we're actually just using one parameter in the declaration of 17465 // the next. 17466 if (isa<ParmVarDecl>(var) && 17467 isa<TranslationUnitDecl>(VarDC)) 17468 return; 17469 17470 // For C code, don't diagnose about capture if we're not actually in code 17471 // right now; it's impossible to write a non-constant expression outside of 17472 // function context, so we'll get other (more useful) diagnostics later. 17473 // 17474 // For C++, things get a bit more nasty... it would be nice to suppress this 17475 // diagnostic for certain cases like using a local variable in an array bound 17476 // for a member of a local class, but the correct predicate is not obvious. 17477 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17478 return; 17479 17480 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17481 unsigned ContextKind = 3; // unknown 17482 if (isa<CXXMethodDecl>(VarDC) && 17483 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17484 ContextKind = 2; 17485 } else if (isa<FunctionDecl>(VarDC)) { 17486 ContextKind = 0; 17487 } else if (isa<BlockDecl>(VarDC)) { 17488 ContextKind = 1; 17489 } 17490 17491 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17492 << var << ValueKind << ContextKind << VarDC; 17493 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17494 << var; 17495 17496 // FIXME: Add additional diagnostic info about class etc. which prevents 17497 // capture. 17498 } 17499 17500 17501 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17502 bool &SubCapturesAreNested, 17503 QualType &CaptureType, 17504 QualType &DeclRefType) { 17505 // Check whether we've already captured it. 17506 if (CSI->CaptureMap.count(Var)) { 17507 // If we found a capture, any subcaptures are nested. 17508 SubCapturesAreNested = true; 17509 17510 // Retrieve the capture type for this variable. 17511 CaptureType = CSI->getCapture(Var).getCaptureType(); 17512 17513 // Compute the type of an expression that refers to this variable. 17514 DeclRefType = CaptureType.getNonReferenceType(); 17515 17516 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17517 // are mutable in the sense that user can change their value - they are 17518 // private instances of the captured declarations. 17519 const Capture &Cap = CSI->getCapture(Var); 17520 if (Cap.isCopyCapture() && 17521 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17522 !(isa<CapturedRegionScopeInfo>(CSI) && 17523 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17524 DeclRefType.addConst(); 17525 return true; 17526 } 17527 return false; 17528 } 17529 17530 // Only block literals, captured statements, and lambda expressions can 17531 // capture; other scopes don't work. 17532 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17533 SourceLocation Loc, 17534 const bool Diagnose, Sema &S) { 17535 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17536 return getLambdaAwareParentOfDeclContext(DC); 17537 else if (Var->hasLocalStorage()) { 17538 if (Diagnose) 17539 diagnoseUncapturableValueReference(S, Loc, Var); 17540 } 17541 return nullptr; 17542 } 17543 17544 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17545 // certain types of variables (unnamed, variably modified types etc.) 17546 // so check for eligibility. 17547 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17548 SourceLocation Loc, 17549 const bool Diagnose, Sema &S) { 17550 17551 bool IsBlock = isa<BlockScopeInfo>(CSI); 17552 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17553 17554 // Lambdas are not allowed to capture unnamed variables 17555 // (e.g. anonymous unions). 17556 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17557 // assuming that's the intent. 17558 if (IsLambda && !Var->getDeclName()) { 17559 if (Diagnose) { 17560 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17561 S.Diag(Var->getLocation(), diag::note_declared_at); 17562 } 17563 return false; 17564 } 17565 17566 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17567 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17568 if (Diagnose) { 17569 S.Diag(Loc, diag::err_ref_vm_type); 17570 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17571 } 17572 return false; 17573 } 17574 // Prohibit structs with flexible array members too. 17575 // We cannot capture what is in the tail end of the struct. 17576 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17577 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17578 if (Diagnose) { 17579 if (IsBlock) 17580 S.Diag(Loc, diag::err_ref_flexarray_type); 17581 else 17582 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17583 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17584 } 17585 return false; 17586 } 17587 } 17588 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17589 // Lambdas and captured statements are not allowed to capture __block 17590 // variables; they don't support the expected semantics. 17591 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17592 if (Diagnose) { 17593 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17594 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17595 } 17596 return false; 17597 } 17598 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17599 if (S.getLangOpts().OpenCL && IsBlock && 17600 Var->getType()->isBlockPointerType()) { 17601 if (Diagnose) 17602 S.Diag(Loc, diag::err_opencl_block_ref_block); 17603 return false; 17604 } 17605 17606 return true; 17607 } 17608 17609 // Returns true if the capture by block was successful. 17610 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17611 SourceLocation Loc, 17612 const bool BuildAndDiagnose, 17613 QualType &CaptureType, 17614 QualType &DeclRefType, 17615 const bool Nested, 17616 Sema &S, bool Invalid) { 17617 bool ByRef = false; 17618 17619 // Blocks are not allowed to capture arrays, excepting OpenCL. 17620 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17621 // (decayed to pointers). 17622 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17623 if (BuildAndDiagnose) { 17624 S.Diag(Loc, diag::err_ref_array_type); 17625 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17626 Invalid = true; 17627 } else { 17628 return false; 17629 } 17630 } 17631 17632 // Forbid the block-capture of autoreleasing variables. 17633 if (!Invalid && 17634 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17635 if (BuildAndDiagnose) { 17636 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17637 << /*block*/ 0; 17638 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17639 Invalid = true; 17640 } else { 17641 return false; 17642 } 17643 } 17644 17645 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17646 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17647 QualType PointeeTy = PT->getPointeeType(); 17648 17649 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17650 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17651 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17652 if (BuildAndDiagnose) { 17653 SourceLocation VarLoc = Var->getLocation(); 17654 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17655 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17656 } 17657 } 17658 } 17659 17660 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17661 if (HasBlocksAttr || CaptureType->isReferenceType() || 17662 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17663 // Block capture by reference does not change the capture or 17664 // declaration reference types. 17665 ByRef = true; 17666 } else { 17667 // Block capture by copy introduces 'const'. 17668 CaptureType = CaptureType.getNonReferenceType().withConst(); 17669 DeclRefType = CaptureType; 17670 } 17671 17672 // Actually capture the variable. 17673 if (BuildAndDiagnose) 17674 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17675 CaptureType, Invalid); 17676 17677 return !Invalid; 17678 } 17679 17680 17681 /// Capture the given variable in the captured region. 17682 static bool captureInCapturedRegion( 17683 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17684 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17685 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17686 bool IsTopScope, Sema &S, bool Invalid) { 17687 // By default, capture variables by reference. 17688 bool ByRef = true; 17689 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17690 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17691 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17692 // Using an LValue reference type is consistent with Lambdas (see below). 17693 if (S.isOpenMPCapturedDecl(Var)) { 17694 bool HasConst = DeclRefType.isConstQualified(); 17695 DeclRefType = DeclRefType.getUnqualifiedType(); 17696 // Don't lose diagnostics about assignments to const. 17697 if (HasConst) 17698 DeclRefType.addConst(); 17699 } 17700 // Do not capture firstprivates in tasks. 17701 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17702 OMPC_unknown) 17703 return true; 17704 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17705 RSI->OpenMPCaptureLevel); 17706 } 17707 17708 if (ByRef) 17709 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17710 else 17711 CaptureType = DeclRefType; 17712 17713 // Actually capture the variable. 17714 if (BuildAndDiagnose) 17715 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17716 Loc, SourceLocation(), CaptureType, Invalid); 17717 17718 return !Invalid; 17719 } 17720 17721 /// Capture the given variable in the lambda. 17722 static bool captureInLambda(LambdaScopeInfo *LSI, 17723 VarDecl *Var, 17724 SourceLocation Loc, 17725 const bool BuildAndDiagnose, 17726 QualType &CaptureType, 17727 QualType &DeclRefType, 17728 const bool RefersToCapturedVariable, 17729 const Sema::TryCaptureKind Kind, 17730 SourceLocation EllipsisLoc, 17731 const bool IsTopScope, 17732 Sema &S, bool Invalid) { 17733 // Determine whether we are capturing by reference or by value. 17734 bool ByRef = false; 17735 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17736 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17737 } else { 17738 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17739 } 17740 17741 // Compute the type of the field that will capture this variable. 17742 if (ByRef) { 17743 // C++11 [expr.prim.lambda]p15: 17744 // An entity is captured by reference if it is implicitly or 17745 // explicitly captured but not captured by copy. It is 17746 // unspecified whether additional unnamed non-static data 17747 // members are declared in the closure type for entities 17748 // captured by reference. 17749 // 17750 // FIXME: It is not clear whether we want to build an lvalue reference 17751 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17752 // to do the former, while EDG does the latter. Core issue 1249 will 17753 // clarify, but for now we follow GCC because it's a more permissive and 17754 // easily defensible position. 17755 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17756 } else { 17757 // C++11 [expr.prim.lambda]p14: 17758 // For each entity captured by copy, an unnamed non-static 17759 // data member is declared in the closure type. The 17760 // declaration order of these members is unspecified. The type 17761 // of such a data member is the type of the corresponding 17762 // captured entity if the entity is not a reference to an 17763 // object, or the referenced type otherwise. [Note: If the 17764 // captured entity is a reference to a function, the 17765 // corresponding data member is also a reference to a 17766 // function. - end note ] 17767 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17768 if (!RefType->getPointeeType()->isFunctionType()) 17769 CaptureType = RefType->getPointeeType(); 17770 } 17771 17772 // Forbid the lambda copy-capture of autoreleasing variables. 17773 if (!Invalid && 17774 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17775 if (BuildAndDiagnose) { 17776 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17777 S.Diag(Var->getLocation(), diag::note_previous_decl) 17778 << Var->getDeclName(); 17779 Invalid = true; 17780 } else { 17781 return false; 17782 } 17783 } 17784 17785 // Make sure that by-copy captures are of a complete and non-abstract type. 17786 if (!Invalid && BuildAndDiagnose) { 17787 if (!CaptureType->isDependentType() && 17788 S.RequireCompleteSizedType( 17789 Loc, CaptureType, 17790 diag::err_capture_of_incomplete_or_sizeless_type, 17791 Var->getDeclName())) 17792 Invalid = true; 17793 else if (S.RequireNonAbstractType(Loc, CaptureType, 17794 diag::err_capture_of_abstract_type)) 17795 Invalid = true; 17796 } 17797 } 17798 17799 // Compute the type of a reference to this captured variable. 17800 if (ByRef) 17801 DeclRefType = CaptureType.getNonReferenceType(); 17802 else { 17803 // C++ [expr.prim.lambda]p5: 17804 // The closure type for a lambda-expression has a public inline 17805 // function call operator [...]. This function call operator is 17806 // declared const (9.3.1) if and only if the lambda-expression's 17807 // parameter-declaration-clause is not followed by mutable. 17808 DeclRefType = CaptureType.getNonReferenceType(); 17809 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17810 DeclRefType.addConst(); 17811 } 17812 17813 // Add the capture. 17814 if (BuildAndDiagnose) 17815 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17816 Loc, EllipsisLoc, CaptureType, Invalid); 17817 17818 return !Invalid; 17819 } 17820 17821 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17822 // Offer a Copy fix even if the type is dependent. 17823 if (Var->getType()->isDependentType()) 17824 return true; 17825 QualType T = Var->getType().getNonReferenceType(); 17826 if (T.isTriviallyCopyableType(Context)) 17827 return true; 17828 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17829 17830 if (!(RD = RD->getDefinition())) 17831 return false; 17832 if (RD->hasSimpleCopyConstructor()) 17833 return true; 17834 if (RD->hasUserDeclaredCopyConstructor()) 17835 for (CXXConstructorDecl *Ctor : RD->ctors()) 17836 if (Ctor->isCopyConstructor()) 17837 return !Ctor->isDeleted(); 17838 } 17839 return false; 17840 } 17841 17842 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17843 /// default capture. Fixes may be omitted if they aren't allowed by the 17844 /// standard, for example we can't emit a default copy capture fix-it if we 17845 /// already explicitly copy capture capture another variable. 17846 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17847 VarDecl *Var) { 17848 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17849 // Don't offer Capture by copy of default capture by copy fixes if Var is 17850 // known not to be copy constructible. 17851 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17852 17853 SmallString<32> FixBuffer; 17854 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17855 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17856 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17857 if (ShouldOfferCopyFix) { 17858 // Offer fixes to insert an explicit capture for the variable. 17859 // [] -> [VarName] 17860 // [OtherCapture] -> [OtherCapture, VarName] 17861 FixBuffer.assign({Separator, Var->getName()}); 17862 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17863 << Var << /*value*/ 0 17864 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17865 } 17866 // As above but capture by reference. 17867 FixBuffer.assign({Separator, "&", Var->getName()}); 17868 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17869 << Var << /*reference*/ 1 17870 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17871 } 17872 17873 // Only try to offer default capture if there are no captures excluding this 17874 // and init captures. 17875 // [this]: OK. 17876 // [X = Y]: OK. 17877 // [&A, &B]: Don't offer. 17878 // [A, B]: Don't offer. 17879 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17880 return !C.isThisCapture() && !C.isInitCapture(); 17881 })) 17882 return; 17883 17884 // The default capture specifiers, '=' or '&', must appear first in the 17885 // capture body. 17886 SourceLocation DefaultInsertLoc = 17887 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17888 17889 if (ShouldOfferCopyFix) { 17890 bool CanDefaultCopyCapture = true; 17891 // [=, *this] OK since c++17 17892 // [=, this] OK since c++20 17893 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17894 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17895 ? LSI->getCXXThisCapture().isCopyCapture() 17896 : false; 17897 // We can't use default capture by copy if any captures already specified 17898 // capture by copy. 17899 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17900 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17901 })) { 17902 FixBuffer.assign({"=", Separator}); 17903 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17904 << /*value*/ 0 17905 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17906 } 17907 } 17908 17909 // We can't use default capture by reference if any captures already specified 17910 // capture by reference. 17911 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17912 return !C.isInitCapture() && C.isReferenceCapture() && 17913 !C.isThisCapture(); 17914 })) { 17915 FixBuffer.assign({"&", Separator}); 17916 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17917 << /*reference*/ 1 17918 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17919 } 17920 } 17921 17922 bool Sema::tryCaptureVariable( 17923 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17924 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17925 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17926 // An init-capture is notionally from the context surrounding its 17927 // declaration, but its parent DC is the lambda class. 17928 DeclContext *VarDC = Var->getDeclContext(); 17929 if (Var->isInitCapture()) 17930 VarDC = VarDC->getParent(); 17931 17932 DeclContext *DC = CurContext; 17933 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17934 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17935 // We need to sync up the Declaration Context with the 17936 // FunctionScopeIndexToStopAt 17937 if (FunctionScopeIndexToStopAt) { 17938 unsigned FSIndex = FunctionScopes.size() - 1; 17939 while (FSIndex != MaxFunctionScopesIndex) { 17940 DC = getLambdaAwareParentOfDeclContext(DC); 17941 --FSIndex; 17942 } 17943 } 17944 17945 17946 // If the variable is declared in the current context, there is no need to 17947 // capture it. 17948 if (VarDC == DC) return true; 17949 17950 // Capture global variables if it is required to use private copy of this 17951 // variable. 17952 bool IsGlobal = !Var->hasLocalStorage(); 17953 if (IsGlobal && 17954 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17955 MaxFunctionScopesIndex))) 17956 return true; 17957 Var = Var->getCanonicalDecl(); 17958 17959 // Walk up the stack to determine whether we can capture the variable, 17960 // performing the "simple" checks that don't depend on type. We stop when 17961 // we've either hit the declared scope of the variable or find an existing 17962 // capture of that variable. We start from the innermost capturing-entity 17963 // (the DC) and ensure that all intervening capturing-entities 17964 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17965 // declcontext can either capture the variable or have already captured 17966 // the variable. 17967 CaptureType = Var->getType(); 17968 DeclRefType = CaptureType.getNonReferenceType(); 17969 bool Nested = false; 17970 bool Explicit = (Kind != TryCapture_Implicit); 17971 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17972 do { 17973 // Only block literals, captured statements, and lambda expressions can 17974 // capture; other scopes don't work. 17975 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17976 ExprLoc, 17977 BuildAndDiagnose, 17978 *this); 17979 // We need to check for the parent *first* because, if we *have* 17980 // private-captured a global variable, we need to recursively capture it in 17981 // intermediate blocks, lambdas, etc. 17982 if (!ParentDC) { 17983 if (IsGlobal) { 17984 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17985 break; 17986 } 17987 return true; 17988 } 17989 17990 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17991 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17992 17993 17994 // Check whether we've already captured it. 17995 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17996 DeclRefType)) { 17997 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17998 break; 17999 } 18000 // If we are instantiating a generic lambda call operator body, 18001 // we do not want to capture new variables. What was captured 18002 // during either a lambdas transformation or initial parsing 18003 // should be used. 18004 if (isGenericLambdaCallOperatorSpecialization(DC)) { 18005 if (BuildAndDiagnose) { 18006 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18007 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 18008 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18009 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18010 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18011 buildLambdaCaptureFixit(*this, LSI, Var); 18012 } else 18013 diagnoseUncapturableValueReference(*this, ExprLoc, Var); 18014 } 18015 return true; 18016 } 18017 18018 // Try to capture variable-length arrays types. 18019 if (Var->getType()->isVariablyModifiedType()) { 18020 // We're going to walk down into the type and look for VLA 18021 // expressions. 18022 QualType QTy = Var->getType(); 18023 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18024 QTy = PVD->getOriginalType(); 18025 captureVariablyModifiedType(Context, QTy, CSI); 18026 } 18027 18028 if (getLangOpts().OpenMP) { 18029 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18030 // OpenMP private variables should not be captured in outer scope, so 18031 // just break here. Similarly, global variables that are captured in a 18032 // target region should not be captured outside the scope of the region. 18033 if (RSI->CapRegionKind == CR_OpenMP) { 18034 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 18035 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 18036 // If the variable is private (i.e. not captured) and has variably 18037 // modified type, we still need to capture the type for correct 18038 // codegen in all regions, associated with the construct. Currently, 18039 // it is captured in the innermost captured region only. 18040 if (IsOpenMPPrivateDecl != OMPC_unknown && 18041 Var->getType()->isVariablyModifiedType()) { 18042 QualType QTy = Var->getType(); 18043 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18044 QTy = PVD->getOriginalType(); 18045 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 18046 I < E; ++I) { 18047 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 18048 FunctionScopes[FunctionScopesIndex - I]); 18049 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 18050 "Wrong number of captured regions associated with the " 18051 "OpenMP construct."); 18052 captureVariablyModifiedType(Context, QTy, OuterRSI); 18053 } 18054 } 18055 bool IsTargetCap = 18056 IsOpenMPPrivateDecl != OMPC_private && 18057 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 18058 RSI->OpenMPCaptureLevel); 18059 // Do not capture global if it is not privatized in outer regions. 18060 bool IsGlobalCap = 18061 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 18062 RSI->OpenMPCaptureLevel); 18063 18064 // When we detect target captures we are looking from inside the 18065 // target region, therefore we need to propagate the capture from the 18066 // enclosing region. Therefore, the capture is not initially nested. 18067 if (IsTargetCap) 18068 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18069 18070 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18071 (IsGlobal && !IsGlobalCap)) { 18072 Nested = !IsTargetCap; 18073 bool HasConst = DeclRefType.isConstQualified(); 18074 DeclRefType = DeclRefType.getUnqualifiedType(); 18075 // Don't lose diagnostics about assignments to const. 18076 if (HasConst) 18077 DeclRefType.addConst(); 18078 CaptureType = Context.getLValueReferenceType(DeclRefType); 18079 break; 18080 } 18081 } 18082 } 18083 } 18084 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18085 // No capture-default, and this is not an explicit capture 18086 // so cannot capture this variable. 18087 if (BuildAndDiagnose) { 18088 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18089 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18090 auto *LSI = cast<LambdaScopeInfo>(CSI); 18091 if (LSI->Lambda) { 18092 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18093 buildLambdaCaptureFixit(*this, LSI, Var); 18094 } 18095 // FIXME: If we error out because an outer lambda can not implicitly 18096 // capture a variable that an inner lambda explicitly captures, we 18097 // should have the inner lambda do the explicit capture - because 18098 // it makes for cleaner diagnostics later. This would purely be done 18099 // so that the diagnostic does not misleadingly claim that a variable 18100 // can not be captured by a lambda implicitly even though it is captured 18101 // explicitly. Suggestion: 18102 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18103 // at the function head 18104 // - cache the StartingDeclContext - this must be a lambda 18105 // - captureInLambda in the innermost lambda the variable. 18106 } 18107 return true; 18108 } 18109 18110 FunctionScopesIndex--; 18111 DC = ParentDC; 18112 Explicit = false; 18113 } while (!VarDC->Equals(DC)); 18114 18115 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18116 // computing the type of the capture at each step, checking type-specific 18117 // requirements, and adding captures if requested. 18118 // If the variable had already been captured previously, we start capturing 18119 // at the lambda nested within that one. 18120 bool Invalid = false; 18121 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18122 ++I) { 18123 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18124 18125 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18126 // certain types of variables (unnamed, variably modified types etc.) 18127 // so check for eligibility. 18128 if (!Invalid) 18129 Invalid = 18130 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18131 18132 // After encountering an error, if we're actually supposed to capture, keep 18133 // capturing in nested contexts to suppress any follow-on diagnostics. 18134 if (Invalid && !BuildAndDiagnose) 18135 return true; 18136 18137 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18138 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18139 DeclRefType, Nested, *this, Invalid); 18140 Nested = true; 18141 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18142 Invalid = !captureInCapturedRegion( 18143 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18144 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18145 Nested = true; 18146 } else { 18147 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18148 Invalid = 18149 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18150 DeclRefType, Nested, Kind, EllipsisLoc, 18151 /*IsTopScope*/ I == N - 1, *this, Invalid); 18152 Nested = true; 18153 } 18154 18155 if (Invalid && !BuildAndDiagnose) 18156 return true; 18157 } 18158 return Invalid; 18159 } 18160 18161 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18162 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18163 QualType CaptureType; 18164 QualType DeclRefType; 18165 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18166 /*BuildAndDiagnose=*/true, CaptureType, 18167 DeclRefType, nullptr); 18168 } 18169 18170 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18171 QualType CaptureType; 18172 QualType DeclRefType; 18173 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18174 /*BuildAndDiagnose=*/false, CaptureType, 18175 DeclRefType, nullptr); 18176 } 18177 18178 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18179 QualType CaptureType; 18180 QualType DeclRefType; 18181 18182 // Determine whether we can capture this variable. 18183 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18184 /*BuildAndDiagnose=*/false, CaptureType, 18185 DeclRefType, nullptr)) 18186 return QualType(); 18187 18188 return DeclRefType; 18189 } 18190 18191 namespace { 18192 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18193 // The produced TemplateArgumentListInfo* points to data stored within this 18194 // object, so should only be used in contexts where the pointer will not be 18195 // used after the CopiedTemplateArgs object is destroyed. 18196 class CopiedTemplateArgs { 18197 bool HasArgs; 18198 TemplateArgumentListInfo TemplateArgStorage; 18199 public: 18200 template<typename RefExpr> 18201 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18202 if (HasArgs) 18203 E->copyTemplateArgumentsInto(TemplateArgStorage); 18204 } 18205 operator TemplateArgumentListInfo*() 18206 #ifdef __has_cpp_attribute 18207 #if __has_cpp_attribute(clang::lifetimebound) 18208 [[clang::lifetimebound]] 18209 #endif 18210 #endif 18211 { 18212 return HasArgs ? &TemplateArgStorage : nullptr; 18213 } 18214 }; 18215 } 18216 18217 /// Walk the set of potential results of an expression and mark them all as 18218 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18219 /// 18220 /// \return A new expression if we found any potential results, ExprEmpty() if 18221 /// not, and ExprError() if we diagnosed an error. 18222 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18223 NonOdrUseReason NOUR) { 18224 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18225 // an object that satisfies the requirements for appearing in a 18226 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18227 // is immediately applied." This function handles the lvalue-to-rvalue 18228 // conversion part. 18229 // 18230 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18231 // transform it into the relevant kind of non-odr-use node and rebuild the 18232 // tree of nodes leading to it. 18233 // 18234 // This is a mini-TreeTransform that only transforms a restricted subset of 18235 // nodes (and only certain operands of them). 18236 18237 // Rebuild a subexpression. 18238 auto Rebuild = [&](Expr *Sub) { 18239 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18240 }; 18241 18242 // Check whether a potential result satisfies the requirements of NOUR. 18243 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18244 // Any entity other than a VarDecl is always odr-used whenever it's named 18245 // in a potentially-evaluated expression. 18246 auto *VD = dyn_cast<VarDecl>(D); 18247 if (!VD) 18248 return true; 18249 18250 // C++2a [basic.def.odr]p4: 18251 // A variable x whose name appears as a potentially-evalauted expression 18252 // e is odr-used by e unless 18253 // -- x is a reference that is usable in constant expressions, or 18254 // -- x is a variable of non-reference type that is usable in constant 18255 // expressions and has no mutable subobjects, and e is an element of 18256 // the set of potential results of an expression of 18257 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18258 // conversion is applied, or 18259 // -- x is a variable of non-reference type, and e is an element of the 18260 // set of potential results of a discarded-value expression to which 18261 // the lvalue-to-rvalue conversion is not applied 18262 // 18263 // We check the first bullet and the "potentially-evaluated" condition in 18264 // BuildDeclRefExpr. We check the type requirements in the second bullet 18265 // in CheckLValueToRValueConversionOperand below. 18266 switch (NOUR) { 18267 case NOUR_None: 18268 case NOUR_Unevaluated: 18269 llvm_unreachable("unexpected non-odr-use-reason"); 18270 18271 case NOUR_Constant: 18272 // Constant references were handled when they were built. 18273 if (VD->getType()->isReferenceType()) 18274 return true; 18275 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18276 if (RD->hasMutableFields()) 18277 return true; 18278 if (!VD->isUsableInConstantExpressions(S.Context)) 18279 return true; 18280 break; 18281 18282 case NOUR_Discarded: 18283 if (VD->getType()->isReferenceType()) 18284 return true; 18285 break; 18286 } 18287 return false; 18288 }; 18289 18290 // Mark that this expression does not constitute an odr-use. 18291 auto MarkNotOdrUsed = [&] { 18292 S.MaybeODRUseExprs.remove(E); 18293 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18294 LSI->markVariableExprAsNonODRUsed(E); 18295 }; 18296 18297 // C++2a [basic.def.odr]p2: 18298 // The set of potential results of an expression e is defined as follows: 18299 switch (E->getStmtClass()) { 18300 // -- If e is an id-expression, ... 18301 case Expr::DeclRefExprClass: { 18302 auto *DRE = cast<DeclRefExpr>(E); 18303 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18304 break; 18305 18306 // Rebuild as a non-odr-use DeclRefExpr. 18307 MarkNotOdrUsed(); 18308 return DeclRefExpr::Create( 18309 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18310 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18311 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18312 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18313 } 18314 18315 case Expr::FunctionParmPackExprClass: { 18316 auto *FPPE = cast<FunctionParmPackExpr>(E); 18317 // If any of the declarations in the pack is odr-used, then the expression 18318 // as a whole constitutes an odr-use. 18319 for (VarDecl *D : *FPPE) 18320 if (IsPotentialResultOdrUsed(D)) 18321 return ExprEmpty(); 18322 18323 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18324 // nothing cares about whether we marked this as an odr-use, but it might 18325 // be useful for non-compiler tools. 18326 MarkNotOdrUsed(); 18327 break; 18328 } 18329 18330 // -- If e is a subscripting operation with an array operand... 18331 case Expr::ArraySubscriptExprClass: { 18332 auto *ASE = cast<ArraySubscriptExpr>(E); 18333 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18334 if (!OldBase->getType()->isArrayType()) 18335 break; 18336 ExprResult Base = Rebuild(OldBase); 18337 if (!Base.isUsable()) 18338 return Base; 18339 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18340 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18341 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18342 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18343 ASE->getRBracketLoc()); 18344 } 18345 18346 case Expr::MemberExprClass: { 18347 auto *ME = cast<MemberExpr>(E); 18348 // -- If e is a class member access expression [...] naming a non-static 18349 // data member... 18350 if (isa<FieldDecl>(ME->getMemberDecl())) { 18351 ExprResult Base = Rebuild(ME->getBase()); 18352 if (!Base.isUsable()) 18353 return Base; 18354 return MemberExpr::Create( 18355 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18356 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18357 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18358 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18359 ME->getObjectKind(), ME->isNonOdrUse()); 18360 } 18361 18362 if (ME->getMemberDecl()->isCXXInstanceMember()) 18363 break; 18364 18365 // -- If e is a class member access expression naming a static data member, 18366 // ... 18367 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18368 break; 18369 18370 // Rebuild as a non-odr-use MemberExpr. 18371 MarkNotOdrUsed(); 18372 return MemberExpr::Create( 18373 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18374 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18375 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18376 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18377 } 18378 18379 case Expr::BinaryOperatorClass: { 18380 auto *BO = cast<BinaryOperator>(E); 18381 Expr *LHS = BO->getLHS(); 18382 Expr *RHS = BO->getRHS(); 18383 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18384 if (BO->getOpcode() == BO_PtrMemD) { 18385 ExprResult Sub = Rebuild(LHS); 18386 if (!Sub.isUsable()) 18387 return Sub; 18388 LHS = Sub.get(); 18389 // -- If e is a comma expression, ... 18390 } else if (BO->getOpcode() == BO_Comma) { 18391 ExprResult Sub = Rebuild(RHS); 18392 if (!Sub.isUsable()) 18393 return Sub; 18394 RHS = Sub.get(); 18395 } else { 18396 break; 18397 } 18398 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18399 LHS, RHS); 18400 } 18401 18402 // -- If e has the form (e1)... 18403 case Expr::ParenExprClass: { 18404 auto *PE = cast<ParenExpr>(E); 18405 ExprResult Sub = Rebuild(PE->getSubExpr()); 18406 if (!Sub.isUsable()) 18407 return Sub; 18408 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18409 } 18410 18411 // -- If e is a glvalue conditional expression, ... 18412 // We don't apply this to a binary conditional operator. FIXME: Should we? 18413 case Expr::ConditionalOperatorClass: { 18414 auto *CO = cast<ConditionalOperator>(E); 18415 ExprResult LHS = Rebuild(CO->getLHS()); 18416 if (LHS.isInvalid()) 18417 return ExprError(); 18418 ExprResult RHS = Rebuild(CO->getRHS()); 18419 if (RHS.isInvalid()) 18420 return ExprError(); 18421 if (!LHS.isUsable() && !RHS.isUsable()) 18422 return ExprEmpty(); 18423 if (!LHS.isUsable()) 18424 LHS = CO->getLHS(); 18425 if (!RHS.isUsable()) 18426 RHS = CO->getRHS(); 18427 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18428 CO->getCond(), LHS.get(), RHS.get()); 18429 } 18430 18431 // [Clang extension] 18432 // -- If e has the form __extension__ e1... 18433 case Expr::UnaryOperatorClass: { 18434 auto *UO = cast<UnaryOperator>(E); 18435 if (UO->getOpcode() != UO_Extension) 18436 break; 18437 ExprResult Sub = Rebuild(UO->getSubExpr()); 18438 if (!Sub.isUsable()) 18439 return Sub; 18440 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18441 Sub.get()); 18442 } 18443 18444 // [Clang extension] 18445 // -- If e has the form _Generic(...), the set of potential results is the 18446 // union of the sets of potential results of the associated expressions. 18447 case Expr::GenericSelectionExprClass: { 18448 auto *GSE = cast<GenericSelectionExpr>(E); 18449 18450 SmallVector<Expr *, 4> AssocExprs; 18451 bool AnyChanged = false; 18452 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18453 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18454 if (AssocExpr.isInvalid()) 18455 return ExprError(); 18456 if (AssocExpr.isUsable()) { 18457 AssocExprs.push_back(AssocExpr.get()); 18458 AnyChanged = true; 18459 } else { 18460 AssocExprs.push_back(OrigAssocExpr); 18461 } 18462 } 18463 18464 return AnyChanged ? S.CreateGenericSelectionExpr( 18465 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18466 GSE->getRParenLoc(), GSE->getControllingExpr(), 18467 GSE->getAssocTypeSourceInfos(), AssocExprs) 18468 : ExprEmpty(); 18469 } 18470 18471 // [Clang extension] 18472 // -- If e has the form __builtin_choose_expr(...), the set of potential 18473 // results is the union of the sets of potential results of the 18474 // second and third subexpressions. 18475 case Expr::ChooseExprClass: { 18476 auto *CE = cast<ChooseExpr>(E); 18477 18478 ExprResult LHS = Rebuild(CE->getLHS()); 18479 if (LHS.isInvalid()) 18480 return ExprError(); 18481 18482 ExprResult RHS = Rebuild(CE->getLHS()); 18483 if (RHS.isInvalid()) 18484 return ExprError(); 18485 18486 if (!LHS.get() && !RHS.get()) 18487 return ExprEmpty(); 18488 if (!LHS.isUsable()) 18489 LHS = CE->getLHS(); 18490 if (!RHS.isUsable()) 18491 RHS = CE->getRHS(); 18492 18493 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18494 RHS.get(), CE->getRParenLoc()); 18495 } 18496 18497 // Step through non-syntactic nodes. 18498 case Expr::ConstantExprClass: { 18499 auto *CE = cast<ConstantExpr>(E); 18500 ExprResult Sub = Rebuild(CE->getSubExpr()); 18501 if (!Sub.isUsable()) 18502 return Sub; 18503 return ConstantExpr::Create(S.Context, Sub.get()); 18504 } 18505 18506 // We could mostly rely on the recursive rebuilding to rebuild implicit 18507 // casts, but not at the top level, so rebuild them here. 18508 case Expr::ImplicitCastExprClass: { 18509 auto *ICE = cast<ImplicitCastExpr>(E); 18510 // Only step through the narrow set of cast kinds we expect to encounter. 18511 // Anything else suggests we've left the region in which potential results 18512 // can be found. 18513 switch (ICE->getCastKind()) { 18514 case CK_NoOp: 18515 case CK_DerivedToBase: 18516 case CK_UncheckedDerivedToBase: { 18517 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18518 if (!Sub.isUsable()) 18519 return Sub; 18520 CXXCastPath Path(ICE->path()); 18521 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18522 ICE->getValueKind(), &Path); 18523 } 18524 18525 default: 18526 break; 18527 } 18528 break; 18529 } 18530 18531 default: 18532 break; 18533 } 18534 18535 // Can't traverse through this node. Nothing to do. 18536 return ExprEmpty(); 18537 } 18538 18539 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18540 // Check whether the operand is or contains an object of non-trivial C union 18541 // type. 18542 if (E->getType().isVolatileQualified() && 18543 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18544 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18545 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18546 Sema::NTCUC_LValueToRValueVolatile, 18547 NTCUK_Destruct|NTCUK_Copy); 18548 18549 // C++2a [basic.def.odr]p4: 18550 // [...] an expression of non-volatile-qualified non-class type to which 18551 // the lvalue-to-rvalue conversion is applied [...] 18552 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18553 return E; 18554 18555 ExprResult Result = 18556 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18557 if (Result.isInvalid()) 18558 return ExprError(); 18559 return Result.get() ? Result : E; 18560 } 18561 18562 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18563 Res = CorrectDelayedTyposInExpr(Res); 18564 18565 if (!Res.isUsable()) 18566 return Res; 18567 18568 // If a constant-expression is a reference to a variable where we delay 18569 // deciding whether it is an odr-use, just assume we will apply the 18570 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18571 // (a non-type template argument), we have special handling anyway. 18572 return CheckLValueToRValueConversionOperand(Res.get()); 18573 } 18574 18575 void Sema::CleanupVarDeclMarking() { 18576 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18577 // call. 18578 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18579 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18580 18581 for (Expr *E : LocalMaybeODRUseExprs) { 18582 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18583 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18584 DRE->getLocation(), *this); 18585 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18586 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18587 *this); 18588 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18589 for (VarDecl *VD : *FP) 18590 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18591 } else { 18592 llvm_unreachable("Unexpected expression"); 18593 } 18594 } 18595 18596 assert(MaybeODRUseExprs.empty() && 18597 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18598 } 18599 18600 static void DoMarkVarDeclReferenced( 18601 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18602 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18603 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18604 isa<FunctionParmPackExpr>(E)) && 18605 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18606 Var->setReferenced(); 18607 18608 if (Var->isInvalidDecl()) 18609 return; 18610 18611 auto *MSI = Var->getMemberSpecializationInfo(); 18612 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18613 : Var->getTemplateSpecializationKind(); 18614 18615 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18616 bool UsableInConstantExpr = 18617 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18618 18619 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18620 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18621 } 18622 18623 // C++20 [expr.const]p12: 18624 // A variable [...] is needed for constant evaluation if it is [...] a 18625 // variable whose name appears as a potentially constant evaluated 18626 // expression that is either a contexpr variable or is of non-volatile 18627 // const-qualified integral type or of reference type 18628 bool NeededForConstantEvaluation = 18629 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18630 18631 bool NeedDefinition = 18632 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18633 18634 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18635 "Can't instantiate a partial template specialization."); 18636 18637 // If this might be a member specialization of a static data member, check 18638 // the specialization is visible. We already did the checks for variable 18639 // template specializations when we created them. 18640 if (NeedDefinition && TSK != TSK_Undeclared && 18641 !isa<VarTemplateSpecializationDecl>(Var)) 18642 SemaRef.checkSpecializationVisibility(Loc, Var); 18643 18644 // Perform implicit instantiation of static data members, static data member 18645 // templates of class templates, and variable template specializations. Delay 18646 // instantiations of variable templates, except for those that could be used 18647 // in a constant expression. 18648 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18649 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18650 // instantiation declaration if a variable is usable in a constant 18651 // expression (among other cases). 18652 bool TryInstantiating = 18653 TSK == TSK_ImplicitInstantiation || 18654 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18655 18656 if (TryInstantiating) { 18657 SourceLocation PointOfInstantiation = 18658 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18659 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18660 if (FirstInstantiation) { 18661 PointOfInstantiation = Loc; 18662 if (MSI) 18663 MSI->setPointOfInstantiation(PointOfInstantiation); 18664 // FIXME: Notify listener. 18665 else 18666 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18667 } 18668 18669 if (UsableInConstantExpr) { 18670 // Do not defer instantiations of variables that could be used in a 18671 // constant expression. 18672 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18673 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18674 }); 18675 18676 // Re-set the member to trigger a recomputation of the dependence bits 18677 // for the expression. 18678 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18679 DRE->setDecl(DRE->getDecl()); 18680 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18681 ME->setMemberDecl(ME->getMemberDecl()); 18682 } else if (FirstInstantiation || 18683 isa<VarTemplateSpecializationDecl>(Var)) { 18684 // FIXME: For a specialization of a variable template, we don't 18685 // distinguish between "declaration and type implicitly instantiated" 18686 // and "implicit instantiation of definition requested", so we have 18687 // no direct way to avoid enqueueing the pending instantiation 18688 // multiple times. 18689 SemaRef.PendingInstantiations 18690 .push_back(std::make_pair(Var, PointOfInstantiation)); 18691 } 18692 } 18693 } 18694 18695 // C++2a [basic.def.odr]p4: 18696 // A variable x whose name appears as a potentially-evaluated expression e 18697 // is odr-used by e unless 18698 // -- x is a reference that is usable in constant expressions 18699 // -- x is a variable of non-reference type that is usable in constant 18700 // expressions and has no mutable subobjects [FIXME], and e is an 18701 // element of the set of potential results of an expression of 18702 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18703 // conversion is applied 18704 // -- x is a variable of non-reference type, and e is an element of the set 18705 // of potential results of a discarded-value expression to which the 18706 // lvalue-to-rvalue conversion is not applied [FIXME] 18707 // 18708 // We check the first part of the second bullet here, and 18709 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18710 // FIXME: To get the third bullet right, we need to delay this even for 18711 // variables that are not usable in constant expressions. 18712 18713 // If we already know this isn't an odr-use, there's nothing more to do. 18714 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18715 if (DRE->isNonOdrUse()) 18716 return; 18717 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18718 if (ME->isNonOdrUse()) 18719 return; 18720 18721 switch (OdrUse) { 18722 case OdrUseContext::None: 18723 assert((!E || isa<FunctionParmPackExpr>(E)) && 18724 "missing non-odr-use marking for unevaluated decl ref"); 18725 break; 18726 18727 case OdrUseContext::FormallyOdrUsed: 18728 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18729 // behavior. 18730 break; 18731 18732 case OdrUseContext::Used: 18733 // If we might later find that this expression isn't actually an odr-use, 18734 // delay the marking. 18735 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18736 SemaRef.MaybeODRUseExprs.insert(E); 18737 else 18738 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18739 break; 18740 18741 case OdrUseContext::Dependent: 18742 // If this is a dependent context, we don't need to mark variables as 18743 // odr-used, but we may still need to track them for lambda capture. 18744 // FIXME: Do we also need to do this inside dependent typeid expressions 18745 // (which are modeled as unevaluated at this point)? 18746 const bool RefersToEnclosingScope = 18747 (SemaRef.CurContext != Var->getDeclContext() && 18748 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18749 if (RefersToEnclosingScope) { 18750 LambdaScopeInfo *const LSI = 18751 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18752 if (LSI && (!LSI->CallOperator || 18753 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18754 // If a variable could potentially be odr-used, defer marking it so 18755 // until we finish analyzing the full expression for any 18756 // lvalue-to-rvalue 18757 // or discarded value conversions that would obviate odr-use. 18758 // Add it to the list of potential captures that will be analyzed 18759 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18760 // unless the variable is a reference that was initialized by a constant 18761 // expression (this will never need to be captured or odr-used). 18762 // 18763 // FIXME: We can simplify this a lot after implementing P0588R1. 18764 assert(E && "Capture variable should be used in an expression."); 18765 if (!Var->getType()->isReferenceType() || 18766 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18767 LSI->addPotentialCapture(E->IgnoreParens()); 18768 } 18769 } 18770 break; 18771 } 18772 } 18773 18774 /// Mark a variable referenced, and check whether it is odr-used 18775 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18776 /// used directly for normal expressions referring to VarDecl. 18777 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18778 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18779 } 18780 18781 static void 18782 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18783 bool MightBeOdrUse, 18784 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18785 if (SemaRef.isInOpenMPDeclareTargetContext()) 18786 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18787 18788 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18789 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18790 return; 18791 } 18792 18793 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18794 18795 // If this is a call to a method via a cast, also mark the method in the 18796 // derived class used in case codegen can devirtualize the call. 18797 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18798 if (!ME) 18799 return; 18800 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18801 if (!MD) 18802 return; 18803 // Only attempt to devirtualize if this is truly a virtual call. 18804 bool IsVirtualCall = MD->isVirtual() && 18805 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18806 if (!IsVirtualCall) 18807 return; 18808 18809 // If it's possible to devirtualize the call, mark the called function 18810 // referenced. 18811 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18812 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18813 if (DM) 18814 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18815 } 18816 18817 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18818 /// 18819 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18820 /// handled with care if the DeclRefExpr is not newly-created. 18821 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18822 // TODO: update this with DR# once a defect report is filed. 18823 // C++11 defect. The address of a pure member should not be an ODR use, even 18824 // if it's a qualified reference. 18825 bool OdrUse = true; 18826 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18827 if (Method->isVirtual() && 18828 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18829 OdrUse = false; 18830 18831 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18832 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18833 FD->isConsteval() && !RebuildingImmediateInvocation) 18834 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18835 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18836 RefsMinusAssignments); 18837 } 18838 18839 /// Perform reference-marking and odr-use handling for a MemberExpr. 18840 void Sema::MarkMemberReferenced(MemberExpr *E) { 18841 // C++11 [basic.def.odr]p2: 18842 // A non-overloaded function whose name appears as a potentially-evaluated 18843 // expression or a member of a set of candidate functions, if selected by 18844 // overload resolution when referred to from a potentially-evaluated 18845 // expression, is odr-used, unless it is a pure virtual function and its 18846 // name is not explicitly qualified. 18847 bool MightBeOdrUse = true; 18848 if (E->performsVirtualDispatch(getLangOpts())) { 18849 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18850 if (Method->isPure()) 18851 MightBeOdrUse = false; 18852 } 18853 SourceLocation Loc = 18854 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18855 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18856 RefsMinusAssignments); 18857 } 18858 18859 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18860 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18861 for (VarDecl *VD : *E) 18862 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18863 RefsMinusAssignments); 18864 } 18865 18866 /// Perform marking for a reference to an arbitrary declaration. It 18867 /// marks the declaration referenced, and performs odr-use checking for 18868 /// functions and variables. This method should not be used when building a 18869 /// normal expression which refers to a variable. 18870 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18871 bool MightBeOdrUse) { 18872 if (MightBeOdrUse) { 18873 if (auto *VD = dyn_cast<VarDecl>(D)) { 18874 MarkVariableReferenced(Loc, VD); 18875 return; 18876 } 18877 } 18878 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18879 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18880 return; 18881 } 18882 D->setReferenced(); 18883 } 18884 18885 namespace { 18886 // Mark all of the declarations used by a type as referenced. 18887 // FIXME: Not fully implemented yet! We need to have a better understanding 18888 // of when we're entering a context we should not recurse into. 18889 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18890 // TreeTransforms rebuilding the type in a new context. Rather than 18891 // duplicating the TreeTransform logic, we should consider reusing it here. 18892 // Currently that causes problems when rebuilding LambdaExprs. 18893 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18894 Sema &S; 18895 SourceLocation Loc; 18896 18897 public: 18898 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18899 18900 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18901 18902 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18903 }; 18904 } 18905 18906 bool MarkReferencedDecls::TraverseTemplateArgument( 18907 const TemplateArgument &Arg) { 18908 { 18909 // A non-type template argument is a constant-evaluated context. 18910 EnterExpressionEvaluationContext Evaluated( 18911 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18912 if (Arg.getKind() == TemplateArgument::Declaration) { 18913 if (Decl *D = Arg.getAsDecl()) 18914 S.MarkAnyDeclReferenced(Loc, D, true); 18915 } else if (Arg.getKind() == TemplateArgument::Expression) { 18916 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18917 } 18918 } 18919 18920 return Inherited::TraverseTemplateArgument(Arg); 18921 } 18922 18923 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18924 MarkReferencedDecls Marker(*this, Loc); 18925 Marker.TraverseType(T); 18926 } 18927 18928 namespace { 18929 /// Helper class that marks all of the declarations referenced by 18930 /// potentially-evaluated subexpressions as "referenced". 18931 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18932 public: 18933 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18934 bool SkipLocalVariables; 18935 ArrayRef<const Expr *> StopAt; 18936 18937 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 18938 ArrayRef<const Expr *> StopAt) 18939 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 18940 18941 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18942 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18943 } 18944 18945 void Visit(Expr *E) { 18946 if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end()) 18947 return; 18948 Inherited::Visit(E); 18949 } 18950 18951 void VisitDeclRefExpr(DeclRefExpr *E) { 18952 // If we were asked not to visit local variables, don't. 18953 if (SkipLocalVariables) { 18954 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18955 if (VD->hasLocalStorage()) 18956 return; 18957 } 18958 18959 // FIXME: This can trigger the instantiation of the initializer of a 18960 // variable, which can cause the expression to become value-dependent 18961 // or error-dependent. Do we need to propagate the new dependence bits? 18962 S.MarkDeclRefReferenced(E); 18963 } 18964 18965 void VisitMemberExpr(MemberExpr *E) { 18966 S.MarkMemberReferenced(E); 18967 Visit(E->getBase()); 18968 } 18969 }; 18970 } // namespace 18971 18972 /// Mark any declarations that appear within this expression or any 18973 /// potentially-evaluated subexpressions as "referenced". 18974 /// 18975 /// \param SkipLocalVariables If true, don't mark local variables as 18976 /// 'referenced'. 18977 /// \param StopAt Subexpressions that we shouldn't recurse into. 18978 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18979 bool SkipLocalVariables, 18980 ArrayRef<const Expr*> StopAt) { 18981 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 18982 } 18983 18984 /// Emit a diagnostic when statements are reachable. 18985 /// FIXME: check for reachability even in expressions for which we don't build a 18986 /// CFG (eg, in the initializer of a global or in a constant expression). 18987 /// For example, 18988 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 18989 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 18990 const PartialDiagnostic &PD) { 18991 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18992 if (!FunctionScopes.empty()) 18993 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 18994 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18995 return true; 18996 } 18997 18998 // The initializer of a constexpr variable or of the first declaration of a 18999 // static data member is not syntactically a constant evaluated constant, 19000 // but nonetheless is always required to be a constant expression, so we 19001 // can skip diagnosing. 19002 // FIXME: Using the mangling context here is a hack. 19003 if (auto *VD = dyn_cast_or_null<VarDecl>( 19004 ExprEvalContexts.back().ManglingContextDecl)) { 19005 if (VD->isConstexpr() || 19006 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 19007 return false; 19008 // FIXME: For any other kind of variable, we should build a CFG for its 19009 // initializer and check whether the context in question is reachable. 19010 } 19011 19012 Diag(Loc, PD); 19013 return true; 19014 } 19015 19016 /// Emit a diagnostic that describes an effect on the run-time behavior 19017 /// of the program being compiled. 19018 /// 19019 /// This routine emits the given diagnostic when the code currently being 19020 /// type-checked is "potentially evaluated", meaning that there is a 19021 /// possibility that the code will actually be executable. Code in sizeof() 19022 /// expressions, code used only during overload resolution, etc., are not 19023 /// potentially evaluated. This routine will suppress such diagnostics or, 19024 /// in the absolutely nutty case of potentially potentially evaluated 19025 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 19026 /// later. 19027 /// 19028 /// This routine should be used for all diagnostics that describe the run-time 19029 /// behavior of a program, such as passing a non-POD value through an ellipsis. 19030 /// Failure to do so will likely result in spurious diagnostics or failures 19031 /// during overload resolution or within sizeof/alignof/typeof/typeid. 19032 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 19033 const PartialDiagnostic &PD) { 19034 19035 if (ExprEvalContexts.back().isDiscardedStatementContext()) 19036 return false; 19037 19038 switch (ExprEvalContexts.back().Context) { 19039 case ExpressionEvaluationContext::Unevaluated: 19040 case ExpressionEvaluationContext::UnevaluatedList: 19041 case ExpressionEvaluationContext::UnevaluatedAbstract: 19042 case ExpressionEvaluationContext::DiscardedStatement: 19043 // The argument will never be evaluated, so don't complain. 19044 break; 19045 19046 case ExpressionEvaluationContext::ConstantEvaluated: 19047 case ExpressionEvaluationContext::ImmediateFunctionContext: 19048 // Relevant diagnostics should be produced by constant evaluation. 19049 break; 19050 19051 case ExpressionEvaluationContext::PotentiallyEvaluated: 19052 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 19053 return DiagIfReachable(Loc, Stmts, PD); 19054 } 19055 19056 return false; 19057 } 19058 19059 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 19060 const PartialDiagnostic &PD) { 19061 return DiagRuntimeBehavior( 19062 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 19063 } 19064 19065 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 19066 CallExpr *CE, FunctionDecl *FD) { 19067 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 19068 return false; 19069 19070 // If we're inside a decltype's expression, don't check for a valid return 19071 // type or construct temporaries until we know whether this is the last call. 19072 if (ExprEvalContexts.back().ExprContext == 19073 ExpressionEvaluationContextRecord::EK_Decltype) { 19074 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 19075 return false; 19076 } 19077 19078 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19079 FunctionDecl *FD; 19080 CallExpr *CE; 19081 19082 public: 19083 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19084 : FD(FD), CE(CE) { } 19085 19086 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19087 if (!FD) { 19088 S.Diag(Loc, diag::err_call_incomplete_return) 19089 << T << CE->getSourceRange(); 19090 return; 19091 } 19092 19093 S.Diag(Loc, diag::err_call_function_incomplete_return) 19094 << CE->getSourceRange() << FD << T; 19095 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19096 << FD->getDeclName(); 19097 } 19098 } Diagnoser(FD, CE); 19099 19100 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19101 return true; 19102 19103 return false; 19104 } 19105 19106 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19107 // will prevent this condition from triggering, which is what we want. 19108 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19109 SourceLocation Loc; 19110 19111 unsigned diagnostic = diag::warn_condition_is_assignment; 19112 bool IsOrAssign = false; 19113 19114 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19115 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19116 return; 19117 19118 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19119 19120 // Greylist some idioms by putting them into a warning subcategory. 19121 if (ObjCMessageExpr *ME 19122 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19123 Selector Sel = ME->getSelector(); 19124 19125 // self = [<foo> init...] 19126 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19127 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19128 19129 // <foo> = [<bar> nextObject] 19130 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19131 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19132 } 19133 19134 Loc = Op->getOperatorLoc(); 19135 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19136 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19137 return; 19138 19139 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19140 Loc = Op->getOperatorLoc(); 19141 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19142 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19143 else { 19144 // Not an assignment. 19145 return; 19146 } 19147 19148 Diag(Loc, diagnostic) << E->getSourceRange(); 19149 19150 SourceLocation Open = E->getBeginLoc(); 19151 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19152 Diag(Loc, diag::note_condition_assign_silence) 19153 << FixItHint::CreateInsertion(Open, "(") 19154 << FixItHint::CreateInsertion(Close, ")"); 19155 19156 if (IsOrAssign) 19157 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19158 << FixItHint::CreateReplacement(Loc, "!="); 19159 else 19160 Diag(Loc, diag::note_condition_assign_to_comparison) 19161 << FixItHint::CreateReplacement(Loc, "=="); 19162 } 19163 19164 /// Redundant parentheses over an equality comparison can indicate 19165 /// that the user intended an assignment used as condition. 19166 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19167 // Don't warn if the parens came from a macro. 19168 SourceLocation parenLoc = ParenE->getBeginLoc(); 19169 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19170 return; 19171 // Don't warn for dependent expressions. 19172 if (ParenE->isTypeDependent()) 19173 return; 19174 19175 Expr *E = ParenE->IgnoreParens(); 19176 19177 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19178 if (opE->getOpcode() == BO_EQ && 19179 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19180 == Expr::MLV_Valid) { 19181 SourceLocation Loc = opE->getOperatorLoc(); 19182 19183 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19184 SourceRange ParenERange = ParenE->getSourceRange(); 19185 Diag(Loc, diag::note_equality_comparison_silence) 19186 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19187 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19188 Diag(Loc, diag::note_equality_comparison_to_assign) 19189 << FixItHint::CreateReplacement(Loc, "="); 19190 } 19191 } 19192 19193 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19194 bool IsConstexpr) { 19195 DiagnoseAssignmentAsCondition(E); 19196 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19197 DiagnoseEqualityWithExtraParens(parenE); 19198 19199 ExprResult result = CheckPlaceholderExpr(E); 19200 if (result.isInvalid()) return ExprError(); 19201 E = result.get(); 19202 19203 if (!E->isTypeDependent()) { 19204 if (getLangOpts().CPlusPlus) 19205 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19206 19207 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19208 if (ERes.isInvalid()) 19209 return ExprError(); 19210 E = ERes.get(); 19211 19212 QualType T = E->getType(); 19213 if (!T->isScalarType()) { // C99 6.8.4.1p1 19214 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19215 << T << E->getSourceRange(); 19216 return ExprError(); 19217 } 19218 CheckBoolLikeConversion(E, Loc); 19219 } 19220 19221 return E; 19222 } 19223 19224 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19225 Expr *SubExpr, ConditionKind CK, 19226 bool MissingOK) { 19227 // MissingOK indicates whether having no condition expression is valid 19228 // (for loop) or invalid (e.g. while loop). 19229 if (!SubExpr) 19230 return MissingOK ? ConditionResult() : ConditionError(); 19231 19232 ExprResult Cond; 19233 switch (CK) { 19234 case ConditionKind::Boolean: 19235 Cond = CheckBooleanCondition(Loc, SubExpr); 19236 break; 19237 19238 case ConditionKind::ConstexprIf: 19239 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19240 break; 19241 19242 case ConditionKind::Switch: 19243 Cond = CheckSwitchCondition(Loc, SubExpr); 19244 break; 19245 } 19246 if (Cond.isInvalid()) { 19247 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19248 {SubExpr}, PreferredConditionType(CK)); 19249 if (!Cond.get()) 19250 return ConditionError(); 19251 } 19252 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19253 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19254 if (!FullExpr.get()) 19255 return ConditionError(); 19256 19257 return ConditionResult(*this, nullptr, FullExpr, 19258 CK == ConditionKind::ConstexprIf); 19259 } 19260 19261 namespace { 19262 /// A visitor for rebuilding a call to an __unknown_any expression 19263 /// to have an appropriate type. 19264 struct RebuildUnknownAnyFunction 19265 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19266 19267 Sema &S; 19268 19269 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19270 19271 ExprResult VisitStmt(Stmt *S) { 19272 llvm_unreachable("unexpected statement!"); 19273 } 19274 19275 ExprResult VisitExpr(Expr *E) { 19276 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19277 << E->getSourceRange(); 19278 return ExprError(); 19279 } 19280 19281 /// Rebuild an expression which simply semantically wraps another 19282 /// expression which it shares the type and value kind of. 19283 template <class T> ExprResult rebuildSugarExpr(T *E) { 19284 ExprResult SubResult = Visit(E->getSubExpr()); 19285 if (SubResult.isInvalid()) return ExprError(); 19286 19287 Expr *SubExpr = SubResult.get(); 19288 E->setSubExpr(SubExpr); 19289 E->setType(SubExpr->getType()); 19290 E->setValueKind(SubExpr->getValueKind()); 19291 assert(E->getObjectKind() == OK_Ordinary); 19292 return E; 19293 } 19294 19295 ExprResult VisitParenExpr(ParenExpr *E) { 19296 return rebuildSugarExpr(E); 19297 } 19298 19299 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19300 return rebuildSugarExpr(E); 19301 } 19302 19303 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19304 ExprResult SubResult = Visit(E->getSubExpr()); 19305 if (SubResult.isInvalid()) return ExprError(); 19306 19307 Expr *SubExpr = SubResult.get(); 19308 E->setSubExpr(SubExpr); 19309 E->setType(S.Context.getPointerType(SubExpr->getType())); 19310 assert(E->isPRValue()); 19311 assert(E->getObjectKind() == OK_Ordinary); 19312 return E; 19313 } 19314 19315 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19316 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19317 19318 E->setType(VD->getType()); 19319 19320 assert(E->isPRValue()); 19321 if (S.getLangOpts().CPlusPlus && 19322 !(isa<CXXMethodDecl>(VD) && 19323 cast<CXXMethodDecl>(VD)->isInstance())) 19324 E->setValueKind(VK_LValue); 19325 19326 return E; 19327 } 19328 19329 ExprResult VisitMemberExpr(MemberExpr *E) { 19330 return resolveDecl(E, E->getMemberDecl()); 19331 } 19332 19333 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19334 return resolveDecl(E, E->getDecl()); 19335 } 19336 }; 19337 } 19338 19339 /// Given a function expression of unknown-any type, try to rebuild it 19340 /// to have a function type. 19341 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19342 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19343 if (Result.isInvalid()) return ExprError(); 19344 return S.DefaultFunctionArrayConversion(Result.get()); 19345 } 19346 19347 namespace { 19348 /// A visitor for rebuilding an expression of type __unknown_anytype 19349 /// into one which resolves the type directly on the referring 19350 /// expression. Strict preservation of the original source 19351 /// structure is not a goal. 19352 struct RebuildUnknownAnyExpr 19353 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19354 19355 Sema &S; 19356 19357 /// The current destination type. 19358 QualType DestType; 19359 19360 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19361 : S(S), DestType(CastType) {} 19362 19363 ExprResult VisitStmt(Stmt *S) { 19364 llvm_unreachable("unexpected statement!"); 19365 } 19366 19367 ExprResult VisitExpr(Expr *E) { 19368 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19369 << E->getSourceRange(); 19370 return ExprError(); 19371 } 19372 19373 ExprResult VisitCallExpr(CallExpr *E); 19374 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19375 19376 /// Rebuild an expression which simply semantically wraps another 19377 /// expression which it shares the type and value kind of. 19378 template <class T> ExprResult rebuildSugarExpr(T *E) { 19379 ExprResult SubResult = Visit(E->getSubExpr()); 19380 if (SubResult.isInvalid()) return ExprError(); 19381 Expr *SubExpr = SubResult.get(); 19382 E->setSubExpr(SubExpr); 19383 E->setType(SubExpr->getType()); 19384 E->setValueKind(SubExpr->getValueKind()); 19385 assert(E->getObjectKind() == OK_Ordinary); 19386 return E; 19387 } 19388 19389 ExprResult VisitParenExpr(ParenExpr *E) { 19390 return rebuildSugarExpr(E); 19391 } 19392 19393 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19394 return rebuildSugarExpr(E); 19395 } 19396 19397 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19398 const PointerType *Ptr = DestType->getAs<PointerType>(); 19399 if (!Ptr) { 19400 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19401 << E->getSourceRange(); 19402 return ExprError(); 19403 } 19404 19405 if (isa<CallExpr>(E->getSubExpr())) { 19406 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19407 << E->getSourceRange(); 19408 return ExprError(); 19409 } 19410 19411 assert(E->isPRValue()); 19412 assert(E->getObjectKind() == OK_Ordinary); 19413 E->setType(DestType); 19414 19415 // Build the sub-expression as if it were an object of the pointee type. 19416 DestType = Ptr->getPointeeType(); 19417 ExprResult SubResult = Visit(E->getSubExpr()); 19418 if (SubResult.isInvalid()) return ExprError(); 19419 E->setSubExpr(SubResult.get()); 19420 return E; 19421 } 19422 19423 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19424 19425 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19426 19427 ExprResult VisitMemberExpr(MemberExpr *E) { 19428 return resolveDecl(E, E->getMemberDecl()); 19429 } 19430 19431 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19432 return resolveDecl(E, E->getDecl()); 19433 } 19434 }; 19435 } 19436 19437 /// Rebuilds a call expression which yielded __unknown_anytype. 19438 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19439 Expr *CalleeExpr = E->getCallee(); 19440 19441 enum FnKind { 19442 FK_MemberFunction, 19443 FK_FunctionPointer, 19444 FK_BlockPointer 19445 }; 19446 19447 FnKind Kind; 19448 QualType CalleeType = CalleeExpr->getType(); 19449 if (CalleeType == S.Context.BoundMemberTy) { 19450 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19451 Kind = FK_MemberFunction; 19452 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19453 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19454 CalleeType = Ptr->getPointeeType(); 19455 Kind = FK_FunctionPointer; 19456 } else { 19457 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19458 Kind = FK_BlockPointer; 19459 } 19460 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19461 19462 // Verify that this is a legal result type of a function. 19463 if (DestType->isArrayType() || DestType->isFunctionType()) { 19464 unsigned diagID = diag::err_func_returning_array_function; 19465 if (Kind == FK_BlockPointer) 19466 diagID = diag::err_block_returning_array_function; 19467 19468 S.Diag(E->getExprLoc(), diagID) 19469 << DestType->isFunctionType() << DestType; 19470 return ExprError(); 19471 } 19472 19473 // Otherwise, go ahead and set DestType as the call's result. 19474 E->setType(DestType.getNonLValueExprType(S.Context)); 19475 E->setValueKind(Expr::getValueKindForType(DestType)); 19476 assert(E->getObjectKind() == OK_Ordinary); 19477 19478 // Rebuild the function type, replacing the result type with DestType. 19479 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19480 if (Proto) { 19481 // __unknown_anytype(...) is a special case used by the debugger when 19482 // it has no idea what a function's signature is. 19483 // 19484 // We want to build this call essentially under the K&R 19485 // unprototyped rules, but making a FunctionNoProtoType in C++ 19486 // would foul up all sorts of assumptions. However, we cannot 19487 // simply pass all arguments as variadic arguments, nor can we 19488 // portably just call the function under a non-variadic type; see 19489 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19490 // However, it turns out that in practice it is generally safe to 19491 // call a function declared as "A foo(B,C,D);" under the prototype 19492 // "A foo(B,C,D,...);". The only known exception is with the 19493 // Windows ABI, where any variadic function is implicitly cdecl 19494 // regardless of its normal CC. Therefore we change the parameter 19495 // types to match the types of the arguments. 19496 // 19497 // This is a hack, but it is far superior to moving the 19498 // corresponding target-specific code from IR-gen to Sema/AST. 19499 19500 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19501 SmallVector<QualType, 8> ArgTypes; 19502 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19503 ArgTypes.reserve(E->getNumArgs()); 19504 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19505 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19506 } 19507 ParamTypes = ArgTypes; 19508 } 19509 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19510 Proto->getExtProtoInfo()); 19511 } else { 19512 DestType = S.Context.getFunctionNoProtoType(DestType, 19513 FnType->getExtInfo()); 19514 } 19515 19516 // Rebuild the appropriate pointer-to-function type. 19517 switch (Kind) { 19518 case FK_MemberFunction: 19519 // Nothing to do. 19520 break; 19521 19522 case FK_FunctionPointer: 19523 DestType = S.Context.getPointerType(DestType); 19524 break; 19525 19526 case FK_BlockPointer: 19527 DestType = S.Context.getBlockPointerType(DestType); 19528 break; 19529 } 19530 19531 // Finally, we can recurse. 19532 ExprResult CalleeResult = Visit(CalleeExpr); 19533 if (!CalleeResult.isUsable()) return ExprError(); 19534 E->setCallee(CalleeResult.get()); 19535 19536 // Bind a temporary if necessary. 19537 return S.MaybeBindToTemporary(E); 19538 } 19539 19540 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19541 // Verify that this is a legal result type of a call. 19542 if (DestType->isArrayType() || DestType->isFunctionType()) { 19543 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19544 << DestType->isFunctionType() << DestType; 19545 return ExprError(); 19546 } 19547 19548 // Rewrite the method result type if available. 19549 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19550 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19551 Method->setReturnType(DestType); 19552 } 19553 19554 // Change the type of the message. 19555 E->setType(DestType.getNonReferenceType()); 19556 E->setValueKind(Expr::getValueKindForType(DestType)); 19557 19558 return S.MaybeBindToTemporary(E); 19559 } 19560 19561 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19562 // The only case we should ever see here is a function-to-pointer decay. 19563 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19564 assert(E->isPRValue()); 19565 assert(E->getObjectKind() == OK_Ordinary); 19566 19567 E->setType(DestType); 19568 19569 // Rebuild the sub-expression as the pointee (function) type. 19570 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19571 19572 ExprResult Result = Visit(E->getSubExpr()); 19573 if (!Result.isUsable()) return ExprError(); 19574 19575 E->setSubExpr(Result.get()); 19576 return E; 19577 } else if (E->getCastKind() == CK_LValueToRValue) { 19578 assert(E->isPRValue()); 19579 assert(E->getObjectKind() == OK_Ordinary); 19580 19581 assert(isa<BlockPointerType>(E->getType())); 19582 19583 E->setType(DestType); 19584 19585 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19586 DestType = S.Context.getLValueReferenceType(DestType); 19587 19588 ExprResult Result = Visit(E->getSubExpr()); 19589 if (!Result.isUsable()) return ExprError(); 19590 19591 E->setSubExpr(Result.get()); 19592 return E; 19593 } else { 19594 llvm_unreachable("Unhandled cast type!"); 19595 } 19596 } 19597 19598 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19599 ExprValueKind ValueKind = VK_LValue; 19600 QualType Type = DestType; 19601 19602 // We know how to make this work for certain kinds of decls: 19603 19604 // - functions 19605 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19606 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19607 DestType = Ptr->getPointeeType(); 19608 ExprResult Result = resolveDecl(E, VD); 19609 if (Result.isInvalid()) return ExprError(); 19610 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19611 VK_PRValue); 19612 } 19613 19614 if (!Type->isFunctionType()) { 19615 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19616 << VD << E->getSourceRange(); 19617 return ExprError(); 19618 } 19619 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19620 // We must match the FunctionDecl's type to the hack introduced in 19621 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19622 // type. See the lengthy commentary in that routine. 19623 QualType FDT = FD->getType(); 19624 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19625 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19626 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19627 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19628 SourceLocation Loc = FD->getLocation(); 19629 FunctionDecl *NewFD = FunctionDecl::Create( 19630 S.Context, FD->getDeclContext(), Loc, Loc, 19631 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19632 SC_None, S.getCurFPFeatures().isFPConstrained(), 19633 false /*isInlineSpecified*/, FD->hasPrototype(), 19634 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19635 19636 if (FD->getQualifier()) 19637 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19638 19639 SmallVector<ParmVarDecl*, 16> Params; 19640 for (const auto &AI : FT->param_types()) { 19641 ParmVarDecl *Param = 19642 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19643 Param->setScopeInfo(0, Params.size()); 19644 Params.push_back(Param); 19645 } 19646 NewFD->setParams(Params); 19647 DRE->setDecl(NewFD); 19648 VD = DRE->getDecl(); 19649 } 19650 } 19651 19652 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19653 if (MD->isInstance()) { 19654 ValueKind = VK_PRValue; 19655 Type = S.Context.BoundMemberTy; 19656 } 19657 19658 // Function references aren't l-values in C. 19659 if (!S.getLangOpts().CPlusPlus) 19660 ValueKind = VK_PRValue; 19661 19662 // - variables 19663 } else if (isa<VarDecl>(VD)) { 19664 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19665 Type = RefTy->getPointeeType(); 19666 } else if (Type->isFunctionType()) { 19667 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19668 << VD << E->getSourceRange(); 19669 return ExprError(); 19670 } 19671 19672 // - nothing else 19673 } else { 19674 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19675 << VD << E->getSourceRange(); 19676 return ExprError(); 19677 } 19678 19679 // Modifying the declaration like this is friendly to IR-gen but 19680 // also really dangerous. 19681 VD->setType(DestType); 19682 E->setType(Type); 19683 E->setValueKind(ValueKind); 19684 return E; 19685 } 19686 19687 /// Check a cast of an unknown-any type. We intentionally only 19688 /// trigger this for C-style casts. 19689 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19690 Expr *CastExpr, CastKind &CastKind, 19691 ExprValueKind &VK, CXXCastPath &Path) { 19692 // The type we're casting to must be either void or complete. 19693 if (!CastType->isVoidType() && 19694 RequireCompleteType(TypeRange.getBegin(), CastType, 19695 diag::err_typecheck_cast_to_incomplete)) 19696 return ExprError(); 19697 19698 // Rewrite the casted expression from scratch. 19699 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19700 if (!result.isUsable()) return ExprError(); 19701 19702 CastExpr = result.get(); 19703 VK = CastExpr->getValueKind(); 19704 CastKind = CK_NoOp; 19705 19706 return CastExpr; 19707 } 19708 19709 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19710 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19711 } 19712 19713 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19714 Expr *arg, QualType ¶mType) { 19715 // If the syntactic form of the argument is not an explicit cast of 19716 // any sort, just do default argument promotion. 19717 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19718 if (!castArg) { 19719 ExprResult result = DefaultArgumentPromotion(arg); 19720 if (result.isInvalid()) return ExprError(); 19721 paramType = result.get()->getType(); 19722 return result; 19723 } 19724 19725 // Otherwise, use the type that was written in the explicit cast. 19726 assert(!arg->hasPlaceholderType()); 19727 paramType = castArg->getTypeAsWritten(); 19728 19729 // Copy-initialize a parameter of that type. 19730 InitializedEntity entity = 19731 InitializedEntity::InitializeParameter(Context, paramType, 19732 /*consumed*/ false); 19733 return PerformCopyInitialization(entity, callLoc, arg); 19734 } 19735 19736 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19737 Expr *orig = E; 19738 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19739 while (true) { 19740 E = E->IgnoreParenImpCasts(); 19741 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19742 E = call->getCallee(); 19743 diagID = diag::err_uncasted_call_of_unknown_any; 19744 } else { 19745 break; 19746 } 19747 } 19748 19749 SourceLocation loc; 19750 NamedDecl *d; 19751 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19752 loc = ref->getLocation(); 19753 d = ref->getDecl(); 19754 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19755 loc = mem->getMemberLoc(); 19756 d = mem->getMemberDecl(); 19757 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19758 diagID = diag::err_uncasted_call_of_unknown_any; 19759 loc = msg->getSelectorStartLoc(); 19760 d = msg->getMethodDecl(); 19761 if (!d) { 19762 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19763 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19764 << orig->getSourceRange(); 19765 return ExprError(); 19766 } 19767 } else { 19768 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19769 << E->getSourceRange(); 19770 return ExprError(); 19771 } 19772 19773 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19774 19775 // Never recoverable. 19776 return ExprError(); 19777 } 19778 19779 /// Check for operands with placeholder types and complain if found. 19780 /// Returns ExprError() if there was an error and no recovery was possible. 19781 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19782 if (!Context.isDependenceAllowed()) { 19783 // C cannot handle TypoExpr nodes on either side of a binop because it 19784 // doesn't handle dependent types properly, so make sure any TypoExprs have 19785 // been dealt with before checking the operands. 19786 ExprResult Result = CorrectDelayedTyposInExpr(E); 19787 if (!Result.isUsable()) return ExprError(); 19788 E = Result.get(); 19789 } 19790 19791 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19792 if (!placeholderType) return E; 19793 19794 switch (placeholderType->getKind()) { 19795 19796 // Overloaded expressions. 19797 case BuiltinType::Overload: { 19798 // Try to resolve a single function template specialization. 19799 // This is obligatory. 19800 ExprResult Result = E; 19801 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19802 return Result; 19803 19804 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19805 // leaves Result unchanged on failure. 19806 Result = E; 19807 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19808 return Result; 19809 19810 // If that failed, try to recover with a call. 19811 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19812 /*complain*/ true); 19813 return Result; 19814 } 19815 19816 // Bound member functions. 19817 case BuiltinType::BoundMember: { 19818 ExprResult result = E; 19819 const Expr *BME = E->IgnoreParens(); 19820 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19821 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19822 if (isa<CXXPseudoDestructorExpr>(BME)) { 19823 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19824 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19825 if (ME->getMemberNameInfo().getName().getNameKind() == 19826 DeclarationName::CXXDestructorName) 19827 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19828 } 19829 tryToRecoverWithCall(result, PD, 19830 /*complain*/ true); 19831 return result; 19832 } 19833 19834 // ARC unbridged casts. 19835 case BuiltinType::ARCUnbridgedCast: { 19836 Expr *realCast = stripARCUnbridgedCast(E); 19837 diagnoseARCUnbridgedCast(realCast); 19838 return realCast; 19839 } 19840 19841 // Expressions of unknown type. 19842 case BuiltinType::UnknownAny: 19843 return diagnoseUnknownAnyExpr(*this, E); 19844 19845 // Pseudo-objects. 19846 case BuiltinType::PseudoObject: 19847 return checkPseudoObjectRValue(E); 19848 19849 case BuiltinType::BuiltinFn: { 19850 // Accept __noop without parens by implicitly converting it to a call expr. 19851 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19852 if (DRE) { 19853 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19854 if (FD->getBuiltinID() == Builtin::BI__noop) { 19855 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19856 CK_BuiltinFnToFnPtr) 19857 .get(); 19858 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19859 VK_PRValue, SourceLocation(), 19860 FPOptionsOverride()); 19861 } 19862 } 19863 19864 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19865 return ExprError(); 19866 } 19867 19868 case BuiltinType::IncompleteMatrixIdx: 19869 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19870 ->getRowIdx() 19871 ->getBeginLoc(), 19872 diag::err_matrix_incomplete_index); 19873 return ExprError(); 19874 19875 // Expressions of unknown type. 19876 case BuiltinType::OMPArraySection: 19877 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19878 return ExprError(); 19879 19880 // Expressions of unknown type. 19881 case BuiltinType::OMPArrayShaping: 19882 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19883 19884 case BuiltinType::OMPIterator: 19885 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19886 19887 // Everything else should be impossible. 19888 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19889 case BuiltinType::Id: 19890 #include "clang/Basic/OpenCLImageTypes.def" 19891 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19892 case BuiltinType::Id: 19893 #include "clang/Basic/OpenCLExtensionTypes.def" 19894 #define SVE_TYPE(Name, Id, SingletonId) \ 19895 case BuiltinType::Id: 19896 #include "clang/Basic/AArch64SVEACLETypes.def" 19897 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19898 case BuiltinType::Id: 19899 #include "clang/Basic/PPCTypes.def" 19900 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19901 #include "clang/Basic/RISCVVTypes.def" 19902 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19903 #define PLACEHOLDER_TYPE(Id, SingletonId) 19904 #include "clang/AST/BuiltinTypes.def" 19905 break; 19906 } 19907 19908 llvm_unreachable("invalid placeholder type!"); 19909 } 19910 19911 bool Sema::CheckCaseExpression(Expr *E) { 19912 if (E->isTypeDependent()) 19913 return true; 19914 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19915 return E->getType()->isIntegralOrEnumerationType(); 19916 return false; 19917 } 19918 19919 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19920 ExprResult 19921 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19922 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19923 "Unknown Objective-C Boolean value!"); 19924 QualType BoolT = Context.ObjCBuiltinBoolTy; 19925 if (!Context.getBOOLDecl()) { 19926 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19927 Sema::LookupOrdinaryName); 19928 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19929 NamedDecl *ND = Result.getFoundDecl(); 19930 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19931 Context.setBOOLDecl(TD); 19932 } 19933 } 19934 if (Context.getBOOLDecl()) 19935 BoolT = Context.getBOOLType(); 19936 return new (Context) 19937 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19938 } 19939 19940 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19941 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19942 SourceLocation RParen) { 19943 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19944 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19945 return Spec.getPlatform() == Platform; 19946 }); 19947 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19948 // for "maccatalyst" if "maccatalyst" is not specified. 19949 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19950 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19951 return Spec.getPlatform() == "ios"; 19952 }); 19953 } 19954 if (Spec == AvailSpecs.end()) 19955 return None; 19956 return Spec->getVersion(); 19957 }; 19958 19959 VersionTuple Version; 19960 if (auto MaybeVersion = 19961 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19962 Version = *MaybeVersion; 19963 19964 // The use of `@available` in the enclosing context should be analyzed to 19965 // warn when it's used inappropriately (i.e. not if(@available)). 19966 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19967 Context->HasPotentialAvailabilityViolations = true; 19968 19969 return new (Context) 19970 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19971 } 19972 19973 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19974 ArrayRef<Expr *> SubExprs, QualType T) { 19975 if (!Context.getLangOpts().RecoveryAST) 19976 return ExprError(); 19977 19978 if (isSFINAEContext()) 19979 return ExprError(); 19980 19981 if (T.isNull() || T->isUndeducedType() || 19982 !Context.getLangOpts().RecoveryASTType) 19983 // We don't know the concrete type, fallback to dependent type. 19984 T = Context.DependentTy; 19985 19986 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19987 } 19988